Expand crafting, shops, gathering visuals, and fix dark material tints.
Add axe craft chain and pickaxe-style sprites, let buysItems shops take transferable goods (filled cheques with a 5% fee), show the gather tool equip overlay while mining, and desaturate magenta tints toward the target colour's luminance so dark materials like coal stay dark.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -82,6 +82,18 @@
82
82
<button id="tile-config-save" type="button">Save</button>
83
83
</footer>
84
84
</div>
85
86
<div id="shop-item-search-backdrop" hidden></div>
87
<div id="shop-item-search-modal" hidden>
88
<header>
89
<h2>Add shop item</h2>
90
<button id="shop-item-search-close" type="button">Close</button>
91
</header>
92
<div class="shop-item-search-body">
93
<input id="shop-item-search-input" type="search" placeholder="Search items…" autocomplete="off">
94
<div id="shop-item-search-results"></div>
95
</div>
96
</div>
85
97
<script src="/framework/framework.js"></script>
86
98
<script type="module" src="/src/editor/main.js"></script>
87
99
</body>
@@ -82,6 +82,18 @@82
<button id="tile-config-save" type="button">Save</button>82
<button id="tile-config-save" type="button">Save</button>83
</footer>83
</footer>84
</div>84
</div>85
86
<div id="shop-item-search-backdrop" hidden></div>87
<div id="shop-item-search-modal" hidden>88
<header>89
<h2>Add shop item</h2>90
<button id="shop-item-search-close" type="button">Close</button>91
</header>92
<div class="shop-item-search-body">93
<input id="shop-item-search-input" type="search" placeholder="Search items…" autocomplete="off">94
<div id="shop-item-search-results"></div>95
</div>96
</div>85
<script src="/framework/framework.js"></script>97
<script src="/framework/framework.js"></script>86
<script type="module" src="/src/editor/main.js"></script>98
<script type="module" src="/src/editor/main.js"></script>87
</body>99
</body>@@ -16,6 +16,7 @@
16
16
<button id="leave" type="button">Leave world</button>
17
17
</div>
18
18
<div id="toast-stack" aria-live="polite"></div>
19
<div id="world-tooltip" hidden></div>
19
20
<aside id="bag-panel" hidden>
20
21
<h2>Bag</h2>
21
22
<p id="bag-coins" hidden>0 coins</p>
@@ -64,7 +65,6 @@
64
65
<aside id="skills-panel" hidden>
65
66
<h2>Skills</h2>
66
67
<div id="skills-list" class="skills-grid"></div>
67
<p class="hint">Successful melee hits split XP between the weapon skill and Strength.</p>
68
68
</aside>
69
69
70
70
<div id="send-backdrop" class="modal-backdrop" hidden></div>
@@ -179,8 +179,45 @@
179
179
<h2 id="shop-title">Shop</h2>
180
180
<button id="shop-close" type="button">Close</button>
181
181
</header>
182
<div id="shop-stock" class="shop-stock"></div>
183
<p id="shop-status" class="hint"></p>
182
<div class="shop-body">
183
<div id="shop-grid" class="shop-grid"></div>
184
<div id="shop-detail" class="shop-detail" hidden>
185
<img id="shop-detail-icon" alt="">
186
<strong id="shop-detail-name"></strong>
187
<span id="shop-detail-price" class="hint"></span>
188
<span id="shop-detail-stock" class="hint"></span>
189
<div class="shop-buy-row">
190
<button id="shop-buy-1" type="button">Buy 1</button>
191
<button id="shop-buy-5" type="button">Buy 5</button>
192
<button id="shop-buy-10" type="button">Buy 10</button>
193
<button id="shop-buy-x" type="button">Buy x</button>
194
</div>
195
<p id="shop-bag-warn" class="shop-bag-warn" hidden>Inventory full; purchases will be sent to your bank.</p>
196
</div>
197
</div>
198
<div id="shop-sell-section" class="shop-sell-section" hidden>
199
<strong>Sell to shop</strong>
200
<div id="shop-sell-list" class="shop-sell-list"></div>
201
<div id="shop-sell-detail" class="shop-sell-detail" hidden>
202
<span id="shop-sell-price" class="hint"></span>
203
<span id="shop-sell-fee" class="hint" hidden></span>
204
<button id="shop-sell-confirm" type="button">Sell 1</button>
205
</div>
206
</div>
207
<p id="shop-coins" class="shop-coins">Coins: 0</p>
208
</aside>
209
210
<div id="shop-qty-backdrop" class="modal-backdrop" hidden></div>
211
<aside id="shop-qty-panel" hidden>
212
<header>
213
<h2>Buy quantity</h2>
214
<button id="shop-qty-close" type="button">Close</button>
215
</header>
216
<p id="shop-qty-hint" class="hint"></p>
217
<label class="send-row">Quantity
218
<input id="shop-qty-input" type="number" min="1" step="1" value="1">
219
</label>
220
<button id="shop-qty-confirm" type="button">Buy</button>
184
221
</aside>
185
222
186
223
<div id="cauldron-backdrop" class="modal-backdrop" hidden></div>
@@ -16,6 +16,7 @@16
<button id="leave" type="button">Leave world</button>16
<button id="leave" type="button">Leave world</button>17
</div>17
</div>18
<div id="toast-stack" aria-live="polite"></div>18
<div id="toast-stack" aria-live="polite"></div>19
<div id="world-tooltip" hidden></div>19
<aside id="bag-panel" hidden>20
<aside id="bag-panel" hidden>20
<h2>Bag</h2>21
<h2>Bag</h2>21
<p id="bag-coins" hidden>0 coins</p>22
<p id="bag-coins" hidden>0 coins</p>@@ -64,7 +65,6 @@64
<aside id="skills-panel" hidden>65
<aside id="skills-panel" hidden>65
<h2>Skills</h2>66
<h2>Skills</h2>66
<div id="skills-list" class="skills-grid"></div>67
<div id="skills-list" class="skills-grid"></div>67
<p class="hint">Successful melee hits split XP between the weapon skill and Strength.</p>68
</aside>68
</aside>69
69
70
<div id="send-backdrop" class="modal-backdrop" hidden></div>70
<div id="send-backdrop" class="modal-backdrop" hidden></div>@@ -179,8 +179,45 @@179
<h2 id="shop-title">Shop</h2>179
<h2 id="shop-title">Shop</h2>180
<button id="shop-close" type="button">Close</button>180
<button id="shop-close" type="button">Close</button>181
</header>181
</header>182
<div id="shop-stock" class="shop-stock"></div>182
<div class="shop-body">183
<p id="shop-status" class="hint"></p>183
<div id="shop-grid" class="shop-grid"></div>184
<div id="shop-detail" class="shop-detail" hidden>185
<img id="shop-detail-icon" alt="">186
<strong id="shop-detail-name"></strong>187
<span id="shop-detail-price" class="hint"></span>188
<span id="shop-detail-stock" class="hint"></span>189
<div class="shop-buy-row">190
<button id="shop-buy-1" type="button">Buy 1</button>191
<button id="shop-buy-5" type="button">Buy 5</button>192
<button id="shop-buy-10" type="button">Buy 10</button>193
<button id="shop-buy-x" type="button">Buy x</button>194
</div>195
<p id="shop-bag-warn" class="shop-bag-warn" hidden>Inventory full; purchases will be sent to your bank.</p>196
</div>197
</div>198
<div id="shop-sell-section" class="shop-sell-section" hidden>199
<strong>Sell to shop</strong>200
<div id="shop-sell-list" class="shop-sell-list"></div>201
<div id="shop-sell-detail" class="shop-sell-detail" hidden>202
<span id="shop-sell-price" class="hint"></span>203
<span id="shop-sell-fee" class="hint" hidden></span>204
<button id="shop-sell-confirm" type="button">Sell 1</button>205
</div>206
</div>207
<p id="shop-coins" class="shop-coins">Coins: 0</p>208
</aside>209
210
<div id="shop-qty-backdrop" class="modal-backdrop" hidden></div>211
<aside id="shop-qty-panel" hidden>212
<header>213
<h2>Buy quantity</h2>214
<button id="shop-qty-close" type="button">Close</button>215
</header>216
<p id="shop-qty-hint" class="hint"></p>217
<label class="send-row">Quantity218
<input id="shop-qty-input" type="number" min="1" step="1" value="1">219
</label>220
<button id="shop-qty-confirm" type="button">Buy</button>184
</aside>221
</aside>185
222
186
<div id="cauldron-backdrop" class="modal-backdrop" hidden></div>223
<div id="cauldron-backdrop" class="modal-backdrop" hidden></div>@@ -1,4 +1,18 @@
1
import { WORLD_SETTING_CATEGORIES, coerceSettingValue, formatSettingValue, settingsValuesEqual } from "/shared/definitions/worldSettings.js";
1
import {
2
WORLD_SETTING_CATEGORIES,
3
coerceSettingValue,
4
formatSettingValue,
5
settingsValuesEqual,
6
itemSeedMapsEqual
7
} from "/shared/definitions/worldSettings.js";
8
import {
9
listPricedItems,
10
itemPriceSnapshot,
11
normalizeItemSeedValues,
12
effectiveSeedValue
13
} from "/shared/shop/pricing.js";
14
15
const SEED_PAGE_SIZE = 20;
2
16
3
17
export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })
4
18
{
@@ -11,6 +25,13 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
11
25
let open = false;
12
26
let loaded = false;
13
27
let activeCategory = WORLD_SETTING_CATEGORIES[0]?.id ?? null;
28
/** @type {Record<string, number>} draft sparse overrides */
29
let draftSeeds = {};
30
/** @type {Record<string, object>} optional last-sale records from server */
31
let itemLastSales = {};
32
let seedQuery = "";
33
let seedPage = 0;
34
let seedPanel = null;
14
35
15
36
buildForm(form, {
16
37
getActiveCategory: () => activeCategory,
@@ -18,22 +39,56 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
18
39
{
19
40
activeCategory = id;
20
41
syncTabs(form, activeCategory);
42
if (id === "basePrices")
43
{ renderSeedPanel(); }
21
44
},
22
45
onFieldInput (field)
23
46
{
24
47
if (field.previewNightHour != null && onPreviewNight)
25
48
{ onPreviewNight(field.previewNightHour); }
49
},
50
onSeedPanelReady (panel)
51
{
52
seedPanel = panel;
26
53
}
27
54
});
28
form.addEventListener("input", () => refreshDirty(form, baseline, loaded));
29
form.addEventListener("change", () => refreshDirty(form, baseline, loaded));
55
56
form.addEventListener("seed-search", (event) =>
57
{
58
seedQuery = event.detail?.query ?? "";
59
seedPage = 0;
60
renderSeedPanel();
61
});
62
form.addEventListener("seed-page", (event) =>
63
{
64
seedPage += event.detail?.delta ?? 0;
65
renderSeedPanel();
66
});
67
form.addEventListener("input", (event) =>
68
{
69
if (event.target?.dataset?.seedItemId)
70
{ return; }
71
refreshDirty();
72
});
73
form.addEventListener("change", (event) =>
74
{
75
if (event.target?.dataset?.seedItemId)
76
{ return; }
77
refreshDirty();
78
});
30
79
31
80
function show (visible)
32
81
{
33
82
if (!visible)
34
83
{
35
84
fillForm(form, baseline);
36
refreshDirty(form, baseline, loaded);
85
draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };
86
seedQuery = "";
87
seedPage = 0;
88
if (seedPanel?.search)
89
{ seedPanel.search.value = ""; }
90
renderSeedPanel();
91
refreshDirty();
37
92
}
38
93
open = visible;
39
94
backdrop.hidden = !visible;
@@ -52,27 +107,189 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
52
107
{
53
108
if (!loaded)
54
109
{ return; }
55
const changed = dirtyValues(form, baseline);
110
const changed = collectDirty();
56
111
if (Object.keys(changed).length === 0)
57
112
{ return; }
58
113
socket.send({ type: MessageType.editorSaveSettings, settings: changed });
59
114
});
60
115
116
function currentSettingsPreview ()
117
{
118
return {
119
...baseline,
120
...scalarDirtyValues(form, baseline),
121
itemSeedValues: draftSeeds
122
};
123
}
124
125
function collectDirty ()
126
{
127
const changed = scalarDirtyValues(form, baseline);
128
const nextSeeds = normalizeItemSeedValues(draftSeeds);
129
const prevSeeds = normalizeItemSeedValues(baseline.itemSeedValues);
130
if (!itemSeedMapsEqual(prevSeeds, nextSeeds))
131
{ changed.itemSeedValues = nextSeeds; }
132
return changed;
133
}
134
135
function refreshDirty ()
136
{
137
const changed = loaded ? collectDirty() : {};
138
for (const row of form.querySelectorAll(".setting-row[data-key]"))
139
{
140
row.classList.toggle("dirty", Object.prototype.hasOwnProperty.call(changed, row.dataset.key));
141
}
142
for (const row of form.querySelectorAll(".seed-price-row[data-item-id]"))
143
{
144
const itemId = row.dataset.itemId;
145
const baselineSeed = effectiveSeedValue(Number(itemId), baseline);
146
const draftSeed = effectiveSeedValue(Number(itemId), { itemSeedValues: draftSeeds });
147
row.classList.toggle("dirty", !settingsValuesEqual(baselineSeed, draftSeed));
148
}
149
const count = Object.keys(changed).length;
150
save.disabled = count === 0;
151
save.textContent = count
152
? `Save ${count} change${count === 1 ? "" : "s"}`
153
: "Save";
154
}
155
156
function filteredSeedItems ()
157
{
158
const q = seedQuery.trim().toLowerCase();
159
const items = listPricedItems();
160
if (!q)
161
{ return items; }
162
return items.filter((item) =>
163
item.displayName.toLowerCase().includes(q)
164
|| item.key.toLowerCase().includes(q)
165
|| String(item.itemId).includes(q)
166
);
167
}
168
169
function renderSeedPanel ()
170
{
171
if (!seedPanel)
172
{ return; }
173
const items = filteredSeedItems();
174
const pageCount = Math.max(1, Math.ceil(items.length / SEED_PAGE_SIZE) || 1);
175
seedPage = Math.max(0, Math.min(seedPage, pageCount - 1));
176
const start = seedPage * SEED_PAGE_SIZE;
177
const pageItems = items.slice(start, start + SEED_PAGE_SIZE);
178
const settingsPreview = currentSettingsPreview();
179
180
seedPanel.meta.textContent = items.length
181
? `Showing ${start + 1}–${start + pageItems.length} of ${items.length}`
182
: "No items match.";
183
seedPanel.prev.disabled = seedPage <= 0;
184
seedPanel.next.disabled = seedPage >= pageCount - 1 || items.length === 0;
185
seedPanel.pageLabel.textContent = `Page ${seedPage + 1} / ${pageCount}`;
186
187
seedPanel.list.innerHTML = "";
188
for (const item of pageItems)
189
{
190
const snap = itemPriceSnapshot(item.itemId, {
191
settings: settingsPreview,
192
lastSale: itemLastSales[String(item.itemId)] ?? itemLastSales[item.itemId] ?? null
193
});
194
const row = document.createElement("div");
195
row.className = "seed-price-row";
196
row.dataset.itemId = String(item.itemId);
197
198
const name = document.createElement("div");
199
name.className = "seed-price-name";
200
name.innerHTML = `<strong>${escapeHtml(item.displayName)}</strong><small>#${item.itemId} · ${escapeHtml(item.key)}</small>`;
201
202
const seedField = document.createElement("label");
203
seedField.className = "seed-price-seed";
204
const seedCaption = document.createElement("span");
205
seedCaption.textContent = "Seed";
206
const seedInput = document.createElement("input");
207
seedInput.type = "number";
208
seedInput.min = "1";
209
seedInput.step = "1";
210
seedInput.dataset.seedItemId = String(item.itemId);
211
seedInput.value = String(snap?.seedValue ?? item.definitionSeedValue);
212
seedInput.addEventListener("input", () =>
213
{
214
const itemId = Number(seedInput.dataset.seedItemId);
215
const raw = Math.round(Number(seedInput.value));
216
const defSeed = item.definitionSeedValue;
217
const nextMap = { ...draftSeeds };
218
if (!Number.isFinite(raw) || raw < 1)
219
{
220
refreshDirty();
221
return;
222
}
223
if (raw === defSeed)
224
{ delete nextMap[String(itemId)]; }
225
else
226
{ nextMap[String(itemId)] = raw; }
227
draftSeeds = nextMap;
228
updateSeedRowReadouts(row, item.itemId);
229
refreshDirty();
230
});
231
seedField.append(seedCaption, seedInput);
232
233
const market = document.createElement("div");
234
market.className = "seed-price-readonly";
235
market.dataset.role = "market";
236
237
const shop = document.createElement("div");
238
shop.className = "seed-price-readonly";
239
shop.dataset.role = "shop";
240
241
row.append(name, seedField, market, shop);
242
updateSeedRowReadouts(row, item.itemId, snap);
243
seedPanel.list.append(row);
244
}
245
refreshDirty();
246
}
247
248
function updateSeedRowReadouts (row, itemId, snap = null)
249
{
250
const resolved = snap ?? itemPriceSnapshot(itemId, {
251
settings: currentSettingsPreview(),
252
lastSale: itemLastSales[String(itemId)] ?? itemLastSales[itemId] ?? null
253
});
254
const market = row.querySelector('[data-role="market"]');
255
const shop = row.querySelector('[data-role="shop"]');
256
if (market)
257
{
258
market.innerHTML = resolved?.marketKnown
259
? `<span>Market</span><strong>${formatSettingValue(resolved.marketValue)}</strong>`
260
: `<span>Market</span><strong class="muted">—</strong>`;
261
}
262
if (shop)
263
{
264
shop.innerHTML = resolved
265
? `<span>Shop</span><strong>${formatSettingValue(resolved.shopPrice)}</strong>`
266
: `<span>Shop</span><strong class="muted">—</strong>`;
267
}
268
}
269
61
270
return {
62
271
isOpen: () => open,
63
272
handleMessage (message)
64
273
{
65
274
loaded = true;
66
baseline = { ...message.settings };
275
baseline = {
276
...message.settings,
277
itemSeedValues: normalizeItemSeedValues(message.settings?.itemSeedValues)
278
};
279
itemLastSales = message.itemLastSales && typeof message.itemLastSales === "object"
280
? message.itemLastSales
281
: {};
282
draftSeeds = { ...baseline.itemSeedValues };
67
283
fillForm(form, baseline);
68
refreshDirty(form, baseline, loaded);
284
renderSeedPanel();
285
refreshDirty();
69
286
renderLog(log, message.changelog ?? []);
70
287
onApplied?.(message.settings);
71
288
}
72
289
};
73
290
}
74
291
75
function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput })
292
function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady })
76
293
{
77
294
form.innerHTML = "";
78
295
const tabs = document.createElement("div");
@@ -94,40 +311,57 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput }
94
311
const section = document.createElement("section");
95
312
section.className = "settings-category";
96
313
section.dataset.category = category.id;
97
for (const field of category.fields)
314
315
if (category.panel === "itemSeedPrices")
98
316
{
99
const row = document.createElement("label");
100
row.className = "setting-row";
101
row.dataset.key = field.key;
102
const title = document.createElement("span");
103
title.className = "setting-label";
104
title.textContent = field.label;
105
const input = document.createElement("input");
106
input.id = `setting-${field.key}`;
107
input.dataset.key = field.key;
108
input.type = field.type === "range" ? "range" : "number";
109
if (field.min != null)
110
{ input.min = String(field.min); }
111
if (field.max != null)
112
{ input.max = String(field.max); }
113
if (field.step != null)
114
{ input.step = String(field.step); }
115
const valueLabel = document.createElement("span");
116
valueLabel.className = "setting-value";
117
input.addEventListener("input", () =>
118
{
119
valueLabel.textContent = formatSettingValue(Number(input.value));
120
onFieldInput?.(field);
317
const panel = buildSeedPricePanel({
318
onSearch (query)
319
{ form.dispatchEvent(new CustomEvent("seed-search", { detail: { query } })); },
320
onPrev ()
321
{ form.dispatchEvent(new CustomEvent("seed-page", { detail: { delta: -1 } })); },
322
onNext ()
323
{ form.dispatchEvent(new CustomEvent("seed-page", { detail: { delta: 1 } })); }
121
324
});
122
row.append(title, input, valueLabel);
123
if (field.hint)
325
section.append(panel.root);
326
onSeedPanelReady?.(panel);
327
}
328
else
329
{
330
for (const field of category.fields)
124
331
{
125
const hint = document.createElement("small");
126
hint.className = "hint";
127
hint.textContent = field.hint;
128
row.append(hint);
332
const row = document.createElement("label");
333
row.className = "setting-row";
334
row.dataset.key = field.key;
335
const title = document.createElement("span");
336
title.className = "setting-label";
337
title.textContent = field.label;
338
const input = document.createElement("input");
339
input.id = `setting-${field.key}`;
340
input.dataset.key = field.key;
341
input.type = field.type === "range" ? "range" : "number";
342
if (field.min != null)
343
{ input.min = String(field.min); }
344
if (field.max != null)
345
{ input.max = String(field.max); }
346
if (field.step != null)
347
{ input.step = String(field.step); }
348
const valueLabel = document.createElement("span");
349
valueLabel.className = "setting-value";
350
input.addEventListener("input", () =>
351
{
352
valueLabel.textContent = formatSettingValue(Number(input.value));
353
onFieldInput?.(field);
354
});
355
row.append(title, input, valueLabel);
356
if (field.hint)
357
{
358
const hint = document.createElement("small");
359
hint.className = "hint";
360
hint.textContent = field.hint;
361
row.append(hint);
362
}
363
section.append(row);
129
364
}
130
section.append(row);
131
365
}
132
366
panels.append(section);
133
367
}
@@ -136,6 +370,53 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput }
136
370
syncTabs(form, getActiveCategory());
137
371
}
138
372
373
function buildSeedPricePanel ({ onSearch, onPrev, onNext })
374
{
375
const root = document.createElement("div");
376
root.className = "seed-price-panel";
377
378
const toolbar = document.createElement("div");
379
toolbar.className = "seed-price-toolbar";
380
381
const search = document.createElement("input");
382
search.type = "search";
383
search.className = "seed-price-search";
384
search.placeholder = "Search items…";
385
search.addEventListener("input", () => onSearch(search.value));
386
387
const meta = document.createElement("span");
388
meta.className = "seed-price-meta hint";
389
390
const pager = document.createElement("div");
391
pager.className = "seed-price-pager";
392
const prev = document.createElement("button");
393
prev.type = "button";
394
prev.textContent = "Previous";
395
prev.addEventListener("click", onPrev);
396
const pageLabel = document.createElement("span");
397
const next = document.createElement("button");
398
next.type = "button";
399
next.textContent = "Next";
400
next.addEventListener("click", onNext);
401
pager.append(prev, pageLabel, next);
402
403
toolbar.append(search, meta, pager);
404
405
const header = document.createElement("div");
406
header.className = "seed-price-header";
407
header.innerHTML = "<span>Item</span><span>Seed</span><span>Market</span><span>Shop</span>";
408
409
const list = document.createElement("div");
410
list.className = "seed-price-list";
411
412
const hint = document.createElement("p");
413
hint.className = "hint";
414
hint.textContent = "Seed is the world base price. Market shows the last-sale lerp when known; Shop is the undiscounted catalog price from the current seed.";
415
416
root.append(toolbar, hint, header, list);
417
return { root, search, meta, list, prev, next, pageLabel };
418
}
419
139
420
function syncTabs (form, activeCategory)
140
421
{
141
422
for (const tab of form.querySelectorAll(".settings-tab"))
@@ -156,7 +437,7 @@ function fillForm (form, settings)
156
437
}
157
438
}
158
439
159
function dirtyValues (form, baseline)
440
function scalarDirtyValues (form, baseline)
160
441
{
161
442
const changed = {};
162
443
for (const input of form.querySelectorAll("input[data-key]"))
@@ -170,20 +451,6 @@ function dirtyValues (form, baseline)
170
451
return changed;
171
452
}
172
453
173
function refreshDirty (form, baseline, loaded)
174
{
175
const changed = loaded ? dirtyValues(form, baseline) : {};
176
for (const row of form.querySelectorAll(".setting-row"))
177
{
178
row.classList.toggle("dirty", Object.prototype.hasOwnProperty.call(changed, row.dataset.key));
179
}
180
const save = document.getElementById("settings-save");
181
save.disabled = Object.keys(changed).length === 0;
182
save.textContent = Object.keys(changed).length
183
? `Save ${Object.keys(changed).length} change${Object.keys(changed).length === 1 ? "" : "s"}`
184
: "Save";
185
}
186
187
454
function renderLog (log, changelog)
188
455
{
189
456
log.innerHTML = "";
@@ -219,3 +486,12 @@ function findField (key)
219
486
}
220
487
return { key };
221
488
}
489
490
function escapeHtml (text)
491
{
492
return String(text)
493
.replaceAll("&", "&")
494
.replaceAll("<", "<")
495
.replaceAll(">", ">")
496
.replaceAll("\"", """);
497
}
@@ -1,4 +1,18 @@1
import { WORLD_SETTING_CATEGORIES, coerceSettingValue, formatSettingValue, settingsValuesEqual } from "/shared/definitions/worldSettings.js";1
import {2
WORLD_SETTING_CATEGORIES,3
coerceSettingValue,4
formatSettingValue,5
settingsValuesEqual,6
itemSeedMapsEqual7
} from "/shared/definitions/worldSettings.js";8
import {9
listPricedItems,10
itemPriceSnapshot,11
normalizeItemSeedValues,12
effectiveSeedValue13
} from "/shared/shop/pricing.js";14
15
const SEED_PAGE_SIZE = 20;2
16
3
export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })17
export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })4
{18
{@@ -11,6 +25,13 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi11
let open = false;25
let open = false;12
let loaded = false;26
let loaded = false;13
let activeCategory = WORLD_SETTING_CATEGORIES[0]?.id ?? null;27
let activeCategory = WORLD_SETTING_CATEGORIES[0]?.id ?? null;28
/** @type {Record<string, number>} draft sparse overrides */29
let draftSeeds = {};30
/** @type {Record<string, object>} optional last-sale records from server */31
let itemLastSales = {};32
let seedQuery = "";33
let seedPage = 0;34
let seedPanel = null;14
35
15
buildForm(form, {36
buildForm(form, {16
getActiveCategory: () => activeCategory,37
getActiveCategory: () => activeCategory,@@ -18,22 +39,56 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi18
{39
{19
activeCategory = id;40
activeCategory = id;20
syncTabs(form, activeCategory);41
syncTabs(form, activeCategory);42
if (id === "basePrices")43
{ renderSeedPanel(); }21
},44
},22
onFieldInput (field)45
onFieldInput (field)23
{46
{24
if (field.previewNightHour != null && onPreviewNight)47
if (field.previewNightHour != null && onPreviewNight)25
{ onPreviewNight(field.previewNightHour); }48
{ onPreviewNight(field.previewNightHour); }49
},50
onSeedPanelReady (panel)51
{52
seedPanel = panel;26
}53
}27
});54
});28
form.addEventListener("input", () => refreshDirty(form, baseline, loaded));55
29
form.addEventListener("change", () => refreshDirty(form, baseline, loaded));56
form.addEventListener("seed-search", (event) =>57
{58
seedQuery = event.detail?.query ?? "";59
seedPage = 0;60
renderSeedPanel();61
});62
form.addEventListener("seed-page", (event) =>63
{64
seedPage += event.detail?.delta ?? 0;65
renderSeedPanel();66
});67
form.addEventListener("input", (event) =>68
{69
if (event.target?.dataset?.seedItemId)70
{ return; }71
refreshDirty();72
});73
form.addEventListener("change", (event) =>74
{75
if (event.target?.dataset?.seedItemId)76
{ return; }77
refreshDirty();78
});30
79
31
function show (visible)80
function show (visible)32
{81
{33
if (!visible)82
if (!visible)34
{83
{35
fillForm(form, baseline);84
fillForm(form, baseline);36
refreshDirty(form, baseline, loaded);85
draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };86
seedQuery = "";87
seedPage = 0;88
if (seedPanel?.search)89
{ seedPanel.search.value = ""; }90
renderSeedPanel();91
refreshDirty();37
}92
}38
open = visible;93
open = visible;39
backdrop.hidden = !visible;94
backdrop.hidden = !visible;@@ -52,27 +107,189 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi52
{107
{53
if (!loaded)108
if (!loaded)54
{ return; }109
{ return; }55
const changed = dirtyValues(form, baseline);110
const changed = collectDirty();56
if (Object.keys(changed).length === 0)111
if (Object.keys(changed).length === 0)57
{ return; }112
{ return; }58
socket.send({ type: MessageType.editorSaveSettings, settings: changed });113
socket.send({ type: MessageType.editorSaveSettings, settings: changed });59
});114
});60
115
116
function currentSettingsPreview ()117
{118
return {119
...baseline,120
...scalarDirtyValues(form, baseline),121
itemSeedValues: draftSeeds122
};123
}124
125
function collectDirty ()126
{127
const changed = scalarDirtyValues(form, baseline);128
const nextSeeds = normalizeItemSeedValues(draftSeeds);129
const prevSeeds = normalizeItemSeedValues(baseline.itemSeedValues);130
if (!itemSeedMapsEqual(prevSeeds, nextSeeds))131
{ changed.itemSeedValues = nextSeeds; }132
return changed;133
}134
135
function refreshDirty ()136
{137
const changed = loaded ? collectDirty() : {};138
for (const row of form.querySelectorAll(".setting-row[data-key]"))139
{140
row.classList.toggle("dirty", Object.prototype.hasOwnProperty.call(changed, row.dataset.key));141
}142
for (const row of form.querySelectorAll(".seed-price-row[data-item-id]"))143
{144
const itemId = row.dataset.itemId;145
const baselineSeed = effectiveSeedValue(Number(itemId), baseline);146
const draftSeed = effectiveSeedValue(Number(itemId), { itemSeedValues: draftSeeds });147
row.classList.toggle("dirty", !settingsValuesEqual(baselineSeed, draftSeed));148
}149
const count = Object.keys(changed).length;150
save.disabled = count === 0;151
save.textContent = count152
? `Save ${count} change${count === 1 ? "" : "s"}`153
: "Save";154
}155
156
function filteredSeedItems ()157
{158
const q = seedQuery.trim().toLowerCase();159
const items = listPricedItems();160
if (!q)161
{ return items; }162
return items.filter((item) =>163
item.displayName.toLowerCase().includes(q)164
|| item.key.toLowerCase().includes(q)165
|| String(item.itemId).includes(q)166
);167
}168
169
function renderSeedPanel ()170
{171
if (!seedPanel)172
{ return; }173
const items = filteredSeedItems();174
const pageCount = Math.max(1, Math.ceil(items.length / SEED_PAGE_SIZE) || 1);175
seedPage = Math.max(0, Math.min(seedPage, pageCount - 1));176
const start = seedPage * SEED_PAGE_SIZE;177
const pageItems = items.slice(start, start + SEED_PAGE_SIZE);178
const settingsPreview = currentSettingsPreview();179
180
seedPanel.meta.textContent = items.length181
? `Showing ${start + 1}–${start + pageItems.length} of ${items.length}`182
: "No items match.";183
seedPanel.prev.disabled = seedPage <= 0;184
seedPanel.next.disabled = seedPage >= pageCount - 1 || items.length === 0;185
seedPanel.pageLabel.textContent = `Page ${seedPage + 1} / ${pageCount}`;186
187
seedPanel.list.innerHTML = "";188
for (const item of pageItems)189
{190
const snap = itemPriceSnapshot(item.itemId, {191
settings: settingsPreview,192
lastSale: itemLastSales[String(item.itemId)] ?? itemLastSales[item.itemId] ?? null193
});194
const row = document.createElement("div");195
row.className = "seed-price-row";196
row.dataset.itemId = String(item.itemId);197
198
const name = document.createElement("div");199
name.className = "seed-price-name";200
name.innerHTML = `<strong>${escapeHtml(item.displayName)}</strong><small>#${item.itemId} · ${escapeHtml(item.key)}</small>`;201
202
const seedField = document.createElement("label");203
seedField.className = "seed-price-seed";204
const seedCaption = document.createElement("span");205
seedCaption.textContent = "Seed";206
const seedInput = document.createElement("input");207
seedInput.type = "number";208
seedInput.min = "1";209
seedInput.step = "1";210
seedInput.dataset.seedItemId = String(item.itemId);211
seedInput.value = String(snap?.seedValue ?? item.definitionSeedValue);212
seedInput.addEventListener("input", () =>213
{214
const itemId = Number(seedInput.dataset.seedItemId);215
const raw = Math.round(Number(seedInput.value));216
const defSeed = item.definitionSeedValue;217
const nextMap = { ...draftSeeds };218
if (!Number.isFinite(raw) || raw < 1)219
{220
refreshDirty();221
return;222
}223
if (raw === defSeed)224
{ delete nextMap[String(itemId)]; }225
else226
{ nextMap[String(itemId)] = raw; }227
draftSeeds = nextMap;228
updateSeedRowReadouts(row, item.itemId);229
refreshDirty();230
});231
seedField.append(seedCaption, seedInput);232
233
const market = document.createElement("div");234
market.className = "seed-price-readonly";235
market.dataset.role = "market";236
237
const shop = document.createElement("div");238
shop.className = "seed-price-readonly";239
shop.dataset.role = "shop";240
241
row.append(name, seedField, market, shop);242
updateSeedRowReadouts(row, item.itemId, snap);243
seedPanel.list.append(row);244
}245
refreshDirty();246
}247
248
function updateSeedRowReadouts (row, itemId, snap = null)249
{250
const resolved = snap ?? itemPriceSnapshot(itemId, {251
settings: currentSettingsPreview(),252
lastSale: itemLastSales[String(itemId)] ?? itemLastSales[itemId] ?? null253
});254
const market = row.querySelector('[data-role="market"]');255
const shop = row.querySelector('[data-role="shop"]');256
if (market)257
{258
market.innerHTML = resolved?.marketKnown259
? `<span>Market</span><strong>${formatSettingValue(resolved.marketValue)}</strong>`260
: `<span>Market</span><strong class="muted">—</strong>`;261
}262
if (shop)263
{264
shop.innerHTML = resolved265
? `<span>Shop</span><strong>${formatSettingValue(resolved.shopPrice)}</strong>`266
: `<span>Shop</span><strong class="muted">—</strong>`;267
}268
}269
61
return {270
return {62
isOpen: () => open,271
isOpen: () => open,63
handleMessage (message)272
handleMessage (message)64
{273
{65
loaded = true;274
loaded = true;66
baseline = { ...message.settings };275
baseline = {276
...message.settings,277
itemSeedValues: normalizeItemSeedValues(message.settings?.itemSeedValues)278
};279
itemLastSales = message.itemLastSales && typeof message.itemLastSales === "object"280
? message.itemLastSales281
: {};282
draftSeeds = { ...baseline.itemSeedValues };67
fillForm(form, baseline);283
fillForm(form, baseline);68
refreshDirty(form, baseline, loaded);284
renderSeedPanel();285
refreshDirty();69
renderLog(log, message.changelog ?? []);286
renderLog(log, message.changelog ?? []);70
onApplied?.(message.settings);287
onApplied?.(message.settings);71
}288
}72
};289
};73
}290
}74
291
75
function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput })292
function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady })76
{293
{77
form.innerHTML = "";294
form.innerHTML = "";78
const tabs = document.createElement("div");295
const tabs = document.createElement("div");@@ -94,40 +311,57 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput }94
const section = document.createElement("section");311
const section = document.createElement("section");95
section.className = "settings-category";312
section.className = "settings-category";96
section.dataset.category = category.id;313
section.dataset.category = category.id;97
for (const field of category.fields)314
315
if (category.panel === "itemSeedPrices")98
{316
{99
const row = document.createElement("label");317
const panel = buildSeedPricePanel({100
row.className = "setting-row";318
onSearch (query)101
row.dataset.key = field.key;319
{ form.dispatchEvent(new CustomEvent("seed-search", { detail: { query } })); },102
const title = document.createElement("span");320
onPrev ()103
title.className = "setting-label";321
{ form.dispatchEvent(new CustomEvent("seed-page", { detail: { delta: -1 } })); },104
title.textContent = field.label;322
onNext ()105
const input = document.createElement("input");323
{ form.dispatchEvent(new CustomEvent("seed-page", { detail: { delta: 1 } })); }106
input.id = `setting-${field.key}`;107
input.dataset.key = field.key;108
input.type = field.type === "range" ? "range" : "number";109
if (field.min != null)110
{ input.min = String(field.min); }111
if (field.max != null)112
{ input.max = String(field.max); }113
if (field.step != null)114
{ input.step = String(field.step); }115
const valueLabel = document.createElement("span");116
valueLabel.className = "setting-value";117
input.addEventListener("input", () =>118
{119
valueLabel.textContent = formatSettingValue(Number(input.value));120
onFieldInput?.(field);121
});324
});122
row.append(title, input, valueLabel);325
section.append(panel.root);123
if (field.hint)326
onSeedPanelReady?.(panel);327
}328
else329
{330
for (const field of category.fields)124
{331
{125
const hint = document.createElement("small");332
const row = document.createElement("label");126
hint.className = "hint";333
row.className = "setting-row";127
hint.textContent = field.hint;334
row.dataset.key = field.key;128
row.append(hint);335
const title = document.createElement("span");336
title.className = "setting-label";337
title.textContent = field.label;338
const input = document.createElement("input");339
input.id = `setting-${field.key}`;340
input.dataset.key = field.key;341
input.type = field.type === "range" ? "range" : "number";342
if (field.min != null)343
{ input.min = String(field.min); }344
if (field.max != null)345
{ input.max = String(field.max); }346
if (field.step != null)347
{ input.step = String(field.step); }348
const valueLabel = document.createElement("span");349
valueLabel.className = "setting-value";350
input.addEventListener("input", () =>351
{352
valueLabel.textContent = formatSettingValue(Number(input.value));353
onFieldInput?.(field);354
});355
row.append(title, input, valueLabel);356
if (field.hint)357
{358
const hint = document.createElement("small");359
hint.className = "hint";360
hint.textContent = field.hint;361
row.append(hint);362
}363
section.append(row);129
}364
}130
section.append(row);131
}365
}132
panels.append(section);366
panels.append(section);133
}367
}@@ -136,6 +370,53 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput }136
syncTabs(form, getActiveCategory());370
syncTabs(form, getActiveCategory());137
}371
}138
372
373
function buildSeedPricePanel ({ onSearch, onPrev, onNext })374
{375
const root = document.createElement("div");376
root.className = "seed-price-panel";377
378
const toolbar = document.createElement("div");379
toolbar.className = "seed-price-toolbar";380
381
const search = document.createElement("input");382
search.type = "search";383
search.className = "seed-price-search";384
search.placeholder = "Search items…";385
search.addEventListener("input", () => onSearch(search.value));386
387
const meta = document.createElement("span");388
meta.className = "seed-price-meta hint";389
390
const pager = document.createElement("div");391
pager.className = "seed-price-pager";392
const prev = document.createElement("button");393
prev.type = "button";394
prev.textContent = "Previous";395
prev.addEventListener("click", onPrev);396
const pageLabel = document.createElement("span");397
const next = document.createElement("button");398
next.type = "button";399
next.textContent = "Next";400
next.addEventListener("click", onNext);401
pager.append(prev, pageLabel, next);402
403
toolbar.append(search, meta, pager);404
405
const header = document.createElement("div");406
header.className = "seed-price-header";407
header.innerHTML = "<span>Item</span><span>Seed</span><span>Market</span><span>Shop</span>";408
409
const list = document.createElement("div");410
list.className = "seed-price-list";411
412
const hint = document.createElement("p");413
hint.className = "hint";414
hint.textContent = "Seed is the world base price. Market shows the last-sale lerp when known; Shop is the undiscounted catalog price from the current seed.";415
416
root.append(toolbar, hint, header, list);417
return { root, search, meta, list, prev, next, pageLabel };418
}419
139
function syncTabs (form, activeCategory)420
function syncTabs (form, activeCategory)140
{421
{141
for (const tab of form.querySelectorAll(".settings-tab"))422
for (const tab of form.querySelectorAll(".settings-tab"))@@ -156,7 +437,7 @@ function fillForm (form, settings)156
}437
}157
}438
}158
439
159
function dirtyValues (form, baseline)440
function scalarDirtyValues (form, baseline)160
{441
{161
const changed = {};442
const changed = {};162
for (const input of form.querySelectorAll("input[data-key]"))443
for (const input of form.querySelectorAll("input[data-key]"))@@ -170,20 +451,6 @@ function dirtyValues (form, baseline)170
return changed;451
return changed;171
}452
}172
453
173
function refreshDirty (form, baseline, loaded)174
{175
const changed = loaded ? dirtyValues(form, baseline) : {};176
for (const row of form.querySelectorAll(".setting-row"))177
{178
row.classList.toggle("dirty", Object.prototype.hasOwnProperty.call(changed, row.dataset.key));179
}180
const save = document.getElementById("settings-save");181
save.disabled = Object.keys(changed).length === 0;182
save.textContent = Object.keys(changed).length183
? `Save ${Object.keys(changed).length} change${Object.keys(changed).length === 1 ? "" : "s"}`184
: "Save";185
}186
187
function renderLog (log, changelog)454
function renderLog (log, changelog)188
{455
{189
log.innerHTML = "";456
log.innerHTML = "";@@ -219,3 +486,12 @@ function findField (key)219
}486
}220
return { key };487
return { key };221
}488
}489
490
function escapeHtml (text)491
{492
return String(text)493
.replaceAll("&", "&")494
.replaceAll("<", "<")495
.replaceAll(">", ">")496
.replaceAll("\"", """);497
}@@ -9,16 +9,7 @@ import {
9
9
} from "/shared/definitions/mobs.js";
10
10
import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
11
11
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
12
13
const SHOP_STOCK_PRESETS = Object.freeze([
14
{ itemId: ItemId.copperOre, label: "Copper ore" },
15
{ itemId: ItemId.tinOre, label: "Tin ore" },
16
{ itemId: ItemId.coal, label: "Coal" },
17
{ itemId: ItemId.ironOre, label: "Iron ore" },
18
{ itemId: ItemId.pineLog, label: "Pine log" },
19
{ itemId: ItemId.birchLog, label: "Birch log" },
20
{ itemId: ItemId.oakLog, label: "Oak log" }
21
]);
12
import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
22
13
23
14
const EQUIP_PRESETS = Object.freeze([
24
15
{ itemId: ItemId.clothShirt, slot: EQUIPMENT_SLOT.chest },
@@ -34,8 +25,14 @@ export function initTileConfigModal ({ onSave, onRemove })
34
25
const modal = document.getElementById("tile-config-modal");
35
26
const form = document.getElementById("tile-config-form");
36
27
const title = document.getElementById("tile-config-title");
28
const itemSearchBackdrop = document.getElementById("shop-item-search-backdrop");
29
const itemSearchModal = document.getElementById("shop-item-search-modal");
30
const itemSearchInput = document.getElementById("shop-item-search-input");
31
const itemSearchResults = document.getElementById("shop-item-search-results");
37
32
let open = false;
38
33
let context = null;
34
/** @type {{ itemId: number, quantity: number }[]} */
35
let sellsDraft = [];
39
36
40
37
function show (visible)
41
38
{
@@ -43,7 +40,111 @@ export function initTileConfigModal ({ onSave, onRemove })
43
40
backdrop.hidden = !visible;
44
41
modal.hidden = !visible;
45
42
if (!visible)
46
{ context = null; }
43
{
44
context = null;
45
closeItemSearch();
46
}
47
}
48
49
function closeItemSearch ()
50
{
51
if (itemSearchBackdrop)
52
{ itemSearchBackdrop.hidden = true; }
53
if (itemSearchModal)
54
{ itemSearchModal.hidden = true; }
55
}
56
57
function openItemSearch ()
58
{
59
if (!itemSearchBackdrop || !itemSearchModal || !itemSearchInput)
60
{ return; }
61
itemSearchInput.value = "";
62
renderItemSearchResults("");
63
itemSearchBackdrop.hidden = false;
64
itemSearchModal.hidden = false;
65
itemSearchInput.focus();
66
}
67
68
function renderItemSearchResults (query)
69
{
70
if (!itemSearchResults)
71
{ return; }
72
itemSearchResults.innerHTML = "";
73
const q = String(query ?? "").trim().toLowerCase();
74
const taken = new Set(sellsDraft.map((line) => line.itemId));
75
const matches = listNpcShopSellableItems().filter((item) =>
76
{
77
if (taken.has(item.itemId))
78
{ return false; }
79
if (!q)
80
{ return true; }
81
return item.displayName.toLowerCase().includes(q) || item.key.toLowerCase().includes(q);
82
}).slice(0, 80);
83
if (!matches.length)
84
{
85
itemSearchResults.textContent = "No matching items.";
86
return;
87
}
88
for (const item of matches)
89
{
90
const row = document.createElement("button");
91
row.type = "button";
92
row.className = "shop-item-search-row";
93
row.textContent = item.displayName;
94
row.addEventListener("click", () =>
95
{
96
sellsDraft.push({ itemId: item.itemId, quantity: 0 });
97
renderSellsList();
98
closeItemSearch();
99
});
100
itemSearchResults.append(row);
101
}
102
}
103
104
function renderSellsList ()
105
{
106
const list = form.querySelector("[data-sells-list]");
107
if (!list)
108
{ return; }
109
list.innerHTML = "";
110
if (!sellsDraft.length)
111
{
112
const empty = document.createElement("p");
113
empty.className = "hint";
114
empty.textContent = "No items yet. Use + to add stock.";
115
list.append(empty);
116
return;
117
}
118
for (let index = 0; index < sellsDraft.length; index++)
119
{
120
const line = sellsDraft[index];
121
const def = itemDefinition(line.itemId);
122
const row = document.createElement("div");
123
row.className = "spawner-sells-row";
124
const name = document.createElement("span");
125
name.className = "spawner-sells-name";
126
name.textContent = def?.displayName ?? `Item ${line.itemId}`;
127
const qty = document.createElement("input");
128
qty.type = "number";
129
qty.min = "0";
130
qty.step = "1";
131
qty.value = String(line.quantity | 0);
132
qty.title = "0 = infinite; otherwise restocks this many at 00:00 UTC";
133
qty.addEventListener("input", () =>
134
{
135
sellsDraft[index].quantity = Math.max(0, Number(qty.value) || 0) | 0;
136
});
137
const remove = document.createElement("button");
138
remove.type = "button";
139
remove.textContent = "Remove";
140
remove.addEventListener("click", () =>
141
{
142
sellsDraft.splice(index, 1);
143
renderSellsList();
144
});
145
row.append(name, qty, remove);
146
list.append(row);
147
}
47
148
}
48
149
49
150
function renderHumanoidFields (config)
@@ -63,24 +164,46 @@ export function initTileConfigModal ({ onSave, onRemove })
63
164
));
64
165
}
65
166
wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
66
const stockLabel = document.createElement("div");
67
stockLabel.textContent = "Sells";
68
stockLabel.style.marginTop = "0.5rem";
69
wrap.append(stockLabel);
70
for (const preset of SHOP_STOCK_PRESETS)
167
168
const sellsHeader = document.createElement("div");
169
sellsHeader.className = "spawner-sells-header";
170
const sellsTitle = document.createElement("strong");
171
sellsTitle.textContent = "Sells";
172
const addBtn = document.createElement("button");
173
addBtn.type = "button";
174
addBtn.textContent = "+";
175
addBtn.title = "Add item";
176
addBtn.addEventListener("click", () => openItemSearch());
177
sellsHeader.append(sellsTitle, addBtn);
178
wrap.append(sellsHeader);
179
180
const list = document.createElement("div");
181
list.className = "spawner-sells-list";
182
list.dataset.sellsList = "1";
183
wrap.append(list);
184
185
const buysLabel = document.createElement("label");
186
buysLabel.className = "spawner-buys-row";
187
const buys = document.createElement("input");
188
buys.type = "checkbox";
189
buys.name = "buysItems";
190
buys.checked = !!config.buysItems;
191
buysLabel.append(buys, document.createTextNode(" Buys items"));
192
wrap.append(buysLabel);
193
194
const hint = document.createElement("p");
195
hint.className = "hint";
196
hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 UTC. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock.";
197
wrap.append(hint);
198
199
sellsDraft = (config.sells ?? []).map((line) =>
71
200
{
72
const row = document.createElement("label");
73
row.style.display = "flex";
74
row.style.gap = "0.4rem";
75
row.style.alignItems = "center";
76
const box = document.createElement("input");
77
box.type = "checkbox";
78
box.name = "sells";
79
box.value = String(preset.itemId);
80
box.checked = (config.sells ?? []).includes(preset.itemId);
81
row.append(box, document.createTextNode(preset.label));
82
wrap.append(row);
83
}
201
if (line && typeof line === "object")
202
{ return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
203
return { itemId: line | 0, quantity: 0 };
204
}).filter((line) => line.itemId > 0);
205
206
queueMicrotask(() => renderSellsList());
84
207
return wrap;
85
208
}
86
209
@@ -89,7 +212,10 @@ export function initTileConfigModal ({ onSave, onRemove })
89
212
form.querySelector("[data-humanoid]")?.remove();
90
213
const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value;
91
214
if (!isHumanoidMob(mobTypeId))
92
{ return; }
215
{
216
sellsDraft = [];
217
return;
218
}
93
219
form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
94
220
mobTypeId: MobId.humanoid
95
221
}, "spawner")));
@@ -137,12 +263,15 @@ export function initTileConfigModal ({ onSave, onRemove })
137
263
document.getElementById("tile-config-close").addEventListener("click", () => show(false));
138
264
document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
139
265
backdrop.addEventListener("click", () => show(false));
266
document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
267
itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
268
itemSearchInput?.addEventListener("input", () => renderItemSearchResults(itemSearchInput.value));
269
140
270
document.getElementById("tile-config-save").addEventListener("click", () =>
141
271
{
142
272
if (!context)
143
273
{ return; }
144
274
const data = new FormData(form);
145
const sells = data.getAll("sells").map((value) => Number(value)).filter((id) => id > 0);
146
275
const equipment = {};
147
276
for (const slot of EQUIPMENT_SLOTS)
148
277
{
@@ -158,7 +287,8 @@ export function initTileConfigModal ({ onSave, onRemove })
158
287
sex: String(data.get("sex") || "male"),
159
288
displayName: String(data.get("displayName") || ""),
160
289
equipment,
161
sells,
290
sells: sellsDraft,
291
buysItems: data.get("buysItems") === "on",
162
292
hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9)
163
293
}, context.config.spawnerId));
164
294
show(false);
@@ -9,16 +9,7 @@ import {9
} from "/shared/definitions/mobs.js";9
} from "/shared/definitions/mobs.js";10
import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";10
import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";11
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";11
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";12
12
import { listNpcShopSellableItems } from "/shared/shop/pricing.js";13
const SHOP_STOCK_PRESETS = Object.freeze([14
{ itemId: ItemId.copperOre, label: "Copper ore" },15
{ itemId: ItemId.tinOre, label: "Tin ore" },16
{ itemId: ItemId.coal, label: "Coal" },17
{ itemId: ItemId.ironOre, label: "Iron ore" },18
{ itemId: ItemId.pineLog, label: "Pine log" },19
{ itemId: ItemId.birchLog, label: "Birch log" },20
{ itemId: ItemId.oakLog, label: "Oak log" }21
]);22
13
23
const EQUIP_PRESETS = Object.freeze([14
const EQUIP_PRESETS = Object.freeze([24
{ itemId: ItemId.clothShirt, slot: EQUIPMENT_SLOT.chest },15
{ itemId: ItemId.clothShirt, slot: EQUIPMENT_SLOT.chest },@@ -34,8 +25,14 @@ export function initTileConfigModal ({ onSave, onRemove })34
const modal = document.getElementById("tile-config-modal");25
const modal = document.getElementById("tile-config-modal");35
const form = document.getElementById("tile-config-form");26
const form = document.getElementById("tile-config-form");36
const title = document.getElementById("tile-config-title");27
const title = document.getElementById("tile-config-title");28
const itemSearchBackdrop = document.getElementById("shop-item-search-backdrop");29
const itemSearchModal = document.getElementById("shop-item-search-modal");30
const itemSearchInput = document.getElementById("shop-item-search-input");31
const itemSearchResults = document.getElementById("shop-item-search-results");37
let open = false;32
let open = false;38
let context = null;33
let context = null;34
/** @type {{ itemId: number, quantity: number }[]} */35
let sellsDraft = [];39
36
40
function show (visible)37
function show (visible)41
{38
{@@ -43,7 +40,111 @@ export function initTileConfigModal ({ onSave, onRemove })43
backdrop.hidden = !visible;40
backdrop.hidden = !visible;44
modal.hidden = !visible;41
modal.hidden = !visible;45
if (!visible)42
if (!visible)46
{ context = null; }43
{44
context = null;45
closeItemSearch();46
}47
}48
49
function closeItemSearch ()50
{51
if (itemSearchBackdrop)52
{ itemSearchBackdrop.hidden = true; }53
if (itemSearchModal)54
{ itemSearchModal.hidden = true; }55
}56
57
function openItemSearch ()58
{59
if (!itemSearchBackdrop || !itemSearchModal || !itemSearchInput)60
{ return; }61
itemSearchInput.value = "";62
renderItemSearchResults("");63
itemSearchBackdrop.hidden = false;64
itemSearchModal.hidden = false;65
itemSearchInput.focus();66
}67
68
function renderItemSearchResults (query)69
{70
if (!itemSearchResults)71
{ return; }72
itemSearchResults.innerHTML = "";73
const q = String(query ?? "").trim().toLowerCase();74
const taken = new Set(sellsDraft.map((line) => line.itemId));75
const matches = listNpcShopSellableItems().filter((item) =>76
{77
if (taken.has(item.itemId))78
{ return false; }79
if (!q)80
{ return true; }81
return item.displayName.toLowerCase().includes(q) || item.key.toLowerCase().includes(q);82
}).slice(0, 80);83
if (!matches.length)84
{85
itemSearchResults.textContent = "No matching items.";86
return;87
}88
for (const item of matches)89
{90
const row = document.createElement("button");91
row.type = "button";92
row.className = "shop-item-search-row";93
row.textContent = item.displayName;94
row.addEventListener("click", () =>95
{96
sellsDraft.push({ itemId: item.itemId, quantity: 0 });97
renderSellsList();98
closeItemSearch();99
});100
itemSearchResults.append(row);101
}102
}103
104
function renderSellsList ()105
{106
const list = form.querySelector("[data-sells-list]");107
if (!list)108
{ return; }109
list.innerHTML = "";110
if (!sellsDraft.length)111
{112
const empty = document.createElement("p");113
empty.className = "hint";114
empty.textContent = "No items yet. Use + to add stock.";115
list.append(empty);116
return;117
}118
for (let index = 0; index < sellsDraft.length; index++)119
{120
const line = sellsDraft[index];121
const def = itemDefinition(line.itemId);122
const row = document.createElement("div");123
row.className = "spawner-sells-row";124
const name = document.createElement("span");125
name.className = "spawner-sells-name";126
name.textContent = def?.displayName ?? `Item ${line.itemId}`;127
const qty = document.createElement("input");128
qty.type = "number";129
qty.min = "0";130
qty.step = "1";131
qty.value = String(line.quantity | 0);132
qty.title = "0 = infinite; otherwise restocks this many at 00:00 UTC";133
qty.addEventListener("input", () =>134
{135
sellsDraft[index].quantity = Math.max(0, Number(qty.value) || 0) | 0;136
});137
const remove = document.createElement("button");138
remove.type = "button";139
remove.textContent = "Remove";140
remove.addEventListener("click", () =>141
{142
sellsDraft.splice(index, 1);143
renderSellsList();144
});145
row.append(name, qty, remove);146
list.append(row);147
}47
}148
}48
149
49
function renderHumanoidFields (config)150
function renderHumanoidFields (config)@@ -63,24 +164,46 @@ export function initTileConfigModal ({ onSave, onRemove })63
));164
));64
}165
}65
wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));166
wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));66
const stockLabel = document.createElement("div");167
67
stockLabel.textContent = "Sells";168
const sellsHeader = document.createElement("div");68
stockLabel.style.marginTop = "0.5rem";169
sellsHeader.className = "spawner-sells-header";69
wrap.append(stockLabel);170
const sellsTitle = document.createElement("strong");70
for (const preset of SHOP_STOCK_PRESETS)171
sellsTitle.textContent = "Sells";172
const addBtn = document.createElement("button");173
addBtn.type = "button";174
addBtn.textContent = "+";175
addBtn.title = "Add item";176
addBtn.addEventListener("click", () => openItemSearch());177
sellsHeader.append(sellsTitle, addBtn);178
wrap.append(sellsHeader);179
180
const list = document.createElement("div");181
list.className = "spawner-sells-list";182
list.dataset.sellsList = "1";183
wrap.append(list);184
185
const buysLabel = document.createElement("label");186
buysLabel.className = "spawner-buys-row";187
const buys = document.createElement("input");188
buys.type = "checkbox";189
buys.name = "buysItems";190
buys.checked = !!config.buysItems;191
buysLabel.append(buys, document.createTextNode(" Buys items"));192
wrap.append(buysLabel);193
194
const hint = document.createElement("p");195
hint.className = "hint";196
hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 UTC. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock.";197
wrap.append(hint);198
199
sellsDraft = (config.sells ?? []).map((line) =>71
{200
{72
const row = document.createElement("label");201
if (line && typeof line === "object")73
row.style.display = "flex";202
{ return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }74
row.style.gap = "0.4rem";203
return { itemId: line | 0, quantity: 0 };75
row.style.alignItems = "center";204
}).filter((line) => line.itemId > 0);76
const box = document.createElement("input");205
77
box.type = "checkbox";206
queueMicrotask(() => renderSellsList());78
box.name = "sells";79
box.value = String(preset.itemId);80
box.checked = (config.sells ?? []).includes(preset.itemId);81
row.append(box, document.createTextNode(preset.label));82
wrap.append(row);83
}84
return wrap;207
return wrap;85
}208
}86
209
@@ -89,7 +212,10 @@ export function initTileConfigModal ({ onSave, onRemove })89
form.querySelector("[data-humanoid]")?.remove();212
form.querySelector("[data-humanoid]")?.remove();90
const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value;213
const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value;91
if (!isHumanoidMob(mobTypeId))214
if (!isHumanoidMob(mobTypeId))92
{ return; }215
{216
sellsDraft = [];217
return;218
}93
form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({219
form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({94
mobTypeId: MobId.humanoid220
mobTypeId: MobId.humanoid95
}, "spawner")));221
}, "spawner")));@@ -137,12 +263,15 @@ export function initTileConfigModal ({ onSave, onRemove })137
document.getElementById("tile-config-close").addEventListener("click", () => show(false));263
document.getElementById("tile-config-close").addEventListener("click", () => show(false));138
document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));264
document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));139
backdrop.addEventListener("click", () => show(false));265
backdrop.addEventListener("click", () => show(false));266
document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());267
itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());268
itemSearchInput?.addEventListener("input", () => renderItemSearchResults(itemSearchInput.value));269
140
document.getElementById("tile-config-save").addEventListener("click", () =>270
document.getElementById("tile-config-save").addEventListener("click", () =>141
{271
{142
if (!context)272
if (!context)143
{ return; }273
{ return; }144
const data = new FormData(form);274
const data = new FormData(form);145
const sells = data.getAll("sells").map((value) => Number(value)).filter((id) => id > 0);146
const equipment = {};275
const equipment = {};147
for (const slot of EQUIPMENT_SLOTS)276
for (const slot of EQUIPMENT_SLOTS)148
{277
{@@ -158,7 +287,8 @@ export function initTileConfigModal ({ onSave, onRemove })158
sex: String(data.get("sex") || "male"),287
sex: String(data.get("sex") || "male"),159
displayName: String(data.get("displayName") || ""),288
displayName: String(data.get("displayName") || ""),160
equipment,289
equipment,161
sells,290
sells: sellsDraft,291
buysItems: data.get("buysItems") === "on",162
hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9)292
hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9)163
}, context.config.spawnerId));293
}, context.config.spawnerId));164
show(false);294
show(false);@@ -1,10 +1,15 @@
1
export function initContextMenu ({ root = document.body } = {})
1
export function initContextMenu ({ root = document.body, onSuppressWorldClick } = {})
2
2
{
3
3
const menu = document.createElement("div");
4
4
menu.id = "context-menu";
5
5
menu.hidden = true;
6
6
root.append(menu);
7
7
8
function suppressWorldClick ()
9
{
10
onSuppressWorldClick?.();
11
}
12
8
13
function hide ()
9
14
{
10
15
menu.hidden = true;
@@ -31,10 +36,18 @@ export function initContextMenu ({ root = document.body } = {})
31
36
const button = document.createElement("button");
32
37
button.type = "button";
33
38
button.textContent = item.label;
39
button.addEventListener("mousedown", (event) =>
40
{
41
// Consume before the menu closes so the held button does not become a world LMB.
42
event.preventDefault();
43
event.stopPropagation();
44
suppressWorldClick();
45
});
34
46
button.addEventListener("click", (event) =>
35
47
{
36
48
event.preventDefault();
37
49
event.stopPropagation();
50
suppressWorldClick();
38
51
hide();
39
52
item.onSelect?.();
40
53
});
@@ -1,10 +1,15 @@1
export function initContextMenu ({ root = document.body } = {})1
export function initContextMenu ({ root = document.body, onSuppressWorldClick } = {})2
{2
{3
const menu = document.createElement("div");3
const menu = document.createElement("div");4
menu.id = "context-menu";4
menu.id = "context-menu";5
menu.hidden = true;5
menu.hidden = true;6
root.append(menu);6
root.append(menu);7
7
8
function suppressWorldClick ()9
{10
onSuppressWorldClick?.();11
}12
8
function hide ()13
function hide ()9
{14
{10
menu.hidden = true;15
menu.hidden = true;@@ -31,10 +36,18 @@ export function initContextMenu ({ root = document.body } = {})31
const button = document.createElement("button");36
const button = document.createElement("button");32
button.type = "button";37
button.type = "button";33
button.textContent = item.label;38
button.textContent = item.label;39
button.addEventListener("mousedown", (event) =>40
{41
// Consume before the menu closes so the held button does not become a world LMB.42
event.preventDefault();43
event.stopPropagation();44
suppressWorldClick();45
});34
button.addEventListener("click", (event) =>46
button.addEventListener("click", (event) =>35
{47
{36
event.preventDefault();48
event.preventDefault();37
event.stopPropagation();49
event.stopPropagation();50
suppressWorldClick();38
hide();51
hide();39
item.onSelect?.();52
item.onSelect?.();40
});53
});@@ -1,5 +1,5 @@
1
1
import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2
import { BlockType } from "/shared/definitions/tiles.js";
2
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName } from "/shared/definitions/tiles.js";
3
3
import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4
4
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
5
5
import { WorldView } from "../render/worldView.js";
@@ -26,6 +26,7 @@ const overlay = document.getElementById("overlay");
26
26
const statusEl = document.getElementById("status");
27
27
const characterList = document.getElementById("character-list");
28
28
const errorEl = document.getElementById("error");
29
const worldTooltip = document.getElementById("world-tooltip");
29
30
30
31
let socket;
31
32
let session = null;
@@ -48,9 +49,16 @@ let shop;
48
49
let pendingPickup = null;
49
50
/** @type {{ kind: "bank" | "cauldron" | "station" | "mine", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
50
51
let pendingInteract = null;
52
/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
53
let approachMove = null;
51
54
/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
52
55
let leftClickConsumed = false;
53
56
57
function consumeWorldClick ()
58
{
59
leftClickConsumed = true;
60
}
61
54
62
function showError (message)
55
63
{
56
64
errorEl.textContent = message ?? "";
@@ -88,7 +96,8 @@ function renderCharacters (characters)
88
96
function uiBlocked ()
89
97
{
90
98
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
91
|| crafting?.isBlocking() || alchemy?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
99
|| crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
100
|| contextMenu?.isOpen() || death?.isBlocking());
92
101
}
93
102
94
103
function clearPendingPickup ()
@@ -99,6 +108,7 @@ function clearPendingPickup ()
99
108
function clearPendingInteract ()
100
109
{
101
110
pendingInteract = null;
111
approachMove = null;
102
112
}
103
113
104
114
function clearAllPendingActions ()
@@ -111,9 +121,14 @@ function approachAdjacentTile (tileX, tileY)
111
121
{
112
122
const local = view.entities.get(view.localEntityId);
113
123
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
114
{ return true; }
115
let best = null;
116
let bestDist = Infinity;
124
{
125
approachMove = null;
126
return true;
127
}
128
let bestWalkable = null;
129
let bestWalkableDist = Infinity;
130
let bestAny = null;
131
let bestAnyDist = Infinity;
117
132
for (let dy = -1; dy <= 1; dy++)
118
133
{
119
134
for (let dx = -1; dx <= 1; dx++)
@@ -125,15 +140,36 @@ function approachAdjacentTile (tileX, tileY)
125
140
const dist = local
126
141
? chebyshev(local.tileX, local.tileY, destX, destY)
127
142
: 0;
128
if (dist < bestDist)
143
if (dist < bestAnyDist)
144
{
145
bestAnyDist = dist;
146
bestAny = { tileX: destX, tileY: destY };
147
}
148
if (isClientApproachable(destX, destY) && dist < bestWalkableDist)
129
149
{
130
bestDist = dist;
131
best = { tileX: destX, tileY: destY };
150
bestWalkableDist = dist;
151
bestWalkable = { tileX: destX, tileY: destY };
132
152
}
133
153
}
134
154
}
135
if (best)
136
{ socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); }
155
const best = bestWalkable ?? bestAny;
156
if (!best)
157
{ return false; }
158
if (
159
approachMove
160
&& approachMove.focusX === tileX
161
&& approachMove.focusY === tileY
162
&& approachMove.destX === best.tileX
163
&& approachMove.destY === best.tileY
164
)
165
{ return false; }
166
approachMove = {
167
focusX: tileX,
168
focusY: tileY,
169
destX: best.tileX,
170
destY: best.tileY
171
};
172
socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY });
137
173
return false;
138
174
}
139
175
@@ -188,9 +224,9 @@ function requestMine (tileX, tileY)
188
224
189
225
function requestTalk (targetEntityId)
190
226
{
191
clearPendingPickup();
227
clearAllPendingActions();
192
228
pendingInteract = { kind: "talk", targetEntityId };
193
const target = view.entities.get(targetEntityId);
229
const target = view?.entities.get(targetEntityId);
194
230
if (!target)
195
231
{
196
232
clearPendingInteract();
@@ -367,6 +403,8 @@ function handleLeftClick (mouseX, mouseY)
367
403
{ requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
368
404
else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
369
405
{ requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
406
else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
407
{ requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
370
408
else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
371
409
{ requestMine(tile.tileX, tile.tileY); }
372
410
else
@@ -408,10 +446,17 @@ function handleRightClick (event, mouseX, mouseY)
408
446
});
409
447
if (entity.untargetable)
410
448
{ continue; }
411
if (entity.talkable)
449
if (entity.hasShop)
450
{
451
items.push({
452
label: `Shop ${targetName}`,
453
onSelect: () => requestTalk(entity.entityId)
454
});
455
}
456
else if (entity.talkable)
412
457
{
413
458
items.push({
414
label: `Trade with ${targetName}`,
459
label: `Talk to ${targetName}`,
415
460
onSelect: () => requestTalk(entity.entityId)
416
461
});
417
462
}
@@ -485,6 +530,14 @@ function handleRightClick (event, mouseX, mouseY)
485
530
});
486
531
}
487
532
533
if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
534
{
535
items.push({
536
label: "Craft",
537
onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY)
538
});
539
}
540
488
541
if (isOreBoulderTile(view, tile.tileX, tile.tileY))
489
542
{
490
543
items.push({
@@ -566,7 +619,10 @@ function startPlay (payload)
566
619
flushPendingInteract();
567
620
social?.updateNametag(view, scene, view.localEntityId);
568
621
chat?.update(view, scene);
622
updateWorldTooltip();
569
623
}
624
else
625
{ hideWorldTooltip(); }
570
626
view.update(dt);
571
627
};
572
628
scene.addObject(ticker);
@@ -617,7 +673,7 @@ async function main ()
617
673
socket: { send (payload) { socket.send(payload); } },
618
674
MessageType
619
675
});
620
contextMenu = initContextMenu();
676
contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
621
677
inventory = initInventory({
622
678
socket: { send (payload) { socket.send(payload); } },
623
679
MessageType,
@@ -662,9 +718,14 @@ async function main ()
662
718
shop = initShop({
663
719
socket: { send (payload) { socket.send(payload); } },
664
720
MessageType,
721
onSuppressWorldClick: consumeWorldClick,
665
722
getCoinCount ()
666
723
{
667
724
return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
725
},
726
getInventorySlots ()
727
{
728
return inventory?.getInventorySlots?.() ?? [];
668
729
}
669
730
});
670
731
chat = initChat({
@@ -801,6 +862,9 @@ async function main ()
801
862
case MessageType.shopOpen:
802
863
shop?.handleShopOpen(message);
803
864
break;
865
case MessageType.shopClosed:
866
shop?.handleShopClosed(message);
867
break;
804
868
case MessageType.itemBubble:
805
869
chat?.showItemBubble(message);
806
870
break;
@@ -869,6 +933,8 @@ function returnToMenu (reason = "")
869
933
skills?.hide();
870
934
contextMenu?.hide();
871
935
death?.reset();
936
shop?.close({ notifyServer: false });
937
hideWorldTooltip();
872
938
if (view)
873
939
{
874
940
for (const key of [...(view.chunks?.keys?.() ?? [])])
@@ -932,12 +998,59 @@ function isWoodworkingBenchTile (view, tileX, tileY)
932
998
return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
933
999
}
934
1000
1001
function isCraftingBenchTile (view, tileX, tileY)
1002
{
1003
return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
1004
}
1005
935
1006
function isOreBoulderTile (view, tileX, tileY)
936
1007
{
937
1008
const block = blockAt(view, tileX, tileY);
938
1009
return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
939
1010
}
940
1011
1012
function hideWorldTooltip ()
1013
{
1014
if (worldTooltip)
1015
{ worldTooltip.hidden = true; }
1016
}
1017
1018
/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
1019
function updateWorldTooltip ()
1020
{
1021
if (!worldTooltip || !view || !scene || uiBlocked())
1022
{
1023
hideWorldTooltip();
1024
return;
1025
}
1026
const canvas = scene.canvas;
1027
const rect = canvas.getBoundingClientRect();
1028
const mouseX = GameInput.mousePosition.x - rect.left;
1029
const mouseY = GameInput.mousePosition.y - rect.top;
1030
if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
1031
{
1032
hideWorldTooltip();
1033
return;
1034
}
1035
const entity = view.entityAtScreen(mouseX, mouseY);
1036
if (entity && entity.entityId !== view.localEntityId)
1037
{
1038
hideWorldTooltip();
1039
return;
1040
}
1041
const tile = view.screenToTile(mouseX, mouseY);
1042
const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
1043
if (!label)
1044
{
1045
hideWorldTooltip();
1046
return;
1047
}
1048
worldTooltip.hidden = false;
1049
worldTooltip.textContent = label;
1050
worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
1051
worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
1052
}
1053
941
1054
function blockTypeAt (view, tileX, tileY)
942
1055
{
943
1056
return blockAt(view, tileX, tileY)?.typeId ?? null;
@@ -955,6 +1068,45 @@ function blockAt (view, tileX, tileY)
955
1068
return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
956
1069
}
957
1070
1071
function groundTypeAt (view, tileX, tileY)
1072
{
1073
const chunkX = Math.floor(tileX / CHUNK_SIZE);
1074
const chunkY = Math.floor(tileY / CHUNK_SIZE);
1075
const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
1076
if (!snapshot)
1077
{ return null; }
1078
const localX = tileX - chunkX * CHUNK_SIZE;
1079
const localY = tileY - chunkY * CHUNK_SIZE;
1080
return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
1081
}
1082
1083
/** Best-effort client filter for approach destinations (server still authorizes paths). */
1084
function isClientApproachable (tileX, tileY)
1085
{
1086
if (!view)
1087
{ return true; }
1088
const groundId = groundTypeAt(view, tileX, tileY);
1089
const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
1090
if (groundDef && !groundDef.passable)
1091
{ return false; }
1092
const block = blockAt(view, tileX, tileY);
1093
if (block?.typeId != null)
1094
{
1095
const blockDef = BLOCK_DEFINITIONS[block.typeId];
1096
if (blockDef && !blockDef.passable)
1097
{ return false; }
1098
}
1099
for (const entity of view.entitiesAtTile(tileX, tileY))
1100
{
1101
if (entity.entityId === view.localEntityId)
1102
{ continue; }
1103
if (entity.untargetable || entity.freeFlight)
1104
{ continue; }
1105
return false;
1106
}
1107
return true;
1108
}
1109
958
1110
function chebyshev (ax, ay, bx, by)
959
1111
{
960
1112
return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
@@ -1,5 +1,5 @@1
import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";1
import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";2
import { BlockType } from "/shared/definitions/tiles.js";2
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName } from "/shared/definitions/tiles.js";3
import { GameSocket, defaultSocketUrl } from "../net/socket.js";3
import { GameSocket, defaultSocketUrl } from "../net/socket.js";4
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";4
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";5
import { WorldView } from "../render/worldView.js";5
import { WorldView } from "../render/worldView.js";@@ -26,6 +26,7 @@ const overlay = document.getElementById("overlay");26
const statusEl = document.getElementById("status");26
const statusEl = document.getElementById("status");27
const characterList = document.getElementById("character-list");27
const characterList = document.getElementById("character-list");28
const errorEl = document.getElementById("error");28
const errorEl = document.getElementById("error");29
const worldTooltip = document.getElementById("world-tooltip");29
30
30
let socket;31
let socket;31
let session = null;32
let session = null;@@ -48,9 +49,16 @@ let shop;48
let pendingPickup = null;49
let pendingPickup = null;49
/** @type {{ kind: "bank" | "cauldron" | "station" | "mine", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */50
/** @type {{ kind: "bank" | "cauldron" | "station" | "mine", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */50
let pendingInteract = null;51
let pendingInteract = null;52
/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */53
let approachMove = null;51
/** Framework can report mousePressed for two frames; latch so one physical click is one command. */54
/** Framework can report mousePressed for two frames; latch so one physical click is one command. */52
let leftClickConsumed = false;55
let leftClickConsumed = false;53
56
57
function consumeWorldClick ()58
{59
leftClickConsumed = true;60
}61
54
function showError (message)62
function showError (message)55
{63
{56
errorEl.textContent = message ?? "";64
errorEl.textContent = message ?? "";@@ -88,7 +96,8 @@ function renderCharacters (characters)88
function uiBlocked ()96
function uiBlocked ()89
{97
{90
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()98
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()91
|| crafting?.isBlocking() || alchemy?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());99
|| crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()100
|| contextMenu?.isOpen() || death?.isBlocking());92
}101
}93
102
94
function clearPendingPickup ()103
function clearPendingPickup ()@@ -99,6 +108,7 @@ function clearPendingPickup ()99
function clearPendingInteract ()108
function clearPendingInteract ()100
{109
{101
pendingInteract = null;110
pendingInteract = null;111
approachMove = null;102
}112
}103
113
104
function clearAllPendingActions ()114
function clearAllPendingActions ()@@ -111,9 +121,14 @@ function approachAdjacentTile (tileX, tileY)111
{121
{112
const local = view.entities.get(view.localEntityId);122
const local = view.entities.get(view.localEntityId);113
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)123
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)114
{ return true; }124
{115
let best = null;125
approachMove = null;116
let bestDist = Infinity;126
return true;127
}128
let bestWalkable = null;129
let bestWalkableDist = Infinity;130
let bestAny = null;131
let bestAnyDist = Infinity;117
for (let dy = -1; dy <= 1; dy++)132
for (let dy = -1; dy <= 1; dy++)118
{133
{119
for (let dx = -1; dx <= 1; dx++)134
for (let dx = -1; dx <= 1; dx++)@@ -125,15 +140,36 @@ function approachAdjacentTile (tileX, tileY)125
const dist = local140
const dist = local126
? chebyshev(local.tileX, local.tileY, destX, destY)141
? chebyshev(local.tileX, local.tileY, destX, destY)127
: 0;142
: 0;128
if (dist < bestDist)143
if (dist < bestAnyDist)144
{145
bestAnyDist = dist;146
bestAny = { tileX: destX, tileY: destY };147
}148
if (isClientApproachable(destX, destY) && dist < bestWalkableDist)129
{149
{130
bestDist = dist;150
bestWalkableDist = dist;131
best = { tileX: destX, tileY: destY };151
bestWalkable = { tileX: destX, tileY: destY };132
}152
}133
}153
}134
}154
}135
if (best)155
const best = bestWalkable ?? bestAny;136
{ socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); }156
if (!best)157
{ return false; }158
if (159
approachMove160
&& approachMove.focusX === tileX161
&& approachMove.focusY === tileY162
&& approachMove.destX === best.tileX163
&& approachMove.destY === best.tileY164
)165
{ return false; }166
approachMove = {167
focusX: tileX,168
focusY: tileY,169
destX: best.tileX,170
destY: best.tileY171
};172
socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY });137
return false;173
return false;138
}174
}139
175
@@ -188,9 +224,9 @@ function requestMine (tileX, tileY)188
224
189
function requestTalk (targetEntityId)225
function requestTalk (targetEntityId)190
{226
{191
clearPendingPickup();227
clearAllPendingActions();192
pendingInteract = { kind: "talk", targetEntityId };228
pendingInteract = { kind: "talk", targetEntityId };193
const target = view.entities.get(targetEntityId);229
const target = view?.entities.get(targetEntityId);194
if (!target)230
if (!target)195
{231
{196
clearPendingInteract();232
clearPendingInteract();@@ -367,6 +403,8 @@ function handleLeftClick (mouseX, mouseY)367
{ requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }403
{ requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }368
else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))404
else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))369
{ requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }405
{ requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }406
else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))407
{ requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }370
else if (isOreBoulderTile(view, tile.tileX, tile.tileY))408
else if (isOreBoulderTile(view, tile.tileX, tile.tileY))371
{ requestMine(tile.tileX, tile.tileY); }409
{ requestMine(tile.tileX, tile.tileY); }372
else410
else@@ -408,10 +446,17 @@ function handleRightClick (event, mouseX, mouseY)408
});446
});409
if (entity.untargetable)447
if (entity.untargetable)410
{ continue; }448
{ continue; }411
if (entity.talkable)449
if (entity.hasShop)450
{451
items.push({452
label: `Shop ${targetName}`,453
onSelect: () => requestTalk(entity.entityId)454
});455
}456
else if (entity.talkable)412
{457
{413
items.push({458
items.push({414
label: `Trade with ${targetName}`,459
label: `Talk to ${targetName}`,415
onSelect: () => requestTalk(entity.entityId)460
onSelect: () => requestTalk(entity.entityId)416
});461
});417
}462
}@@ -485,6 +530,14 @@ function handleRightClick (event, mouseX, mouseY)485
});530
});486
}531
}487
532
533
if (isCraftingBenchTile(view, tile.tileX, tile.tileY))534
{535
items.push({536
label: "Craft",537
onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY)538
});539
}540
488
if (isOreBoulderTile(view, tile.tileX, tile.tileY))541
if (isOreBoulderTile(view, tile.tileX, tile.tileY))489
{542
{490
items.push({543
items.push({@@ -566,7 +619,10 @@ function startPlay (payload)566
flushPendingInteract();619
flushPendingInteract();567
social?.updateNametag(view, scene, view.localEntityId);620
social?.updateNametag(view, scene, view.localEntityId);568
chat?.update(view, scene);621
chat?.update(view, scene);622
updateWorldTooltip();569
}623
}624
else625
{ hideWorldTooltip(); }570
view.update(dt);626
view.update(dt);571
};627
};572
scene.addObject(ticker);628
scene.addObject(ticker);@@ -617,7 +673,7 @@ async function main ()617
socket: { send (payload) { socket.send(payload); } },673
socket: { send (payload) { socket.send(payload); } },618
MessageType674
MessageType619
});675
});620
contextMenu = initContextMenu();676
contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });621
inventory = initInventory({677
inventory = initInventory({622
socket: { send (payload) { socket.send(payload); } },678
socket: { send (payload) { socket.send(payload); } },623
MessageType,679
MessageType,@@ -662,9 +718,14 @@ async function main ()662
shop = initShop({718
shop = initShop({663
socket: { send (payload) { socket.send(payload); } },719
socket: { send (payload) { socket.send(payload); } },664
MessageType,720
MessageType,721
onSuppressWorldClick: consumeWorldClick,665
getCoinCount ()722
getCoinCount ()666
{723
{667
return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);724
return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);725
},726
getInventorySlots ()727
{728
return inventory?.getInventorySlots?.() ?? [];668
}729
}669
});730
});670
chat = initChat({731
chat = initChat({@@ -801,6 +862,9 @@ async function main ()801
case MessageType.shopOpen:862
case MessageType.shopOpen:802
shop?.handleShopOpen(message);863
shop?.handleShopOpen(message);803
break;864
break;865
case MessageType.shopClosed:866
shop?.handleShopClosed(message);867
break;804
case MessageType.itemBubble:868
case MessageType.itemBubble:805
chat?.showItemBubble(message);869
chat?.showItemBubble(message);806
break;870
break;@@ -869,6 +933,8 @@ function returnToMenu (reason = "")869
skills?.hide();933
skills?.hide();870
contextMenu?.hide();934
contextMenu?.hide();871
death?.reset();935
death?.reset();936
shop?.close({ notifyServer: false });937
hideWorldTooltip();872
if (view)938
if (view)873
{939
{874
for (const key of [...(view.chunks?.keys?.() ?? [])])940
for (const key of [...(view.chunks?.keys?.() ?? [])])@@ -932,12 +998,59 @@ function isWoodworkingBenchTile (view, tileX, tileY)932
return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;998
return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;933
}999
}934
1000
1001
function isCraftingBenchTile (view, tileX, tileY)1002
{1003
return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;1004
}1005
935
function isOreBoulderTile (view, tileX, tileY)1006
function isOreBoulderTile (view, tileX, tileY)936
{1007
{937
const block = blockAt(view, tileX, tileY);1008
const block = blockAt(view, tileX, tileY);938
return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);1009
return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);939
}1010
}940
1011
1012
function hideWorldTooltip ()1013
{1014
if (worldTooltip)1015
{ worldTooltip.hidden = true; }1016
}1017
1018
/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */1019
function updateWorldTooltip ()1020
{1021
if (!worldTooltip || !view || !scene || uiBlocked())1022
{1023
hideWorldTooltip();1024
return;1025
}1026
const canvas = scene.canvas;1027
const rect = canvas.getBoundingClientRect();1028
const mouseX = GameInput.mousePosition.x - rect.left;1029
const mouseY = GameInput.mousePosition.y - rect.top;1030
if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)1031
{1032
hideWorldTooltip();1033
return;1034
}1035
const entity = view.entityAtScreen(mouseX, mouseY);1036
if (entity && entity.entityId !== view.localEntityId)1037
{1038
hideWorldTooltip();1039
return;1040
}1041
const tile = view.screenToTile(mouseX, mouseY);1042
const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));1043
if (!label)1044
{1045
hideWorldTooltip();1046
return;1047
}1048
worldTooltip.hidden = false;1049
worldTooltip.textContent = label;1050
worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;1051
worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;1052
}1053
941
function blockTypeAt (view, tileX, tileY)1054
function blockTypeAt (view, tileX, tileY)942
{1055
{943
return blockAt(view, tileX, tileY)?.typeId ?? null;1056
return blockAt(view, tileX, tileY)?.typeId ?? null;@@ -955,6 +1068,45 @@ function blockAt (view, tileX, tileY)955
return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;1068
return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;956
}1069
}957
1070
1071
function groundTypeAt (view, tileX, tileY)1072
{1073
const chunkX = Math.floor(tileX / CHUNK_SIZE);1074
const chunkY = Math.floor(tileY / CHUNK_SIZE);1075
const snapshot = view.chunks.get(`${chunkX},${chunkY}`);1076
if (!snapshot)1077
{ return null; }1078
const localX = tileX - chunkX * CHUNK_SIZE;1079
const localY = tileY - chunkY * CHUNK_SIZE;1080
return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;1081
}1082
1083
/** Best-effort client filter for approach destinations (server still authorizes paths). */1084
function isClientApproachable (tileX, tileY)1085
{1086
if (!view)1087
{ return true; }1088
const groundId = groundTypeAt(view, tileX, tileY);1089
const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;1090
if (groundDef && !groundDef.passable)1091
{ return false; }1092
const block = blockAt(view, tileX, tileY);1093
if (block?.typeId != null)1094
{1095
const blockDef = BLOCK_DEFINITIONS[block.typeId];1096
if (blockDef && !blockDef.passable)1097
{ return false; }1098
}1099
for (const entity of view.entitiesAtTile(tileX, tileY))1100
{1101
if (entity.entityId === view.localEntityId)1102
{ continue; }1103
if (entity.untargetable || entity.freeFlight)1104
{ continue; }1105
return false;1106
}1107
return true;1108
}1109
958
function chebyshev (ax, ay, bx, by)1110
function chebyshev (ax, ay, bx, by)959
{1111
{960
return Math.max(Math.abs(ax - bx), Math.abs(ay - by));1112
return Math.max(Math.abs(ax - bx), Math.abs(ay - by));@@ -4,88 +4,396 @@ import {
4
4
itemAssetPathForStack,
5
5
formatQuantity
6
6
} from "/shared/definitions/items.js";
7
import { insertStack } from "/shared/items/inventory.js";
8
import {
9
canPlayerSellToNpc,
10
resolveShopSellQuote
11
} from "/shared/shop/pricing.js";
12
import { subjectPronoun } from "/shared/speech/pronouns.js";
7
13
import { applyItemIcon } from "../render/potionIcon.js";
8
14
9
15
export function initShop ({
10
16
socket,
11
17
MessageType,
12
18
getCoinCount,
13
onError
19
getInventorySlots,
20
onSuppressWorldClick
14
21
})
15
22
{
16
23
const backdrop = document.getElementById("shop-backdrop");
17
24
const panel = document.getElementById("shop-panel");
18
25
const title = document.getElementById("shop-title");
19
const list = document.getElementById("shop-stock");
20
const statusEl = document.getElementById("shop-status");
26
const grid = document.getElementById("shop-grid");
27
const detail = document.getElementById("shop-detail");
28
const detailIcon = document.getElementById("shop-detail-icon");
29
const detailName = document.getElementById("shop-detail-name");
30
const detailPrice = document.getElementById("shop-detail-price");
31
const detailStock = document.getElementById("shop-detail-stock");
32
const bagWarn = document.getElementById("shop-bag-warn");
33
const coinsEl = document.getElementById("shop-coins");
34
const sellSection = document.getElementById("shop-sell-section");
35
const sellList = document.getElementById("shop-sell-list");
36
const sellDetail = document.getElementById("shop-sell-detail");
37
const sellPrice = document.getElementById("shop-sell-price");
38
const sellFee = document.getElementById("shop-sell-fee");
39
const sellConfirm = document.getElementById("shop-sell-confirm");
40
const qtyBackdrop = document.getElementById("shop-qty-backdrop");
41
const qtyPanel = document.getElementById("shop-qty-panel");
42
const qtyInput = document.getElementById("shop-qty-input");
43
const qtyHint = document.getElementById("shop-qty-hint");
44
21
45
let npcEntityId = null;
22
46
let stock = [];
47
let selectedListingId = null;
48
let selectedSellSlotIndex = null;
49
let buysItems = false;
50
let displayName = "Shop";
51
let sex = "male";
52
53
function suppressWorldClick ()
54
{
55
onSuppressWorldClick?.();
56
}
23
57
24
58
document.getElementById("shop-close")?.addEventListener("click", () => close());
59
backdrop?.addEventListener("mousedown", (event) =>
60
{
61
event.preventDefault();
62
suppressWorldClick();
63
});
25
64
backdrop?.addEventListener("click", () => close());
65
panel?.addEventListener("mousedown", (event) =>
66
{
67
event.stopPropagation();
68
suppressWorldClick();
69
});
70
qtyBackdrop?.addEventListener("mousedown", (event) =>
71
{
72
event.preventDefault();
73
suppressWorldClick();
74
});
75
qtyPanel?.addEventListener("mousedown", (event) =>
76
{
77
event.stopPropagation();
78
suppressWorldClick();
79
});
80
document.getElementById("shop-buy-1")?.addEventListener("click", () => buy(1));
81
document.getElementById("shop-buy-5")?.addEventListener("click", () => buy(5));
82
document.getElementById("shop-buy-10")?.addEventListener("click", () => buy(10));
83
document.getElementById("shop-buy-x")?.addEventListener("click", () => openQtyModal());
84
document.getElementById("shop-qty-close")?.addEventListener("click", () => closeQtyModal());
85
document.getElementById("shop-qty-confirm")?.addEventListener("click", () => confirmQtyBuy());
86
qtyBackdrop?.addEventListener("click", () => closeQtyModal());
87
qtyInput?.addEventListener("keydown", (event) =>
88
{
89
if (event.key === "Enter")
90
{ confirmQtyBuy(); }
91
});
92
sellConfirm?.addEventListener("click", () => sellSelected());
26
93
27
94
function open (payload)
28
95
{
29
96
npcEntityId = payload.npcEntityId | 0;
30
title.textContent = payload.displayName || "Shop";
97
displayName = payload.displayName || "Shop";
98
sex = payload.sex === "female" ? "female" : "male";
99
title.textContent = displayName;
100
buysItems = !!payload.buysItems;
31
101
stock = Array.isArray(payload.stock) ? payload.stock : [];
32
statusEl.textContent = "";
102
if (selectedListingId == null || !stock.some((row) => row.listingId === selectedListingId))
103
{ selectedListingId = stock[0]?.listingId ?? null; }
104
closeQtyModal();
33
105
render();
34
106
backdrop.hidden = false;
35
107
panel.hidden = false;
108
suppressWorldClick();
36
109
}
37
110
38
function close ()
111
function close ({ notifyServer = true } = {})
39
112
{
113
const closingNpcId = npcEntityId;
114
closeQtyModal();
40
115
backdrop.hidden = true;
41
116
panel.hidden = true;
42
117
npcEntityId = null;
43
118
stock = [];
119
selectedListingId = null;
120
selectedSellSlotIndex = null;
121
buysItems = false;
122
sex = "male";
123
suppressWorldClick();
124
if (notifyServer && closingNpcId)
125
{
126
socket.send({
127
type: MessageType.closeShop,
128
npcEntityId: closingNpcId
129
});
130
}
131
}
132
133
function selectedEntry ()
134
{
135
return stock.find((row) => row.listingId === selectedListingId) ?? null;
136
}
137
138
function maxBuyable (entry)
139
{
140
const price = Math.max(1, entry?.unitPrice | 0 || 1);
141
const coins = getCoinCount?.() ?? 0;
142
const affordable = Math.max(0, Math.floor(coins / price));
143
const available = entry?.available == null ? affordable : Math.max(0, entry.available | 0);
144
return Math.min(affordable, available);
145
}
146
147
function inventoryFits (itemId, quantity)
148
{
149
const def = itemDefinition(itemId);
150
if (!def)
151
{ return false; }
152
const slots = getInventorySlots?.() ?? [];
153
const added = insertStack(slots.map((slot) => (slot ? structuredClone(slot) : null)), {
154
itemId,
155
quantity: Math.max(1, quantity | 0 || 1)
156
}, def);
157
return added.ok && added.remainder === 0;
158
}
159
160
function buy (quantity)
161
{
162
const entry = selectedEntry();
163
if (!npcEntityId || !entry)
164
{ return; }
165
const qty = Math.max(1, quantity | 0 || 1);
166
const max = maxBuyable(entry);
167
if (qty > max)
168
{ return; }
169
socket.send({
170
type: MessageType.buyFromShop,
171
npcEntityId,
172
itemId: entry.itemId,
173
quantity: qty,
174
listingId: entry.listingId,
175
source: entry.source
176
});
177
}
178
179
function openQtyModal ()
180
{
181
const entry = selectedEntry();
182
if (!entry)
183
{ return; }
184
const max = maxBuyable(entry);
185
if (max < 1)
186
{ return; }
187
qtyInput.value = String(Math.min(max, 1));
188
qtyHint.textContent = `Max ${max}`;
189
qtyBackdrop.hidden = false;
190
qtyPanel.hidden = false;
191
suppressWorldClick();
192
qtyInput.focus();
193
qtyInput.select();
194
}
195
196
function closeQtyModal ()
197
{
198
qtyBackdrop.hidden = true;
199
qtyPanel.hidden = true;
200
}
201
202
function confirmQtyBuy ()
203
{
204
const entry = selectedEntry();
205
if (!entry)
206
{
207
closeQtyModal();
208
return;
209
}
210
const max = maxBuyable(entry);
211
const qty = Math.min(max, Math.max(1, Number(qtyInput.value) | 0 || 1));
212
closeQtyModal();
213
buy(qty);
214
}
215
216
function selectedSellSlot ()
217
{
218
if (selectedSellSlotIndex == null)
219
{ return null; }
220
const slots = getInventorySlots?.() ?? [];
221
const slot = slots[selectedSellSlotIndex];
222
if (!slot?.itemId || !canPlayerSellToNpc(slot))
223
{ return null; }
224
return slot;
225
}
226
227
function sellSelected ()
228
{
229
if (!npcEntityId || selectedSellSlotIndex == null || !selectedSellSlot())
230
{ return; }
231
socket.send({
232
type: MessageType.sellToShop,
233
npcEntityId,
234
slotIndex: selectedSellSlotIndex,
235
quantity: 1
236
});
237
}
238
239
function renderSellDetail ()
240
{
241
if (!sellDetail || !sellPrice || !sellFee || !sellConfirm)
242
{ return; }
243
const slot = selectedSellSlot();
244
if (!slot)
245
{
246
sellDetail.hidden = true;
247
sellFee.hidden = true;
248
return;
249
}
250
const quote = resolveShopSellQuote(slot, { quantity: 1 });
251
if (!quote)
252
{
253
sellDetail.hidden = true;
254
sellFee.hidden = true;
255
return;
256
}
257
sellDetail.hidden = false;
258
sellPrice.textContent = quote.isCheque
259
? `You receive ${formatQuantity(quote.payout)} coins`
260
: `${formatQuantity(quote.unitPrice)} coins each`;
261
if (quote.isCheque)
262
{
263
sellFee.hidden = false;
264
sellFee.textContent = `${formatQuantity(quote.adminFee)} coins charged as administrative fee`;
265
}
266
else
267
{
268
sellFee.hidden = true;
269
sellFee.textContent = "";
270
}
271
sellConfirm.disabled = false;
272
}
273
274
function renderSellList ()
275
{
276
if (!sellSection || !sellList)
277
{ return; }
278
if (!buysItems)
279
{
280
sellSection.hidden = true;
281
selectedSellSlotIndex = null;
282
if (sellDetail)
283
{ sellDetail.hidden = true; }
284
return;
285
}
286
sellSection.hidden = false;
287
sellList.innerHTML = "";
288
const slots = getInventorySlots?.() ?? [];
289
const sellableIndexes = [];
290
slots.forEach((slot, slotIndex) =>
291
{
292
if (!slot?.itemId || !canPlayerSellToNpc(slot))
293
{ return; }
294
sellableIndexes.push(slotIndex);
295
});
296
if (selectedSellSlotIndex != null && !sellableIndexes.includes(selectedSellSlotIndex))
297
{ selectedSellSlotIndex = null; }
298
if (selectedSellSlotIndex == null && sellableIndexes.length)
299
{ selectedSellSlotIndex = sellableIndexes[0]; }
300
if (!sellableIndexes.length)
301
{
302
sellList.textContent = `Nothing ${subjectPronoun(sex)} will buy in your bag.`;
303
selectedSellSlotIndex = null;
304
renderSellDetail();
305
return;
306
}
307
for (const slotIndex of sellableIndexes)
308
{
309
const slot = slots[slotIndex];
310
const row = document.createElement("button");
311
row.type = "button";
312
row.className = "shop-sell-row";
313
if (slotIndex === selectedSellSlotIndex)
314
{ row.classList.add("selected"); }
315
row.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;
316
row.addEventListener("click", () =>
317
{
318
selectedSellSlotIndex = slotIndex;
319
renderSellList();
320
});
321
sellList.append(row);
322
}
323
renderSellDetail();
44
324
}
45
325
46
326
function render ()
47
327
{
48
list.innerHTML = "";
328
grid.innerHTML = "";
329
const coins = getCoinCount?.() ?? 0;
330
coinsEl.textContent = `Coins: ${formatQuantity(coins)}`;
331
49
332
if (!stock.length)
50
333
{
51
list.textContent = "Nothing for sale.";
334
grid.textContent = buysItems ? "No stock for sale right now." : "Nothing for sale.";
335
detail.hidden = true;
336
bagWarn.hidden = true;
337
renderSellList();
52
338
return;
53
339
}
54
const coins = getCoinCount?.() ?? 0;
340
55
341
for (const entry of stock)
56
342
{
57
const def = itemDefinition(entry.itemId);
58
const row = document.createElement("div");
59
row.className = "shop-row";
343
const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });
344
const btn = document.createElement("button");
345
btn.type = "button";
346
btn.className = "shop-cell";
347
if (entry.listingId === selectedListingId)
348
{ btn.classList.add("selected"); }
349
btn.title = name;
60
350
const img = document.createElement("img");
61
img.alt = entry.displayName ?? def?.displayName ?? "item";
351
img.alt = name;
62
352
applyItemIcon(img, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));
63
const meta = document.createElement("div");
64
meta.className = "shop-row-meta";
65
const name = document.createElement("strong");
66
name.textContent = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });
67
const price = document.createElement("span");
68
price.className = "hint";
69
price.textContent = `${formatQuantity(entry.unitPrice)} coins`;
70
meta.append(name, price);
71
const buy = document.createElement("button");
72
buy.type = "button";
73
buy.textContent = "Buy";
74
buy.disabled = coins < (entry.unitPrice | 0);
75
buy.addEventListener("click", () =>
353
btn.append(img);
354
btn.addEventListener("click", () =>
76
355
{
77
if (!npcEntityId)
78
{ return; }
79
socket.send({
80
type: MessageType.buyFromShop,
81
npcEntityId,
82
itemId: entry.itemId,
83
quantity: 1
84
});
356
selectedListingId = entry.listingId;
357
render();
85
358
});
86
row.append(img, meta, buy);
87
list.append(row);
359
grid.append(btn);
88
360
}
361
362
const entry = selectedEntry();
363
if (!entry)
364
{
365
detail.hidden = true;
366
bagWarn.hidden = true;
367
renderSellList();
368
return;
369
}
370
371
detail.hidden = false;
372
const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });
373
detailName.textContent = name;
374
detailPrice.textContent = `${formatQuantity(entry.unitPrice)} coins each`;
375
detailStock.textContent = entry.available == null
376
? "In stock"
377
: `Stock: ${formatQuantity(entry.available)}`;
378
applyItemIcon(detailIcon, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));
379
380
const max = maxBuyable(entry);
381
const setBuy = (id, qty) =>
382
{
383
const el = document.getElementById(id);
384
if (!el)
385
{ return; }
386
el.disabled = max < qty;
387
};
388
setBuy("shop-buy-1", 1);
389
setBuy("shop-buy-5", 5);
390
setBuy("shop-buy-10", 10);
391
const buyX = document.getElementById("shop-buy-x");
392
if (buyX)
393
{ buyX.disabled = max < 1; }
394
395
bagWarn.hidden = inventoryFits(entry.itemId, 1);
396
renderSellList();
89
397
}
90
398
91
399
function handleShopOpen (message)
@@ -93,6 +401,12 @@ export function initShop ({
93
401
open(message);
94
402
}
95
403
404
function handleShopClosed (message)
405
{
406
if ((message?.npcEntityId | 0) === npcEntityId)
407
{ close({ notifyServer: false }); }
408
}
409
96
410
function refresh ()
97
411
{
98
412
if (npcEntityId != null && !panel.hidden)
@@ -101,8 +415,10 @@ export function initShop ({
101
415
102
416
return {
103
417
handleShopOpen,
418
handleShopClosed,
104
419
refresh,
105
420
close,
421
isBlocking: () => !panel.hidden || !qtyPanel.hidden,
106
422
isOpen: () => !panel.hidden
107
423
};
108
424
}
@@ -4,88 +4,396 @@ import {4
itemAssetPathForStack,4
itemAssetPathForStack,5
formatQuantity5
formatQuantity6
} from "/shared/definitions/items.js";6
} from "/shared/definitions/items.js";7
import { insertStack } from "/shared/items/inventory.js";8
import {9
canPlayerSellToNpc,10
resolveShopSellQuote11
} from "/shared/shop/pricing.js";12
import { subjectPronoun } from "/shared/speech/pronouns.js";7
import { applyItemIcon } from "../render/potionIcon.js";13
import { applyItemIcon } from "../render/potionIcon.js";8
14
9
export function initShop ({15
export function initShop ({10
socket,16
socket,11
MessageType,17
MessageType,12
getCoinCount,18
getCoinCount,13
onError19
getInventorySlots,20
onSuppressWorldClick14
})21
})15
{22
{16
const backdrop = document.getElementById("shop-backdrop");23
const backdrop = document.getElementById("shop-backdrop");17
const panel = document.getElementById("shop-panel");24
const panel = document.getElementById("shop-panel");18
const title = document.getElementById("shop-title");25
const title = document.getElementById("shop-title");19
const list = document.getElementById("shop-stock");26
const grid = document.getElementById("shop-grid");20
const statusEl = document.getElementById("shop-status");27
const detail = document.getElementById("shop-detail");28
const detailIcon = document.getElementById("shop-detail-icon");29
const detailName = document.getElementById("shop-detail-name");30
const detailPrice = document.getElementById("shop-detail-price");31
const detailStock = document.getElementById("shop-detail-stock");32
const bagWarn = document.getElementById("shop-bag-warn");33
const coinsEl = document.getElementById("shop-coins");34
const sellSection = document.getElementById("shop-sell-section");35
const sellList = document.getElementById("shop-sell-list");36
const sellDetail = document.getElementById("shop-sell-detail");37
const sellPrice = document.getElementById("shop-sell-price");38
const sellFee = document.getElementById("shop-sell-fee");39
const sellConfirm = document.getElementById("shop-sell-confirm");40
const qtyBackdrop = document.getElementById("shop-qty-backdrop");41
const qtyPanel = document.getElementById("shop-qty-panel");42
const qtyInput = document.getElementById("shop-qty-input");43
const qtyHint = document.getElementById("shop-qty-hint");44
21
let npcEntityId = null;45
let npcEntityId = null;22
let stock = [];46
let stock = [];47
let selectedListingId = null;48
let selectedSellSlotIndex = null;49
let buysItems = false;50
let displayName = "Shop";51
let sex = "male";52
53
function suppressWorldClick ()54
{55
onSuppressWorldClick?.();56
}23
57
24
document.getElementById("shop-close")?.addEventListener("click", () => close());58
document.getElementById("shop-close")?.addEventListener("click", () => close());59
backdrop?.addEventListener("mousedown", (event) =>60
{61
event.preventDefault();62
suppressWorldClick();63
});25
backdrop?.addEventListener("click", () => close());64
backdrop?.addEventListener("click", () => close());65
panel?.addEventListener("mousedown", (event) =>66
{67
event.stopPropagation();68
suppressWorldClick();69
});70
qtyBackdrop?.addEventListener("mousedown", (event) =>71
{72
event.preventDefault();73
suppressWorldClick();74
});75
qtyPanel?.addEventListener("mousedown", (event) =>76
{77
event.stopPropagation();78
suppressWorldClick();79
});80
document.getElementById("shop-buy-1")?.addEventListener("click", () => buy(1));81
document.getElementById("shop-buy-5")?.addEventListener("click", () => buy(5));82
document.getElementById("shop-buy-10")?.addEventListener("click", () => buy(10));83
document.getElementById("shop-buy-x")?.addEventListener("click", () => openQtyModal());84
document.getElementById("shop-qty-close")?.addEventListener("click", () => closeQtyModal());85
document.getElementById("shop-qty-confirm")?.addEventListener("click", () => confirmQtyBuy());86
qtyBackdrop?.addEventListener("click", () => closeQtyModal());87
qtyInput?.addEventListener("keydown", (event) =>88
{89
if (event.key === "Enter")90
{ confirmQtyBuy(); }91
});92
sellConfirm?.addEventListener("click", () => sellSelected());26
93
27
function open (payload)94
function open (payload)28
{95
{29
npcEntityId = payload.npcEntityId | 0;96
npcEntityId = payload.npcEntityId | 0;30
title.textContent = payload.displayName || "Shop";97
displayName = payload.displayName || "Shop";98
sex = payload.sex === "female" ? "female" : "male";99
title.textContent = displayName;100
buysItems = !!payload.buysItems;31
stock = Array.isArray(payload.stock) ? payload.stock : [];101
stock = Array.isArray(payload.stock) ? payload.stock : [];32
statusEl.textContent = "";102
if (selectedListingId == null || !stock.some((row) => row.listingId === selectedListingId))103
{ selectedListingId = stock[0]?.listingId ?? null; }104
closeQtyModal();33
render();105
render();34
backdrop.hidden = false;106
backdrop.hidden = false;35
panel.hidden = false;107
panel.hidden = false;108
suppressWorldClick();36
}109
}37
110
38
function close ()111
function close ({ notifyServer = true } = {})39
{112
{113
const closingNpcId = npcEntityId;114
closeQtyModal();40
backdrop.hidden = true;115
backdrop.hidden = true;41
panel.hidden = true;116
panel.hidden = true;42
npcEntityId = null;117
npcEntityId = null;43
stock = [];118
stock = [];119
selectedListingId = null;120
selectedSellSlotIndex = null;121
buysItems = false;122
sex = "male";123
suppressWorldClick();124
if (notifyServer && closingNpcId)125
{126
socket.send({127
type: MessageType.closeShop,128
npcEntityId: closingNpcId129
});130
}131
}132
133
function selectedEntry ()134
{135
return stock.find((row) => row.listingId === selectedListingId) ?? null;136
}137
138
function maxBuyable (entry)139
{140
const price = Math.max(1, entry?.unitPrice | 0 || 1);141
const coins = getCoinCount?.() ?? 0;142
const affordable = Math.max(0, Math.floor(coins / price));143
const available = entry?.available == null ? affordable : Math.max(0, entry.available | 0);144
return Math.min(affordable, available);145
}146
147
function inventoryFits (itemId, quantity)148
{149
const def = itemDefinition(itemId);150
if (!def)151
{ return false; }152
const slots = getInventorySlots?.() ?? [];153
const added = insertStack(slots.map((slot) => (slot ? structuredClone(slot) : null)), {154
itemId,155
quantity: Math.max(1, quantity | 0 || 1)156
}, def);157
return added.ok && added.remainder === 0;158
}159
160
function buy (quantity)161
{162
const entry = selectedEntry();163
if (!npcEntityId || !entry)164
{ return; }165
const qty = Math.max(1, quantity | 0 || 1);166
const max = maxBuyable(entry);167
if (qty > max)168
{ return; }169
socket.send({170
type: MessageType.buyFromShop,171
npcEntityId,172
itemId: entry.itemId,173
quantity: qty,174
listingId: entry.listingId,175
source: entry.source176
});177
}178
179
function openQtyModal ()180
{181
const entry = selectedEntry();182
if (!entry)183
{ return; }184
const max = maxBuyable(entry);185
if (max < 1)186
{ return; }187
qtyInput.value = String(Math.min(max, 1));188
qtyHint.textContent = `Max ${max}`;189
qtyBackdrop.hidden = false;190
qtyPanel.hidden = false;191
suppressWorldClick();192
qtyInput.focus();193
qtyInput.select();194
}195
196
function closeQtyModal ()197
{198
qtyBackdrop.hidden = true;199
qtyPanel.hidden = true;200
}201
202
function confirmQtyBuy ()203
{204
const entry = selectedEntry();205
if (!entry)206
{207
closeQtyModal();208
return;209
}210
const max = maxBuyable(entry);211
const qty = Math.min(max, Math.max(1, Number(qtyInput.value) | 0 || 1));212
closeQtyModal();213
buy(qty);214
}215
216
function selectedSellSlot ()217
{218
if (selectedSellSlotIndex == null)219
{ return null; }220
const slots = getInventorySlots?.() ?? [];221
const slot = slots[selectedSellSlotIndex];222
if (!slot?.itemId || !canPlayerSellToNpc(slot))223
{ return null; }224
return slot;225
}226
227
function sellSelected ()228
{229
if (!npcEntityId || selectedSellSlotIndex == null || !selectedSellSlot())230
{ return; }231
socket.send({232
type: MessageType.sellToShop,233
npcEntityId,234
slotIndex: selectedSellSlotIndex,235
quantity: 1236
});237
}238
239
function renderSellDetail ()240
{241
if (!sellDetail || !sellPrice || !sellFee || !sellConfirm)242
{ return; }243
const slot = selectedSellSlot();244
if (!slot)245
{246
sellDetail.hidden = true;247
sellFee.hidden = true;248
return;249
}250
const quote = resolveShopSellQuote(slot, { quantity: 1 });251
if (!quote)252
{253
sellDetail.hidden = true;254
sellFee.hidden = true;255
return;256
}257
sellDetail.hidden = false;258
sellPrice.textContent = quote.isCheque259
? `You receive ${formatQuantity(quote.payout)} coins`260
: `${formatQuantity(quote.unitPrice)} coins each`;261
if (quote.isCheque)262
{263
sellFee.hidden = false;264
sellFee.textContent = `${formatQuantity(quote.adminFee)} coins charged as administrative fee`;265
}266
else267
{268
sellFee.hidden = true;269
sellFee.textContent = "";270
}271
sellConfirm.disabled = false;272
}273
274
function renderSellList ()275
{276
if (!sellSection || !sellList)277
{ return; }278
if (!buysItems)279
{280
sellSection.hidden = true;281
selectedSellSlotIndex = null;282
if (sellDetail)283
{ sellDetail.hidden = true; }284
return;285
}286
sellSection.hidden = false;287
sellList.innerHTML = "";288
const slots = getInventorySlots?.() ?? [];289
const sellableIndexes = [];290
slots.forEach((slot, slotIndex) =>291
{292
if (!slot?.itemId || !canPlayerSellToNpc(slot))293
{ return; }294
sellableIndexes.push(slotIndex);295
});296
if (selectedSellSlotIndex != null && !sellableIndexes.includes(selectedSellSlotIndex))297
{ selectedSellSlotIndex = null; }298
if (selectedSellSlotIndex == null && sellableIndexes.length)299
{ selectedSellSlotIndex = sellableIndexes[0]; }300
if (!sellableIndexes.length)301
{302
sellList.textContent = `Nothing ${subjectPronoun(sex)} will buy in your bag.`;303
selectedSellSlotIndex = null;304
renderSellDetail();305
return;306
}307
for (const slotIndex of sellableIndexes)308
{309
const slot = slots[slotIndex];310
const row = document.createElement("button");311
row.type = "button";312
row.className = "shop-sell-row";313
if (slotIndex === selectedSellSlotIndex)314
{ row.classList.add("selected"); }315
row.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;316
row.addEventListener("click", () =>317
{318
selectedSellSlotIndex = slotIndex;319
renderSellList();320
});321
sellList.append(row);322
}323
renderSellDetail();44
}324
}45
325
46
function render ()326
function render ()47
{327
{48
list.innerHTML = "";328
grid.innerHTML = "";329
const coins = getCoinCount?.() ?? 0;330
coinsEl.textContent = `Coins: ${formatQuantity(coins)}`;331
49
if (!stock.length)332
if (!stock.length)50
{333
{51
list.textContent = "Nothing for sale.";334
grid.textContent = buysItems ? "No stock for sale right now." : "Nothing for sale.";335
detail.hidden = true;336
bagWarn.hidden = true;337
renderSellList();52
return;338
return;53
}339
}54
const coins = getCoinCount?.() ?? 0;340
55
for (const entry of stock)341
for (const entry of stock)56
{342
{57
const def = itemDefinition(entry.itemId);343
const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });58
const row = document.createElement("div");344
const btn = document.createElement("button");59
row.className = "shop-row";345
btn.type = "button";346
btn.className = "shop-cell";347
if (entry.listingId === selectedListingId)348
{ btn.classList.add("selected"); }349
btn.title = name;60
const img = document.createElement("img");350
const img = document.createElement("img");61
img.alt = entry.displayName ?? def?.displayName ?? "item";351
img.alt = name;62
applyItemIcon(img, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));352
applyItemIcon(img, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));63
const meta = document.createElement("div");353
btn.append(img);64
meta.className = "shop-row-meta";354
btn.addEventListener("click", () =>65
const name = document.createElement("strong");66
name.textContent = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });67
const price = document.createElement("span");68
price.className = "hint";69
price.textContent = `${formatQuantity(entry.unitPrice)} coins`;70
meta.append(name, price);71
const buy = document.createElement("button");72
buy.type = "button";73
buy.textContent = "Buy";74
buy.disabled = coins < (entry.unitPrice | 0);75
buy.addEventListener("click", () =>76
{355
{77
if (!npcEntityId)356
selectedListingId = entry.listingId;78
{ return; }357
render();79
socket.send({80
type: MessageType.buyFromShop,81
npcEntityId,82
itemId: entry.itemId,83
quantity: 184
});85
});358
});86
row.append(img, meta, buy);359
grid.append(btn);87
list.append(row);88
}360
}361
362
const entry = selectedEntry();363
if (!entry)364
{365
detail.hidden = true;366
bagWarn.hidden = true;367
renderSellList();368
return;369
}370
371
detail.hidden = false;372
const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });373
detailName.textContent = name;374
detailPrice.textContent = `${formatQuantity(entry.unitPrice)} coins each`;375
detailStock.textContent = entry.available == null376
? "In stock"377
: `Stock: ${formatQuantity(entry.available)}`;378
applyItemIcon(detailIcon, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));379
380
const max = maxBuyable(entry);381
const setBuy = (id, qty) =>382
{383
const el = document.getElementById(id);384
if (!el)385
{ return; }386
el.disabled = max < qty;387
};388
setBuy("shop-buy-1", 1);389
setBuy("shop-buy-5", 5);390
setBuy("shop-buy-10", 10);391
const buyX = document.getElementById("shop-buy-x");392
if (buyX)393
{ buyX.disabled = max < 1; }394
395
bagWarn.hidden = inventoryFits(entry.itemId, 1);396
renderSellList();89
}397
}90
398
91
function handleShopOpen (message)399
function handleShopOpen (message)@@ -93,6 +401,12 @@ export function initShop ({93
open(message);401
open(message);94
}402
}95
403
404
function handleShopClosed (message)405
{406
if ((message?.npcEntityId | 0) === npcEntityId)407
{ close({ notifyServer: false }); }408
}409
96
function refresh ()410
function refresh ()97
{411
{98
if (npcEntityId != null && !panel.hidden)412
if (npcEntityId != null && !panel.hidden)@@ -101,8 +415,10 @@ export function initShop ({101
415
102
return {416
return {103
handleShopOpen,417
handleShopOpen,418
handleShopClosed,104
refresh,419
refresh,105
close,420
close,421
isBlocking: () => !panel.hidden || !qtyPanel.hidden,106
isOpen: () => !panel.hidden422
isOpen: () => !panel.hidden107
};423
};108
}424
}@@ -2,7 +2,7 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BO
2
2
import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3
3
import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
4
4
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5
import { itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
5
import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
6
6
import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";
7
7
import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";
8
8
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
@@ -27,6 +27,8 @@ const WALK_TILT_DEG = 6;
27
27
const RUN_TILT_DEG = 8;
28
28
const SHOVE_TILE_FRACTION = 0.25;
29
29
const SHOVE_MS = 280;
30
/** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */
31
const GATHER_TOOL_HOLD_MS = 1100;
30
32
const DAMAGE_FLASH_MS = 180;
31
33
const DAMAGE_FLOAT_MS = 900;
32
34
@@ -105,11 +107,11 @@ const TINT_LIT_SPRITE_FRAG = [
105
107
" if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
106
108
" vec3 rgb = color.rgb;",
107
109
" if (u_useTint > 0.5) {",
108
" float eps = 1.0 / 255.0;",
109
" if (abs(color.r - color.b) <= eps && color.g < color.r - eps) {",
110
" if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
110
111
" float L = color.r;",
111
112
" float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
112
" rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;",
113
" float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));",
114
" rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;",
113
115
" }",
114
116
" }",
115
117
" if (u_wade > 0.5 && fromBottom < 5.0) {",
@@ -571,6 +573,7 @@ export class WorldView
571
573
entity.visualY = target.y;
572
574
}
573
575
this.#updateShove(entity, now, size);
576
this.#expireGatherToolOverlay(entity, now);
574
577
this.#placeEntity(entity, now);
575
578
}
576
579
@@ -643,6 +646,8 @@ export class WorldView
643
646
{ return; }
644
647
const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
645
648
this.#applyShove(attacker, pivot.x, pivot.y);
649
if (payload.toolItemId != null)
650
{ this.#setGatherToolOverlay(attacker, payload.toolItemId); }
646
651
}
647
652
648
653
#applyShove (entity, targetVisualX, targetVisualY)
@@ -912,6 +917,7 @@ export class WorldView
912
917
? !!payload.canFight
913
918
: !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
914
919
entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
920
entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
915
921
entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
916
922
entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
917
923
entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
@@ -951,6 +957,55 @@ export class WorldView
951
957
952
958
#applyLayers (entity, layers)
953
959
{
960
entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
961
this.#rebuildOverlays(entity);
962
}
963
964
#setGatherToolOverlay (entity, toolItemId)
965
{
966
entity.gatherToolItemId = toolItemId;
967
entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
968
this.#rebuildOverlays(entity);
969
}
970
971
#expireGatherToolOverlay (entity, now)
972
{
973
if (entity.gatherToolItemId == null)
974
{ return; }
975
if ((entity.gatherToolUntil ?? 0) > now)
976
{ return; }
977
entity.gatherToolItemId = null;
978
entity.gatherToolUntil = 0;
979
this.#rebuildOverlays(entity);
980
}
981
982
/** Prefer the gather tool's equip sprite over the worn weapon while harvesting. */
983
#layersForDisplay (entity)
984
{
985
const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
986
const toolId = entity.gatherToolItemId;
987
if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
988
{ return layers; }
989
const equip = itemEquipSprite(toolId);
990
if (!equip)
991
{ return layers; }
992
const replacement = { sprite: equip, itemId: toolId };
993
for (let index = layers.length - 1; index >= 1; index--)
994
{
995
const def = itemDefinition(layers[index].itemId);
996
if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
997
{
998
layers[index] = replacement;
999
return layers;
1000
}
1001
}
1002
layers.push(replacement);
1003
return layers;
1004
}
1005
1006
#rebuildOverlays (entity)
1007
{
1008
const layers = this.#layersForDisplay(entity);
954
1009
const base = layers[0]?.sprite
955
1010
?? bodySpriteName(entity.sex);
956
1011
if (this.game.images[base])
@@ -2,7 +2,7 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BO2
import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";2
import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";3
import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";3
import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";4
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";4
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";5
import { itemSpriteName, itemDefinition } from "/shared/definitions/items.js";5
import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";6
import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";6
import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";7
import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";7
import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";8
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";8
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";@@ -27,6 +27,8 @@ const WALK_TILT_DEG = 6;27
const RUN_TILT_DEG = 8;27
const RUN_TILT_DEG = 8;28
const SHOVE_TILE_FRACTION = 0.25;28
const SHOVE_TILE_FRACTION = 0.25;29
const SHOVE_MS = 280;29
const SHOVE_MS = 280;30
/** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */31
const GATHER_TOOL_HOLD_MS = 1100;30
const DAMAGE_FLASH_MS = 180;32
const DAMAGE_FLASH_MS = 180;31
const DAMAGE_FLOAT_MS = 900;33
const DAMAGE_FLOAT_MS = 900;32
34
@@ -105,11 +107,11 @@ const TINT_LIT_SPRITE_FRAG = [105
" if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",107
" if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",106
" vec3 rgb = color.rgb;",108
" vec3 rgb = color.rgb;",107
" if (u_useTint > 0.5) {",109
" if (u_useTint > 0.5) {",108
" float eps = 1.0 / 255.0;",110
" if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",109
" if (abs(color.r - color.b) <= eps && color.g < color.r - eps) {",110
" float L = color.r;",111
" float L = color.r;",111
" float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",112
" float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",112
" rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;",113
" float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));",114
" rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;",113
" }",115
" }",114
" }",116
" }",115
" if (u_wade > 0.5 && fromBottom < 5.0) {",117
" if (u_wade > 0.5 && fromBottom < 5.0) {",@@ -571,6 +573,7 @@ export class WorldView571
entity.visualY = target.y;573
entity.visualY = target.y;572
}574
}573
this.#updateShove(entity, now, size);575
this.#updateShove(entity, now, size);576
this.#expireGatherToolOverlay(entity, now);574
this.#placeEntity(entity, now);577
this.#placeEntity(entity, now);575
}578
}576
579
@@ -643,6 +646,8 @@ export class WorldView643
{ return; }646
{ return; }644
const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());647
const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());645
this.#applyShove(attacker, pivot.x, pivot.y);648
this.#applyShove(attacker, pivot.x, pivot.y);649
if (payload.toolItemId != null)650
{ this.#setGatherToolOverlay(attacker, payload.toolItemId); }646
}651
}647
652
648
#applyShove (entity, targetVisualX, targetVisualY)653
#applyShove (entity, targetVisualX, targetVisualY)@@ -912,6 +917,7 @@ export class WorldView912
? !!payload.canFight917
? !!payload.canFight913
: !!(entity.canFight || (payload.mobTypeId && !payload.talkable));918
: !!(entity.canFight || (payload.mobTypeId && !payload.talkable));914
entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;919
entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;920
entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;915
entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;921
entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;916
entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;922
entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;917
entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;923
entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;@@ -951,6 +957,55 @@ export class WorldView951
957
952
#applyLayers (entity, layers)958
#applyLayers (entity, layers)953
{959
{960
entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];961
this.#rebuildOverlays(entity);962
}963
964
#setGatherToolOverlay (entity, toolItemId)965
{966
entity.gatherToolItemId = toolItemId;967
entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;968
this.#rebuildOverlays(entity);969
}970
971
#expireGatherToolOverlay (entity, now)972
{973
if (entity.gatherToolItemId == null)974
{ return; }975
if ((entity.gatherToolUntil ?? 0) > now)976
{ return; }977
entity.gatherToolItemId = null;978
entity.gatherToolUntil = 0;979
this.#rebuildOverlays(entity);980
}981
982
/** Prefer the gather tool's equip sprite over the worn weapon while harvesting. */983
#layersForDisplay (entity)984
{985
const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));986
const toolId = entity.gatherToolItemId;987
if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())988
{ return layers; }989
const equip = itemEquipSprite(toolId);990
if (!equip)991
{ return layers; }992
const replacement = { sprite: equip, itemId: toolId };993
for (let index = layers.length - 1; index >= 1; index--)994
{995
const def = itemDefinition(layers[index].itemId);996
if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)997
{998
layers[index] = replacement;999
return layers;1000
}1001
}1002
layers.push(replacement);1003
return layers;1004
}1005
1006
#rebuildOverlays (entity)1007
{1008
const layers = this.#layersForDisplay(entity);954
const base = layers[0]?.sprite1009
const base = layers[0]?.sprite955
?? bodySpriteName(entity.sex);1010
?? bodySpriteName(entity.sex);956
if (this.game.images[base])1011
if (this.game.images[base])@@ -205,6 +205,142 @@ label { display: block; margin: 0.4rem 0; }
205
205
color: #c5c0b4;
206
206
}
207
207
208
.seed-price-panel {
209
display: flex;
210
flex-direction: column;
211
gap: 0.65rem;
212
min-height: 0;
213
}
214
215
.seed-price-toolbar {
216
display: flex;
217
flex-wrap: wrap;
218
gap: 0.55rem 0.75rem;
219
align-items: center;
220
}
221
222
.seed-price-search {
223
flex: 1 1 12rem;
224
min-width: 10rem;
225
padding: 0.4rem 0.55rem;
226
background: #10141b;
227
border: 1px solid #3a4250;
228
color: #e8e4d9;
229
font: inherit;
230
}
231
232
.seed-price-meta {
233
flex: 0 0 auto;
234
}
235
236
.seed-price-pager {
237
display: flex;
238
align-items: center;
239
gap: 0.45rem;
240
margin-left: auto;
241
}
242
243
.seed-price-pager button {
244
appearance: none;
245
border: 1px solid #3a4250;
246
background: #1c222c;
247
color: #e8e4d9;
248
padding: 0.3rem 0.55rem;
249
cursor: pointer;
250
font: inherit;
251
}
252
253
.seed-price-pager button:disabled {
254
opacity: 0.4;
255
cursor: default;
256
}
257
258
.seed-price-header,
259
.seed-price-row {
260
display: grid;
261
grid-template-columns: minmax(10rem, 1.6fr) 6.5rem 5.5rem 5.5rem;
262
gap: 0.5rem 0.65rem;
263
align-items: center;
264
}
265
266
.seed-price-header {
267
padding: 0.25rem 0.4rem;
268
color: #a8a295;
269
font-size: 0.78rem;
270
text-transform: uppercase;
271
letter-spacing: 0.04em;
272
border-bottom: 1px solid #2c3340;
273
}
274
275
.seed-price-list {
276
display: flex;
277
flex-direction: column;
278
gap: 0.25rem;
279
}
280
281
.seed-price-row {
282
padding: 0.4rem;
283
border-radius: 4px;
284
}
285
286
.seed-price-row.dirty {
287
background: #4a3d18;
288
box-shadow: inset 0 0 0 1px #c4a35a;
289
}
290
291
.seed-price-name {
292
display: flex;
293
flex-direction: column;
294
gap: 0.1rem;
295
min-width: 0;
296
}
297
298
.seed-price-name strong {
299
overflow: hidden;
300
text-overflow: ellipsis;
301
white-space: nowrap;
302
}
303
304
.seed-price-name small {
305
color: #8b8790;
306
font-size: 0.75rem;
307
}
308
309
.seed-price-seed {
310
display: flex;
311
flex-direction: column;
312
gap: 0.15rem;
313
font-size: 0.75rem;
314
color: #a8a295;
315
}
316
317
.seed-price-seed input {
318
width: 100%;
319
padding: 0.3rem 0.4rem;
320
background: #10141b;
321
border: 1px solid #3a4250;
322
color: #e8e4d9;
323
font: inherit;
324
}
325
326
.seed-price-readonly {
327
display: flex;
328
flex-direction: column;
329
gap: 0.15rem;
330
font-size: 0.75rem;
331
color: #a8a295;
332
}
333
334
.seed-price-readonly strong {
335
font-size: 0.95rem;
336
color: #e8e4d9;
337
font-variant-numeric: tabular-nums;
338
}
339
340
.seed-price-readonly strong.muted {
341
color: #6d6875;
342
}
343
208
344
#settings-log-wrap {
209
345
width: min(340px, 32vw);
210
346
flex-shrink: 0;
@@ -251,10 +387,11 @@ label { display: block; margin: 0.4rem 0; }
251
387
}
252
388
253
389
#tile-config-modal {
254
top: 20vh;
390
top: 10vh;
255
391
left: 50%;
256
392
transform: translateX(-50%);
257
width: min(420px, 90vw);
393
width: min(440px, 92vw);
394
max-height: 80vh;
258
395
}
259
396
260
397
#palette-modal[hidden],
@@ -326,6 +463,101 @@ label { display: block; margin: 0.4rem 0; }
326
463
display: flex;
327
464
flex-direction: column;
328
465
gap: 0.35rem;
466
flex: 1;
467
min-height: 0;
468
overflow: auto;
469
}
470
471
.spawner-sells-header {
472
display: flex;
473
align-items: center;
474
justify-content: space-between;
475
gap: 0.5rem;
476
margin-top: 0.55rem;
477
}
478
479
.spawner-sells-list {
480
display: flex;
481
flex-direction: column;
482
gap: 0.35rem;
483
}
484
485
.spawner-sells-row {
486
display: grid;
487
grid-template-columns: 1fr 4.5rem auto;
488
gap: 0.4rem;
489
align-items: center;
490
}
491
492
.spawner-sells-name {
493
overflow: hidden;
494
text-overflow: ellipsis;
495
white-space: nowrap;
496
}
497
498
.spawner-buys-row {
499
display: flex;
500
align-items: center;
501
gap: 0.4rem;
502
margin-top: 0.45rem;
503
}
504
505
#shop-item-search-backdrop {
506
position: fixed;
507
inset: 0;
508
background: rgba(0, 0, 0, 0.55);
509
z-index: 21;
510
}
511
512
#shop-item-search-modal {
513
position: fixed;
514
z-index: 22;
515
top: 18vh;
516
left: 50%;
517
transform: translateX(-50%);
518
width: min(380px, 90vw);
519
max-height: 60vh;
520
display: flex;
521
flex-direction: column;
522
background: #161a22;
523
border: 1px solid #3a4250;
524
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
525
}
526
527
#shop-item-search-modal[hidden],
528
#shop-item-search-backdrop[hidden] {
529
display: none !important;
530
}
531
532
#shop-item-search-modal > header {
533
display: flex;
534
align-items: center;
535
justify-content: space-between;
536
gap: 0.75rem;
537
padding: 0.75rem 1rem;
538
border-bottom: 1px solid #2c3340;
539
}
540
541
#shop-item-search-modal > .shop-item-search-body {
542
padding: 0.75rem 1rem 1rem;
543
display: flex;
544
flex-direction: column;
545
gap: 0.5rem;
546
min-height: 0;
547
overflow: hidden;
548
}
549
550
#shop-item-search-results {
551
overflow: auto;
552
max-height: 40vh;
553
display: flex;
554
flex-direction: column;
555
gap: 0.25rem;
556
}
557
558
.shop-item-search-row {
559
text-align: left;
560
padding: 0.4rem 0.5rem;
329
561
}
330
562
331
563
#tile-tooltip {
@@ -205,6 +205,142 @@ label { display: block; margin: 0.4rem 0; }205
color: #c5c0b4;205
color: #c5c0b4;206
}206
}207
207
208
.seed-price-panel {209
display: flex;210
flex-direction: column;211
gap: 0.65rem;212
min-height: 0;213
}214
215
.seed-price-toolbar {216
display: flex;217
flex-wrap: wrap;218
gap: 0.55rem 0.75rem;219
align-items: center;220
}221
222
.seed-price-search {223
flex: 1 1 12rem;224
min-width: 10rem;225
padding: 0.4rem 0.55rem;226
background: #10141b;227
border: 1px solid #3a4250;228
color: #e8e4d9;229
font: inherit;230
}231
232
.seed-price-meta {233
flex: 0 0 auto;234
}235
236
.seed-price-pager {237
display: flex;238
align-items: center;239
gap: 0.45rem;240
margin-left: auto;241
}242
243
.seed-price-pager button {244
appearance: none;245
border: 1px solid #3a4250;246
background: #1c222c;247
color: #e8e4d9;248
padding: 0.3rem 0.55rem;249
cursor: pointer;250
font: inherit;251
}252
253
.seed-price-pager button:disabled {254
opacity: 0.4;255
cursor: default;256
}257
258
.seed-price-header,259
.seed-price-row {260
display: grid;261
grid-template-columns: minmax(10rem, 1.6fr) 6.5rem 5.5rem 5.5rem;262
gap: 0.5rem 0.65rem;263
align-items: center;264
}265
266
.seed-price-header {267
padding: 0.25rem 0.4rem;268
color: #a8a295;269
font-size: 0.78rem;270
text-transform: uppercase;271
letter-spacing: 0.04em;272
border-bottom: 1px solid #2c3340;273
}274
275
.seed-price-list {276
display: flex;277
flex-direction: column;278
gap: 0.25rem;279
}280
281
.seed-price-row {282
padding: 0.4rem;283
border-radius: 4px;284
}285
286
.seed-price-row.dirty {287
background: #4a3d18;288
box-shadow: inset 0 0 0 1px #c4a35a;289
}290
291
.seed-price-name {292
display: flex;293
flex-direction: column;294
gap: 0.1rem;295
min-width: 0;296
}297
298
.seed-price-name strong {299
overflow: hidden;300
text-overflow: ellipsis;301
white-space: nowrap;302
}303
304
.seed-price-name small {305
color: #8b8790;306
font-size: 0.75rem;307
}308
309
.seed-price-seed {310
display: flex;311
flex-direction: column;312
gap: 0.15rem;313
font-size: 0.75rem;314
color: #a8a295;315
}316
317
.seed-price-seed input {318
width: 100%;319
padding: 0.3rem 0.4rem;320
background: #10141b;321
border: 1px solid #3a4250;322
color: #e8e4d9;323
font: inherit;324
}325
326
.seed-price-readonly {327
display: flex;328
flex-direction: column;329
gap: 0.15rem;330
font-size: 0.75rem;331
color: #a8a295;332
}333
334
.seed-price-readonly strong {335
font-size: 0.95rem;336
color: #e8e4d9;337
font-variant-numeric: tabular-nums;338
}339
340
.seed-price-readonly strong.muted {341
color: #6d6875;342
}343
208
#settings-log-wrap {344
#settings-log-wrap {209
width: min(340px, 32vw);345
width: min(340px, 32vw);210
flex-shrink: 0;346
flex-shrink: 0;@@ -251,10 +387,11 @@ label { display: block; margin: 0.4rem 0; }251
}387
}252
388
253
#tile-config-modal {389
#tile-config-modal {254
top: 20vh;390
top: 10vh;255
left: 50%;391
left: 50%;256
transform: translateX(-50%);392
transform: translateX(-50%);257
width: min(420px, 90vw);393
width: min(440px, 92vw);394
max-height: 80vh;258
}395
}259
396
260
#palette-modal[hidden],397
#palette-modal[hidden],@@ -326,6 +463,101 @@ label { display: block; margin: 0.4rem 0; }326
display: flex;463
display: flex;327
flex-direction: column;464
flex-direction: column;328
gap: 0.35rem;465
gap: 0.35rem;466
flex: 1;467
min-height: 0;468
overflow: auto;469
}470
471
.spawner-sells-header {472
display: flex;473
align-items: center;474
justify-content: space-between;475
gap: 0.5rem;476
margin-top: 0.55rem;477
}478
479
.spawner-sells-list {480
display: flex;481
flex-direction: column;482
gap: 0.35rem;483
}484
485
.spawner-sells-row {486
display: grid;487
grid-template-columns: 1fr 4.5rem auto;488
gap: 0.4rem;489
align-items: center;490
}491
492
.spawner-sells-name {493
overflow: hidden;494
text-overflow: ellipsis;495
white-space: nowrap;496
}497
498
.spawner-buys-row {499
display: flex;500
align-items: center;501
gap: 0.4rem;502
margin-top: 0.45rem;503
}504
505
#shop-item-search-backdrop {506
position: fixed;507
inset: 0;508
background: rgba(0, 0, 0, 0.55);509
z-index: 21;510
}511
512
#shop-item-search-modal {513
position: fixed;514
z-index: 22;515
top: 18vh;516
left: 50%;517
transform: translateX(-50%);518
width: min(380px, 90vw);519
max-height: 60vh;520
display: flex;521
flex-direction: column;522
background: #161a22;523
border: 1px solid #3a4250;524
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);525
}526
527
#shop-item-search-modal[hidden],528
#shop-item-search-backdrop[hidden] {529
display: none !important;530
}531
532
#shop-item-search-modal > header {533
display: flex;534
align-items: center;535
justify-content: space-between;536
gap: 0.75rem;537
padding: 0.75rem 1rem;538
border-bottom: 1px solid #2c3340;539
}540
541
#shop-item-search-modal > .shop-item-search-body {542
padding: 0.75rem 1rem 1rem;543
display: flex;544
flex-direction: column;545
gap: 0.5rem;546
min-height: 0;547
overflow: hidden;548
}549
550
#shop-item-search-results {551
overflow: auto;552
max-height: 40vh;553
display: flex;554
flex-direction: column;555
gap: 0.25rem;556
}557
558
.shop-item-search-row {559
text-align: left;560
padding: 0.4rem 0.5rem;329
}561
}330
562
331
#tile-tooltip {563
#tile-tooltip {@@ -52,6 +52,24 @@ html, body {
52
52
width: max-content;
53
53
}
54
54
55
#world-tooltip {
56
position: fixed;
57
z-index: 11;
58
pointer-events: none;
59
max-width: 14rem;
60
padding: 0.3rem 0.5rem;
61
background: rgba(12, 14, 18, 0.92);
62
border: 1px solid #3a4250;
63
color: #e8e4d9;
64
font-size: 0.8rem;
65
line-height: 1.25;
66
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.4);
67
}
68
69
#world-tooltip[hidden] {
70
display: none !important;
71
}
72
55
73
.toast {
56
74
box-sizing: border-box;
57
75
width: 100%;
@@ -818,8 +836,14 @@ a { color: #d4c48a; }
818
836
#cauldron-backdrop[hidden],
819
837
#cauldron-pick-panel[hidden],
820
838
#cauldron-pick-backdrop[hidden],
839
#shop-panel[hidden],
840
#shop-backdrop[hidden],
841
#shop-qty-panel[hidden],
842
#shop-qty-backdrop[hidden],
821
843
#nametag[hidden],
822
#chat-bar[hidden] {
844
#chat-bar[hidden],
845
.shop-detail[hidden],
846
.shop-bag-warn[hidden] {
823
847
display: none !important;
824
848
}
825
849
@@ -914,9 +938,10 @@ a { color: #d4c48a; }
914
938
top: 50%;
915
939
left: 50%;
916
940
transform: translate(-50%, -50%);
917
width: min(420px, 92vw);
918
max-height: min(70vh, 520px);
919
overflow: auto;
941
width: min(560px, 94vw);
942
max-height: min(75vh, 560px);
943
display: flex;
944
flex-direction: column;
920
945
background: #1a1e26;
921
946
border: 1px solid #2c3340;
922
947
padding: 0.75rem 1rem 1rem;
@@ -930,31 +955,152 @@ a { color: #d4c48a; }
930
955
margin-bottom: 0.75rem;
931
956
}
932
957
933
.shop-stock {
934
display: flex;
935
flex-direction: column;
936
gap: 0.5rem;
958
.shop-body {
959
display: grid;
960
grid-template-columns: 1fr minmax(180px, 42%);
961
gap: 0.85rem;
962
min-height: 0;
963
flex: 1;
964
overflow: hidden;
937
965
}
938
966
939
.shop-row {
967
.shop-grid {
940
968
display: grid;
941
grid-template-columns: 32px 1fr auto;
942
gap: 0.65rem;
943
align-items: center;
944
padding: 0.35rem 0.25rem;
945
border-bottom: 1px solid #2c3340;
969
grid-template-columns: repeat(auto-fill, minmax(40px, 1fr));
970
gap: 0.35rem;
971
align-content: start;
972
overflow: auto;
973
padding: 0.15rem;
974
min-height: 120px;
975
max-height: min(50vh, 360px);
976
}
977
978
.shop-cell {
979
width: 40px;
980
height: 40px;
981
padding: 0;
982
display: grid;
983
place-items: center;
984
background: #12151c;
985
border: 1px solid #2c3340;
986
cursor: pointer;
946
987
}
947
988
948
.shop-row img {
989
.shop-cell.selected {
990
border-color: #8ab4ff;
991
box-shadow: inset 0 0 0 1px #8ab4ff;
992
}
993
994
.shop-cell img {
949
995
width: 32px;
950
996
height: 32px;
951
997
image-rendering: pixelated;
952
998
}
953
999
954
.shop-row-meta {
1000
.shop-detail {
955
1001
display: flex;
956
1002
flex-direction: column;
957
gap: 0.15rem;
1003
gap: 0.4rem;
1004
align-items: flex-start;
1005
padding: 0.35rem 0.15rem;
1006
border-left: 1px solid #2c3340;
1007
padding-left: 0.85rem;
1008
min-width: 0;
1009
}
1010
1011
.shop-detail img {
1012
width: 48px;
1013
height: 48px;
1014
image-rendering: pixelated;
1015
}
1016
1017
.shop-buy-row {
1018
display: flex;
1019
flex-wrap: wrap;
1020
gap: 0.35rem;
1021
margin-top: 0.25rem;
1022
}
1023
1024
.shop-bag-warn {
1025
margin: 0.35rem 0 0;
1026
color: #e6b35a;
1027
font-size: 0.85rem;
1028
line-height: 1.3;
1029
}
1030
1031
.shop-coins {
1032
margin: 0.75rem 0 0;
1033
padding-top: 0.55rem;
1034
border-top: 1px solid #2c3340;
1035
font-weight: 600;
1036
}
1037
1038
.shop-sell-section {
1039
margin-top: 0.75rem;
1040
padding-top: 0.55rem;
1041
border-top: 1px solid #2c3340;
1042
display: flex;
1043
flex-direction: column;
1044
gap: 0.4rem;
1045
}
1046
1047
.shop-sell-list {
1048
display: flex;
1049
flex-direction: column;
1050
gap: 0.3rem;
1051
max-height: 8rem;
1052
overflow: auto;
1053
}
1054
1055
.shop-sell-row {
1056
display: flex;
1057
align-items: center;
1058
justify-content: space-between;
1059
gap: 0.5rem;
1060
width: 100%;
1061
text-align: left;
1062
background: transparent;
1063
border: 1px solid transparent;
1064
color: inherit;
1065
padding: 0.2rem 0.35rem;
1066
cursor: pointer;
1067
}
1068
1069
.shop-sell-row.selected {
1070
border-color: #4a5568;
1071
background: #222833;
1072
}
1073
1074
.shop-sell-detail {
1075
display: flex;
1076
flex-direction: column;
1077
align-items: flex-start;
1078
gap: 0.25rem;
1079
margin-top: 0.35rem;
1080
}
1081
1082
#shop-qty-panel {
1083
position: fixed;
1084
z-index: 7;
1085
top: 50%;
1086
left: 50%;
1087
transform: translate(-50%, -50%);
1088
width: min(320px, 92vw);
1089
background: #1a1e26;
1090
border: 1px solid #2c3340;
1091
padding: 0.75rem 1rem 1rem;
1092
}
1093
1094
#shop-qty-panel header {
1095
display: flex;
1096
justify-content: space-between;
1097
align-items: center;
1098
gap: 0.75rem;
1099
margin-bottom: 0.75rem;
1100
}
1101
1102
#shop-qty-backdrop {
1103
z-index: 7;
958
1104
}
959
1105
960
1106
.chat-bubble {
@@ -52,6 +52,24 @@ html, body {52
width: max-content;52
width: max-content;53
}53
}54
54
55
#world-tooltip {56
position: fixed;57
z-index: 11;58
pointer-events: none;59
max-width: 14rem;60
padding: 0.3rem 0.5rem;61
background: rgba(12, 14, 18, 0.92);62
border: 1px solid #3a4250;63
color: #e8e4d9;64
font-size: 0.8rem;65
line-height: 1.25;66
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.4);67
}68
69
#world-tooltip[hidden] {70
display: none !important;71
}72
55
.toast {73
.toast {56
box-sizing: border-box;74
box-sizing: border-box;57
width: 100%;75
width: 100%;@@ -818,8 +836,14 @@ a { color: #d4c48a; }818
#cauldron-backdrop[hidden],836
#cauldron-backdrop[hidden],819
#cauldron-pick-panel[hidden],837
#cauldron-pick-panel[hidden],820
#cauldron-pick-backdrop[hidden],838
#cauldron-pick-backdrop[hidden],839
#shop-panel[hidden],840
#shop-backdrop[hidden],841
#shop-qty-panel[hidden],842
#shop-qty-backdrop[hidden],821
#nametag[hidden],843
#nametag[hidden],822
#chat-bar[hidden] {844
#chat-bar[hidden],845
.shop-detail[hidden],846
.shop-bag-warn[hidden] {823
display: none !important;847
display: none !important;824
}848
}825
849
@@ -914,9 +938,10 @@ a { color: #d4c48a; }914
top: 50%;938
top: 50%;915
left: 50%;939
left: 50%;916
transform: translate(-50%, -50%);940
transform: translate(-50%, -50%);917
width: min(420px, 92vw);941
width: min(560px, 94vw);918
max-height: min(70vh, 520px);942
max-height: min(75vh, 560px);919
overflow: auto;943
display: flex;944
flex-direction: column;920
background: #1a1e26;945
background: #1a1e26;921
border: 1px solid #2c3340;946
border: 1px solid #2c3340;922
padding: 0.75rem 1rem 1rem;947
padding: 0.75rem 1rem 1rem;@@ -930,31 +955,152 @@ a { color: #d4c48a; }930
margin-bottom: 0.75rem;955
margin-bottom: 0.75rem;931
}956
}932
957
933
.shop-stock {958
.shop-body {934
display: flex;959
display: grid;935
flex-direction: column;960
grid-template-columns: 1fr minmax(180px, 42%);936
gap: 0.5rem;961
gap: 0.85rem;962
min-height: 0;963
flex: 1;964
overflow: hidden;937
}965
}938
966
939
.shop-row {967
.shop-grid {940
display: grid;968
display: grid;941
grid-template-columns: 32px 1fr auto;969
grid-template-columns: repeat(auto-fill, minmax(40px, 1fr));942
gap: 0.65rem;970
gap: 0.35rem;943
align-items: center;971
align-content: start;944
padding: 0.35rem 0.25rem;972
overflow: auto;945
border-bottom: 1px solid #2c3340;973
padding: 0.15rem;974
min-height: 120px;975
max-height: min(50vh, 360px);976
}977
978
.shop-cell {979
width: 40px;980
height: 40px;981
padding: 0;982
display: grid;983
place-items: center;984
background: #12151c;985
border: 1px solid #2c3340;986
cursor: pointer;946
}987
}947
988
948
.shop-row img {989
.shop-cell.selected {990
border-color: #8ab4ff;991
box-shadow: inset 0 0 0 1px #8ab4ff;992
}993
994
.shop-cell img {949
width: 32px;995
width: 32px;950
height: 32px;996
height: 32px;951
image-rendering: pixelated;997
image-rendering: pixelated;952
}998
}953
999
954
.shop-row-meta {1000
.shop-detail {955
display: flex;1001
display: flex;956
flex-direction: column;1002
flex-direction: column;957
gap: 0.15rem;1003
gap: 0.4rem;1004
align-items: flex-start;1005
padding: 0.35rem 0.15rem;1006
border-left: 1px solid #2c3340;1007
padding-left: 0.85rem;1008
min-width: 0;1009
}1010
1011
.shop-detail img {1012
width: 48px;1013
height: 48px;1014
image-rendering: pixelated;1015
}1016
1017
.shop-buy-row {1018
display: flex;1019
flex-wrap: wrap;1020
gap: 0.35rem;1021
margin-top: 0.25rem;1022
}1023
1024
.shop-bag-warn {1025
margin: 0.35rem 0 0;1026
color: #e6b35a;1027
font-size: 0.85rem;1028
line-height: 1.3;1029
}1030
1031
.shop-coins {1032
margin: 0.75rem 0 0;1033
padding-top: 0.55rem;1034
border-top: 1px solid #2c3340;1035
font-weight: 600;1036
}1037
1038
.shop-sell-section {1039
margin-top: 0.75rem;1040
padding-top: 0.55rem;1041
border-top: 1px solid #2c3340;1042
display: flex;1043
flex-direction: column;1044
gap: 0.4rem;1045
}1046
1047
.shop-sell-list {1048
display: flex;1049
flex-direction: column;1050
gap: 0.3rem;1051
max-height: 8rem;1052
overflow: auto;1053
}1054
1055
.shop-sell-row {1056
display: flex;1057
align-items: center;1058
justify-content: space-between;1059
gap: 0.5rem;1060
width: 100%;1061
text-align: left;1062
background: transparent;1063
border: 1px solid transparent;1064
color: inherit;1065
padding: 0.2rem 0.35rem;1066
cursor: pointer;1067
}1068
1069
.shop-sell-row.selected {1070
border-color: #4a5568;1071
background: #222833;1072
}1073
1074
.shop-sell-detail {1075
display: flex;1076
flex-direction: column;1077
align-items: flex-start;1078
gap: 0.25rem;1079
margin-top: 0.35rem;1080
}1081
1082
#shop-qty-panel {1083
position: fixed;1084
z-index: 7;1085
top: 50%;1086
left: 50%;1087
transform: translate(-50%, -50%);1088
width: min(320px, 92vw);1089
background: #1a1e26;1090
border: 1px solid #2c3340;1091
padding: 0.75rem 1rem 1rem;1092
}1093
1094
#shop-qty-panel header {1095
display: flex;1096
justify-content: space-between;1097
align-items: center;1098
gap: 0.75rem;1099
margin-bottom: 0.75rem;1100
}1101
1102
#shop-qty-backdrop {1103
z-index: 7;958
}1104
}959
1105
960
.chat-bubble {1106
.chat-bubble {@@ -52,13 +52,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
52
52
## World settings
53
53
54
54
**Status:** full
55
**Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
56
**Code:** `shared/definitions/worldSettings.js`, `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
55
**Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
56
**Code:** `shared/definitions/worldSettings.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
57
57
58
58
## Baked lighting
59
59
60
60
**Status:** full
61
**Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through passable tiles, including across chunk borders. Store a 16×16 intensity map (0–255, smoothstep falloff by tile distance). Torch range is 8 tiles.
61
**Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through passable tiles, including across chunk borders. Store a 16×16 intensity map (0–255, smoothstep falloff by tile distance). Torch range is 8 tiles; furnace is 4.
62
62
**Code:** `server/src/lighting/baker.js`, tests in `server/tests/lighting.test.js`
63
63
64
64
## World editor (server)
@@ -178,7 +178,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
178
178
## Spawners
179
179
180
180
**Status:** full
181
**Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include deer and rats; the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked; courier pigeons cannot.
181
**Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include deer and rats; the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked (retaliate on first swing); **rats are aggressive** and auto-engage players within 5 tiles with line of sight.; courier pigeons cannot.
182
182
**Code:** `server/src/simulation/spawners.js`, `server/src/simulation/workerWorld.js`, `server/src/world/chunkData.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
183
183
184
184
## Mob definitions (content schema)
@@ -208,8 +208,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
208
208
## Combat, skills, groups, pigeons
209
209
210
210
**Status:** partial
211
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs retaliate when attacked and keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
212
**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
211
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
212
**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
213
213
214
214
## Player death and respawn
215
215
@@ -228,23 +228,23 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
228
228
## Equipment tiers and worn stat bonuses
229
229
230
230
**Status:** partial
231
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; trees/axes later — logs may be bought from NPC shops for now.
232
**Shared sprites + magenta tint:** one base sprite per shape (ore, bar, pickaxe, log, handle, boulder-ore); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint.
233
**TODO:** full combat gear catalog; tree nodes / woodcutting gather; tooltips.
231
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; trees later — axe sprites (`items/axe`) match pickaxe style for woodcutting; logs may be bought from NPC shops for now.
232
**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), and boulder-ore; tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint.
233
**TODO:** full combat gear catalog; tree nodes / woodcutting gather; silver/gold jewelry / other precious recipes.
234
234
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
235
235
236
236
## Gathering, crafting, and production skills
237
237
238
**Status:** partial (mining + smelting + pickaxe craft chain live)
239
**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX. Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper and **steel** = 1 iron ore + 1 coal. Smithing XP on success. **Pickaxe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head; woodworking assembles matching-tier handle + head → pickaxe (pine↔bronze … elder↔dragon). Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. Woodcutting trees / fishing / other stations later.
240
**Code:** `shared/definitions/gathering.js`, `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/crafting.test.js`
238
**Status:** partial (mining + smelting + pickaxe/axe craft chains live)
239
**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore node shows a cursor tooltip with the resource name (`resourceNodeDisplayName` — ores today; trees / fishing / herbs later). **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. Woodcutting trees / fishing / other stations later.
240
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/crafting.test.js`
241
241
242
242
## Crafting stations
243
243
244
**Status:** partial (furnace, anvil, woodworking bench live; UI shell for others)
245
**Spec:** Furnace / anvil / woodworking-bench blocks (anvil & woodworking use furnace placeholder art for now) + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`).
246
**TODO:** oven/campfire burn, spinning wheel once sheep exist; dedicated anvil/woodworking sprites.
247
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace` / `anvil` / `woodworkingBench`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
244
**Status:** partial (furnace, anvil, woodworking bench, crafting bench live; UI shell for others)
245
**Spec:** Furnace / anvil / woodworking-bench / crafting-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle).
246
**TODO:** oven/campfire burn, spinning wheel once sheep exist; dedicated station sprites where still placeholder.
247
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace` / `anvil` / `woodworkingBench` / `craftingBench`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
248
248
249
249
## Stamina and running
250
250
@@ -294,7 +294,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
294
294
## Banking, cheques, shops, player-driven marketplace
295
295
296
296
**Status:** partial (banks/cheques/origins live; NPC shops sell stock; player marketplace UI later)
297
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment slots, `sells[]`, hidden discount) spawn talkable shopkeepers using player body sprites + equipment overlays. Interact / Trade opens a buy panel; prices use `seedValue` with market last-sale lerp × discount (`shared/shop/pricing.js`). Buying stamps shop origin. Player marketplace order book remains later; marketplace sell rules for cheques are already enforced in shared item definitions.
297
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 UTC** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. Player marketplace remains later.
298
298
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
299
299
300
300
## Player scripting hooks
@@ -52,13 +52,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi52
## World settings52
## World settings53
53
54
**Status:** full 54
**Status:** full 55
**Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist. 55
**Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist. 56
**Code:** `shared/definitions/worldSettings.js`, `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`56
**Code:** `shared/definitions/worldSettings.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`57
57
58
## Baked lighting58
## Baked lighting59
59
60
**Status:** full 60
**Status:** full 61
**Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through passable tiles, including across chunk borders. Store a 16×16 intensity map (0–255, smoothstep falloff by tile distance). Torch range is 8 tiles. 61
**Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through passable tiles, including across chunk borders. Store a 16×16 intensity map (0–255, smoothstep falloff by tile distance). Torch range is 8 tiles; furnace is 4. 62
**Code:** `server/src/lighting/baker.js`, tests in `server/tests/lighting.test.js`62
**Code:** `server/src/lighting/baker.js`, tests in `server/tests/lighting.test.js`63
63
64
## World editor (server)64
## World editor (server)@@ -178,7 +178,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi178
## Spawners178
## Spawners179
179
180
**Status:** full 180
**Status:** full 181
**Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include deer and rats; the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked; courier pigeons cannot. 181
**Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include deer and rats; the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked (retaliate on first swing); **rats are aggressive** and auto-engage players within 5 tiles with line of sight.; courier pigeons cannot. 182
**Code:** `server/src/simulation/spawners.js`, `server/src/simulation/workerWorld.js`, `server/src/world/chunkData.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`182
**Code:** `server/src/simulation/spawners.js`, `server/src/simulation/workerWorld.js`, `server/src/world/chunkData.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`183
183
184
## Mob definitions (content schema)184
## Mob definitions (content schema)@@ -208,8 +208,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi208
## Combat, skills, groups, pigeons208
## Combat, skills, groups, pigeons209
209
210
**Status:** partial 210
**Status:** partial 211
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs retaliate when attacked and keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later. 211
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later. 212
**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)212
**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)213
213
214
## Player death and respawn214
## Player death and respawn215
215
@@ -228,23 +228,23 @@ Each entry is a short note on behaviour and where the code lives. Update this fi228
## Equipment tiers and worn stat bonuses228
## Equipment tiers and worn stat bonuses229
229
230
**Status:** partial 230
**Status:** partial 231
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; trees/axes later — logs may be bought from NPC shops for now. 231
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; trees later — axe sprites (`items/axe`) match pickaxe style for woodcutting; logs may be bought from NPC shops for now. 232
**Shared sprites + magenta tint:** one base sprite per shape (ore, bar, pickaxe, log, handle, boulder-ore); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. 232
**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), and boulder-ore; tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. 233
**TODO:** full combat gear catalog; tree nodes / woodcutting gather; tooltips. 233
**TODO:** full combat gear catalog; tree nodes / woodcutting gather; silver/gold jewelry / other precious recipes. 234
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`234
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`235
235
236
## Gathering, crafting, and production skills236
## Gathering, crafting, and production skills237
237
238
**Status:** partial (mining + smelting + pickaxe craft chain live) 238
**Status:** partial (mining + smelting + pickaxe/axe craft chains live) 239
**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX. Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper and **steel** = 1 iron ore + 1 coal. Smithing XP on success. **Pickaxe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head; woodworking assembles matching-tier handle + head → pickaxe (pine↔bronze … elder↔dragon). Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. Woodcutting trees / fishing / other stations later.239
**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore node shows a cursor tooltip with the resource name (`resourceNodeDisplayName` — ores today; trees / fishing / herbs later). **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. Woodcutting trees / fishing / other stations later.240
**Code:** `shared/definitions/gathering.js`, `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/crafting.test.js`240
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/crafting.test.js`241
241
242
## Crafting stations242
## Crafting stations243
243
244
**Status:** partial (furnace, anvil, woodworking bench live; UI shell for others) 244
**Status:** partial (furnace, anvil, woodworking bench, crafting bench live; UI shell for others) 245
**Spec:** Furnace / anvil / woodworking-bench blocks (anvil & woodworking use furnace placeholder art for now) + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). 245
**Spec:** Furnace / anvil / woodworking-bench / crafting-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). 246
**TODO:** oven/campfire burn, spinning wheel once sheep exist; dedicated anvil/woodworking sprites. 246
**TODO:** oven/campfire burn, spinning wheel once sheep exist; dedicated station sprites where still placeholder. 247
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace` / `anvil` / `woodworkingBench`), `server/src/crafting/service.js`, `client/src/play/crafting.js`247
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace` / `anvil` / `woodworkingBench` / `craftingBench`), `server/src/crafting/service.js`, `client/src/play/crafting.js`248
248
249
## Stamina and running249
## Stamina and running250
250
@@ -294,7 +294,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi294
## Banking, cheques, shops, player-driven marketplace294
## Banking, cheques, shops, player-driven marketplace295
295
296
**Status:** partial (banks/cheques/origins live; NPC shops sell stock; player marketplace UI later) 296
**Status:** partial (banks/cheques/origins live; NPC shops sell stock; player marketplace UI later) 297
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment slots, `sells[]`, hidden discount) spawn talkable shopkeepers using player body sprites + equipment overlays. Interact / Trade opens a buy panel; prices use `seedValue` with market last-sale lerp × discount (`shared/shop/pricing.js`). Buying stamps shop origin. Player marketplace order book remains later; marketplace sell rules for cheques are already enforced in shared item definitions. 297
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 UTC** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. Player marketplace remains later. 298
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`298
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`299
299
300
## Player scripting hooks300
## Player scripting hooks@@ -161,7 +161,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
161
161
const state = oreBoulderState(material);
162
162
if (!states.includes(state))
163
163
{ states.push(state); }
164
const tint = materialTintColor(material);
164
const tint = materialTintColor(material, { ore: true });
165
165
imagesForType.push({
166
166
name: spriteImageName(layer, def.key, state),
167
167
url: `/assets/${urlFolder}/${def.key}/boulder-ore.png`,
@@ -161,7 +161,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)161
const state = oreBoulderState(material);161
const state = oreBoulderState(material);162
if (!states.includes(state))162
if (!states.includes(state))163
{ states.push(state); }163
{ states.push(state); }164
const tint = materialTintColor(material);164
const tint = materialTintColor(material, { ore: true });165
imagesForType.push({165
imagesForType.push({166
name: spriteImageName(layer, def.key, state),166
name: spriteImageName(layer, def.key, state),167
url: `/assets/${urlFolder}/${def.key}/boulder-ore.png`,167
url: `/assets/${urlFolder}/${def.key}/boulder-ore.png`,@@ -4,7 +4,9 @@ import { mobDefinition } from "../../../shared/definitions/mobs.js";
4
4
import {
5
5
mobCanFightType,
6
6
mobMeleeAttackProfile,
7
mobSkillLevels
7
mobSkillLevels,
8
mobIsAggressive,
9
mobAggroRangeTiles
8
10
} from "../../../shared/definitions/mobCombat.js";
9
11
import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
10
12
import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
@@ -15,6 +17,7 @@ import {
15
17
import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
16
18
import { chunkBoundsAround, findPath } from "../navigation/astar.js";
17
19
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
20
import { rayReaches } from "../../../shared/lighting/raycast.js";
18
21
19
22
export function chebyshev (ax, ay, bx, by)
20
23
{
@@ -119,6 +122,73 @@ export function clearEngage (ecs, entityId)
119
122
{ combat.targetEntityId = null; }
120
123
}
121
124
125
export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
126
{
127
return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));
128
}
129
130
/**
131
* Aggressive mobs auto-engage the nearest player character within aggro range
132
* when they have line of sight. Does nothing while already engaged.
133
*/
134
export function stepAggression (world, now = Date.now())
135
{
136
for (const entity of world.ecs.query(Component.creature, Component.position))
137
{
138
if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))
139
{ continue; }
140
const def = mobDefinition(entity.creature.mobTypeId);
141
if (!mobIsAggressive(def))
142
{ continue; }
143
if (world.ecs.has(entity.handle, Component.dead))
144
{ continue; }
145
const health = world.ecs.get(entity.handle, Component.health);
146
if (health && health.current <= 0)
147
{ continue; }
148
const combat = world.ecs.get(entity.handle, Component.combat);
149
if (combat?.targetEntityId != null)
150
{ continue; }
151
152
const range = mobAggroRangeTiles(def);
153
let bestId = null;
154
let bestDist = Infinity;
155
for (const player of world.ecs.query(Component.character, Component.position))
156
{
157
if (world.ecs.has(player.handle, Component.dead))
158
{ continue; }
159
const playerHealth = world.ecs.get(player.handle, Component.health);
160
if (playerHealth && playerHealth.current <= 0)
161
{ continue; }
162
const dist = chebyshev(
163
entity.position.tileX,
164
entity.position.tileY,
165
player.position.tileX,
166
player.position.tileY
167
);
168
if (dist < 1 || dist > range)
169
{ continue; }
170
if (!hasCombatLineOfSight(
171
world,
172
entity.position.tileX,
173
entity.position.tileY,
174
player.position.tileX,
175
player.position.tileY
176
))
177
{ continue; }
178
if (dist < bestDist)
179
{
180
bestDist = dist;
181
bestId = player.entityId;
182
}
183
}
184
if (bestId == null)
185
{ continue; }
186
if (!ensureMobCombat(world.ecs, entity.entityId))
187
{ continue; }
188
engageTarget(world.ecs, entity.entityId, bestId, now);
189
}
190
}
191
122
192
/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
123
193
export function resolveCombatTarget (world, targetId)
124
194
{
@@ -426,6 +496,7 @@ function applyLocalMeleeHit (
426
496
if (attackerHandle != null)
427
497
{
428
498
const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
499
// Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
429
500
if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
430
501
{ engageTarget(world.ecs, targetId, attackerId, now); }
431
502
}
@@ -4,7 +4,9 @@ import { mobDefinition } from "../../../shared/definitions/mobs.js";4
import {4
import {5
mobCanFightType,5
mobCanFightType,6
mobMeleeAttackProfile,6
mobMeleeAttackProfile,7
mobSkillLevels7
mobSkillLevels,8
mobIsAggressive,9
mobAggroRangeTiles8
} from "../../../shared/definitions/mobCombat.js";10
} from "../../../shared/definitions/mobCombat.js";9
import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";11
import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";10
import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";12
import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";@@ -15,6 +17,7 @@ import {15
import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";17
import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";16
import { chunkBoundsAround, findPath } from "../navigation/astar.js";18
import { chunkBoundsAround, findPath } from "../navigation/astar.js";17
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";19
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";20
import { rayReaches } from "../../../shared/lighting/raycast.js";18
21
19
export function chebyshev (ax, ay, bx, by)22
export function chebyshev (ax, ay, bx, by)20
{23
{@@ -119,6 +122,73 @@ export function clearEngage (ecs, entityId)119
{ combat.targetEntityId = null; }122
{ combat.targetEntityId = null; }120
}123
}121
124
125
export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)126
{127
return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));128
}129
130
/**131
* Aggressive mobs auto-engage the nearest player character within aggro range132
* when they have line of sight. Does nothing while already engaged.133
*/134
export function stepAggression (world, now = Date.now())135
{136
for (const entity of world.ecs.query(Component.creature, Component.position))137
{138
if (!world.chunkIsSimulating?.(entity.position.tileX, entity.position.tileY))139
{ continue; }140
const def = mobDefinition(entity.creature.mobTypeId);141
if (!mobIsAggressive(def))142
{ continue; }143
if (world.ecs.has(entity.handle, Component.dead))144
{ continue; }145
const health = world.ecs.get(entity.handle, Component.health);146
if (health && health.current <= 0)147
{ continue; }148
const combat = world.ecs.get(entity.handle, Component.combat);149
if (combat?.targetEntityId != null)150
{ continue; }151
152
const range = mobAggroRangeTiles(def);153
let bestId = null;154
let bestDist = Infinity;155
for (const player of world.ecs.query(Component.character, Component.position))156
{157
if (world.ecs.has(player.handle, Component.dead))158
{ continue; }159
const playerHealth = world.ecs.get(player.handle, Component.health);160
if (playerHealth && playerHealth.current <= 0)161
{ continue; }162
const dist = chebyshev(163
entity.position.tileX,164
entity.position.tileY,165
player.position.tileX,166
player.position.tileY167
);168
if (dist < 1 || dist > range)169
{ continue; }170
if (!hasCombatLineOfSight(171
world,172
entity.position.tileX,173
entity.position.tileY,174
player.position.tileX,175
player.position.tileY176
))177
{ continue; }178
if (dist < bestDist)179
{180
bestDist = dist;181
bestId = player.entityId;182
}183
}184
if (bestId == null)185
{ continue; }186
if (!ensureMobCombat(world.ecs, entity.entityId))187
{ continue; }188
engageTarget(world.ecs, entity.entityId, bestId, now);189
}190
}191
122
/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */192
/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */123
export function resolveCombatTarget (world, targetId)193
export function resolveCombatTarget (world, targetId)124
{194
{@@ -426,6 +496,7 @@ function applyLocalMeleeHit (426
if (attackerHandle != null)496
if (attackerHandle != null)427
{497
{428
const attackerCharacter = world.ecs.get(attackerHandle, Component.character);498
const attackerCharacter = world.ecs.get(attackerHandle, Component.character);499
// Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.429
if (attackerCharacter && ensureMobCombat(world.ecs, targetId))500
if (attackerCharacter && ensureMobCombat(world.ecs, targetId))430
{ engageTarget(world.ecs, targetId, attackerId, now); }501
{ engageTarget(world.ecs, targetId, attackerId, now); }431
}502
}@@ -55,6 +55,8 @@ function stationBlockType (stationId)
55
55
{ return BlockType.anvil; }
56
56
if (stationId === CraftingStationId.woodworkingBench)
57
57
{ return BlockType.woodworkingBench; }
58
if (stationId === CraftingStationId.craftingBench)
59
{ return BlockType.craftingBench; }
58
60
return null;
59
61
}
60
62
@@ -55,6 +55,8 @@ function stationBlockType (stationId)55
{ return BlockType.anvil; }55
{ return BlockType.anvil; }56
if (stationId === CraftingStationId.woodworkingBench)56
if (stationId === CraftingStationId.woodworkingBench)57
{ return BlockType.woodworkingBench; }57
{ return BlockType.woodworkingBench; }58
if (stationId === CraftingStationId.craftingBench)59
{ return BlockType.craftingBench; }58
return null;60
return null;59
}61
}60
62
@@ -3,6 +3,7 @@ import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from
3
3
import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4
4
import { mobDefinition } from "../../../shared/definitions/mobs.js";
5
5
import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
6
import { shopHasInterface } from "../shop/service.js";
6
7
7
8
function bodySprite (sex)
8
9
{
@@ -83,7 +84,8 @@ export function publicEntityView (ecs, entityId)
83
84
mobTypeId: creature?.mobTypeId ?? null,
84
85
canFight: mob ? mobCanFight(mob) : !!character,
85
86
hostile: !!mob?.hostile,
86
talkable: !!mob?.talkable || !!ecs.get(handle, Component.shop)?.stock?.length,
87
talkable: !!mob?.talkable || shopHasInterface(ecs.get(handle, Component.shop)),
88
hasShop: shopHasInterface(ecs.get(handle, Component.shop)),
87
89
untargetable: !!mob?.untargetable,
88
90
freeFlight: !!mob?.freeFlight,
89
91
health: health ? health.current : undefined,
@@ -133,6 +135,7 @@ export function replicationSpawn (view)
133
135
canFight: !!view.canFight,
134
136
hostile: !!view.hostile,
135
137
talkable: !!view.talkable,
138
hasShop: !!view.hasShop,
136
139
untargetable: !!view.untargetable,
137
140
freeFlight: !!view.freeFlight,
138
141
health: view.health,
@@ -3,6 +3,7 @@ import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from3
import { spriteImageName } from "../../../shared/definitions/tileSprites.js";3
import { spriteImageName } from "../../../shared/definitions/tileSprites.js";4
import { mobDefinition } from "../../../shared/definitions/mobs.js";4
import { mobDefinition } from "../../../shared/definitions/mobs.js";5
import { mobCanFight } from "../../../shared/definitions/mobCombat.js";5
import { mobCanFight } from "../../../shared/definitions/mobCombat.js";6
import { shopHasInterface } from "../shop/service.js";6
7
7
function bodySprite (sex)8
function bodySprite (sex)8
{9
{@@ -83,7 +84,8 @@ export function publicEntityView (ecs, entityId)83
mobTypeId: creature?.mobTypeId ?? null,84
mobTypeId: creature?.mobTypeId ?? null,84
canFight: mob ? mobCanFight(mob) : !!character,85
canFight: mob ? mobCanFight(mob) : !!character,85
hostile: !!mob?.hostile,86
hostile: !!mob?.hostile,86
talkable: !!mob?.talkable || !!ecs.get(handle, Component.shop)?.stock?.length,87
talkable: !!mob?.talkable || shopHasInterface(ecs.get(handle, Component.shop)),88
hasShop: shopHasInterface(ecs.get(handle, Component.shop)),87
untargetable: !!mob?.untargetable,89
untargetable: !!mob?.untargetable,88
freeFlight: !!mob?.freeFlight,90
freeFlight: !!mob?.freeFlight,89
health: health ? health.current : undefined,91
health: health ? health.current : undefined,@@ -133,6 +135,7 @@ export function replicationSpawn (view)133
canFight: !!view.canFight,135
canFight: !!view.canFight,134
hostile: !!view.hostile,136
hostile: !!view.hostile,135
talkable: !!view.talkable,137
talkable: !!view.talkable,138
hasShop: !!view.hasShop,136
untargetable: !!view.untargetable,139
untargetable: !!view.untargetable,137
freeFlight: !!view.freeFlight,140
freeFlight: !!view.freeFlight,138
health: view.health,141
health: view.health,@@ -5,7 +5,10 @@ import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob,
5
5
import { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";
6
6
import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
7
7
import { closedNeighborEdges } from "../world/chunkFlags.js";
8
import { coerceSettingValue, diffSettings, allSettingFields } from "../../../shared/definitions/worldSettings.js";
8
import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js";
9
import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
10
import { itemDefinition } from "../../../shared/definitions/items.js";
11
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
9
12
10
13
export class EditorService
11
14
{
@@ -100,7 +103,14 @@ export class EditorService
100
103
saveSettings (partial, editorAdminId)
101
104
{
102
105
const current = this.worldDb.getLiveSettings();
103
const next = { ...current };
106
const next = {
107
...current,
108
itemSeedValues: {
109
...(current.itemSeedValues && typeof current.itemSeedValues === "object"
110
? current.itemSeedValues
111
: {})
112
}
113
};
104
114
for (const field of allSettingFields())
105
115
{
106
116
if (!Object.prototype.hasOwnProperty.call(partial, field.key))
@@ -110,7 +120,24 @@ export class EditorService
110
120
{ continue; }
111
121
next[field.key] = value;
112
122
}
113
const { bullets, changed } = diffSettings(current, next);
123
if (Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))
124
{
125
next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues);
126
}
127
const { bullets: scalarBullets, changed } = diffSettings(current, next);
128
const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
129
? diffItemSeedValues(
130
normalizeItemSeedValues(current.itemSeedValues),
131
next.itemSeedValues,
132
(itemId) => itemDefinition(itemId)?.displayName ?? null
133
)
134
: [];
135
if (!itemSeedMapsEqual(current.itemSeedValues, next.itemSeedValues)
136
&& Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))
137
{
138
changed.itemSeedValues = next.itemSeedValues;
139
}
140
const bullets = [...scalarBullets, ...seedBullets];
114
141
if (Object.keys(changed).length === 0)
115
142
{
116
143
return {
@@ -119,7 +146,13 @@ export class EditorService
119
146
changed: {}
120
147
};
121
148
}
122
const settings = { ...current, ...changed };
149
const settings = {
150
...current,
151
...changed,
152
itemSeedValues: changed.itemSeedValues
153
?? normalizeItemSeedValues(current.itemSeedValues)
154
?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) }
155
};
123
156
this.worldDb.saveLiveSettings(settings, editorAdminId);
124
157
this.worldDb.appendSettingsChangelog(editorAdminId, bullets);
125
158
return {
@@ -5,7 +5,10 @@ import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob,5
import { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";5
import { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";6
import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";6
import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";7
import { closedNeighborEdges } from "../world/chunkFlags.js";7
import { closedNeighborEdges } from "../world/chunkFlags.js";8
import { coerceSettingValue, diffSettings, allSettingFields } from "../../../shared/definitions/worldSettings.js";8
import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js";9
import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";10
import { itemDefinition } from "../../../shared/definitions/items.js";11
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";9
12
10
export class EditorService13
export class EditorService11
{14
{@@ -100,7 +103,14 @@ export class EditorService100
saveSettings (partial, editorAdminId)103
saveSettings (partial, editorAdminId)101
{104
{102
const current = this.worldDb.getLiveSettings();105
const current = this.worldDb.getLiveSettings();103
const next = { ...current };106
const next = {107
...current,108
itemSeedValues: {109
...(current.itemSeedValues && typeof current.itemSeedValues === "object"110
? current.itemSeedValues111
: {})112
}113
};104
for (const field of allSettingFields())114
for (const field of allSettingFields())105
{115
{106
if (!Object.prototype.hasOwnProperty.call(partial, field.key))116
if (!Object.prototype.hasOwnProperty.call(partial, field.key))@@ -110,7 +120,24 @@ export class EditorService110
{ continue; }120
{ continue; }111
next[field.key] = value;121
next[field.key] = value;112
}122
}113
const { bullets, changed } = diffSettings(current, next);123
if (Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))124
{125
next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues);126
}127
const { bullets: scalarBullets, changed } = diffSettings(current, next);128
const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")129
? diffItemSeedValues(130
normalizeItemSeedValues(current.itemSeedValues),131
next.itemSeedValues,132
(itemId) => itemDefinition(itemId)?.displayName ?? null133
)134
: [];135
if (!itemSeedMapsEqual(current.itemSeedValues, next.itemSeedValues)136
&& Object.prototype.hasOwnProperty.call(partial, "itemSeedValues"))137
{138
changed.itemSeedValues = next.itemSeedValues;139
}140
const bullets = [...scalarBullets, ...seedBullets];114
if (Object.keys(changed).length === 0)141
if (Object.keys(changed).length === 0)115
{142
{116
return {143
return {@@ -119,7 +146,13 @@ export class EditorService119
changed: {}146
changed: {}120
};147
};121
}148
}122
const settings = { ...current, ...changed };149
const settings = {150
...current,151
...changed,152
itemSeedValues: changed.itemSeedValues153
?? normalizeItemSeedValues(current.itemSeedValues)154
?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) }155
};123
this.worldDb.saveLiveSettings(settings, editorAdminId);156
this.worldDb.saveLiveSettings(settings, editorAdminId);124
this.worldDb.appendSettingsChangelog(editorAdminId, bullets);157
this.worldDb.appendSettingsChangelog(editorAdminId, bullets);125
return {158
return {@@ -402,9 +402,29 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
402
402
characterId: session.characterId,
403
403
npcEntityId: message.npcEntityId | 0,
404
404
itemId: message.itemId | 0,
405
quantity: message.quantity | 0 || 1,
406
listingId: typeof message.listingId === "string" ? message.listingId : null,
407
source: typeof message.source === "string" ? message.source : null
408
});
409
break;
410
case MessageType.sellToShop:
411
requirePlaying(session);
412
simulation.enqueue(session.id, {
413
type: "sell-to-shop",
414
characterId: session.characterId,
415
npcEntityId: message.npcEntityId | 0,
416
slotIndex: message.slotIndex | 0,
405
417
quantity: message.quantity | 0 || 1
406
418
});
407
419
break;
420
case MessageType.closeShop:
421
requirePlaying(session);
422
simulation.enqueue(session.id, {
423
type: "close-shop",
424
characterId: session.characterId,
425
npcEntityId: message.npcEntityId | 0
426
});
427
break;
408
428
case MessageType.follow:
409
429
requirePlaying(session);
410
430
simulation.enqueue(session.id, {
@@ -486,7 +506,11 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
486
506
break;
487
507
case MessageType.editorLoadSettings:
488
508
requireAdmin(session);
489
send(session, { type: MessageType.editorSettings, ...editor.loadSettings() });
509
send(session, {
510
type: MessageType.editorSettings,
511
...editor.loadSettings(),
512
itemLastSales: simulation.itemLastSalesSnapshot?.() ?? {}
513
});
490
514
break;
491
515
case MessageType.editorSaveSettings:
492
516
requireAdmin(session);
@@ -846,11 +870,25 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
846
870
type: MessageType.shopOpen,
847
871
npcEntityId: event.npcEntityId,
848
872
displayName: event.displayName,
873
sex: event.sex === "female" ? "female" : "male",
874
buysItems: !!event.buysItems,
849
875
stock: event.stock ?? []
850
876
});
851
877
}
852
878
continue;
853
879
}
880
if (event.type === "shop-closed")
881
{
882
const session = sessions.get(event.sessionId);
883
if (session)
884
{
885
send(session, {
886
type: MessageType.shopClosed,
887
npcEntityId: event.npcEntityId
888
});
889
}
890
continue;
891
}
854
892
if (event.type === "item-bubble")
855
893
{
856
894
broadcastItemBubble(
@@ -402,9 +402,29 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,402
characterId: session.characterId,402
characterId: session.characterId,403
npcEntityId: message.npcEntityId | 0,403
npcEntityId: message.npcEntityId | 0,404
itemId: message.itemId | 0,404
itemId: message.itemId | 0,405
quantity: message.quantity | 0 || 1,406
listingId: typeof message.listingId === "string" ? message.listingId : null,407
source: typeof message.source === "string" ? message.source : null408
});409
break;410
case MessageType.sellToShop:411
requirePlaying(session);412
simulation.enqueue(session.id, {413
type: "sell-to-shop",414
characterId: session.characterId,415
npcEntityId: message.npcEntityId | 0,416
slotIndex: message.slotIndex | 0,405
quantity: message.quantity | 0 || 1417
quantity: message.quantity | 0 || 1406
});418
});407
break;419
break;420
case MessageType.closeShop:421
requirePlaying(session);422
simulation.enqueue(session.id, {423
type: "close-shop",424
characterId: session.characterId,425
npcEntityId: message.npcEntityId | 0426
});427
break;408
case MessageType.follow:428
case MessageType.follow:409
requirePlaying(session);429
requirePlaying(session);410
simulation.enqueue(session.id, {430
simulation.enqueue(session.id, {@@ -486,7 +506,11 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,486
break;506
break;487
case MessageType.editorLoadSettings:507
case MessageType.editorLoadSettings:488
requireAdmin(session);508
requireAdmin(session);489
send(session, { type: MessageType.editorSettings, ...editor.loadSettings() });509
send(session, {510
type: MessageType.editorSettings,511
...editor.loadSettings(),512
itemLastSales: simulation.itemLastSalesSnapshot?.() ?? {}513
});490
break;514
break;491
case MessageType.editorSaveSettings:515
case MessageType.editorSaveSettings:492
requireAdmin(session);516
requireAdmin(session);@@ -846,11 +870,25 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,846
type: MessageType.shopOpen,870
type: MessageType.shopOpen,847
npcEntityId: event.npcEntityId,871
npcEntityId: event.npcEntityId,848
displayName: event.displayName,872
displayName: event.displayName,873
sex: event.sex === "female" ? "female" : "male",874
buysItems: !!event.buysItems,849
stock: event.stock ?? []875
stock: event.stock ?? []850
});876
});851
}877
}852
continue;878
continue;853
}879
}880
if (event.type === "shop-closed")881
{882
const session = sessions.get(event.sessionId);883
if (session)884
{885
send(session, {886
type: MessageType.shopClosed,887
npcEntityId: event.npcEntityId888
});889
}890
continue;891
}854
if (event.type === "item-bubble")892
if (event.type === "item-bubble")855
{893
{856
broadcastItemBubble(894
broadcastItemBubble(@@ -162,12 +162,14 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)
162
162
const path = world.ecs.get(handle, Component.path);
163
163
if (path)
164
164
{ path.tiles = []; }
165
const toolItemId = pickaxe.tool.stack?.itemId ?? null;
165
166
world.ecs.add(handle, Component.gather, {
166
167
kind: "mining",
167
168
tileX,
168
169
tileY,
169
170
materialId,
170
171
toolTier: pickaxe.tool.tier,
172
toolItemId,
171
173
startedAt: now,
172
174
finishesAt: now + durationMs,
173
175
nextSwingAt: now
@@ -181,6 +183,7 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)
181
183
tileY,
182
184
fromTileX: position.tileX,
183
185
fromTileY: position.tileY,
186
toolItemId,
184
187
swipe: false
185
188
}]
186
189
};
@@ -224,6 +227,7 @@ export function stepGather (world, now)
224
227
tileY: gather.tileY,
225
228
fromTileX: position.tileX,
226
229
fromTileY: position.tileY,
230
toolItemId: gather.toolItemId ?? null,
227
231
swipe: false
228
232
});
229
233
}
@@ -162,12 +162,14 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)162
const path = world.ecs.get(handle, Component.path);162
const path = world.ecs.get(handle, Component.path);163
if (path)163
if (path)164
{ path.tiles = []; }164
{ path.tiles = []; }165
const toolItemId = pickaxe.tool.stack?.itemId ?? null;165
world.ecs.add(handle, Component.gather, {166
world.ecs.add(handle, Component.gather, {166
kind: "mining",167
kind: "mining",167
tileX,168
tileX,168
tileY,169
tileY,169
materialId,170
materialId,170
toolTier: pickaxe.tool.tier,171
toolTier: pickaxe.tool.tier,172
toolItemId,171
startedAt: now,173
startedAt: now,172
finishesAt: now + durationMs,174
finishesAt: now + durationMs,173
nextSwingAt: now175
nextSwingAt: now@@ -181,6 +183,7 @@ export function startMine (world, sessionId, characterId, tileX, tileY, now)181
tileY,183
tileY,182
fromTileX: position.tileX,184
fromTileX: position.tileX,183
fromTileY: position.tileY,185
fromTileY: position.tileY,186
toolItemId,184
swipe: false187
swipe: false185
}]188
}]186
};189
};@@ -224,6 +227,7 @@ export function stepGather (world, now)224
tileY: gather.tileY,227
tileY: gather.tileY,225
fromTileX: position.tileX,228
fromTileX: position.tileX,226
fromTileY: position.tileY,229
fromTileY: position.tileY,230
toolItemId: gather.toolItemId ?? null,227
swipe: false231
swipe: false228
});232
});229
}233
}@@ -1,15 +1,27 @@
1
1
import { Component } from "../ecs/components.js";
2
import { bagView } from "../items/bags.js";
3
import { itemDefinition } from "../../../shared/definitions/items.js";
2
import { bagView, findReservedChequeIndex } from "../items/bags.js";
3
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4
4
import { ItemOriginKind, attachOrigins } from "../../../shared/items/origin.js";
5
5
import {
6
addCoinsToSlots,
7
cloneStack,
6
8
countCoinsInSlots,
7
9
insertStack,
8
takeCoinsFromSlots
10
insertStackGrowable,
11
takeCoinsFromSlots,
12
takeFromSlot
9
13
} from "../../../shared/items/inventory.js";
10
import { canSellInNpcShop, shopUnitPrice } from "../../../shared/shop/pricing.js";
14
import {
15
canSellInNpcShop,
16
canPlayerSellToNpc,
17
resolveShopSellQuote,
18
shopUnitPrice,
19
shopBoughtResalePrice,
20
shopRestockDayKey
21
} from "../../../shared/shop/pricing.js";
11
22
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
12
23
import { chebyshev } from "../combat/service.js";
24
import { objectPronoun } from "../../../shared/speech/pronouns.js";
13
25
14
26
function userError (message)
15
27
{
@@ -18,38 +30,259 @@ function userError (message)
18
30
return error;
19
31
}
20
32
33
function npcSex (world, npcHandle)
34
{
35
const appearance = world.ecs.get(npcHandle, Component.appearance);
36
return appearance?.sex === "female" ? "female" : "male";
37
}
38
39
/** Runtime map of characterId → true; plain object so entity transfer can clone it. */
40
function ensureBrowsers (shop)
41
{
42
if (!shop.browsers || typeof shop.browsers !== "object" || Array.isArray(shop.browsers))
43
{ shop.browsers = Object.create(null); }
44
return shop.browsers;
45
}
46
47
export function shopHasActiveBrowsers (shop)
48
{
49
const browsers = shop?.browsers;
50
if (!browsers || typeof browsers !== "object")
51
{ return false; }
52
return Object.keys(browsers).length > 0;
53
}
54
55
function stopNpcMovement (world, npcHandle)
56
{
57
const path = world.ecs.get(npcHandle, Component.path);
58
if (path)
59
{ path.tiles = []; }
60
}
61
62
function addShopBrowser (world, shop, npcHandle, characterId)
63
{
64
ensureBrowsers(shop)[characterId] = true;
65
stopNpcMovement(world, npcHandle);
66
}
67
68
function removeShopBrowser (shop, characterId)
69
{
70
if (!shop?.browsers)
71
{ return; }
72
delete shop.browsers[characterId];
73
}
74
75
export function releaseShopBrowsersForCharacter (world, characterId)
76
{
77
if (characterId == null)
78
{ return; }
79
for (const entity of world.ecs.query(Component.shop))
80
{ removeShopBrowser(entity.shop, characterId); }
81
}
82
83
/**
84
* Drop browsers who left / walked away, pin paths while anyone browses,
85
* and emit shop-closed so clients dismiss the UI.
86
*/
87
export function pruneShopBrowsers (world)
88
{
89
const events = [];
90
for (const entity of world.ecs.query(Component.shop, Component.position))
91
{
92
const shop = entity.shop;
93
const browsers = ensureBrowsers(shop);
94
const ids = Object.keys(browsers).map((id) => Number(id));
95
if (!ids.length)
96
{ continue; }
97
stopNpcMovement(world, entity.handle);
98
for (const characterId of ids)
99
{
100
const playerEntityId = world.characterEntities.get(characterId);
101
if (playerEntityId == null)
102
{
103
removeShopBrowser(shop, characterId);
104
continue;
105
}
106
const playerHandle = world.ecs.handleOf(playerEntityId);
107
const playerPos = world.ecs.get(playerHandle, Component.position);
108
const stillNear = playerPos
109
&& chebyshev(
110
playerPos.tileX,
111
playerPos.tileY,
112
entity.position.tileX,
113
entity.position.tileY
114
) <= 1;
115
if (stillNear)
116
{ continue; }
117
removeShopBrowser(shop, characterId);
118
const identity = world.ecs.get(playerHandle, Component.networkIdentity);
119
if (identity?.sessionId != null)
120
{
121
events.push({
122
type: "shop-closed",
123
sessionId: identity.sessionId,
124
characterId,
125
npcEntityId: entity.entityId
126
});
127
}
128
}
129
}
130
return events;
131
}
132
21
133
function lastSaleFor (world, itemId)
22
134
{
23
135
return world.itemLastSales?.get(itemId) ?? null;
24
136
}
25
137
26
function shopStockView (world, shop, now)
138
function lerpDuration (world)
27
139
{
28
const lerpDurationMs = world.settings?.shopPriceLerpDurationMs
140
return world.settings?.shopPriceLerpDurationMs
29
141
?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
142
}
143
144
function shopDisplayName (shop, npcHandle, world)
145
{
146
const appearance = world.ecs.get(npcHandle, Component.appearance);
147
return shop.displayName
148
|| [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")
149
|| "Shopkeeper";
150
}
151
152
function ensureVault (ecs, handle)
153
{
154
let vault = ecs.get(handle, Component.vault);
155
if (!vault)
156
{ vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); }
157
if (!Array.isArray(vault.slots))
158
{ vault.slots = []; }
159
if (!Array.isArray(vault.reserved))
160
{ vault.reserved = []; }
161
return vault;
162
}
163
164
/** Refresh catalog remaining and clear bought-from-players stock at UTC midnight. */
165
export function ensureShopRestocked (shop, now = Date.now())
166
{
167
if (!shop)
168
{ return; }
169
if (!Array.isArray(shop.catalog))
170
{ shop.catalog = []; }
171
if (Array.isArray(shop.stock) && !shop.catalog.length)
172
{
173
shop.catalog = shop.stock
174
.map((id) => ({ itemId: id | 0, quantity: 0 }))
175
.filter((line) => line.itemId > 0);
176
}
177
if (!shop.remaining || typeof shop.remaining !== "object")
178
{ shop.remaining = Object.create(null); }
179
if (!shop.boughtStock || typeof shop.boughtStock !== "object")
180
{ shop.boughtStock = Object.create(null); }
181
const day = shopRestockDayKey(now);
182
if (shop.restockDay === day)
183
{ return; }
184
shop.restockDay = day;
185
shop.boughtStock = Object.create(null);
186
shop.remaining = Object.create(null);
187
for (const line of shop.catalog)
188
{
189
const itemId = line.itemId | 0;
190
const quantity = Math.max(0, line.quantity | 0 || 0);
191
if (itemId > 0 && quantity > 0)
192
{ shop.remaining[itemId] = quantity; }
193
}
194
}
195
196
function catalogLine (shop, itemId)
197
{
198
return (shop.catalog ?? []).find((line) => (line.itemId | 0) === (itemId | 0)) ?? null;
199
}
200
201
function catalogAvailable (shop, itemId)
202
{
203
const line = catalogLine(shop, itemId);
204
if (!line)
205
{ return 0; }
206
if ((line.quantity | 0) <= 0)
207
{ return Number.POSITIVE_INFINITY; }
208
return Math.max(0, shop.remaining?.[itemId] | 0 || 0);
209
}
210
211
function boughtAvailable (shop, itemId)
212
{
213
return Math.max(0, shop.boughtStock?.[itemId] | 0 || 0);
214
}
215
216
function shopStockView (world, shop, now)
217
{
218
ensureShopRestocked(shop, now);
219
const lastSaleOpts = (itemId) => ({
220
lastSale: lastSaleFor(world, itemId),
221
now,
222
lerpDurationMs: lerpDuration(world),
223
settings: world.settings ?? null
224
});
30
225
const stock = [];
31
for (const itemId of shop.stock ?? [])
226
for (const line of shop.catalog ?? [])
32
227
{
228
const itemId = line.itemId | 0;
33
229
if (!canSellInNpcShop(itemId))
34
230
{ continue; }
35
231
const def = itemDefinition(itemId);
36
232
if (!def)
37
233
{ continue; }
234
const available = catalogAvailable(shop, itemId);
235
if (available === 0)
236
{ continue; }
38
237
stock.push({
238
listingId: `stock:${itemId}`,
39
239
itemId,
40
240
displayName: def.displayName,
41
241
unitPrice: shopUnitPrice(itemId, {
42
lastSale: lastSaleFor(world, itemId),
43
now,
44
lerpDurationMs,
242
...lastSaleOpts(itemId),
45
243
hiddenDiscount: shop.hiddenDiscount ?? 1
46
})
244
}),
245
available: Number.isFinite(available) ? available : null,
246
source: "stock"
247
});
248
}
249
for (const [key, qty] of Object.entries(shop.boughtStock ?? {}))
250
{
251
const itemId = key | 0;
252
const available = qty | 0;
253
if (available <= 0 || !canSellInNpcShop(itemId))
254
{ continue; }
255
const def = itemDefinition(itemId);
256
if (!def)
257
{ continue; }
258
stock.push({
259
listingId: `bought:${itemId}`,
260
itemId,
261
displayName: def.displayName,
262
unitPrice: shopBoughtResalePrice(itemId, lastSaleOpts(itemId)),
263
available,
264
source: "bought"
47
265
});
48
266
}
49
267
return stock;
50
268
}
51
269
52
export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now())
270
function shopOpenEvent (world, sessionId, characterId, npcEntityId, shop, displayName, now)
271
{
272
const npcHandle = world.ecs.handleOf(npcEntityId);
273
return {
274
type: "shop-open",
275
sessionId,
276
characterId,
277
npcEntityId,
278
displayName,
279
sex: npcHandle != null ? npcSex(world, npcHandle) : "male",
280
buysItems: !!shop.buysItems,
281
stock: shopStockView(world, shop, now)
282
};
283
}
284
285
function requireShopAccess (world, sessionId, characterId, npcEntityId)
53
286
{
54
287
const entityId = world.characterEntities.get(characterId);
55
288
if (entityId == null)
@@ -65,70 +298,95 @@ export function openShop (world, sessionId, characterId, npcEntityId, now = Date
65
298
if (npcHandle == null)
66
299
{ throw userError("Target is not here."); }
67
300
const shop = world.ecs.get(npcHandle, Component.shop);
68
if (!shop?.stock?.length)
69
{ throw userError("They are not selling anything."); }
301
const sex = npcSex(world, npcHandle);
302
if (!shop || (!(shop.catalog?.length) && !shop.buysItems))
303
{
304
const who = sex === "female" ? "She" : "He";
305
throw userError(`${who} is not selling anything.`);
306
}
70
307
71
308
const playerPos = world.ecs.get(handle, Component.position);
72
309
const npcPos = world.ecs.get(npcHandle, Component.position);
73
310
if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)
74
{ throw userError("You need to stand next to them."); }
311
{ throw userError(`You need to stand next to ${objectPronoun(sex)}.`); }
75
312
76
const appearance = world.ecs.get(npcHandle, Component.appearance);
77
const displayName = shop.displayName
78
|| [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")
79
|| "Shopkeeper";
313
return { handle, npcHandle, shop, entityId };
314
}
80
315
316
export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now())
317
{
318
const { shop, npcHandle } = requireShopAccess(world, sessionId, characterId, npcEntityId);
319
ensureShopRestocked(shop, now);
320
addShopBrowser(world, shop, npcHandle, characterId);
321
const displayName = shopDisplayName(shop, npcHandle, world);
81
322
return {
82
events: [{
83
type: "shop-open",
84
sessionId,
85
characterId,
86
npcEntityId,
87
displayName,
88
stock: shopStockView(world, shop, now)
89
}]
323
events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)]
90
324
};
91
325
}
92
326
93
export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now())
327
export function closeShop (world, sessionId, characterId, npcEntityId)
94
328
{
95
329
const entityId = world.characterEntities.get(characterId);
96
330
if (entityId == null)
97
{ throw userError("Character is not in the world."); }
331
{ return { events: [] }; }
98
332
const handle = world.ecs.handleOf(entityId);
99
333
const identity = world.ecs.get(handle, Component.networkIdentity);
100
334
if (!identity || identity.sessionId !== sessionId)
101
{ throw userError("Character is not in the world."); }
102
if (world.ecs.has(handle, Component.dead))
103
{ throw userError("You are dead."); }
104
105
const npcHandle = world.ecs.handleOf(npcEntityId);
335
{ return { events: [] }; }
336
const npcHandle = world.ecs.handleOf(npcEntityId | 0);
106
337
if (npcHandle == null)
107
{ throw userError("Target is not here."); }
338
{ return { events: [] }; }
108
339
const shop = world.ecs.get(npcHandle, Component.shop);
109
if (!shop?.stock?.includes(itemId | 0))
110
{ throw userError("They do not sell that."); }
111
if (!canSellInNpcShop(itemId))
112
{ throw userError("That item cannot be sold here."); }
340
removeShopBrowser(shop, characterId);
341
return { events: [] };
342
}
113
343
114
const playerPos = world.ecs.get(handle, Component.position);
115
const npcPos = world.ecs.get(npcHandle, Component.position);
116
if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)
117
{ throw userError("You need to stand next to them."); }
344
function parseListing (listingId, itemId, source)
345
{
346
if (typeof listingId === "string" && listingId.includes(":"))
347
{
348
const [kind, id] = listingId.split(":");
349
return { source: kind === "bought" ? "bought" : "stock", itemId: id | 0 };
350
}
351
if (source === "bought")
352
{ return { source: "bought", itemId: itemId | 0 }; }
353
return { source: "stock", itemId: itemId | 0 };
354
}
355
356
export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now(), listingId = null, source = null)
357
{
358
const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId);
359
ensureShopRestocked(shop, now);
360
const listing = parseListing(listingId, itemId, source);
361
const buyItemId = listing.itemId;
362
if (!canSellInNpcShop(buyItemId))
363
{ throw userError("That item cannot be sold here."); }
118
364
119
const qty = Math.max(1, Math.min(99, quantity | 0 || 1));
120
const def = itemDefinition(itemId);
365
const qty = Math.max(1, quantity | 0 || 1);
366
const def = itemDefinition(buyItemId);
121
367
if (!def)
122
368
{ throw userError("Unknown item."); }
123
369
124
const lerpDurationMs = world.settings?.shopPriceLerpDurationMs
125
?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
126
const unitPrice = shopUnitPrice(itemId, {
127
lastSale: lastSaleFor(world, itemId),
128
now,
129
lerpDurationMs,
130
hiddenDiscount: shop.hiddenDiscount ?? 1
131
});
370
const available = listing.source === "bought"
371
? boughtAvailable(shop, buyItemId)
372
: catalogAvailable(shop, buyItemId);
373
if (available < qty)
374
{ throw userError("Not enough stock."); }
375
376
const unitPrice = listing.source === "bought"
377
? shopBoughtResalePrice(buyItemId, {
378
lastSale: lastSaleFor(world, buyItemId),
379
now,
380
lerpDurationMs: lerpDuration(world),
381
settings: world.settings ?? null
382
})
383
: shopUnitPrice(buyItemId, {
384
lastSale: lastSaleFor(world, buyItemId),
385
now,
386
lerpDurationMs: lerpDuration(world),
387
hiddenDiscount: shop.hiddenDiscount ?? 1,
388
settings: world.settings ?? null
389
});
132
390
const total = unitPrice * qty;
133
391
const inventory = world.ecs.get(handle, Component.inventory);
134
392
if (!inventory)
@@ -140,32 +398,186 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
140
398
if (!paid.ok)
141
399
{ throw userError("You cannot afford that."); }
142
400
143
const appearance = world.ecs.get(npcHandle, Component.appearance);
144
const displayName = shop.displayName
145
|| [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")
146
|| "Shopkeeper";
401
const displayName = shopDisplayName(shop, npcHandle, world);
402
const shopOrigin = { kind: ItemOriginKind.shop, displayName };
147
403
const stack = attachOrigins({
148
itemId,
404
itemId: buyItemId,
149
405
quantity: qty,
150
origins: [{
151
origin: { kind: ItemOriginKind.shop, displayName },
152
quantity: qty
153
}]
406
origins: [{ origin: shopOrigin, quantity: qty }]
154
407
});
155
408
const added = insertStack(paid.slots, stack, def);
156
if (!added.ok || added.remainder > 0)
157
{ throw userError("Not enough bag space."); }
158
159
409
inventory.slots = added.slots;
410
if (added.remainder > 0)
411
{
412
const overflow = attachOrigins({
413
itemId: buyItemId,
414
quantity: added.remainder,
415
origins: [{ origin: shopOrigin, quantity: added.remainder }]
416
});
417
const vault = ensureVault(world.ecs, handle);
418
const vaulted = insertStackGrowable(vault.slots, overflow, def);
419
if (!vaulted.ok || vaulted.remainder > 0)
420
{ throw userError("Your bank cannot hold that purchase."); }
421
vault.slots = vaulted.slots;
422
}
423
424
if (listing.source === "bought")
425
{
426
shop.boughtStock[buyItemId] = boughtAvailable(shop, buyItemId) - qty;
427
if (shop.boughtStock[buyItemId] <= 0)
428
{ delete shop.boughtStock[buyItemId]; }
429
}
430
else
431
{
432
const line = catalogLine(shop, buyItemId);
433
if (line && (line.quantity | 0) > 0)
434
{ shop.remaining[buyItemId] = catalogAvailable(shop, buyItemId) - qty; }
435
}
436
160
437
return {
161
events: [{
162
type: "shop-open",
163
sessionId,
164
characterId,
165
npcEntityId,
166
displayName,
167
stock: shopStockView(world, shop, now)
168
}],
438
events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)],
439
private: bagView(world.ecs, handle)
440
};
441
}
442
443
/**
444
* Player sells to NPC (requires buysItems).
445
* Buys any transferable bag goods except blank cheques.
446
* Filled cheques sell as their reserved goods with a 5% admin fee.
447
* Limited catalog lines refill first; remainder goes into boughtStock
448
* (cleared at midnight). Infinite catalog lines absorb goods without resale stock.
449
*/
450
export function sellToShop (world, sessionId, characterId, npcEntityId, slotIndex, quantity = 1, now = Date.now())
451
{
452
const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId);
453
ensureShopRestocked(shop, now);
454
if (!shop.buysItems)
455
{ throw userError("They are not buying anything."); }
456
457
const inventory = world.ecs.get(handle, Component.inventory);
458
if (!inventory)
459
{ throw userError("No inventory."); }
460
const slot = inventory.slots[slotIndex | 0];
461
if (!slot)
462
{ throw userError("That slot is empty."); }
463
if (!canPlayerSellToNpc(slot))
464
{ throw userError("They will not buy that."); }
465
466
const isCheque = (slot.itemId | 0) === ItemId.filledCheque;
467
const quote = resolveShopSellQuote(slot, {
468
lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),
469
now,
470
lerpDurationMs: lerpDuration(world),
471
settings: world.settings ?? null,
472
quantity: isCheque ? 1 : (quantity | 0 || 1)
473
});
474
if (!quote)
475
{ throw userError("They will not buy that."); }
476
477
const goodsItemId = quote.goodsItemId;
478
const qty = quote.goodsQuantity;
479
const line = catalogLine(shop, goodsItemId);
480
let refill = 0;
481
let leftover = qty;
482
if (line)
483
{
484
if ((line.quantity | 0) <= 0)
485
{
486
refill = qty;
487
leftover = 0;
488
}
489
else
490
{
491
const space = Math.max(0, (line.quantity | 0) - catalogAvailable(shop, goodsItemId));
492
refill = Math.min(qty, space);
493
leftover = qty - refill;
494
}
495
}
496
497
const total = quote.payout;
498
let reservedStack = null;
499
let chequeTaken = null;
500
let taken = null;
501
502
if (isCheque)
503
{
504
const instance = slot.instance;
505
const issuerId = instance.issuerCharacterId;
506
chequeTaken = takeFromSlot(inventory.slots, slotIndex | 0, 1);
507
if (!chequeTaken.ok)
508
{ throw userError("Could not take that item."); }
509
inventory.slots = chequeTaken.slots;
510
511
if (Number(issuerId) === Number(characterId))
512
{
513
const vault = world.ecs.get(handle, Component.vault);
514
if (!vault)
515
{
516
inventory.slots[slotIndex | 0] = chequeTaken.taken;
517
throw userError("That cheque cannot be sold.");
518
}
519
if (!Array.isArray(vault.reserved))
520
{ vault.reserved = []; }
521
const index = findReservedChequeIndex(vault.reserved, instance);
522
if (index < 0)
523
{
524
inventory.slots[slotIndex | 0] = chequeTaken.taken;
525
throw userError("That cheque cannot be sold.");
526
}
527
reservedStack = cloneStack(vault.reserved[index]);
528
vault.reserved = vault.reserved.filter((_, i) => i !== index);
529
}
530
else
531
{
532
const release = world.releaseChequeReservation?.(issuerId, instance.chequeId, instance);
533
if (!release?.ok)
534
{
535
inventory.slots[slotIndex | 0] = chequeTaken.taken;
536
throw userError(release?.error ?? "That cheque cannot be sold.");
537
}
538
reservedStack = release.stack;
539
}
540
}
541
else
542
{
543
taken = takeFromSlot(inventory.slots, slotIndex | 0, qty);
544
if (!taken.ok)
545
{ throw userError("Could not take that item."); }
546
}
547
548
const slotsAfterTake = isCheque ? inventory.slots : taken.slots;
549
const paid = addCoinsToSlots(slotsAfterTake, total);
550
if (!paid.ok)
551
{
552
if (isCheque)
553
{
554
inventory.slots[slotIndex | 0] = chequeTaken.taken;
555
if (Number(slot.instance.issuerCharacterId) === Number(characterId))
556
{
557
const vault = world.ecs.get(handle, Component.vault);
558
if (vault && reservedStack)
559
{ vault.reserved = [...(vault.reserved ?? []), reservedStack]; }
560
}
561
else if (reservedStack)
562
{ world.restoreChequeReservation?.(slot.instance.issuerCharacterId, reservedStack); }
563
}
564
else
565
{
566
const def = itemDefinition(goodsItemId);
567
inventory.slots = insertStack(taken.slots, taken.taken, def).slots;
568
}
569
throw userError("Not enough bag space for coins.");
570
}
571
inventory.slots = paid.slots;
572
573
if (line && (line.quantity | 0) > 0 && refill > 0)
574
{ shop.remaining[goodsItemId] = catalogAvailable(shop, goodsItemId) + refill; }
575
if (leftover > 0)
576
{ shop.boughtStock[goodsItemId] = boughtAvailable(shop, goodsItemId) + leftover; }
577
578
const displayName = shopDisplayName(shop, npcHandle, world);
579
return {
580
events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)],
169
581
private: bagView(world.ecs, handle)
170
582
};
171
583
}
@@ -182,9 +594,39 @@ export function handleShopCommand (world, sessionId, command, now)
182
594
command.npcEntityId | 0,
183
595
command.itemId | 0,
184
596
command.quantity | 0 || 1,
597
now,
598
command.listingId ?? null,
599
command.source ?? null
600
);
601
case "sell-to-shop":
602
return sellToShop(
603
world,
604
sessionId,
605
command.characterId,
606
command.npcEntityId | 0,
607
command.slotIndex | 0,
608
command.quantity | 0 || 1,
185
609
now
186
610
);
611
case "close-shop":
612
return closeShop(world, sessionId, command.characterId, command.npcEntityId | 0);
187
613
default:
188
614
return null;
189
615
}
190
616
}
617
618
export function shopHasInterface (shop)
619
{
620
if (!shop)
621
{ return false; }
622
if (shop.buysItems)
623
{ return true; }
624
if ((shop.catalog?.length ?? 0) > 0)
625
{ return true; }
626
if (Object.keys(shop.boughtStock ?? {}).length > 0)
627
{ return true; }
628
// Legacy shops spawned before catalog migration.
629
if ((shop.stock?.length ?? 0) > 0)
630
{ return true; }
631
return false;
632
}
@@ -1,15 +1,27 @@1
import { Component } from "../ecs/components.js";1
import { Component } from "../ecs/components.js";2
import { bagView } from "../items/bags.js";2
import { bagView, findReservedChequeIndex } from "../items/bags.js";3
import { itemDefinition } from "../../../shared/definitions/items.js";3
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";4
import { ItemOriginKind, attachOrigins } from "../../../shared/items/origin.js";4
import { ItemOriginKind, attachOrigins } from "../../../shared/items/origin.js";5
import {5
import {6
addCoinsToSlots,7
cloneStack,6
countCoinsInSlots,8
countCoinsInSlots,7
insertStack,9
insertStack,8
takeCoinsFromSlots10
insertStackGrowable,11
takeCoinsFromSlots,12
takeFromSlot9
} from "../../../shared/items/inventory.js";13
} from "../../../shared/items/inventory.js";10
import { canSellInNpcShop, shopUnitPrice } from "../../../shared/shop/pricing.js";14
import {15
canSellInNpcShop,16
canPlayerSellToNpc,17
resolveShopSellQuote,18
shopUnitPrice,19
shopBoughtResalePrice,20
shopRestockDayKey21
} from "../../../shared/shop/pricing.js";11
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";22
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";12
import { chebyshev } from "../combat/service.js";23
import { chebyshev } from "../combat/service.js";24
import { objectPronoun } from "../../../shared/speech/pronouns.js";13
25
14
function userError (message)26
function userError (message)15
{27
{@@ -18,38 +30,259 @@ function userError (message)18
return error;30
return error;19
}31
}20
32
33
function npcSex (world, npcHandle)34
{35
const appearance = world.ecs.get(npcHandle, Component.appearance);36
return appearance?.sex === "female" ? "female" : "male";37
}38
39
/** Runtime map of characterId → true; plain object so entity transfer can clone it. */40
function ensureBrowsers (shop)41
{42
if (!shop.browsers || typeof shop.browsers !== "object" || Array.isArray(shop.browsers))43
{ shop.browsers = Object.create(null); }44
return shop.browsers;45
}46
47
export function shopHasActiveBrowsers (shop)48
{49
const browsers = shop?.browsers;50
if (!browsers || typeof browsers !== "object")51
{ return false; }52
return Object.keys(browsers).length > 0;53
}54
55
function stopNpcMovement (world, npcHandle)56
{57
const path = world.ecs.get(npcHandle, Component.path);58
if (path)59
{ path.tiles = []; }60
}61
62
function addShopBrowser (world, shop, npcHandle, characterId)63
{64
ensureBrowsers(shop)[characterId] = true;65
stopNpcMovement(world, npcHandle);66
}67
68
function removeShopBrowser (shop, characterId)69
{70
if (!shop?.browsers)71
{ return; }72
delete shop.browsers[characterId];73
}74
75
export function releaseShopBrowsersForCharacter (world, characterId)76
{77
if (characterId == null)78
{ return; }79
for (const entity of world.ecs.query(Component.shop))80
{ removeShopBrowser(entity.shop, characterId); }81
}82
83
/**84
* Drop browsers who left / walked away, pin paths while anyone browses,85
* and emit shop-closed so clients dismiss the UI.86
*/87
export function pruneShopBrowsers (world)88
{89
const events = [];90
for (const entity of world.ecs.query(Component.shop, Component.position))91
{92
const shop = entity.shop;93
const browsers = ensureBrowsers(shop);94
const ids = Object.keys(browsers).map((id) => Number(id));95
if (!ids.length)96
{ continue; }97
stopNpcMovement(world, entity.handle);98
for (const characterId of ids)99
{100
const playerEntityId = world.characterEntities.get(characterId);101
if (playerEntityId == null)102
{103
removeShopBrowser(shop, characterId);104
continue;105
}106
const playerHandle = world.ecs.handleOf(playerEntityId);107
const playerPos = world.ecs.get(playerHandle, Component.position);108
const stillNear = playerPos109
&& chebyshev(110
playerPos.tileX,111
playerPos.tileY,112
entity.position.tileX,113
entity.position.tileY114
) <= 1;115
if (stillNear)116
{ continue; }117
removeShopBrowser(shop, characterId);118
const identity = world.ecs.get(playerHandle, Component.networkIdentity);119
if (identity?.sessionId != null)120
{121
events.push({122
type: "shop-closed",123
sessionId: identity.sessionId,124
characterId,125
npcEntityId: entity.entityId126
});127
}128
}129
}130
return events;131
}132
21
function lastSaleFor (world, itemId)133
function lastSaleFor (world, itemId)22
{134
{23
return world.itemLastSales?.get(itemId) ?? null;135
return world.itemLastSales?.get(itemId) ?? null;24
}136
}25
137
26
function shopStockView (world, shop, now)138
function lerpDuration (world)27
{139
{28
const lerpDurationMs = world.settings?.shopPriceLerpDurationMs140
return world.settings?.shopPriceLerpDurationMs29
?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;141
?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;142
}143
144
function shopDisplayName (shop, npcHandle, world)145
{146
const appearance = world.ecs.get(npcHandle, Component.appearance);147
return shop.displayName148
|| [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")149
|| "Shopkeeper";150
}151
152
function ensureVault (ecs, handle)153
{154
let vault = ecs.get(handle, Component.vault);155
if (!vault)156
{ vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); }157
if (!Array.isArray(vault.slots))158
{ vault.slots = []; }159
if (!Array.isArray(vault.reserved))160
{ vault.reserved = []; }161
return vault;162
}163
164
/** Refresh catalog remaining and clear bought-from-players stock at UTC midnight. */165
export function ensureShopRestocked (shop, now = Date.now())166
{167
if (!shop)168
{ return; }169
if (!Array.isArray(shop.catalog))170
{ shop.catalog = []; }171
if (Array.isArray(shop.stock) && !shop.catalog.length)172
{173
shop.catalog = shop.stock174
.map((id) => ({ itemId: id | 0, quantity: 0 }))175
.filter((line) => line.itemId > 0);176
}177
if (!shop.remaining || typeof shop.remaining !== "object")178
{ shop.remaining = Object.create(null); }179
if (!shop.boughtStock || typeof shop.boughtStock !== "object")180
{ shop.boughtStock = Object.create(null); }181
const day = shopRestockDayKey(now);182
if (shop.restockDay === day)183
{ return; }184
shop.restockDay = day;185
shop.boughtStock = Object.create(null);186
shop.remaining = Object.create(null);187
for (const line of shop.catalog)188
{189
const itemId = line.itemId | 0;190
const quantity = Math.max(0, line.quantity | 0 || 0);191
if (itemId > 0 && quantity > 0)192
{ shop.remaining[itemId] = quantity; }193
}194
}195
196
function catalogLine (shop, itemId)197
{198
return (shop.catalog ?? []).find((line) => (line.itemId | 0) === (itemId | 0)) ?? null;199
}200
201
function catalogAvailable (shop, itemId)202
{203
const line = catalogLine(shop, itemId);204
if (!line)205
{ return 0; }206
if ((line.quantity | 0) <= 0)207
{ return Number.POSITIVE_INFINITY; }208
return Math.max(0, shop.remaining?.[itemId] | 0 || 0);209
}210
211
function boughtAvailable (shop, itemId)212
{213
return Math.max(0, shop.boughtStock?.[itemId] | 0 || 0);214
}215
216
function shopStockView (world, shop, now)217
{218
ensureShopRestocked(shop, now);219
const lastSaleOpts = (itemId) => ({220
lastSale: lastSaleFor(world, itemId),221
now,222
lerpDurationMs: lerpDuration(world),223
settings: world.settings ?? null224
});30
const stock = [];225
const stock = [];31
for (const itemId of shop.stock ?? [])226
for (const line of shop.catalog ?? [])32
{227
{228
const itemId = line.itemId | 0;33
if (!canSellInNpcShop(itemId))229
if (!canSellInNpcShop(itemId))34
{ continue; }230
{ continue; }35
const def = itemDefinition(itemId);231
const def = itemDefinition(itemId);36
if (!def)232
if (!def)37
{ continue; }233
{ continue; }234
const available = catalogAvailable(shop, itemId);235
if (available === 0)236
{ continue; }38
stock.push({237
stock.push({238
listingId: `stock:${itemId}`,39
itemId,239
itemId,40
displayName: def.displayName,240
displayName: def.displayName,41
unitPrice: shopUnitPrice(itemId, {241
unitPrice: shopUnitPrice(itemId, {42
lastSale: lastSaleFor(world, itemId),242
...lastSaleOpts(itemId),43
now,44
lerpDurationMs,45
hiddenDiscount: shop.hiddenDiscount ?? 1243
hiddenDiscount: shop.hiddenDiscount ?? 146
})244
}),245
available: Number.isFinite(available) ? available : null,246
source: "stock"247
});248
}249
for (const [key, qty] of Object.entries(shop.boughtStock ?? {}))250
{251
const itemId = key | 0;252
const available = qty | 0;253
if (available <= 0 || !canSellInNpcShop(itemId))254
{ continue; }255
const def = itemDefinition(itemId);256
if (!def)257
{ continue; }258
stock.push({259
listingId: `bought:${itemId}`,260
itemId,261
displayName: def.displayName,262
unitPrice: shopBoughtResalePrice(itemId, lastSaleOpts(itemId)),263
available,264
source: "bought"47
});265
});48
}266
}49
return stock;267
return stock;50
}268
}51
269
52
export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now())270
function shopOpenEvent (world, sessionId, characterId, npcEntityId, shop, displayName, now)271
{272
const npcHandle = world.ecs.handleOf(npcEntityId);273
return {274
type: "shop-open",275
sessionId,276
characterId,277
npcEntityId,278
displayName,279
sex: npcHandle != null ? npcSex(world, npcHandle) : "male",280
buysItems: !!shop.buysItems,281
stock: shopStockView(world, shop, now)282
};283
}284
285
function requireShopAccess (world, sessionId, characterId, npcEntityId)53
{286
{54
const entityId = world.characterEntities.get(characterId);287
const entityId = world.characterEntities.get(characterId);55
if (entityId == null)288
if (entityId == null)@@ -65,70 +298,95 @@ export function openShop (world, sessionId, characterId, npcEntityId, now = Date65
if (npcHandle == null)298
if (npcHandle == null)66
{ throw userError("Target is not here."); }299
{ throw userError("Target is not here."); }67
const shop = world.ecs.get(npcHandle, Component.shop);300
const shop = world.ecs.get(npcHandle, Component.shop);68
if (!shop?.stock?.length)301
const sex = npcSex(world, npcHandle);69
{ throw userError("They are not selling anything."); }302
if (!shop || (!(shop.catalog?.length) && !shop.buysItems))303
{304
const who = sex === "female" ? "She" : "He";305
throw userError(`${who} is not selling anything.`);306
}70
307
71
const playerPos = world.ecs.get(handle, Component.position);308
const playerPos = world.ecs.get(handle, Component.position);72
const npcPos = world.ecs.get(npcHandle, Component.position);309
const npcPos = world.ecs.get(npcHandle, Component.position);73
if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)310
if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)74
{ throw userError("You need to stand next to them."); }311
{ throw userError(`You need to stand next to ${objectPronoun(sex)}.`); }75
312
76
const appearance = world.ecs.get(npcHandle, Component.appearance);313
return { handle, npcHandle, shop, entityId };77
const displayName = shop.displayName314
}78
|| [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")79
|| "Shopkeeper";80
315
316
export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now())317
{318
const { shop, npcHandle } = requireShopAccess(world, sessionId, characterId, npcEntityId);319
ensureShopRestocked(shop, now);320
addShopBrowser(world, shop, npcHandle, characterId);321
const displayName = shopDisplayName(shop, npcHandle, world);81
return {322
return {82
events: [{323
events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)]83
type: "shop-open",84
sessionId,85
characterId,86
npcEntityId,87
displayName,88
stock: shopStockView(world, shop, now)89
}]90
};324
};91
}325
}92
326
93
export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now())327
export function closeShop (world, sessionId, characterId, npcEntityId)94
{328
{95
const entityId = world.characterEntities.get(characterId);329
const entityId = world.characterEntities.get(characterId);96
if (entityId == null)330
if (entityId == null)97
{ throw userError("Character is not in the world."); }331
{ return { events: [] }; }98
const handle = world.ecs.handleOf(entityId);332
const handle = world.ecs.handleOf(entityId);99
const identity = world.ecs.get(handle, Component.networkIdentity);333
const identity = world.ecs.get(handle, Component.networkIdentity);100
if (!identity || identity.sessionId !== sessionId)334
if (!identity || identity.sessionId !== sessionId)101
{ throw userError("Character is not in the world."); }335
{ return { events: [] }; }102
if (world.ecs.has(handle, Component.dead))336
const npcHandle = world.ecs.handleOf(npcEntityId | 0);103
{ throw userError("You are dead."); }104
105
const npcHandle = world.ecs.handleOf(npcEntityId);106
if (npcHandle == null)337
if (npcHandle == null)107
{ throw userError("Target is not here."); }338
{ return { events: [] }; }108
const shop = world.ecs.get(npcHandle, Component.shop);339
const shop = world.ecs.get(npcHandle, Component.shop);109
if (!shop?.stock?.includes(itemId | 0))340
removeShopBrowser(shop, characterId);110
{ throw userError("They do not sell that."); }341
return { events: [] };111
if (!canSellInNpcShop(itemId))342
}112
{ throw userError("That item cannot be sold here."); }113
343
114
const playerPos = world.ecs.get(handle, Component.position);344
function parseListing (listingId, itemId, source)115
const npcPos = world.ecs.get(npcHandle, Component.position);345
{116
if (!playerPos || !npcPos || chebyshev(playerPos.tileX, playerPos.tileY, npcPos.tileX, npcPos.tileY) > 1)346
if (typeof listingId === "string" && listingId.includes(":"))117
{ throw userError("You need to stand next to them."); }347
{348
const [kind, id] = listingId.split(":");349
return { source: kind === "bought" ? "bought" : "stock", itemId: id | 0 };350
}351
if (source === "bought")352
{ return { source: "bought", itemId: itemId | 0 }; }353
return { source: "stock", itemId: itemId | 0 };354
}355
356
export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now(), listingId = null, source = null)357
{358
const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId);359
ensureShopRestocked(shop, now);360
const listing = parseListing(listingId, itemId, source);361
const buyItemId = listing.itemId;362
if (!canSellInNpcShop(buyItemId))363
{ throw userError("That item cannot be sold here."); }118
364
119
const qty = Math.max(1, Math.min(99, quantity | 0 || 1));365
const qty = Math.max(1, quantity | 0 || 1);120
const def = itemDefinition(itemId);366
const def = itemDefinition(buyItemId);121
if (!def)367
if (!def)122
{ throw userError("Unknown item."); }368
{ throw userError("Unknown item."); }123
369
124
const lerpDurationMs = world.settings?.shopPriceLerpDurationMs370
const available = listing.source === "bought"125
?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;371
? boughtAvailable(shop, buyItemId)126
const unitPrice = shopUnitPrice(itemId, {372
: catalogAvailable(shop, buyItemId);127
lastSale: lastSaleFor(world, itemId),373
if (available < qty)128
now,374
{ throw userError("Not enough stock."); }129
lerpDurationMs,375
130
hiddenDiscount: shop.hiddenDiscount ?? 1376
const unitPrice = listing.source === "bought"131
});377
? shopBoughtResalePrice(buyItemId, {378
lastSale: lastSaleFor(world, buyItemId),379
now,380
lerpDurationMs: lerpDuration(world),381
settings: world.settings ?? null382
})383
: shopUnitPrice(buyItemId, {384
lastSale: lastSaleFor(world, buyItemId),385
now,386
lerpDurationMs: lerpDuration(world),387
hiddenDiscount: shop.hiddenDiscount ?? 1,388
settings: world.settings ?? null389
});132
const total = unitPrice * qty;390
const total = unitPrice * qty;133
const inventory = world.ecs.get(handle, Component.inventory);391
const inventory = world.ecs.get(handle, Component.inventory);134
if (!inventory)392
if (!inventory)@@ -140,32 +398,186 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,140
if (!paid.ok)398
if (!paid.ok)141
{ throw userError("You cannot afford that."); }399
{ throw userError("You cannot afford that."); }142
400
143
const appearance = world.ecs.get(npcHandle, Component.appearance);401
const displayName = shopDisplayName(shop, npcHandle, world);144
const displayName = shop.displayName402
const shopOrigin = { kind: ItemOriginKind.shop, displayName };145
|| [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")146
|| "Shopkeeper";147
const stack = attachOrigins({403
const stack = attachOrigins({148
itemId,404
itemId: buyItemId,149
quantity: qty,405
quantity: qty,150
origins: [{406
origins: [{ origin: shopOrigin, quantity: qty }]151
origin: { kind: ItemOriginKind.shop, displayName },152
quantity: qty153
}]154
});407
});155
const added = insertStack(paid.slots, stack, def);408
const added = insertStack(paid.slots, stack, def);156
if (!added.ok || added.remainder > 0)157
{ throw userError("Not enough bag space."); }158
159
inventory.slots = added.slots;409
inventory.slots = added.slots;410
if (added.remainder > 0)411
{412
const overflow = attachOrigins({413
itemId: buyItemId,414
quantity: added.remainder,415
origins: [{ origin: shopOrigin, quantity: added.remainder }]416
});417
const vault = ensureVault(world.ecs, handle);418
const vaulted = insertStackGrowable(vault.slots, overflow, def);419
if (!vaulted.ok || vaulted.remainder > 0)420
{ throw userError("Your bank cannot hold that purchase."); }421
vault.slots = vaulted.slots;422
}423
424
if (listing.source === "bought")425
{426
shop.boughtStock[buyItemId] = boughtAvailable(shop, buyItemId) - qty;427
if (shop.boughtStock[buyItemId] <= 0)428
{ delete shop.boughtStock[buyItemId]; }429
}430
else431
{432
const line = catalogLine(shop, buyItemId);433
if (line && (line.quantity | 0) > 0)434
{ shop.remaining[buyItemId] = catalogAvailable(shop, buyItemId) - qty; }435
}436
160
return {437
return {161
events: [{438
events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)],162
type: "shop-open",439
private: bagView(world.ecs, handle)163
sessionId,440
};164
characterId,441
}165
npcEntityId,442
166
displayName,443
/**167
stock: shopStockView(world, shop, now)444
* Player sells to NPC (requires buysItems).168
}],445
* Buys any transferable bag goods except blank cheques.446
* Filled cheques sell as their reserved goods with a 5% admin fee.447
* Limited catalog lines refill first; remainder goes into boughtStock448
* (cleared at midnight). Infinite catalog lines absorb goods without resale stock.449
*/450
export function sellToShop (world, sessionId, characterId, npcEntityId, slotIndex, quantity = 1, now = Date.now())451
{452
const { handle, npcHandle, shop } = requireShopAccess(world, sessionId, characterId, npcEntityId);453
ensureShopRestocked(shop, now);454
if (!shop.buysItems)455
{ throw userError("They are not buying anything."); }456
457
const inventory = world.ecs.get(handle, Component.inventory);458
if (!inventory)459
{ throw userError("No inventory."); }460
const slot = inventory.slots[slotIndex | 0];461
if (!slot)462
{ throw userError("That slot is empty."); }463
if (!canPlayerSellToNpc(slot))464
{ throw userError("They will not buy that."); }465
466
const isCheque = (slot.itemId | 0) === ItemId.filledCheque;467
const quote = resolveShopSellQuote(slot, {468
lastSale: lastSaleFor(world, isCheque ? (slot.instance.itemId | 0) : (slot.itemId | 0)),469
now,470
lerpDurationMs: lerpDuration(world),471
settings: world.settings ?? null,472
quantity: isCheque ? 1 : (quantity | 0 || 1)473
});474
if (!quote)475
{ throw userError("They will not buy that."); }476
477
const goodsItemId = quote.goodsItemId;478
const qty = quote.goodsQuantity;479
const line = catalogLine(shop, goodsItemId);480
let refill = 0;481
let leftover = qty;482
if (line)483
{484
if ((line.quantity | 0) <= 0)485
{486
refill = qty;487
leftover = 0;488
}489
else490
{491
const space = Math.max(0, (line.quantity | 0) - catalogAvailable(shop, goodsItemId));492
refill = Math.min(qty, space);493
leftover = qty - refill;494
}495
}496
497
const total = quote.payout;498
let reservedStack = null;499
let chequeTaken = null;500
let taken = null;501
502
if (isCheque)503
{504
const instance = slot.instance;505
const issuerId = instance.issuerCharacterId;506
chequeTaken = takeFromSlot(inventory.slots, slotIndex | 0, 1);507
if (!chequeTaken.ok)508
{ throw userError("Could not take that item."); }509
inventory.slots = chequeTaken.slots;510
511
if (Number(issuerId) === Number(characterId))512
{513
const vault = world.ecs.get(handle, Component.vault);514
if (!vault)515
{516
inventory.slots[slotIndex | 0] = chequeTaken.taken;517
throw userError("That cheque cannot be sold.");518
}519
if (!Array.isArray(vault.reserved))520
{ vault.reserved = []; }521
const index = findReservedChequeIndex(vault.reserved, instance);522
if (index < 0)523
{524
inventory.slots[slotIndex | 0] = chequeTaken.taken;525
throw userError("That cheque cannot be sold.");526
}527
reservedStack = cloneStack(vault.reserved[index]);528
vault.reserved = vault.reserved.filter((_, i) => i !== index);529
}530
else531
{532
const release = world.releaseChequeReservation?.(issuerId, instance.chequeId, instance);533
if (!release?.ok)534
{535
inventory.slots[slotIndex | 0] = chequeTaken.taken;536
throw userError(release?.error ?? "That cheque cannot be sold.");537
}538
reservedStack = release.stack;539
}540
}541
else542
{543
taken = takeFromSlot(inventory.slots, slotIndex | 0, qty);544
if (!taken.ok)545
{ throw userError("Could not take that item."); }546
}547
548
const slotsAfterTake = isCheque ? inventory.slots : taken.slots;549
const paid = addCoinsToSlots(slotsAfterTake, total);550
if (!paid.ok)551
{552
if (isCheque)553
{554
inventory.slots[slotIndex | 0] = chequeTaken.taken;555
if (Number(slot.instance.issuerCharacterId) === Number(characterId))556
{557
const vault = world.ecs.get(handle, Component.vault);558
if (vault && reservedStack)559
{ vault.reserved = [...(vault.reserved ?? []), reservedStack]; }560
}561
else if (reservedStack)562
{ world.restoreChequeReservation?.(slot.instance.issuerCharacterId, reservedStack); }563
}564
else565
{566
const def = itemDefinition(goodsItemId);567
inventory.slots = insertStack(taken.slots, taken.taken, def).slots;568
}569
throw userError("Not enough bag space for coins.");570
}571
inventory.slots = paid.slots;572
573
if (line && (line.quantity | 0) > 0 && refill > 0)574
{ shop.remaining[goodsItemId] = catalogAvailable(shop, goodsItemId) + refill; }575
if (leftover > 0)576
{ shop.boughtStock[goodsItemId] = boughtAvailable(shop, goodsItemId) + leftover; }577
578
const displayName = shopDisplayName(shop, npcHandle, world);579
return {580
events: [shopOpenEvent(world, sessionId, characterId, npcEntityId, shop, displayName, now)],169
private: bagView(world.ecs, handle)581
private: bagView(world.ecs, handle)170
};582
};171
}583
}@@ -182,9 +594,39 @@ export function handleShopCommand (world, sessionId, command, now)182
command.npcEntityId | 0,594
command.npcEntityId | 0,183
command.itemId | 0,595
command.itemId | 0,184
command.quantity | 0 || 1,596
command.quantity | 0 || 1,597
now,598
command.listingId ?? null,599
command.source ?? null600
);601
case "sell-to-shop":602
return sellToShop(603
world,604
sessionId,605
command.characterId,606
command.npcEntityId | 0,607
command.slotIndex | 0,608
command.quantity | 0 || 1,185
now609
now186
);610
);611
case "close-shop":612
return closeShop(world, sessionId, command.characterId, command.npcEntityId | 0);187
default:613
default:188
return null;614
return null;189
}615
}190
}616
}617
618
export function shopHasInterface (shop)619
{620
if (!shop)621
{ return false; }622
if (shop.buysItems)623
{ return true; }624
if ((shop.catalog?.length ?? 0) > 0)625
{ return true; }626
if (Object.keys(shop.boughtStock ?? {}).length > 0)627
{ return true; }628
// Legacy shops spawned before catalog migration.629
if ((shop.stock?.length ?? 0) > 0)630
{ return true; }631
return false;632
}@@ -104,6 +104,24 @@ export class Simulation
104
104
this.#configureWorkers();
105
105
}
106
106
107
/** Sparse last-sale map for editor base-price readouts (empty until marketplace writes). */
108
itemLastSalesSnapshot ()
109
{
110
const out = {};
111
for (const worker of this.workers)
112
{
113
const sales = worker.world?.itemLastSales;
114
if (!sales || typeof sales.entries !== "function")
115
{ continue; }
116
for (const [itemId, sale] of sales.entries())
117
{
118
if (sale)
119
{ out[String(itemId)] = sale; }
120
}
121
}
122
return out;
123
}
124
107
125
reloadWorld ()
108
126
{
109
127
this.activeRevisionId = this.worldDb.getActiveRevisionId();
@@ -104,6 +104,24 @@ export class Simulation104
this.#configureWorkers();104
this.#configureWorkers();105
}105
}106
106
107
/** Sparse last-sale map for editor base-price readouts (empty until marketplace writes). */108
itemLastSalesSnapshot ()109
{110
const out = {};111
for (const worker of this.workers)112
{113
const sales = worker.world?.itemLastSales;114
if (!sales || typeof sales.entries !== "function")115
{ continue; }116
for (const [itemId, sale] of sales.entries())117
{118
if (sale)119
{ out[String(itemId)] = sale; }120
}121
}122
return out;123
}124
107
reloadWorld ()125
reloadWorld ()108
{126
{109
this.activeRevisionId = this.worldDb.getActiveRevisionId();127
this.activeRevisionId = this.worldDb.getActiveRevisionId();@@ -52,6 +52,7 @@ export function collectSpawnRequests (world)
52
52
displayName: config.displayName,
53
53
equipment: config.equipment,
54
54
sells: config.sells,
55
buysItems: config.buysItems,
55
56
hiddenDiscount: config.hiddenDiscount
56
57
});
57
58
counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
@@ -133,15 +134,30 @@ export function mobComponents (request)
133
134
if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))
134
135
{ components.equipment = { slots: equipmentSlots }; }
135
136
136
const stock = Array.isArray(request.sells) && request.sells.length
137
? request.sells
138
: [...(def.sells ?? [])];
139
if (stock.length || def.talkable)
137
const catalog = Array.isArray(request.sells)
138
? request.sells.map((entry) =>
139
{
140
if (entry && typeof entry === "object")
141
{
142
return {
143
itemId: entry.itemId | 0,
144
quantity: Math.max(0, entry.quantity | 0 || 0)
145
};
146
}
147
return { itemId: entry | 0, quantity: 0 };
148
}).filter((line) => line.itemId > 0)
149
: [];
150
const buysItems = !!request.buysItems;
151
if (catalog.length || buysItems || def.talkable)
140
152
{
141
153
components.shop = {
142
stock: stock.map((id) => id | 0).filter((id) => id > 0),
154
catalog,
155
buysItems,
143
156
hiddenDiscount: Number(request.hiddenDiscount) || 0.9,
144
displayName
157
displayName,
158
remaining: Object.create(null),
159
boughtStock: Object.create(null),
160
restockDay: null
145
161
};
146
162
}
147
163
return components;
@@ -52,6 +52,7 @@ export function collectSpawnRequests (world)52
displayName: config.displayName,52
displayName: config.displayName,53
equipment: config.equipment,53
equipment: config.equipment,54
sells: config.sells,54
sells: config.sells,55
buysItems: config.buysItems,55
hiddenDiscount: config.hiddenDiscount56
hiddenDiscount: config.hiddenDiscount56
});57
});57
counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);58
counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);@@ -133,15 +134,30 @@ export function mobComponents (request)133
if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))134
if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))134
{ components.equipment = { slots: equipmentSlots }; }135
{ components.equipment = { slots: equipmentSlots }; }135
136
136
const stock = Array.isArray(request.sells) && request.sells.length137
const catalog = Array.isArray(request.sells)137
? request.sells138
? request.sells.map((entry) =>138
: [...(def.sells ?? [])];139
{139
if (stock.length || def.talkable)140
if (entry && typeof entry === "object")141
{142
return {143
itemId: entry.itemId | 0,144
quantity: Math.max(0, entry.quantity | 0 || 0)145
};146
}147
return { itemId: entry | 0, quantity: 0 };148
}).filter((line) => line.itemId > 0)149
: [];150
const buysItems = !!request.buysItems;151
if (catalog.length || buysItems || def.talkable)140
{152
{141
components.shop = {153
components.shop = {142
stock: stock.map((id) => id | 0).filter((id) => id > 0),154
catalog,155
buysItems,143
hiddenDiscount: Number(request.hiddenDiscount) || 0.9,156
hiddenDiscount: Number(request.hiddenDiscount) || 0.9,144
displayName157
displayName,158
remaining: Object.create(null),159
boughtStock: Object.create(null),160
restockDay: null145
};161
};146
}162
}147
return components;163
return components;@@ -1,4 +1,4 @@
1
import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
1
import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";
2
2
import {
3
3
chunkKey,
4
4
chunkToRegion,
@@ -38,7 +38,7 @@ import {
38
38
clearOreRespawnsForChunk
39
39
} from "../gathering/service.js";
40
40
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
41
import { handleShopCommand, openShop } from "../shop/service.js";
41
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
42
42
import {
43
43
applyRemoteMeleeSwing,
44
44
clearEngage,
@@ -46,6 +46,7 @@ import {
46
46
ensureMobCombat,
47
47
isUntargetable,
48
48
resolveCombatTarget,
49
stepAggression,
49
50
stepCombat
50
51
} from "../combat/service.js";
51
52
import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
@@ -346,6 +347,7 @@ export class WorkerWorld
346
347
347
348
#despawnCharacter (characterId)
348
349
{
350
releaseShopBrowsersForCharacter(this, characterId);
349
351
const entityId = this.characterEntities.get(characterId);
350
352
if (!entityId)
351
353
{ return null; }
@@ -660,15 +662,8 @@ export class WorkerWorld
660
662
{ this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
661
663
clearFollow(this.ecs, entityId);
662
664
cancelGather(this.ecs, handle);
665
// Engage only the attacker. Targets retaliate on the first resolved swing.
663
666
engageTarget(this.ecs, entityId, targetEntityId, now);
664
if (target.local)
665
{
666
if (ensureMobCombat(this.ecs, targetEntityId))
667
{ engageTarget(this.ecs, targetEntityId, entityId, now); }
668
const targetPath = this.ecs.get(target.handle, Component.path);
669
if (targetPath)
670
{ targetPath.tiles = []; }
671
}
672
667
const path = this.ecs.get(handle, Component.path);
673
668
if (path)
674
669
{ path.tiles = []; }
@@ -677,23 +672,10 @@ export class WorkerWorld
677
672
678
673
#remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
679
674
{
680
const targetHandle = this.ecs.handleOf(targetEntityId);
681
if (targetHandle == null)
682
{ return { events: [] }; }
683
if (ensureMobCombat(this.ecs, targetEntityId))
684
{
685
engageTarget(this.ecs, targetEntityId, attackerEntityId, now);
686
const targetPath = this.ecs.get(targetHandle, Component.path);
687
if (targetPath)
688
{ targetPath.tiles = []; }
689
}
690
else if (this.ecs.get(targetHandle, Component.character))
691
{
692
engageTarget(this.ecs, targetEntityId, attackerEntityId, now);
693
const targetPath = this.ecs.get(targetHandle, Component.path);
694
if (targetPath)
695
{ targetPath.tiles = []; }
696
}
675
// Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click.
676
void attackerEntityId;
677
void targetEntityId;
678
void now;
697
679
return { events: [] };
698
680
}
699
681
@@ -750,7 +732,7 @@ export class WorkerWorld
750
732
const creature = this.ecs.get(targetHandle, Component.creature);
751
733
const def = creature ? mobDefinition(creature.mobTypeId) : null;
752
734
const shop = this.ecs.get(targetHandle, Component.shop);
753
if (shop?.stock?.length)
735
if (shopHasInterface(shop))
754
736
{ return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
755
737
if (!def?.talkable)
756
738
{
@@ -954,6 +936,7 @@ export class WorkerWorld
954
936
}
955
937
events.push(event);
956
938
}
939
stepAggression(this, now);
957
940
events.push(...stepCombat(this, now));
958
941
stepFollow(this);
959
942
const gather = stepGather(this, now);
@@ -983,6 +966,7 @@ export class WorkerWorld
983
966
{
984
967
const events = expireGroundItems(this, now);
985
968
const transferRequests = [];
969
events.push(...pruneShopBrowsers(this));
986
970
this.#queueAmbientWander();
987
971
this.#queueSpawnerWander();
988
972
for (const entity of this.ecs.query(Component.position, Component.movement))
@@ -995,10 +979,16 @@ export class WorkerWorld
995
979
const path = this.ecs.get(handle, Component.path);
996
980
const tiles = path?.tiles;
997
981
if (this.frozen.has(entityId) || !tiles?.length)
998
{ continue; }
982
{
983
if (path)
984
{ path.stuckSince = null; }
985
continue;
986
}
999
987
if (!this.chunkIsSimulating(position.tileX, position.tileY))
1000
988
{ continue; }
1001
989
990
this.#repathIfNavigationStuck(entityId, position, movement, path, now);
991
1002
992
const stamina = this.ecs.get(handle, Component.stamina);
1003
993
if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))
1004
994
{ movement.gait = GAIT.walk; }
@@ -1011,6 +1001,8 @@ export class WorkerWorld
1011
1001
}
1012
1002
1013
1003
const next = tiles[0];
1004
if (!next)
1005
{ continue; }
1014
1006
const destRegionX = tileToRegion(next.x);
1015
1007
const destRegionY = tileToRegion(next.y);
1016
1008
if (!this.ownsRegion(destRegionX, destRegionY))
@@ -1057,6 +1049,9 @@ export class WorkerWorld
1057
1049
tiles.shift();
1058
1050
if (!flying)
1059
1051
{ this.#occupy(entityId, position.tileX, position.tileY); }
1052
path.stuckSince = now;
1053
path.stuckTileX = position.tileX;
1054
path.stuckTileY = position.tileY;
1060
1055
recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
1061
1056
consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1062
1057
if (!isWalk)
@@ -1066,6 +1061,57 @@ export class WorkerWorld
1066
1061
return { events, transferRequests };
1067
1062
}
1068
1063
1064
/**
1065
* If we still have a destination but have not left this tile for NAV_STUCK_MS,
1066
* recompute A* to the same goal (around whoever is blocking the old route).
1067
*/
1068
#repathIfNavigationStuck (entityId, position, movement, path, now)
1069
{
1070
if (!path?.tiles?.length)
1071
{
1072
path.stuckSince = null;
1073
return;
1074
}
1075
if (
1076
path.stuckSince == null
1077
|| path.stuckTileX !== position.tileX
1078
|| path.stuckTileY !== position.tileY
1079
)
1080
{
1081
path.stuckSince = now;
1082
path.stuckTileX = position.tileX;
1083
path.stuckTileY = position.tileY;
1084
return;
1085
}
1086
if (now - path.stuckSince < NAV_STUCK_MS)
1087
{ return; }
1088
1089
const goal = path.tiles[path.tiles.length - 1];
1090
if (!goal || (goal.x === position.tileX && goal.y === position.tileY))
1091
{
1092
path.tiles = [];
1093
path.stuckSince = null;
1094
return;
1095
}
1096
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1097
path.tiles = findPath(
1098
position.tileX,
1099
position.tileY,
1100
goal.x,
1101
goal.y,
1102
(x, y) => this.walkableFor(entityId, x, y),
1103
bounds.minX,
1104
bounds.minY,
1105
bounds.maxX,
1106
bounds.maxY
1107
);
1108
path.stuckSince = now;
1109
path.stuckTileX = position.tileX;
1110
path.stuckTileY = position.tileY;
1111
if (movement)
1112
{ movement.walkCarry = 0; }
1113
}
1114
1069
1115
#queueAmbientWander ()
1070
1116
{
1071
1117
for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
@@ -1108,6 +1154,9 @@ export class WorkerWorld
1108
1154
const follow = this.ecs.get(entity.handle, Component.follow);
1109
1155
if (follow?.targetEntityId != null)
1110
1156
{ continue; }
1157
const shop = this.ecs.get(entity.handle, Component.shop);
1158
if (shopHasActiveBrowsers(shop))
1159
{ continue; }
1111
1160
const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1112
1161
if (def?.freeFlight)
1113
1162
{ continue; }
@@ -1,4 +1,4 @@1
import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";1
import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";2
import {2
import {3
chunkKey,3
chunkKey,4
chunkToRegion,4
chunkToRegion,@@ -38,7 +38,7 @@ import {38
clearOreRespawnsForChunk38
clearOreRespawnsForChunk39
} from "../gathering/service.js";39
} from "../gathering/service.js";40
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";40
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";41
import { handleShopCommand, openShop } from "../shop/service.js";41
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";42
import {42
import {43
applyRemoteMeleeSwing,43
applyRemoteMeleeSwing,44
clearEngage,44
clearEngage,@@ -46,6 +46,7 @@ import {46
ensureMobCombat,46
ensureMobCombat,47
isUntargetable,47
isUntargetable,48
resolveCombatTarget,48
resolveCombatTarget,49
stepAggression,49
stepCombat50
stepCombat50
} from "../combat/service.js";51
} from "../combat/service.js";51
import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";52
import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";@@ -346,6 +347,7 @@ export class WorkerWorld346
347
347
#despawnCharacter (characterId)348
#despawnCharacter (characterId)348
{349
{350
releaseShopBrowsersForCharacter(this, characterId);349
const entityId = this.characterEntities.get(characterId);351
const entityId = this.characterEntities.get(characterId);350
if (!entityId)352
if (!entityId)351
{ return null; }353
{ return null; }@@ -660,15 +662,8 @@ export class WorkerWorld660
{ this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }662
{ this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }661
clearFollow(this.ecs, entityId);663
clearFollow(this.ecs, entityId);662
cancelGather(this.ecs, handle);664
cancelGather(this.ecs, handle);665
// Engage only the attacker. Targets retaliate on the first resolved swing.663
engageTarget(this.ecs, entityId, targetEntityId, now);666
engageTarget(this.ecs, entityId, targetEntityId, now);664
if (target.local)665
{666
if (ensureMobCombat(this.ecs, targetEntityId))667
{ engageTarget(this.ecs, targetEntityId, entityId, now); }668
const targetPath = this.ecs.get(target.handle, Component.path);669
if (targetPath)670
{ targetPath.tiles = []; }671
}672
const path = this.ecs.get(handle, Component.path);667
const path = this.ecs.get(handle, Component.path);673
if (path)668
if (path)674
{ path.tiles = []; }669
{ path.tiles = []; }@@ -677,23 +672,10 @@ export class WorkerWorld677
672
678
#remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })673
#remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })679
{674
{680
const targetHandle = this.ecs.handleOf(targetEntityId);675
// Kept for cross-worker hooks; retaliation happens on swing resolution, not Attack click.681
if (targetHandle == null)676
void attackerEntityId;682
{ return { events: [] }; }677
void targetEntityId;683
if (ensureMobCombat(this.ecs, targetEntityId))678
void now;684
{685
engageTarget(this.ecs, targetEntityId, attackerEntityId, now);686
const targetPath = this.ecs.get(targetHandle, Component.path);687
if (targetPath)688
{ targetPath.tiles = []; }689
}690
else if (this.ecs.get(targetHandle, Component.character))691
{692
engageTarget(this.ecs, targetEntityId, attackerEntityId, now);693
const targetPath = this.ecs.get(targetHandle, Component.path);694
if (targetPath)695
{ targetPath.tiles = []; }696
}697
return { events: [] };679
return { events: [] };698
}680
}699
681
@@ -750,7 +732,7 @@ export class WorkerWorld750
const creature = this.ecs.get(targetHandle, Component.creature);732
const creature = this.ecs.get(targetHandle, Component.creature);751
const def = creature ? mobDefinition(creature.mobTypeId) : null;733
const def = creature ? mobDefinition(creature.mobTypeId) : null;752
const shop = this.ecs.get(targetHandle, Component.shop);734
const shop = this.ecs.get(targetHandle, Component.shop);753
if (shop?.stock?.length)735
if (shopHasInterface(shop))754
{ return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }736
{ return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }755
if (!def?.talkable)737
if (!def?.talkable)756
{738
{@@ -954,6 +936,7 @@ export class WorkerWorld954
}936
}955
events.push(event);937
events.push(event);956
}938
}939
stepAggression(this, now);957
events.push(...stepCombat(this, now));940
events.push(...stepCombat(this, now));958
stepFollow(this);941
stepFollow(this);959
const gather = stepGather(this, now);942
const gather = stepGather(this, now);@@ -983,6 +966,7 @@ export class WorkerWorld983
{966
{984
const events = expireGroundItems(this, now);967
const events = expireGroundItems(this, now);985
const transferRequests = [];968
const transferRequests = [];969
events.push(...pruneShopBrowsers(this));986
this.#queueAmbientWander();970
this.#queueAmbientWander();987
this.#queueSpawnerWander();971
this.#queueSpawnerWander();988
for (const entity of this.ecs.query(Component.position, Component.movement))972
for (const entity of this.ecs.query(Component.position, Component.movement))@@ -995,10 +979,16 @@ export class WorkerWorld995
const path = this.ecs.get(handle, Component.path);979
const path = this.ecs.get(handle, Component.path);996
const tiles = path?.tiles;980
const tiles = path?.tiles;997
if (this.frozen.has(entityId) || !tiles?.length)981
if (this.frozen.has(entityId) || !tiles?.length)998
{ continue; }982
{983
if (path)984
{ path.stuckSince = null; }985
continue;986
}999
if (!this.chunkIsSimulating(position.tileX, position.tileY))987
if (!this.chunkIsSimulating(position.tileX, position.tileY))1000
{ continue; }988
{ continue; }1001
989
990
this.#repathIfNavigationStuck(entityId, position, movement, path, now);991
1002
const stamina = this.ecs.get(handle, Component.stamina);992
const stamina = this.ecs.get(handle, Component.stamina);1003
if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))993
if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))1004
{ movement.gait = GAIT.walk; }994
{ movement.gait = GAIT.walk; }@@ -1011,6 +1001,8 @@ export class WorkerWorld1011
}1001
}1012
1002
1013
const next = tiles[0];1003
const next = tiles[0];1004
if (!next)1005
{ continue; }1014
const destRegionX = tileToRegion(next.x);1006
const destRegionX = tileToRegion(next.x);1015
const destRegionY = tileToRegion(next.y);1007
const destRegionY = tileToRegion(next.y);1016
if (!this.ownsRegion(destRegionX, destRegionY))1008
if (!this.ownsRegion(destRegionX, destRegionY))@@ -1057,6 +1049,9 @@ export class WorkerWorld1057
tiles.shift();1049
tiles.shift();1058
if (!flying)1050
if (!flying)1059
{ this.#occupy(entityId, position.tileX, position.tileY); }1051
{ this.#occupy(entityId, position.tileX, position.tileY); }1052
path.stuckSince = now;1053
path.stuckTileX = position.tileX;1054
path.stuckTileY = position.tileY;1060
recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);1055
recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);1061
consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);1056
consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);1062
if (!isWalk)1057
if (!isWalk)@@ -1066,6 +1061,57 @@ export class WorkerWorld1066
return { events, transferRequests };1061
return { events, transferRequests };1067
}1062
}1068
1063
1064
/**1065
* If we still have a destination but have not left this tile for NAV_STUCK_MS,1066
* recompute A* to the same goal (around whoever is blocking the old route).1067
*/1068
#repathIfNavigationStuck (entityId, position, movement, path, now)1069
{1070
if (!path?.tiles?.length)1071
{1072
path.stuckSince = null;1073
return;1074
}1075
if (1076
path.stuckSince == null1077
|| path.stuckTileX !== position.tileX1078
|| path.stuckTileY !== position.tileY1079
)1080
{1081
path.stuckSince = now;1082
path.stuckTileX = position.tileX;1083
path.stuckTileY = position.tileY;1084
return;1085
}1086
if (now - path.stuckSince < NAV_STUCK_MS)1087
{ return; }1088
1089
const goal = path.tiles[path.tiles.length - 1];1090
if (!goal || (goal.x === position.tileX && goal.y === position.tileY))1091
{1092
path.tiles = [];1093
path.stuckSince = null;1094
return;1095
}1096
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);1097
path.tiles = findPath(1098
position.tileX,1099
position.tileY,1100
goal.x,1101
goal.y,1102
(x, y) => this.walkableFor(entityId, x, y),1103
bounds.minX,1104
bounds.minY,1105
bounds.maxX,1106
bounds.maxY1107
);1108
path.stuckSince = now;1109
path.stuckTileX = position.tileX;1110
path.stuckTileY = position.tileY;1111
if (movement)1112
{ movement.walkCarry = 0; }1113
}1114
1069
#queueAmbientWander ()1115
#queueAmbientWander ()1070
{1116
{1071
for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))1117
for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))@@ -1108,6 +1154,9 @@ export class WorkerWorld1108
const follow = this.ecs.get(entity.handle, Component.follow);1154
const follow = this.ecs.get(entity.handle, Component.follow);1109
if (follow?.targetEntityId != null)1155
if (follow?.targetEntityId != null)1110
{ continue; }1156
{ continue; }1157
const shop = this.ecs.get(entity.handle, Component.shop);1158
if (shopHasActiveBrowsers(shop))1159
{ continue; }1111
const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);1160
const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);1112
if (def?.freeFlight)1161
if (def?.freeFlight)1113
{ continue; }1162
{ continue; }@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
3
3
import { mobComponents } from "../src/simulation/spawners.js";
4
4
import { MobId } from "../../shared/definitions/mobs.js";
5
5
import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6
import { BlockType } from "../../shared/definitions/tiles.js";
6
7
import { Component } from "../src/ecs/components.js";
7
8
import { tileKey } from "../src/world/coordinates.js";
8
9
import { WorkerMessage } from "../src/simulation/protocol.js";
@@ -346,31 +347,44 @@ test("cross-worker adjacent click attack ends with player or deer dead", () =>
346
347
});
347
348
});
348
349
349
test("attack engages both combatants and retaliates", () =>
350
test("attack engages the attacker; target retaliates on first swing", () =>
350
351
{
351
352
const harness = makeSimulation({ workerCount: 1 });
352
353
try
353
354
{
354
355
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
355
356
const playerId = harness.simulation.spawnCharacter(1, character);
356
const ratId = harness.simulation.spawnEntity(mobComponents({
357
tileX: 9,
357
// Deer are not aggressive — only retaliate after a real swing.
358
const deerId = harness.simulation.spawnEntity(mobComponents({
359
tileX: 12,
358
360
tileY: 8,
359
mobTypeId: MobId.rat,
361
mobTypeId: MobId.deer,
360
362
spawnerId: null
361
363
}));
362
364
363
365
harness.simulation.enqueue(1, {
364
366
type: "attack",
365
367
characterId: character.character_id,
366
targetEntityId: ratId
368
targetEntityId: deerId
367
369
});
368
370
harness.simulation.step();
369
371
370
const player = componentsOf(harness.simulation, playerId);
371
const rat = componentsOf(harness.simulation, ratId);
372
assert.equal(player.combat.targetEntityId, ratId);
373
assert.equal(rat.combat.targetEntityId, playerId);
372
assert.equal(componentsOf(harness.simulation, playerId).combat.targetEntityId, deerId);
373
assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId ?? null, null);
374
375
let swung = false;
376
for (let i = 0; i < 80; i++)
377
{
378
harness.advance(50);
379
const events = harness.simulation.step().events;
380
if (events.some((event) => event.type === "combat-swing"))
381
{
382
swung = true;
383
break;
384
}
385
}
386
assert.ok(swung, "expected a melee swing once adjacent");
387
assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
374
388
}
375
389
finally
376
390
{ harness.close(); }
@@ -487,7 +501,8 @@ test("deer retaliate when attacked", () =>
487
501
characterId: character.character_id,
488
502
targetEntityId: deerId
489
503
});
490
harness.simulation.step();
504
const events = harness.simulation.step().events;
505
assert.ok(events.some((event) => event.type === "combat-swing"));
491
506
492
507
const deer = componentsOf(harness.simulation, deerId);
493
508
assert.equal(deer.combat?.targetEntityId, playerId);
@@ -497,6 +512,61 @@ test("deer retaliate when attacked", () =>
497
512
{ harness.close(); }
498
513
});
499
514
515
test("aggressive rats engage players within aggro range and LOS", () =>
516
{
517
const harness = makeSimulation({ workerCount: 1 });
518
try
519
{
520
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
521
const playerId = harness.simulation.spawnCharacter(1, character);
522
const ratId = harness.simulation.spawnEntity(mobComponents({
523
tileX: 12,
524
tileY: 8,
525
mobTypeId: MobId.rat,
526
spawnerId: null
527
}));
528
529
harness.simulation.step();
530
assert.equal(componentsOf(harness.simulation, ratId).combat?.targetEntityId, playerId);
531
}
532
finally
533
{ harness.close(); }
534
});
535
536
test("aggressive rats do not aggro through walls or beyond range", () =>
537
{
538
const harness = makeSimulation({ workerCount: 1 });
539
try
540
{
541
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
542
const playerId = harness.simulation.spawnCharacter(1, character);
543
const record = harness.simulation.entityRecord(playerId);
544
const worker = harness.simulation.workers[record.workerId];
545
546
const blockedRat = harness.simulation.spawnEntity(mobComponents({
547
tileX: 12,
548
tileY: 8,
549
mobTypeId: MobId.rat,
550
spawnerId: null
551
}));
552
const data = worker.world.chunkData(0, 0);
553
data.blocks[8 * 16 + 10] = { typeId: BlockType.stoneWall, state: null, config: null };
554
555
const farRat = harness.simulation.spawnEntity(mobComponents({
556
tileX: 14,
557
tileY: 8,
558
mobTypeId: MobId.rat,
559
spawnerId: null
560
}));
561
562
harness.simulation.step();
563
assert.equal(componentsOf(harness.simulation, blockedRat).combat?.targetEntityId ?? null, null);
564
assert.equal(componentsOf(harness.simulation, farRat).combat?.targetEntityId ?? null, null);
565
}
566
finally
567
{ harness.close(); }
568
});
569
500
570
test("attacker keeps pursuing and can swing after the target moves", () =>
501
571
{
502
572
const harness = makeSimulation({ workerCount: 1 });
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";3
import { mobComponents } from "../src/simulation/spawners.js";3
import { mobComponents } from "../src/simulation/spawners.js";4
import { MobId } from "../../shared/definitions/mobs.js";4
import { MobId } from "../../shared/definitions/mobs.js";5
import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";5
import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";6
import { BlockType } from "../../shared/definitions/tiles.js";6
import { Component } from "../src/ecs/components.js";7
import { Component } from "../src/ecs/components.js";7
import { tileKey } from "../src/world/coordinates.js";8
import { tileKey } from "../src/world/coordinates.js";8
import { WorkerMessage } from "../src/simulation/protocol.js";9
import { WorkerMessage } from "../src/simulation/protocol.js";@@ -346,31 +347,44 @@ test("cross-worker adjacent click attack ends with player or deer dead", () =>346
});347
});347
});348
});348
349
349
test("attack engages both combatants and retaliates", () =>350
test("attack engages the attacker; target retaliates on first swing", () =>350
{351
{351
const harness = makeSimulation({ workerCount: 1 });352
const harness = makeSimulation({ workerCount: 1 });352
try353
try353
{354
{354
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });355
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });355
const playerId = harness.simulation.spawnCharacter(1, character);356
const playerId = harness.simulation.spawnCharacter(1, character);356
const ratId = harness.simulation.spawnEntity(mobComponents({357
// Deer are not aggressive — only retaliate after a real swing.357
tileX: 9,358
const deerId = harness.simulation.spawnEntity(mobComponents({359
tileX: 12,358
tileY: 8,360
tileY: 8,359
mobTypeId: MobId.rat,361
mobTypeId: MobId.deer,360
spawnerId: null362
spawnerId: null361
}));363
}));362
364
363
harness.simulation.enqueue(1, {365
harness.simulation.enqueue(1, {364
type: "attack",366
type: "attack",365
characterId: character.character_id,367
characterId: character.character_id,366
targetEntityId: ratId368
targetEntityId: deerId367
});369
});368
harness.simulation.step();370
harness.simulation.step();369
371
370
const player = componentsOf(harness.simulation, playerId);372
assert.equal(componentsOf(harness.simulation, playerId).combat.targetEntityId, deerId);371
const rat = componentsOf(harness.simulation, ratId);373
assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId ?? null, null);372
assert.equal(player.combat.targetEntityId, ratId);374
373
assert.equal(rat.combat.targetEntityId, playerId);375
let swung = false;376
for (let i = 0; i < 80; i++)377
{378
harness.advance(50);379
const events = harness.simulation.step().events;380
if (events.some((event) => event.type === "combat-swing"))381
{382
swung = true;383
break;384
}385
}386
assert.ok(swung, "expected a melee swing once adjacent");387
assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);374
}388
}375
finally389
finally376
{ harness.close(); }390
{ harness.close(); }@@ -487,7 +501,8 @@ test("deer retaliate when attacked", () =>487
characterId: character.character_id,501
characterId: character.character_id,488
targetEntityId: deerId502
targetEntityId: deerId489
});503
});490
harness.simulation.step();504
const events = harness.simulation.step().events;505
assert.ok(events.some((event) => event.type === "combat-swing"));491
506
492
const deer = componentsOf(harness.simulation, deerId);507
const deer = componentsOf(harness.simulation, deerId);493
assert.equal(deer.combat?.targetEntityId, playerId);508
assert.equal(deer.combat?.targetEntityId, playerId);@@ -497,6 +512,61 @@ test("deer retaliate when attacked", () =>497
{ harness.close(); }512
{ harness.close(); }498
});513
});499
514
515
test("aggressive rats engage players within aggro range and LOS", () =>516
{517
const harness = makeSimulation({ workerCount: 1 });518
try519
{520
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });521
const playerId = harness.simulation.spawnCharacter(1, character);522
const ratId = harness.simulation.spawnEntity(mobComponents({523
tileX: 12,524
tileY: 8,525
mobTypeId: MobId.rat,526
spawnerId: null527
}));528
529
harness.simulation.step();530
assert.equal(componentsOf(harness.simulation, ratId).combat?.targetEntityId, playerId);531
}532
finally533
{ harness.close(); }534
});535
536
test("aggressive rats do not aggro through walls or beyond range", () =>537
{538
const harness = makeSimulation({ workerCount: 1 });539
try540
{541
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });542
const playerId = harness.simulation.spawnCharacter(1, character);543
const record = harness.simulation.entityRecord(playerId);544
const worker = harness.simulation.workers[record.workerId];545
546
const blockedRat = harness.simulation.spawnEntity(mobComponents({547
tileX: 12,548
tileY: 8,549
mobTypeId: MobId.rat,550
spawnerId: null551
}));552
const data = worker.world.chunkData(0, 0);553
data.blocks[8 * 16 + 10] = { typeId: BlockType.stoneWall, state: null, config: null };554
555
const farRat = harness.simulation.spawnEntity(mobComponents({556
tileX: 14,557
tileY: 8,558
mobTypeId: MobId.rat,559
spawnerId: null560
}));561
562
harness.simulation.step();563
assert.equal(componentsOf(harness.simulation, blockedRat).combat?.targetEntityId ?? null, null);564
assert.equal(componentsOf(harness.simulation, farRat).combat?.targetEntityId ?? null, null);565
}566
finally567
{ harness.close(); }568
});569
500
test("attacker keeps pursuing and can swing after the target moves", () =>570
test("attacker keeps pursuing and can swing after the target moves", () =>501
{571
{502
const harness = makeSimulation({ workerCount: 1 });572
const harness = makeSimulation({ workerCount: 1 });@@ -72,7 +72,7 @@ function advanceMs (harness, ms)
72
72
}
73
73
}
74
74
75
test("furnace recipes: bronze is tin+copper; steel is iron+coal", () =>
75
test("furnace recipes: bronze is tin+copper; steel is iron+coal; high tiers need coal", () =>
76
76
{
77
77
assert.equal(blockDefinition(BlockType.furnace)?.key, "furnace");
78
78
const bronze = recipeDefinition("smelt-bronze");
@@ -91,6 +91,36 @@ test("furnace recipes: bronze is tin+copper; steel is iron+coal", () =>
91
91
ItemId.ironOre
92
92
].sort());
93
93
assert.equal(steel.output.itemId, ItemId.steelBar);
94
95
const silver = recipesForStation(CraftingStationId.furnace)
96
.find((recipe) => recipe.recipeId === "smelt-silver");
97
assert.ok(silver);
98
assert.deepEqual(silver.inputs.map((row) => row.itemId), [ItemId.silverOre]);
99
assert.equal(silver.output.itemId, ItemId.silverBar);
100
assert.equal(silver.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.silver));
101
102
const gold = recipesForStation(CraftingStationId.furnace)
103
.find((recipe) => recipe.recipeId === "smelt-gold");
104
assert.ok(gold);
105
assert.deepEqual(gold.inputs.map((row) => row.itemId), [ItemId.goldOre]);
106
assert.equal(gold.output.itemId, ItemId.goldBar);
107
assert.equal(gold.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.gold));
108
109
const adamantium = recipeDefinition("smelt-adamantium");
110
assert.deepEqual(adamantium.inputs, [
111
{ itemId: ItemId.adamantiumOre, quantity: 1 },
112
{ itemId: ItemId.coal, quantity: 1 }
113
]);
114
const orichalcum = recipeDefinition("smelt-orichalcum");
115
assert.deepEqual(orichalcum.inputs, [
116
{ itemId: ItemId.orichalcumOre, quantity: 1 },
117
{ itemId: ItemId.coal, quantity: 3 }
118
]);
119
const dragon = recipeDefinition("smelt-dragon");
120
assert.deepEqual(dragon.inputs, [
121
{ itemId: ItemId.dragonOre, quantity: 1 },
122
{ itemId: ItemId.coal, quantity: 5 }
123
]);
94
124
});
95
125
96
126
test("tin copper coal map to associated bar tiers for smelt duration", () =>
@@ -98,12 +128,18 @@ test("tin copper coal map to associated bar tiers for smelt duration", () =>
98
128
assert.equal(associatedBarTier(GatherMaterialId.tin), MaterialTier.bronze);
99
129
assert.equal(associatedBarTier(GatherMaterialId.copper), MaterialTier.bronze);
100
130
assert.equal(associatedBarTier(GatherMaterialId.coal), MaterialTier.steel);
131
assert.equal(associatedBarTier(GatherMaterialId.silver), GatherMaterialId.silver);
132
assert.equal(associatedBarTier(GatherMaterialId.gold), GatherMaterialId.gold);
101
133
assert.equal(smeltingDurationMs(MaterialTier.bronze), 2000);
102
134
assert.equal(smeltingDurationMs(GatherMaterialId.tin), 2000);
103
135
assert.equal(smeltingDurationMs(MaterialTier.steel), 6000);
104
136
assert.equal(smeltingDurationMs(GatherMaterialId.coal), 6000);
137
assert.equal(smeltingDurationMs(GatherMaterialId.silver), 4000);
138
assert.equal(smeltingDurationMs(GatherMaterialId.gold), 6000);
105
139
assert.equal(craftDurationMs(recipeDefinition("smelt-bronze"), CRAFT_DURATION_MS), 2000);
106
140
assert.equal(craftDurationMs(recipeDefinition("smelt-steel"), CRAFT_DURATION_MS), 6000);
141
assert.equal(craftDurationMs(recipeDefinition("smelt-silver"), CRAFT_DURATION_MS), 4000);
142
assert.equal(craftDurationMs(recipeDefinition("smelt-gold"), CRAFT_DURATION_MS), 6000);
107
143
});
108
144
109
145
test("open furnace near station emits shove and station-open", () =>
@@ -306,6 +342,7 @@ test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe"
306
342
const worker = harness.simulation.workers[record.workerId];
307
343
placeStation(worker, 9, 8, BlockType.woodworkingBench, "woodworking-bench");
308
344
placeStation(worker, 9, 9, BlockType.anvil, "anvil");
345
placeStation(worker, 8, 9, BlockType.craftingBench, "crafting-bench");
309
346
giveInventory(harness, playerId, [
310
347
{ itemId: ItemId.pineLog, quantity: 1 },
311
348
{ itemId: ItemId.bronzeBar, quantity: 1 }
@@ -336,7 +373,7 @@ test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe"
336
373
harness.simulation.enqueue(1, {
337
374
type: "start-craft",
338
375
characterId: character.character_id,
339
stationId: CraftingStationId.woodworkingBench,
376
stationId: CraftingStationId.craftingBench,
340
377
recipeId: "pickaxe-bronze"
341
378
});
342
379
advanceMs(harness, craftDurationMs(recipeDefinition("pickaxe-bronze"), CRAFT_DURATION_MS));
@@ -72,7 +72,7 @@ function advanceMs (harness, ms)72
}72
}73
}73
}74
74
75
test("furnace recipes: bronze is tin+copper; steel is iron+coal", () =>75
test("furnace recipes: bronze is tin+copper; steel is iron+coal; high tiers need coal", () =>76
{76
{77
assert.equal(blockDefinition(BlockType.furnace)?.key, "furnace");77
assert.equal(blockDefinition(BlockType.furnace)?.key, "furnace");78
const bronze = recipeDefinition("smelt-bronze");78
const bronze = recipeDefinition("smelt-bronze");@@ -91,6 +91,36 @@ test("furnace recipes: bronze is tin+copper; steel is iron+coal", () =>91
ItemId.ironOre91
ItemId.ironOre92
].sort());92
].sort());93
assert.equal(steel.output.itemId, ItemId.steelBar);93
assert.equal(steel.output.itemId, ItemId.steelBar);94
95
const silver = recipesForStation(CraftingStationId.furnace)96
.find((recipe) => recipe.recipeId === "smelt-silver");97
assert.ok(silver);98
assert.deepEqual(silver.inputs.map((row) => row.itemId), [ItemId.silverOre]);99
assert.equal(silver.output.itemId, ItemId.silverBar);100
assert.equal(silver.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.silver));101
102
const gold = recipesForStation(CraftingStationId.furnace)103
.find((recipe) => recipe.recipeId === "smelt-gold");104
assert.ok(gold);105
assert.deepEqual(gold.inputs.map((row) => row.itemId), [ItemId.goldOre]);106
assert.equal(gold.output.itemId, ItemId.goldBar);107
assert.equal(gold.minSkillLevel, tierSmeltSkillLevel(GatherMaterialId.gold));108
109
const adamantium = recipeDefinition("smelt-adamantium");110
assert.deepEqual(adamantium.inputs, [111
{ itemId: ItemId.adamantiumOre, quantity: 1 },112
{ itemId: ItemId.coal, quantity: 1 }113
]);114
const orichalcum = recipeDefinition("smelt-orichalcum");115
assert.deepEqual(orichalcum.inputs, [116
{ itemId: ItemId.orichalcumOre, quantity: 1 },117
{ itemId: ItemId.coal, quantity: 3 }118
]);119
const dragon = recipeDefinition("smelt-dragon");120
assert.deepEqual(dragon.inputs, [121
{ itemId: ItemId.dragonOre, quantity: 1 },122
{ itemId: ItemId.coal, quantity: 5 }123
]);94
});124
});95
125
96
test("tin copper coal map to associated bar tiers for smelt duration", () =>126
test("tin copper coal map to associated bar tiers for smelt duration", () =>@@ -98,12 +128,18 @@ test("tin copper coal map to associated bar tiers for smelt duration", () =>98
assert.equal(associatedBarTier(GatherMaterialId.tin), MaterialTier.bronze);128
assert.equal(associatedBarTier(GatherMaterialId.tin), MaterialTier.bronze);99
assert.equal(associatedBarTier(GatherMaterialId.copper), MaterialTier.bronze);129
assert.equal(associatedBarTier(GatherMaterialId.copper), MaterialTier.bronze);100
assert.equal(associatedBarTier(GatherMaterialId.coal), MaterialTier.steel);130
assert.equal(associatedBarTier(GatherMaterialId.coal), MaterialTier.steel);131
assert.equal(associatedBarTier(GatherMaterialId.silver), GatherMaterialId.silver);132
assert.equal(associatedBarTier(GatherMaterialId.gold), GatherMaterialId.gold);101
assert.equal(smeltingDurationMs(MaterialTier.bronze), 2000);133
assert.equal(smeltingDurationMs(MaterialTier.bronze), 2000);102
assert.equal(smeltingDurationMs(GatherMaterialId.tin), 2000);134
assert.equal(smeltingDurationMs(GatherMaterialId.tin), 2000);103
assert.equal(smeltingDurationMs(MaterialTier.steel), 6000);135
assert.equal(smeltingDurationMs(MaterialTier.steel), 6000);104
assert.equal(smeltingDurationMs(GatherMaterialId.coal), 6000);136
assert.equal(smeltingDurationMs(GatherMaterialId.coal), 6000);137
assert.equal(smeltingDurationMs(GatherMaterialId.silver), 4000);138
assert.equal(smeltingDurationMs(GatherMaterialId.gold), 6000);105
assert.equal(craftDurationMs(recipeDefinition("smelt-bronze"), CRAFT_DURATION_MS), 2000);139
assert.equal(craftDurationMs(recipeDefinition("smelt-bronze"), CRAFT_DURATION_MS), 2000);106
assert.equal(craftDurationMs(recipeDefinition("smelt-steel"), CRAFT_DURATION_MS), 6000);140
assert.equal(craftDurationMs(recipeDefinition("smelt-steel"), CRAFT_DURATION_MS), 6000);141
assert.equal(craftDurationMs(recipeDefinition("smelt-silver"), CRAFT_DURATION_MS), 4000);142
assert.equal(craftDurationMs(recipeDefinition("smelt-gold"), CRAFT_DURATION_MS), 6000);107
});143
});108
144
109
test("open furnace near station emits shove and station-open", () =>145
test("open furnace near station emits shove and station-open", () =>@@ -306,6 +342,7 @@ test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe"306
const worker = harness.simulation.workers[record.workerId];342
const worker = harness.simulation.workers[record.workerId];307
placeStation(worker, 9, 8, BlockType.woodworkingBench, "woodworking-bench");343
placeStation(worker, 9, 8, BlockType.woodworkingBench, "woodworking-bench");308
placeStation(worker, 9, 9, BlockType.anvil, "anvil");344
placeStation(worker, 9, 9, BlockType.anvil, "anvil");345
placeStation(worker, 8, 9, BlockType.craftingBench, "crafting-bench");309
giveInventory(harness, playerId, [346
giveInventory(harness, playerId, [310
{ itemId: ItemId.pineLog, quantity: 1 },347
{ itemId: ItemId.pineLog, quantity: 1 },311
{ itemId: ItemId.bronzeBar, quantity: 1 }348
{ itemId: ItemId.bronzeBar, quantity: 1 }@@ -336,7 +373,7 @@ test("bronze pickaxe chain: pine log → handle, bar → head, assemble pickaxe"336
harness.simulation.enqueue(1, {373
harness.simulation.enqueue(1, {337
type: "start-craft",374
type: "start-craft",338
characterId: character.character_id,375
characterId: character.character_id,339
stationId: CraftingStationId.woodworkingBench,376
stationId: CraftingStationId.craftingBench,340
recipeId: "pickaxe-bronze"377
recipeId: "pickaxe-bronze"341
});378
});342
advanceMs(harness, craftDurationMs(recipeDefinition("pickaxe-bronze"), CRAFT_DURATION_MS));379
advanceMs(harness, craftDurationMs(recipeDefinition("pickaxe-bronze"), CRAFT_DURATION_MS));@@ -86,9 +86,10 @@ test("crafting item stubs are registered", () =>
86
86
assert.equal(itemDefinition(CraftingItemId.bronzeBar)?.key, "bronze-bar");
87
87
});
88
88
89
test("woodworking and anvil expose pickaxe chain recipes", () =>
89
test("woodworking, anvil, and crafting bench expose pickaxe and axe chain recipes", () =>
90
90
{
91
91
assert.equal(craftingStationDefinition(CraftingStationId.woodworkingBench).skillId, SkillId.crafting);
92
assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting);
92
93
const handle = recipeDefinition("handle-pine");
93
94
assert.ok(handle);
94
95
assert.equal(handle.stationId, CraftingStationId.woodworkingBench);
@@ -99,9 +100,24 @@ test("woodworking and anvil expose pickaxe chain recipes", () =>
99
100
assert.equal(head.output.itemId, ItemId.bronzePickaxeHead);
100
101
const pickaxe = recipeDefinition("pickaxe-bronze");
101
102
assert.ok(pickaxe);
103
assert.equal(pickaxe.stationId, CraftingStationId.craftingBench);
102
104
assert.deepEqual(pickaxe.inputs.map((row) => row.itemId).sort(), [
103
105
ItemId.pineHandle,
104
106
ItemId.bronzePickaxeHead
105
107
].sort());
106
108
assert.equal(pickaxe.output.itemId, ItemId.bronzePickaxe);
109
const axeHead = recipeDefinition("axe-head-bronze");
110
assert.ok(axeHead);
111
assert.equal(axeHead.stationId, CraftingStationId.anvil);
112
assert.equal(axeHead.output.itemId, ItemId.bronzeAxeHead);
113
const axe = recipeDefinition("axe-bronze");
114
assert.ok(axe);
115
assert.equal(axe.stationId, CraftingStationId.craftingBench);
116
assert.deepEqual(axe.inputs.map((row) => row.itemId).sort(), [
117
ItemId.pineHandle,
118
ItemId.bronzeAxeHead
119
].sort());
120
assert.equal(axe.output.itemId, ItemId.bronzeAxe);
121
assert.equal(itemDefinition(ItemId.bronzeAxe)?.stub, undefined);
122
assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");
107
123
});
@@ -86,9 +86,10 @@ test("crafting item stubs are registered", () =>86
assert.equal(itemDefinition(CraftingItemId.bronzeBar)?.key, "bronze-bar");86
assert.equal(itemDefinition(CraftingItemId.bronzeBar)?.key, "bronze-bar");87
});87
});88
88
89
test("woodworking and anvil expose pickaxe chain recipes", () =>89
test("woodworking, anvil, and crafting bench expose pickaxe and axe chain recipes", () =>90
{90
{91
assert.equal(craftingStationDefinition(CraftingStationId.woodworkingBench).skillId, SkillId.crafting);91
assert.equal(craftingStationDefinition(CraftingStationId.woodworkingBench).skillId, SkillId.crafting);92
assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting);92
const handle = recipeDefinition("handle-pine");93
const handle = recipeDefinition("handle-pine");93
assert.ok(handle);94
assert.ok(handle);94
assert.equal(handle.stationId, CraftingStationId.woodworkingBench);95
assert.equal(handle.stationId, CraftingStationId.woodworkingBench);@@ -99,9 +100,24 @@ test("woodworking and anvil expose pickaxe chain recipes", () =>99
assert.equal(head.output.itemId, ItemId.bronzePickaxeHead);100
assert.equal(head.output.itemId, ItemId.bronzePickaxeHead);100
const pickaxe = recipeDefinition("pickaxe-bronze");101
const pickaxe = recipeDefinition("pickaxe-bronze");101
assert.ok(pickaxe);102
assert.ok(pickaxe);103
assert.equal(pickaxe.stationId, CraftingStationId.craftingBench);102
assert.deepEqual(pickaxe.inputs.map((row) => row.itemId).sort(), [104
assert.deepEqual(pickaxe.inputs.map((row) => row.itemId).sort(), [103
ItemId.pineHandle,105
ItemId.pineHandle,104
ItemId.bronzePickaxeHead106
ItemId.bronzePickaxeHead105
].sort());107
].sort());106
assert.equal(pickaxe.output.itemId, ItemId.bronzePickaxe);108
assert.equal(pickaxe.output.itemId, ItemId.bronzePickaxe);109
const axeHead = recipeDefinition("axe-head-bronze");110
assert.ok(axeHead);111
assert.equal(axeHead.stationId, CraftingStationId.anvil);112
assert.equal(axeHead.output.itemId, ItemId.bronzeAxeHead);113
const axe = recipeDefinition("axe-bronze");114
assert.ok(axe);115
assert.equal(axe.stationId, CraftingStationId.craftingBench);116
assert.deepEqual(axe.inputs.map((row) => row.itemId).sort(), [117
ItemId.pineHandle,118
ItemId.bronzeAxeHead119
].sort());120
assert.equal(axe.output.itemId, ItemId.bronzeAxe);121
assert.equal(itemDefinition(ItemId.bronzeAxe)?.stub, undefined);122
assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");107
});123
});@@ -5,6 +5,8 @@ import { tmpdir } from "node:os";
5
5
import { join } from "node:path";
6
6
import { WorldDatabase } from "../src/persistence/worldDb.js";
7
7
import { EditorService } from "../src/editor/service.js";
8
import { ItemId } from "../../shared/definitions/items.js";
9
import { effectiveSeedValue, shopUnitPrice, undiscountedMarketValue } from "../../shared/shop/pricing.js";
8
10
9
11
function tempWorld ()
10
12
{
@@ -35,3 +37,37 @@ test("live settings save writes only changed fields and appends a log", () =>
35
37
finally
36
38
{ worldDb.close(); }
37
39
});
40
41
test("live settings can override item seed values", () =>
42
{
43
const worldDb = tempWorld();
44
try
45
{
46
const editor = new EditorService(worldDb);
47
const saved = editor.saveSettings({
48
itemSeedValues: { [ItemId.copperOre]: 12 }
49
}, "admin-1");
50
assert.equal(saved.settings.itemSeedValues[String(ItemId.copperOre)], 12);
51
assert.equal(worldDb.getLiveSettings().itemSeedValues[String(ItemId.copperOre)], 12);
52
assert.match(saved.changelog[0].diffEntries.join("\n"), /Copper ore seed value/);
53
54
const cleared = editor.saveSettings({ itemSeedValues: {} }, "admin-1");
55
assert.deepEqual(cleared.settings.itemSeedValues, {});
56
assert.match(cleared.changelog.at(-1).diffEntries.join("\n"), /default/);
57
}
58
finally
59
{ worldDb.close(); }
60
});
61
62
test("effectiveSeedValue prefers world overrides", () =>
63
{
64
assert.equal(effectiveSeedValue(ItemId.copperOre), 5);
65
assert.equal(effectiveSeedValue(ItemId.copperOre, { itemSeedValues: { [ItemId.copperOre]: 20 } }), 20);
66
assert.equal(undiscountedMarketValue(ItemId.copperOre, null, Date.now(), 1000, {
67
itemSeedValues: { [String(ItemId.copperOre)]: 9 }
68
}), 9);
69
assert.equal(shopUnitPrice(ItemId.copperOre, {
70
hiddenDiscount: 1,
71
settings: { itemSeedValues: { [ItemId.copperOre]: 9 } }
72
}), 9);
73
});
@@ -5,6 +5,8 @@ import { tmpdir } from "node:os";5
import { join } from "node:path";5
import { join } from "node:path";6
import { WorldDatabase } from "../src/persistence/worldDb.js";6
import { WorldDatabase } from "../src/persistence/worldDb.js";7
import { EditorService } from "../src/editor/service.js";7
import { EditorService } from "../src/editor/service.js";8
import { ItemId } from "../../shared/definitions/items.js";9
import { effectiveSeedValue, shopUnitPrice, undiscountedMarketValue } from "../../shared/shop/pricing.js";8
10
9
function tempWorld ()11
function tempWorld ()10
{12
{@@ -35,3 +37,37 @@ test("live settings save writes only changed fields and appends a log", () =>35
finally37
finally36
{ worldDb.close(); }38
{ worldDb.close(); }37
});39
});40
41
test("live settings can override item seed values", () =>42
{43
const worldDb = tempWorld();44
try45
{46
const editor = new EditorService(worldDb);47
const saved = editor.saveSettings({48
itemSeedValues: { [ItemId.copperOre]: 12 }49
}, "admin-1");50
assert.equal(saved.settings.itemSeedValues[String(ItemId.copperOre)], 12);51
assert.equal(worldDb.getLiveSettings().itemSeedValues[String(ItemId.copperOre)], 12);52
assert.match(saved.changelog[0].diffEntries.join("\n"), /Copper ore seed value/);53
54
const cleared = editor.saveSettings({ itemSeedValues: {} }, "admin-1");55
assert.deepEqual(cleared.settings.itemSeedValues, {});56
assert.match(cleared.changelog.at(-1).diffEntries.join("\n"), /default/);57
}58
finally59
{ worldDb.close(); }60
});61
62
test("effectiveSeedValue prefers world overrides", () =>63
{64
assert.equal(effectiveSeedValue(ItemId.copperOre), 5);65
assert.equal(effectiveSeedValue(ItemId.copperOre, { itemSeedValues: { [ItemId.copperOre]: 20 } }), 20);66
assert.equal(undiscountedMarketValue(ItemId.copperOre, null, Date.now(), 1000, {67
itemSeedValues: { [String(ItemId.copperOre)]: 9 }68
}), 9);69
assert.equal(shopUnitPrice(ItemId.copperOre, {70
hiddenDiscount: 1,71
settings: { itemSeedValues: { [ItemId.copperOre]: 9 } }72
}), 9);73
});@@ -79,6 +79,12 @@ test("tier skill gates: equip / mine / smelt", () =>
79
79
assert.equal(tierMineSkillLevel(MaterialTier.mithril), 18);
80
80
assert.equal(tierSmeltSkillLevel(MaterialTier.iron), 8);
81
81
assert.equal(tierSmeltSkillLevel(MaterialTier.steel), 15);
82
assert.equal(tierMineSkillLevel(GatherMaterialId.silver), 5);
83
assert.equal(tierSmeltSkillLevel(GatherMaterialId.silver), 8);
84
assert.equal(tierRank(GatherMaterialId.silver), 2);
85
assert.equal(tierMineSkillLevel(GatherMaterialId.gold), 10);
86
assert.equal(tierSmeltSkillLevel(GatherMaterialId.gold), 15);
87
assert.equal(tierRank(GatherMaterialId.gold), 3);
82
88
assert.equal(tierRank(MaterialTier.dragon), 7);
83
89
});
84
90
@@ -96,6 +102,8 @@ test("ore exhaust duration is 10s times associated bar rank", () =>
96
102
assert.equal(oreExhaustDurationMs(GatherMaterialId.tin), 10_000);
97
103
assert.equal(oreExhaustDurationMs(GatherMaterialId.copper), 10_000);
98
104
assert.equal(oreExhaustDurationMs(GatherMaterialId.coal), 30_000);
105
assert.equal(oreExhaustDurationMs(GatherMaterialId.gold), 30_000);
106
assert.equal(oreExhaustDurationMs(GatherMaterialId.silver), 20_000);
99
107
assert.equal(oreExhaustDurationMs(MaterialTier.dragon), 70_000);
100
108
});
101
109
@@ -104,9 +112,13 @@ test("ore boulder states map to materials", () =>
104
112
assert.equal(materialFromOreBoulderState("tin-ore"), GatherMaterialId.tin);
105
113
assert.equal(materialFromOreBoulderState("copper-ore"), GatherMaterialId.copper);
106
114
assert.equal(materialFromOreBoulderState("coal"), GatherMaterialId.coal);
115
assert.equal(materialFromOreBoulderState("silver-ore"), GatherMaterialId.silver);
116
assert.equal(materialFromOreBoulderState("gold-ore"), GatherMaterialId.gold);
107
117
assert.equal(materialFromOreBoulderState("boulder"), null);
108
118
assert.equal(materialFromOreBoulderState("bronze-ore"), null);
109
119
assert.equal(oreBoulderState(MaterialTier.mithril), "mithril-ore");
120
assert.equal(oreBoulderState(GatherMaterialId.silver), "silver-ore");
121
assert.equal(oreBoulderState(GatherMaterialId.gold), "gold-ore");
110
122
});
111
123
112
124
test("boulder block exists", () =>
@@ -263,6 +275,8 @@ test("mining grants ore and Mining XP then exhausts and respawns the node", () =
263
275
});
264
276
const start = harness.simulation.step();
265
277
assert.ok(start.events.some((event) => event.type === "gather-swing" || event.type === "tile-shove"));
278
const swing = start.events.find((event) => event.type === "gather-swing");
279
assert.equal(swing?.toolItemId, ItemId.bronzePickaxe);
266
280
267
281
advanceMs(harness, miningDurationMs(GatherMaterialId.copper, MaterialTier.bronze));
268
282
@@ -79,6 +79,12 @@ test("tier skill gates: equip / mine / smelt", () =>79
assert.equal(tierMineSkillLevel(MaterialTier.mithril), 18);79
assert.equal(tierMineSkillLevel(MaterialTier.mithril), 18);80
assert.equal(tierSmeltSkillLevel(MaterialTier.iron), 8);80
assert.equal(tierSmeltSkillLevel(MaterialTier.iron), 8);81
assert.equal(tierSmeltSkillLevel(MaterialTier.steel), 15);81
assert.equal(tierSmeltSkillLevel(MaterialTier.steel), 15);82
assert.equal(tierMineSkillLevel(GatherMaterialId.silver), 5);83
assert.equal(tierSmeltSkillLevel(GatherMaterialId.silver), 8);84
assert.equal(tierRank(GatherMaterialId.silver), 2);85
assert.equal(tierMineSkillLevel(GatherMaterialId.gold), 10);86
assert.equal(tierSmeltSkillLevel(GatherMaterialId.gold), 15);87
assert.equal(tierRank(GatherMaterialId.gold), 3);82
assert.equal(tierRank(MaterialTier.dragon), 7);88
assert.equal(tierRank(MaterialTier.dragon), 7);83
});89
});84
90
@@ -96,6 +102,8 @@ test("ore exhaust duration is 10s times associated bar rank", () =>96
assert.equal(oreExhaustDurationMs(GatherMaterialId.tin), 10_000);102
assert.equal(oreExhaustDurationMs(GatherMaterialId.tin), 10_000);97
assert.equal(oreExhaustDurationMs(GatherMaterialId.copper), 10_000);103
assert.equal(oreExhaustDurationMs(GatherMaterialId.copper), 10_000);98
assert.equal(oreExhaustDurationMs(GatherMaterialId.coal), 30_000);104
assert.equal(oreExhaustDurationMs(GatherMaterialId.coal), 30_000);105
assert.equal(oreExhaustDurationMs(GatherMaterialId.gold), 30_000);106
assert.equal(oreExhaustDurationMs(GatherMaterialId.silver), 20_000);99
assert.equal(oreExhaustDurationMs(MaterialTier.dragon), 70_000);107
assert.equal(oreExhaustDurationMs(MaterialTier.dragon), 70_000);100
});108
});101
109
@@ -104,9 +112,13 @@ test("ore boulder states map to materials", () =>104
assert.equal(materialFromOreBoulderState("tin-ore"), GatherMaterialId.tin);112
assert.equal(materialFromOreBoulderState("tin-ore"), GatherMaterialId.tin);105
assert.equal(materialFromOreBoulderState("copper-ore"), GatherMaterialId.copper);113
assert.equal(materialFromOreBoulderState("copper-ore"), GatherMaterialId.copper);106
assert.equal(materialFromOreBoulderState("coal"), GatherMaterialId.coal);114
assert.equal(materialFromOreBoulderState("coal"), GatherMaterialId.coal);115
assert.equal(materialFromOreBoulderState("silver-ore"), GatherMaterialId.silver);116
assert.equal(materialFromOreBoulderState("gold-ore"), GatherMaterialId.gold);107
assert.equal(materialFromOreBoulderState("boulder"), null);117
assert.equal(materialFromOreBoulderState("boulder"), null);108
assert.equal(materialFromOreBoulderState("bronze-ore"), null);118
assert.equal(materialFromOreBoulderState("bronze-ore"), null);109
assert.equal(oreBoulderState(MaterialTier.mithril), "mithril-ore");119
assert.equal(oreBoulderState(MaterialTier.mithril), "mithril-ore");120
assert.equal(oreBoulderState(GatherMaterialId.silver), "silver-ore");121
assert.equal(oreBoulderState(GatherMaterialId.gold), "gold-ore");110
});122
});111
123
112
test("boulder block exists", () =>124
test("boulder block exists", () =>@@ -263,6 +275,8 @@ test("mining grants ore and Mining XP then exhausts and respawns the node", () =263
});275
});264
const start = harness.simulation.step();276
const start = harness.simulation.step();265
assert.ok(start.events.some((event) => event.type === "gather-swing" || event.type === "tile-shove"));277
assert.ok(start.events.some((event) => event.type === "gather-swing" || event.type === "tile-shove"));278
const swing = start.events.find((event) => event.type === "gather-swing");279
assert.equal(swing?.toolItemId, ItemId.bronzePickaxe);266
280
267
advanceMs(harness, miningDurationMs(GatherMaterialId.copper, MaterialTier.bronze));281
advanceMs(harness, miningDurationMs(GatherMaterialId.copper, MaterialTier.bronze));268
282
@@ -1,26 +1,63 @@
1
1
import test from "node:test";
2
2
import assert from "node:assert/strict";
3
import { shopUnitPrice, undiscountedMarketValue, canSellInNpcShop, lerp } from "../../shared/shop/pricing.js";
3
import {
4
shopUnitPrice,
5
undiscountedMarketValue,
6
canSellInNpcShop,
7
canPlayerSellToNpc,
8
shopBuyFromPlayerPrice,
9
shopBoughtResalePrice,
10
shopChequeAdminFee,
11
resolveShopSellQuote,
12
shopRestockDayKey,
13
lerp
14
} from "../../shared/shop/pricing.js";
4
15
import { ItemId } from "../../shared/definitions/items.js";
5
16
import { MobId, normalizeSpawnerConfig, isHumanoidMob } from "../../shared/definitions/mobs.js";
6
17
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
7
18
import { Component } from "../src/ecs/components.js";
8
import { emptyEquipment, emptySlots, addCoinsToSlots } from "../../shared/items/inventory.js";
19
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
9
20
import { ItemOriginKind } from "../../shared/items/origin.js";
10
21
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
22
import { ensureShopRestocked } from "../src/shop/service.js";
23
import { BlockType } from "../../shared/definitions/tiles.js";
11
24
12
25
test("shop prices fall back to seedValue and apply hidden discount", () =>
13
26
{
14
assert.equal(undiscountedMarketValue(ItemId.copperOre), 2);
15
assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.9 }), 2);
16
assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.5 }), 1);
27
assert.equal(undiscountedMarketValue(ItemId.copperOre), 5);
28
assert.equal(undiscountedMarketValue(ItemId.tinOre), 5);
29
assert.equal(undiscountedMarketValue(ItemId.pineLog), 5);
30
assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.9 }), 5);
31
assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.5 }), 3);
32
assert.equal(shopBuyFromPlayerPrice(ItemId.copperOre), 4);
33
assert.equal(shopBoughtResalePrice(ItemId.copperOre), 6);
17
34
assert.equal(lerp(10, 20, 0.5), 15);
18
35
assert.equal(canSellInNpcShop(ItemId.copperOre), true);
19
36
assert.equal(canSellInNpcShop(ItemId.tinOre), true);
20
37
assert.equal(canSellInNpcShop(ItemId.stick), false);
38
assert.equal(canPlayerSellToNpc({ itemId: ItemId.copperOre, quantity: 1 }), true);
39
assert.equal(canPlayerSellToNpc({ itemId: ItemId.stick, quantity: 1 }), true);
40
assert.equal(canPlayerSellToNpc({ itemId: ItemId.blankCheque, quantity: 1 }), false);
41
assert.equal(canPlayerSellToNpc({ itemId: ItemId.coins, quantity: 10 }), false);
42
assert.equal(canPlayerSellToNpc({
43
itemId: ItemId.filledCheque,
44
quantity: 1,
45
instance: { kind: "filled-cheque", itemId: ItemId.copperOre, quantity: 3 }
46
}), true);
47
assert.equal(shopChequeAdminFee(100), 5);
48
assert.equal(shopChequeAdminFee(10), 1);
49
assert.equal(shopChequeAdminFee(1), 1);
50
const chequeQuote = resolveShopSellQuote({
51
itemId: ItemId.filledCheque,
52
quantity: 1,
53
instance: { kind: "filled-cheque", itemId: ItemId.copperOre, quantity: 2 }
54
});
55
assert.equal(chequeQuote.baseTotal, shopBuyFromPlayerPrice(ItemId.copperOre) * 2);
56
assert.equal(chequeQuote.adminFee, shopChequeAdminFee(chequeQuote.baseTotal));
57
assert.equal(chequeQuote.payout, chequeQuote.baseTotal - chequeQuote.adminFee);
21
58
});
22
59
23
test("humanoid spawner config keeps sex equipment and sells", () =>
60
test("humanoid spawner config keeps sex equipment sells quantities and buysItems", () =>
24
61
{
25
62
assert.equal(isHumanoidMob(MobId.humanoid), true);
26
63
const config = normalizeSpawnerConfig({
@@ -28,13 +65,22 @@ test("humanoid spawner config keeps sex equipment and sells", () =>
28
65
sex: "female",
29
66
displayName: "Ore trader",
30
67
equipment: { chest: ItemId.clothShirt, weapon: ItemId.stick },
31
sells: [ItemId.copperOre, ItemId.tinOre, ItemId.copperOre],
68
sells: [
69
{ itemId: ItemId.copperOre, quantity: 10 },
70
{ itemId: ItemId.tinOre, quantity: 0 },
71
ItemId.copperOre
72
],
73
buysItems: true,
32
74
hiddenDiscount: 0.85
33
75
}, "shop-1");
34
76
assert.equal(config.sex, "female");
35
77
assert.equal(config.displayName, "Ore trader");
36
78
assert.equal(config.equipment.chest, ItemId.clothShirt);
37
assert.deepEqual(config.sells, [ItemId.copperOre, ItemId.tinOre]);
79
assert.deepEqual(config.sells, [
80
{ itemId: ItemId.copperOre, quantity: 10 },
81
{ itemId: ItemId.tinOre, quantity: 0 }
82
]);
83
assert.equal(config.buysItems, true);
38
84
assert.equal(config.hiddenDiscount, 0.85);
39
85
assert.equal(config.maxAlive, 1);
40
86
});
@@ -56,7 +102,10 @@ test("buy copper ore from a spawned shopkeeper", () =>
56
102
maxWanderRangeTiles: 1,
57
103
sex: "male",
58
104
displayName: "Ore trader",
59
sells: [ItemId.copperOre, ItemId.tinOre],
105
sells: [
106
{ itemId: ItemId.copperOre, quantity: 0 },
107
{ itemId: ItemId.tinOre, quantity: 0 }
108
],
60
109
hiddenDiscount: 1,
61
110
equipment: { chest: ItemId.clothShirt }
62
111
}
@@ -113,7 +162,8 @@ test("buy copper ore from a spawned shopkeeper", () =>
113
162
characterId: character.character_id,
114
163
npcEntityId: npcId,
115
164
itemId: ItemId.copperOre,
116
quantity: 1
165
quantity: 1,
166
listingId: `stock:${ItemId.copperOre}`
117
167
});
118
168
const buy = harness.simulation.step();
119
169
assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
@@ -125,3 +175,536 @@ test("buy copper ore from a spawned shopkeeper", () =>
125
175
finally
126
176
{ harness.close(); }
127
177
});
178
179
test("limited shop stock depletes and restocks on a new day", () =>
180
{
181
const shop = {
182
catalog: [{ itemId: ItemId.copperOre, quantity: 2 }],
183
buysItems: false,
184
hiddenDiscount: 1,
185
remaining: Object.create(null),
186
boughtStock: Object.create(null),
187
restockDay: null
188
};
189
const dayA = Date.parse("2026-08-25T12:00:00Z");
190
ensureShopRestocked(shop, dayA);
191
assert.equal(shop.restockDay, shopRestockDayKey(dayA));
192
assert.equal(shop.remaining[ItemId.copperOre], 2);
193
shop.remaining[ItemId.copperOre] = 0;
194
shop.boughtStock[ItemId.tinOre] = 3;
195
ensureShopRestocked(shop, dayA);
196
assert.equal(shop.remaining[ItemId.copperOre], 0);
197
assert.equal(shop.boughtStock[ItemId.tinOre], 3);
198
const dayB = Date.parse("2026-08-26T00:00:01Z");
199
ensureShopRestocked(shop, dayB);
200
assert.equal(shop.remaining[ItemId.copperOre], 2);
201
assert.equal(shop.boughtStock[ItemId.tinOre], undefined);
202
});
203
204
test("shop overflow goes to bank vault when inventory is full", () =>
205
{
206
const harness = makeSimulation({ workerCount: 1 });
207
try
208
{
209
const data = createEmptyChunkData();
210
data.open = true;
211
data.spawners = [{
212
localX: 9,
213
localY: 8,
214
config: {
215
mobTypeId: MobId.humanoid,
216
maxAlive: 1,
217
spawnRangeTiles: 0,
218
maxWanderRangeTiles: 0,
219
displayName: "Ore trader",
220
sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
221
hiddenDiscount: 1
222
}
223
}];
224
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
225
harness.simulation.reloadWorld();
226
227
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
228
const slots = emptySlots();
229
const funded = addCoinsToSlots(slots, 50);
230
assert.equal(funded.ok, true);
231
for (let i = 0; i < funded.slots.length; i++)
232
{
233
if (!funded.slots[i])
234
{ funded.slots[i] = { itemId: ItemId.stick, quantity: 1 }; }
235
}
236
harness.stateDb.saveBag(character.character_id, {
237
inventory: funded.slots,
238
equipment: emptyEquipment(),
239
vault: [],
240
vaultReserved: []
241
});
242
const playerId = harness.simulation.spawnCharacter(1, character);
243
harness.simulation.step();
244
harness.advance(50);
245
harness.simulation.step();
246
247
const record = harness.simulation.entityRecord(playerId);
248
const worker = harness.simulation.workers[record.workerId];
249
let npcId = null;
250
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
251
{
252
if (entity.creature.mobTypeId === MobId.humanoid)
253
{
254
npcId = entity.entityId;
255
break;
256
}
257
}
258
assert.ok(npcId);
259
const npcHandle = worker.world.ecs.handleOf(npcId);
260
const npcPos = worker.world.ecs.get(npcHandle, Component.position);
261
const playerHandle = worker.world.ecs.handleOf(playerId);
262
const playerPos = worker.world.ecs.get(playerHandle, Component.position);
263
playerPos.tileX = npcPos.tileX;
264
playerPos.tileY = npcPos.tileY;
265
266
harness.simulation.enqueue(1, {
267
type: "buy-from-shop",
268
characterId: character.character_id,
269
npcEntityId: npcId,
270
itemId: ItemId.copperOre,
271
quantity: 1,
272
listingId: `stock:${ItemId.copperOre}`
273
});
274
const buy = harness.simulation.step();
275
assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));
276
const bag = harness.simulation.bagOf(playerId);
277
assert.equal((bag.inventory ?? []).some((slot) => slot?.itemId === ItemId.copperOre), false);
278
assert.ok((bag.vault ?? []).some((slot) => slot?.itemId === ItemId.copperOre));
279
}
280
finally
281
{ harness.close(); }
282
});
283
284
test("buysItems refills limited catalog then stores extras for 120% resale", () =>
285
{
286
const harness = makeSimulation({ workerCount: 1 });
287
try
288
{
289
const data = createEmptyChunkData();
290
data.open = true;
291
data.spawners = [{
292
localX: 9,
293
localY: 8,
294
config: {
295
mobTypeId: MobId.humanoid,
296
maxAlive: 1,
297
spawnRangeTiles: 0,
298
maxWanderRangeTiles: 0,
299
displayName: "Buyer",
300
sells: [{ itemId: ItemId.copperOre, quantity: 2 }],
301
buysItems: true,
302
hiddenDiscount: 1
303
}
304
}];
305
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
306
harness.simulation.reloadWorld();
307
308
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
309
harness.stateDb.saveBag(character.character_id, {
310
inventory: emptySlots(INVENTORY_SLOTS),
311
equipment: emptyEquipment(),
312
vault: [],
313
vaultReserved: []
314
});
315
const playerId = harness.simulation.spawnCharacter(1, character);
316
harness.simulation.step();
317
harness.advance(50);
318
harness.simulation.step();
319
320
const record = harness.simulation.entityRecord(playerId);
321
const worker = harness.simulation.workers[record.workerId];
322
let npcId = null;
323
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
324
{
325
if (entity.creature.mobTypeId === MobId.humanoid)
326
{
327
npcId = entity.entityId;
328
break;
329
}
330
}
331
assert.ok(npcId);
332
const npcHandle = worker.world.ecs.handleOf(npcId);
333
const shop = worker.world.ecs.get(npcHandle, Component.shop);
334
const npcPos = worker.world.ecs.get(npcHandle, Component.position);
335
const playerHandle = worker.world.ecs.handleOf(playerId);
336
const playerPos = worker.world.ecs.get(playerHandle, Component.position);
337
playerPos.tileX = npcPos.tileX;
338
playerPos.tileY = npcPos.tileY;
339
340
// Fund coins and buy out limited stock first.
341
const inv = worker.world.ecs.get(playerHandle, Component.inventory);
342
const funded = addCoinsToSlots(inv.slots, 50);
343
assert.equal(funded.ok, true);
344
inv.slots = funded.slots;
345
inv.slots[1] = { itemId: ItemId.copperOre, quantity: 5 };
346
347
harness.simulation.enqueue(1, {
348
type: "buy-from-shop",
349
characterId: character.character_id,
350
npcEntityId: npcId,
351
itemId: ItemId.copperOre,
352
quantity: 2,
353
listingId: `stock:${ItemId.copperOre}`
354
});
355
const boughtOut = harness.simulation.step();
356
assert.equal(boughtOut.events.some((event) => event.type === "command-error"), false, JSON.stringify(boughtOut.events));
357
assert.equal(shop.remaining[ItemId.copperOre], 0);
358
359
const oreSlot = inv.slots.findIndex((slot) => slot?.itemId === ItemId.copperOre && (slot.quantity | 0) >= 5);
360
assert.ok(oreSlot >= 0);
361
362
harness.simulation.enqueue(1, {
363
type: "sell-to-shop",
364
characterId: character.character_id,
365
npcEntityId: npcId,
366
slotIndex: oreSlot,
367
quantity: 5
368
});
369
const sold = harness.simulation.step();
370
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
371
assert.equal(shop.remaining[ItemId.copperOre], 2);
372
assert.equal(shop.boughtStock[ItemId.copperOre], 3);
373
374
const open = sold.events.find((event) => event.type === "shop-open");
375
assert.ok(open.stock.some((row) => row.source === "stock" && row.available === 2));
376
assert.ok(open.stock.some((row) => row.source === "bought" && row.available === 3));
377
}
378
finally
379
{ harness.close(); }
380
});
381
382
test("shop adjacency errors use gendered pronouns", () =>
383
{
384
const harness = makeSimulation({ workerCount: 1 });
385
try
386
{
387
const data = createEmptyChunkData();
388
data.open = true;
389
data.spawners = [{
390
localX: 9,
391
localY: 8,
392
config: {
393
mobTypeId: MobId.humanoid,
394
maxAlive: 1,
395
spawnRangeTiles: 0,
396
maxWanderRangeTiles: 0,
397
sex: "female",
398
displayName: "Trader",
399
sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
400
hiddenDiscount: 1
401
}
402
}];
403
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
404
harness.simulation.reloadWorld();
405
406
const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 2 });
407
harness.stateDb.saveBag(character.character_id, {
408
inventory: emptySlots(INVENTORY_SLOTS),
409
equipment: emptyEquipment(),
410
vault: [],
411
vaultReserved: []
412
});
413
const playerId = harness.simulation.spawnCharacter(1, character);
414
harness.simulation.step();
415
harness.advance(50);
416
harness.simulation.step();
417
418
const record = harness.simulation.entityRecord(playerId);
419
const worker = harness.simulation.workers[record.workerId];
420
let npcId = null;
421
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
422
{
423
if (entity.creature.mobTypeId === MobId.humanoid)
424
{
425
npcId = entity.entityId;
426
break;
427
}
428
}
429
assert.ok(npcId);
430
431
harness.simulation.enqueue(1, {
432
type: "interact",
433
characterId: character.character_id,
434
targetEntityId: npcId
435
});
436
const open = harness.simulation.step();
437
const err = open.events.find((event) => event.type === "command-error");
438
assert.ok(err, JSON.stringify(open.events));
439
assert.match(err.message, /stand next to her/i);
440
assert.doesNotMatch(err.message, /\bthem\b/i);
441
}
442
finally
443
{ harness.close(); }
444
});
445
446
test("shopkeeper stops wandering while a player has the shop open", () =>
447
{
448
const harness = makeSimulation({ workerCount: 1 });
449
try
450
{
451
const data = createEmptyChunkData();
452
data.open = true;
453
data.spawners = [{
454
localX: 8,
455
localY: 8,
456
config: {
457
mobTypeId: MobId.humanoid,
458
maxAlive: 1,
459
spawnRangeTiles: 4,
460
maxWanderRangeTiles: 8,
461
sex: "male",
462
displayName: "Stay put",
463
sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
464
hiddenDiscount: 1
465
}
466
}];
467
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
468
harness.simulation.reloadWorld();
469
470
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
471
harness.stateDb.saveBag(character.character_id, {
472
inventory: emptySlots(INVENTORY_SLOTS),
473
equipment: emptyEquipment(),
474
vault: [],
475
vaultReserved: []
476
});
477
const playerId = harness.simulation.spawnCharacter(1, character);
478
harness.simulation.step();
479
harness.advance(50);
480
harness.simulation.step();
481
482
const record = harness.simulation.entityRecord(playerId);
483
const worker = harness.simulation.workers[record.workerId];
484
let npc = null;
485
for (const entity of worker.world.ecs.query(Component.shop, Component.creature, Component.position, Component.path))
486
{
487
if (entity.creature.mobTypeId === MobId.humanoid)
488
{
489
npc = entity;
490
break;
491
}
492
}
493
assert.ok(npc);
494
495
const playerHandle = worker.world.ecs.handleOf(playerId);
496
const playerPos = worker.world.ecs.get(playerHandle, Component.position);
497
playerPos.tileX = npc.position.tileX;
498
playerPos.tileY = npc.position.tileY;
499
500
harness.simulation.enqueue(1, {
501
type: "interact",
502
characterId: character.character_id,
503
targetEntityId: npc.entityId
504
});
505
const open = harness.simulation.step();
506
assert.ok(open.events.some((event) => event.type === "shop-open"));
507
assert.equal(!!npc.shop.browsers?.[character.character_id], true);
508
509
npc.path.tiles = [{ x: npc.position.tileX + 1, y: npc.position.tileY }];
510
for (let i = 0; i < 20; i++)
511
{ harness.simulation.step(); }
512
assert.equal(npc.path.tiles.length, 0);
513
assert.equal(npc.position.tileX, playerPos.tileX);
514
assert.equal(npc.position.tileY, playerPos.tileY);
515
516
harness.simulation.enqueue(1, {
517
type: "close-shop",
518
characterId: character.character_id,
519
npcEntityId: npc.entityId
520
});
521
harness.simulation.step();
522
assert.equal(!!npc.shop.browsers?.[character.character_id], false);
523
}
524
finally
525
{ harness.close(); }
526
});
527
528
test("buysItems accepts non-ingredient tools like sticks", () =>
529
{
530
const harness = makeSimulation({ workerCount: 1 });
531
try
532
{
533
const data = createEmptyChunkData();
534
data.open = true;
535
data.spawners = [{
536
localX: 9,
537
localY: 8,
538
config: {
539
mobTypeId: MobId.humanoid,
540
maxAlive: 1,
541
spawnRangeTiles: 0,
542
maxWanderRangeTiles: 0,
543
displayName: "Buyer",
544
buysItems: true,
545
hiddenDiscount: 1
546
}
547
}];
548
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
549
harness.simulation.reloadWorld();
550
551
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
552
const slots = emptySlots(INVENTORY_SLOTS);
553
slots[0] = { itemId: ItemId.stick, quantity: 1 };
554
harness.stateDb.saveBag(character.character_id, {
555
inventory: slots,
556
equipment: emptyEquipment(),
557
vault: [],
558
vaultReserved: []
559
});
560
const playerId = harness.simulation.spawnCharacter(1, character);
561
harness.simulation.step();
562
harness.advance(50);
563
harness.simulation.step();
564
565
const record = harness.simulation.entityRecord(playerId);
566
const worker = harness.simulation.workers[record.workerId];
567
let npcId = null;
568
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
569
{
570
if (entity.creature.mobTypeId === MobId.humanoid)
571
{
572
npcId = entity.entityId;
573
break;
574
}
575
}
576
assert.ok(npcId);
577
const npcHandle = worker.world.ecs.handleOf(npcId);
578
const shop = worker.world.ecs.get(npcHandle, Component.shop);
579
const npcPos = worker.world.ecs.get(npcHandle, Component.position);
580
const playerHandle = worker.world.ecs.handleOf(playerId);
581
const playerPos = worker.world.ecs.get(playerHandle, Component.position);
582
playerPos.tileX = npcPos.tileX;
583
playerPos.tileY = npcPos.tileY;
584
585
const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
586
harness.simulation.enqueue(1, {
587
type: "sell-to-shop",
588
characterId: character.character_id,
589
npcEntityId: npcId,
590
slotIndex: 0,
591
quantity: 1
592
});
593
const sold = harness.simulation.step();
594
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
595
const inv = worker.world.ecs.get(playerHandle, Component.inventory);
596
assert.equal(inv.slots[0]?.itemId === ItemId.stick, false);
597
assert.ok(countCoinsInSlots(inv.slots) >= beforeCoins + shopBuyFromPlayerPrice(ItemId.stick));
598
assert.equal(shop.boughtStock[ItemId.stick], 1);
599
}
600
finally
601
{ harness.close(); }
602
});
603
604
test("selling a filled cheque pays reserved-goods price minus 5% admin fee", () =>
605
{
606
const harness = makeSimulation({ workerCount: 1 });
607
try
608
{
609
const data = createEmptyChunkData();
610
data.open = true;
611
data.blocks[8 * 16 + 8] = { typeId: BlockType.bank, state: 0 };
612
data.spawners = [{
613
localX: 9,
614
localY: 8,
615
config: {
616
mobTypeId: MobId.humanoid,
617
maxAlive: 1,
618
spawnRangeTiles: 0,
619
maxWanderRangeTiles: 0,
620
displayName: "Buyer",
621
sells: [{ itemId: ItemId.copperOre, quantity: 0 }],
622
buysItems: true,
623
hiddenDiscount: 1
624
}
625
}];
626
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
627
harness.simulation.reloadWorld();
628
629
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
630
const slots = emptySlots(INVENTORY_SLOTS);
631
slots[0] = { itemId: ItemId.copperOre, quantity: 2 };
632
harness.stateDb.saveBag(character.character_id, {
633
inventory: slots,
634
equipment: emptyEquipment(),
635
vault: [],
636
vaultReserved: []
637
});
638
const playerId = harness.simulation.spawnCharacter(1, character);
639
harness.simulation.step();
640
641
harness.simulation.enqueue(1, {
642
type: "get-blank-cheques",
643
characterId: character.character_id
644
});
645
harness.simulation.step();
646
harness.simulation.enqueue(1, {
647
type: "bank-deposit",
648
characterId: character.character_id,
649
slotIndex: 0,
650
quantity: null
651
});
652
harness.simulation.step();
653
let bag = harness.simulation.bagOf(playerId);
654
const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
655
const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.copperOre);
656
harness.simulation.enqueue(1, {
657
type: "write-cheque",
658
characterId: character.character_id,
659
slotIndex: blankIndex,
660
vaultSlotIndex: vaultIndex,
661
quantity: 2
662
});
663
harness.simulation.step();
664
bag = harness.simulation.bagOf(playerId);
665
const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
666
assert.ok(chequeIndex >= 0);
667
668
const record = harness.simulation.entityRecord(playerId);
669
const worker = harness.simulation.workers[record.workerId];
670
let npcId = null;
671
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
672
{
673
if (entity.creature.mobTypeId === MobId.humanoid)
674
{
675
npcId = entity.entityId;
676
break;
677
}
678
}
679
assert.ok(npcId);
680
const npcHandle = worker.world.ecs.handleOf(npcId);
681
const shop = worker.world.ecs.get(npcHandle, Component.shop);
682
const npcPos = worker.world.ecs.get(npcHandle, Component.position);
683
const playerHandle = worker.world.ecs.handleOf(playerId);
684
const playerPos = worker.world.ecs.get(playerHandle, Component.position);
685
playerPos.tileX = npcPos.tileX;
686
playerPos.tileY = npcPos.tileY;
687
688
const quote = resolveShopSellQuote(bag.inventory[chequeIndex]);
689
assert.ok(quote?.isCheque);
690
const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
691
harness.simulation.enqueue(1, {
692
type: "sell-to-shop",
693
characterId: character.character_id,
694
npcEntityId: npcId,
695
slotIndex: chequeIndex,
696
quantity: 1
697
});
698
const sold = harness.simulation.step();
699
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
700
bag = harness.simulation.bagOf(playerId);
701
assert.equal(bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque), -1);
702
assert.equal((bag.vaultReserved ?? []).length, 0);
703
const afterCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
704
assert.equal(afterCoins - beforeCoins, quote.payout);
705
// Infinite catalog absorbs goods without bought-from-player resale stock.
706
assert.equal(shop.boughtStock?.[ItemId.copperOre] | 0, 0);
707
}
708
finally
709
{ harness.close(); }
710
});
@@ -1,26 +1,63 @@1
import test from "node:test";1
import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { shopUnitPrice, undiscountedMarketValue, canSellInNpcShop, lerp } from "../../shared/shop/pricing.js";3
import {4
shopUnitPrice,5
undiscountedMarketValue,6
canSellInNpcShop,7
canPlayerSellToNpc,8
shopBuyFromPlayerPrice,9
shopBoughtResalePrice,10
shopChequeAdminFee,11
resolveShopSellQuote,12
shopRestockDayKey,13
lerp14
} from "../../shared/shop/pricing.js";4
import { ItemId } from "../../shared/definitions/items.js";15
import { ItemId } from "../../shared/definitions/items.js";5
import { MobId, normalizeSpawnerConfig, isHumanoidMob } from "../../shared/definitions/mobs.js";16
import { MobId, normalizeSpawnerConfig, isHumanoidMob } from "../../shared/definitions/mobs.js";6
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";17
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";7
import { Component } from "../src/ecs/components.js";18
import { Component } from "../src/ecs/components.js";8
import { emptyEquipment, emptySlots, addCoinsToSlots } from "../../shared/items/inventory.js";19
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";9
import { ItemOriginKind } from "../../shared/items/origin.js";20
import { ItemOriginKind } from "../../shared/items/origin.js";10
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";21
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";22
import { ensureShopRestocked } from "../src/shop/service.js";23
import { BlockType } from "../../shared/definitions/tiles.js";11
24
12
test("shop prices fall back to seedValue and apply hidden discount", () =>25
test("shop prices fall back to seedValue and apply hidden discount", () =>13
{26
{14
assert.equal(undiscountedMarketValue(ItemId.copperOre), 2);27
assert.equal(undiscountedMarketValue(ItemId.copperOre), 5);15
assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.9 }), 2);28
assert.equal(undiscountedMarketValue(ItemId.tinOre), 5);16
assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.5 }), 1);29
assert.equal(undiscountedMarketValue(ItemId.pineLog), 5);30
assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.9 }), 5);31
assert.equal(shopUnitPrice(ItemId.copperOre, { hiddenDiscount: 0.5 }), 3);32
assert.equal(shopBuyFromPlayerPrice(ItemId.copperOre), 4);33
assert.equal(shopBoughtResalePrice(ItemId.copperOre), 6);17
assert.equal(lerp(10, 20, 0.5), 15);34
assert.equal(lerp(10, 20, 0.5), 15);18
assert.equal(canSellInNpcShop(ItemId.copperOre), true);35
assert.equal(canSellInNpcShop(ItemId.copperOre), true);19
assert.equal(canSellInNpcShop(ItemId.tinOre), true);36
assert.equal(canSellInNpcShop(ItemId.tinOre), true);20
assert.equal(canSellInNpcShop(ItemId.stick), false);37
assert.equal(canSellInNpcShop(ItemId.stick), false);38
assert.equal(canPlayerSellToNpc({ itemId: ItemId.copperOre, quantity: 1 }), true);39
assert.equal(canPlayerSellToNpc({ itemId: ItemId.stick, quantity: 1 }), true);40
assert.equal(canPlayerSellToNpc({ itemId: ItemId.blankCheque, quantity: 1 }), false);41
assert.equal(canPlayerSellToNpc({ itemId: ItemId.coins, quantity: 10 }), false);42
assert.equal(canPlayerSellToNpc({43
itemId: ItemId.filledCheque,44
quantity: 1,45
instance: { kind: "filled-cheque", itemId: ItemId.copperOre, quantity: 3 }46
}), true);47
assert.equal(shopChequeAdminFee(100), 5);48
assert.equal(shopChequeAdminFee(10), 1);49
assert.equal(shopChequeAdminFee(1), 1);50
const chequeQuote = resolveShopSellQuote({51
itemId: ItemId.filledCheque,52
quantity: 1,53
instance: { kind: "filled-cheque", itemId: ItemId.copperOre, quantity: 2 }54
});55
assert.equal(chequeQuote.baseTotal, shopBuyFromPlayerPrice(ItemId.copperOre) * 2);56
assert.equal(chequeQuote.adminFee, shopChequeAdminFee(chequeQuote.baseTotal));57
assert.equal(chequeQuote.payout, chequeQuote.baseTotal - chequeQuote.adminFee);21
});58
});22
59
23
test("humanoid spawner config keeps sex equipment and sells", () =>60
test("humanoid spawner config keeps sex equipment sells quantities and buysItems", () =>24
{61
{25
assert.equal(isHumanoidMob(MobId.humanoid), true);62
assert.equal(isHumanoidMob(MobId.humanoid), true);26
const config = normalizeSpawnerConfig({63
const config = normalizeSpawnerConfig({@@ -28,13 +65,22 @@ test("humanoid spawner config keeps sex equipment and sells", () =>28
sex: "female",65
sex: "female",29
displayName: "Ore trader",66
displayName: "Ore trader",30
equipment: { chest: ItemId.clothShirt, weapon: ItemId.stick },67
equipment: { chest: ItemId.clothShirt, weapon: ItemId.stick },31
sells: [ItemId.copperOre, ItemId.tinOre, ItemId.copperOre],68
sells: [69
{ itemId: ItemId.copperOre, quantity: 10 },70
{ itemId: ItemId.tinOre, quantity: 0 },71
ItemId.copperOre72
],73
buysItems: true,32
hiddenDiscount: 0.8574
hiddenDiscount: 0.8533
}, "shop-1");75
}, "shop-1");34
assert.equal(config.sex, "female");76
assert.equal(config.sex, "female");35
assert.equal(config.displayName, "Ore trader");77
assert.equal(config.displayName, "Ore trader");36
assert.equal(config.equipment.chest, ItemId.clothShirt);78
assert.equal(config.equipment.chest, ItemId.clothShirt);37
assert.deepEqual(config.sells, [ItemId.copperOre, ItemId.tinOre]);79
assert.deepEqual(config.sells, [80
{ itemId: ItemId.copperOre, quantity: 10 },81
{ itemId: ItemId.tinOre, quantity: 0 }82
]);83
assert.equal(config.buysItems, true);38
assert.equal(config.hiddenDiscount, 0.85);84
assert.equal(config.hiddenDiscount, 0.85);39
assert.equal(config.maxAlive, 1);85
assert.equal(config.maxAlive, 1);40
});86
});@@ -56,7 +102,10 @@ test("buy copper ore from a spawned shopkeeper", () =>56
maxWanderRangeTiles: 1,102
maxWanderRangeTiles: 1,57
sex: "male",103
sex: "male",58
displayName: "Ore trader",104
displayName: "Ore trader",59
sells: [ItemId.copperOre, ItemId.tinOre],105
sells: [106
{ itemId: ItemId.copperOre, quantity: 0 },107
{ itemId: ItemId.tinOre, quantity: 0 }108
],60
hiddenDiscount: 1,109
hiddenDiscount: 1,61
equipment: { chest: ItemId.clothShirt }110
equipment: { chest: ItemId.clothShirt }62
}111
}@@ -113,7 +162,8 @@ test("buy copper ore from a spawned shopkeeper", () =>113
characterId: character.character_id,162
characterId: character.character_id,114
npcEntityId: npcId,163
npcEntityId: npcId,115
itemId: ItemId.copperOre,164
itemId: ItemId.copperOre,116
quantity: 1165
quantity: 1,166
listingId: `stock:${ItemId.copperOre}`117
});167
});118
const buy = harness.simulation.step();168
const buy = harness.simulation.step();119
assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));169
assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));@@ -125,3 +175,536 @@ test("buy copper ore from a spawned shopkeeper", () =>125
finally175
finally126
{ harness.close(); }176
{ harness.close(); }127
});177
});178
179
test("limited shop stock depletes and restocks on a new day", () =>180
{181
const shop = {182
catalog: [{ itemId: ItemId.copperOre, quantity: 2 }],183
buysItems: false,184
hiddenDiscount: 1,185
remaining: Object.create(null),186
boughtStock: Object.create(null),187
restockDay: null188
};189
const dayA = Date.parse("2026-08-25T12:00:00Z");190
ensureShopRestocked(shop, dayA);191
assert.equal(shop.restockDay, shopRestockDayKey(dayA));192
assert.equal(shop.remaining[ItemId.copperOre], 2);193
shop.remaining[ItemId.copperOre] = 0;194
shop.boughtStock[ItemId.tinOre] = 3;195
ensureShopRestocked(shop, dayA);196
assert.equal(shop.remaining[ItemId.copperOre], 0);197
assert.equal(shop.boughtStock[ItemId.tinOre], 3);198
const dayB = Date.parse("2026-08-26T00:00:01Z");199
ensureShopRestocked(shop, dayB);200
assert.equal(shop.remaining[ItemId.copperOre], 2);201
assert.equal(shop.boughtStock[ItemId.tinOre], undefined);202
});203
204
test("shop overflow goes to bank vault when inventory is full", () =>205
{206
const harness = makeSimulation({ workerCount: 1 });207
try208
{209
const data = createEmptyChunkData();210
data.open = true;211
data.spawners = [{212
localX: 9,213
localY: 8,214
config: {215
mobTypeId: MobId.humanoid,216
maxAlive: 1,217
spawnRangeTiles: 0,218
maxWanderRangeTiles: 0,219
displayName: "Ore trader",220
sells: [{ itemId: ItemId.copperOre, quantity: 0 }],221
hiddenDiscount: 1222
}223
}];224
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));225
harness.simulation.reloadWorld();226
227
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });228
const slots = emptySlots();229
const funded = addCoinsToSlots(slots, 50);230
assert.equal(funded.ok, true);231
for (let i = 0; i < funded.slots.length; i++)232
{233
if (!funded.slots[i])234
{ funded.slots[i] = { itemId: ItemId.stick, quantity: 1 }; }235
}236
harness.stateDb.saveBag(character.character_id, {237
inventory: funded.slots,238
equipment: emptyEquipment(),239
vault: [],240
vaultReserved: []241
});242
const playerId = harness.simulation.spawnCharacter(1, character);243
harness.simulation.step();244
harness.advance(50);245
harness.simulation.step();246
247
const record = harness.simulation.entityRecord(playerId);248
const worker = harness.simulation.workers[record.workerId];249
let npcId = null;250
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))251
{252
if (entity.creature.mobTypeId === MobId.humanoid)253
{254
npcId = entity.entityId;255
break;256
}257
}258
assert.ok(npcId);259
const npcHandle = worker.world.ecs.handleOf(npcId);260
const npcPos = worker.world.ecs.get(npcHandle, Component.position);261
const playerHandle = worker.world.ecs.handleOf(playerId);262
const playerPos = worker.world.ecs.get(playerHandle, Component.position);263
playerPos.tileX = npcPos.tileX;264
playerPos.tileY = npcPos.tileY;265
266
harness.simulation.enqueue(1, {267
type: "buy-from-shop",268
characterId: character.character_id,269
npcEntityId: npcId,270
itemId: ItemId.copperOre,271
quantity: 1,272
listingId: `stock:${ItemId.copperOre}`273
});274
const buy = harness.simulation.step();275
assert.equal(buy.events.some((event) => event.type === "command-error"), false, JSON.stringify(buy.events));276
const bag = harness.simulation.bagOf(playerId);277
assert.equal((bag.inventory ?? []).some((slot) => slot?.itemId === ItemId.copperOre), false);278
assert.ok((bag.vault ?? []).some((slot) => slot?.itemId === ItemId.copperOre));279
}280
finally281
{ harness.close(); }282
});283
284
test("buysItems refills limited catalog then stores extras for 120% resale", () =>285
{286
const harness = makeSimulation({ workerCount: 1 });287
try288
{289
const data = createEmptyChunkData();290
data.open = true;291
data.spawners = [{292
localX: 9,293
localY: 8,294
config: {295
mobTypeId: MobId.humanoid,296
maxAlive: 1,297
spawnRangeTiles: 0,298
maxWanderRangeTiles: 0,299
displayName: "Buyer",300
sells: [{ itemId: ItemId.copperOre, quantity: 2 }],301
buysItems: true,302
hiddenDiscount: 1303
}304
}];305
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));306
harness.simulation.reloadWorld();307
308
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });309
harness.stateDb.saveBag(character.character_id, {310
inventory: emptySlots(INVENTORY_SLOTS),311
equipment: emptyEquipment(),312
vault: [],313
vaultReserved: []314
});315
const playerId = harness.simulation.spawnCharacter(1, character);316
harness.simulation.step();317
harness.advance(50);318
harness.simulation.step();319
320
const record = harness.simulation.entityRecord(playerId);321
const worker = harness.simulation.workers[record.workerId];322
let npcId = null;323
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))324
{325
if (entity.creature.mobTypeId === MobId.humanoid)326
{327
npcId = entity.entityId;328
break;329
}330
}331
assert.ok(npcId);332
const npcHandle = worker.world.ecs.handleOf(npcId);333
const shop = worker.world.ecs.get(npcHandle, Component.shop);334
const npcPos = worker.world.ecs.get(npcHandle, Component.position);335
const playerHandle = worker.world.ecs.handleOf(playerId);336
const playerPos = worker.world.ecs.get(playerHandle, Component.position);337
playerPos.tileX = npcPos.tileX;338
playerPos.tileY = npcPos.tileY;339
340
// Fund coins and buy out limited stock first.341
const inv = worker.world.ecs.get(playerHandle, Component.inventory);342
const funded = addCoinsToSlots(inv.slots, 50);343
assert.equal(funded.ok, true);344
inv.slots = funded.slots;345
inv.slots[1] = { itemId: ItemId.copperOre, quantity: 5 };346
347
harness.simulation.enqueue(1, {348
type: "buy-from-shop",349
characterId: character.character_id,350
npcEntityId: npcId,351
itemId: ItemId.copperOre,352
quantity: 2,353
listingId: `stock:${ItemId.copperOre}`354
});355
const boughtOut = harness.simulation.step();356
assert.equal(boughtOut.events.some((event) => event.type === "command-error"), false, JSON.stringify(boughtOut.events));357
assert.equal(shop.remaining[ItemId.copperOre], 0);358
359
const oreSlot = inv.slots.findIndex((slot) => slot?.itemId === ItemId.copperOre && (slot.quantity | 0) >= 5);360
assert.ok(oreSlot >= 0);361
362
harness.simulation.enqueue(1, {363
type: "sell-to-shop",364
characterId: character.character_id,365
npcEntityId: npcId,366
slotIndex: oreSlot,367
quantity: 5368
});369
const sold = harness.simulation.step();370
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));371
assert.equal(shop.remaining[ItemId.copperOre], 2);372
assert.equal(shop.boughtStock[ItemId.copperOre], 3);373
374
const open = sold.events.find((event) => event.type === "shop-open");375
assert.ok(open.stock.some((row) => row.source === "stock" && row.available === 2));376
assert.ok(open.stock.some((row) => row.source === "bought" && row.available === 3));377
}378
finally379
{ harness.close(); }380
});381
382
test("shop adjacency errors use gendered pronouns", () =>383
{384
const harness = makeSimulation({ workerCount: 1 });385
try386
{387
const data = createEmptyChunkData();388
data.open = true;389
data.spawners = [{390
localX: 9,391
localY: 8,392
config: {393
mobTypeId: MobId.humanoid,394
maxAlive: 1,395
spawnRangeTiles: 0,396
maxWanderRangeTiles: 0,397
sex: "female",398
displayName: "Trader",399
sells: [{ itemId: ItemId.copperOre, quantity: 0 }],400
hiddenDiscount: 1401
}402
}];403
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));404
harness.simulation.reloadWorld();405
406
const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 2 });407
harness.stateDb.saveBag(character.character_id, {408
inventory: emptySlots(INVENTORY_SLOTS),409
equipment: emptyEquipment(),410
vault: [],411
vaultReserved: []412
});413
const playerId = harness.simulation.spawnCharacter(1, character);414
harness.simulation.step();415
harness.advance(50);416
harness.simulation.step();417
418
const record = harness.simulation.entityRecord(playerId);419
const worker = harness.simulation.workers[record.workerId];420
let npcId = null;421
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))422
{423
if (entity.creature.mobTypeId === MobId.humanoid)424
{425
npcId = entity.entityId;426
break;427
}428
}429
assert.ok(npcId);430
431
harness.simulation.enqueue(1, {432
type: "interact",433
characterId: character.character_id,434
targetEntityId: npcId435
});436
const open = harness.simulation.step();437
const err = open.events.find((event) => event.type === "command-error");438
assert.ok(err, JSON.stringify(open.events));439
assert.match(err.message, /stand next to her/i);440
assert.doesNotMatch(err.message, /\bthem\b/i);441
}442
finally443
{ harness.close(); }444
});445
446
test("shopkeeper stops wandering while a player has the shop open", () =>447
{448
const harness = makeSimulation({ workerCount: 1 });449
try450
{451
const data = createEmptyChunkData();452
data.open = true;453
data.spawners = [{454
localX: 8,455
localY: 8,456
config: {457
mobTypeId: MobId.humanoid,458
maxAlive: 1,459
spawnRangeTiles: 4,460
maxWanderRangeTiles: 8,461
sex: "male",462
displayName: "Stay put",463
sells: [{ itemId: ItemId.copperOre, quantity: 0 }],464
hiddenDiscount: 1465
}466
}];467
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));468
harness.simulation.reloadWorld();469
470
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });471
harness.stateDb.saveBag(character.character_id, {472
inventory: emptySlots(INVENTORY_SLOTS),473
equipment: emptyEquipment(),474
vault: [],475
vaultReserved: []476
});477
const playerId = harness.simulation.spawnCharacter(1, character);478
harness.simulation.step();479
harness.advance(50);480
harness.simulation.step();481
482
const record = harness.simulation.entityRecord(playerId);483
const worker = harness.simulation.workers[record.workerId];484
let npc = null;485
for (const entity of worker.world.ecs.query(Component.shop, Component.creature, Component.position, Component.path))486
{487
if (entity.creature.mobTypeId === MobId.humanoid)488
{489
npc = entity;490
break;491
}492
}493
assert.ok(npc);494
495
const playerHandle = worker.world.ecs.handleOf(playerId);496
const playerPos = worker.world.ecs.get(playerHandle, Component.position);497
playerPos.tileX = npc.position.tileX;498
playerPos.tileY = npc.position.tileY;499
500
harness.simulation.enqueue(1, {501
type: "interact",502
characterId: character.character_id,503
targetEntityId: npc.entityId504
});505
const open = harness.simulation.step();506
assert.ok(open.events.some((event) => event.type === "shop-open"));507
assert.equal(!!npc.shop.browsers?.[character.character_id], true);508
509
npc.path.tiles = [{ x: npc.position.tileX + 1, y: npc.position.tileY }];510
for (let i = 0; i < 20; i++)511
{ harness.simulation.step(); }512
assert.equal(npc.path.tiles.length, 0);513
assert.equal(npc.position.tileX, playerPos.tileX);514
assert.equal(npc.position.tileY, playerPos.tileY);515
516
harness.simulation.enqueue(1, {517
type: "close-shop",518
characterId: character.character_id,519
npcEntityId: npc.entityId520
});521
harness.simulation.step();522
assert.equal(!!npc.shop.browsers?.[character.character_id], false);523
}524
finally525
{ harness.close(); }526
});527
528
test("buysItems accepts non-ingredient tools like sticks", () =>529
{530
const harness = makeSimulation({ workerCount: 1 });531
try532
{533
const data = createEmptyChunkData();534
data.open = true;535
data.spawners = [{536
localX: 9,537
localY: 8,538
config: {539
mobTypeId: MobId.humanoid,540
maxAlive: 1,541
spawnRangeTiles: 0,542
maxWanderRangeTiles: 0,543
displayName: "Buyer",544
buysItems: true,545
hiddenDiscount: 1546
}547
}];548
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));549
harness.simulation.reloadWorld();550
551
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });552
const slots = emptySlots(INVENTORY_SLOTS);553
slots[0] = { itemId: ItemId.stick, quantity: 1 };554
harness.stateDb.saveBag(character.character_id, {555
inventory: slots,556
equipment: emptyEquipment(),557
vault: [],558
vaultReserved: []559
});560
const playerId = harness.simulation.spawnCharacter(1, character);561
harness.simulation.step();562
harness.advance(50);563
harness.simulation.step();564
565
const record = harness.simulation.entityRecord(playerId);566
const worker = harness.simulation.workers[record.workerId];567
let npcId = null;568
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))569
{570
if (entity.creature.mobTypeId === MobId.humanoid)571
{572
npcId = entity.entityId;573
break;574
}575
}576
assert.ok(npcId);577
const npcHandle = worker.world.ecs.handleOf(npcId);578
const shop = worker.world.ecs.get(npcHandle, Component.shop);579
const npcPos = worker.world.ecs.get(npcHandle, Component.position);580
const playerHandle = worker.world.ecs.handleOf(playerId);581
const playerPos = worker.world.ecs.get(playerHandle, Component.position);582
playerPos.tileX = npcPos.tileX;583
playerPos.tileY = npcPos.tileY;584
585
const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);586
harness.simulation.enqueue(1, {587
type: "sell-to-shop",588
characterId: character.character_id,589
npcEntityId: npcId,590
slotIndex: 0,591
quantity: 1592
});593
const sold = harness.simulation.step();594
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));595
const inv = worker.world.ecs.get(playerHandle, Component.inventory);596
assert.equal(inv.slots[0]?.itemId === ItemId.stick, false);597
assert.ok(countCoinsInSlots(inv.slots) >= beforeCoins + shopBuyFromPlayerPrice(ItemId.stick));598
assert.equal(shop.boughtStock[ItemId.stick], 1);599
}600
finally601
{ harness.close(); }602
});603
604
test("selling a filled cheque pays reserved-goods price minus 5% admin fee", () =>605
{606
const harness = makeSimulation({ workerCount: 1 });607
try608
{609
const data = createEmptyChunkData();610
data.open = true;611
data.blocks[8 * 16 + 8] = { typeId: BlockType.bank, state: 0 };612
data.spawners = [{613
localX: 9,614
localY: 8,615
config: {616
mobTypeId: MobId.humanoid,617
maxAlive: 1,618
spawnRangeTiles: 0,619
maxWanderRangeTiles: 0,620
displayName: "Buyer",621
sells: [{ itemId: ItemId.copperOre, quantity: 0 }],622
buysItems: true,623
hiddenDiscount: 1624
}625
}];626
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));627
harness.simulation.reloadWorld();628
629
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });630
const slots = emptySlots(INVENTORY_SLOTS);631
slots[0] = { itemId: ItemId.copperOre, quantity: 2 };632
harness.stateDb.saveBag(character.character_id, {633
inventory: slots,634
equipment: emptyEquipment(),635
vault: [],636
vaultReserved: []637
});638
const playerId = harness.simulation.spawnCharacter(1, character);639
harness.simulation.step();640
641
harness.simulation.enqueue(1, {642
type: "get-blank-cheques",643
characterId: character.character_id644
});645
harness.simulation.step();646
harness.simulation.enqueue(1, {647
type: "bank-deposit",648
characterId: character.character_id,649
slotIndex: 0,650
quantity: null651
});652
harness.simulation.step();653
let bag = harness.simulation.bagOf(playerId);654
const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);655
const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.copperOre);656
harness.simulation.enqueue(1, {657
type: "write-cheque",658
characterId: character.character_id,659
slotIndex: blankIndex,660
vaultSlotIndex: vaultIndex,661
quantity: 2662
});663
harness.simulation.step();664
bag = harness.simulation.bagOf(playerId);665
const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);666
assert.ok(chequeIndex >= 0);667
668
const record = harness.simulation.entityRecord(playerId);669
const worker = harness.simulation.workers[record.workerId];670
let npcId = null;671
for (const entity of worker.world.ecs.query(Component.shop, Component.creature))672
{673
if (entity.creature.mobTypeId === MobId.humanoid)674
{675
npcId = entity.entityId;676
break;677
}678
}679
assert.ok(npcId);680
const npcHandle = worker.world.ecs.handleOf(npcId);681
const shop = worker.world.ecs.get(npcHandle, Component.shop);682
const npcPos = worker.world.ecs.get(npcHandle, Component.position);683
const playerHandle = worker.world.ecs.handleOf(playerId);684
const playerPos = worker.world.ecs.get(playerHandle, Component.position);685
playerPos.tileX = npcPos.tileX;686
playerPos.tileY = npcPos.tileY;687
688
const quote = resolveShopSellQuote(bag.inventory[chequeIndex]);689
assert.ok(quote?.isCheque);690
const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);691
harness.simulation.enqueue(1, {692
type: "sell-to-shop",693
characterId: character.character_id,694
npcEntityId: npcId,695
slotIndex: chequeIndex,696
quantity: 1697
});698
const sold = harness.simulation.step();699
assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));700
bag = harness.simulation.bagOf(playerId);701
assert.equal(bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque), -1);702
assert.equal((bag.vaultReserved ?? []).length, 0);703
const afterCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);704
assert.equal(afterCoins - beforeCoins, quote.payout);705
// Infinite catalog absorbs goods without bought-from-player resale stock.706
assert.equal(shop.boughtStock?.[ItemId.copperOre] | 0, 0);707
}708
finally709
{ harness.close(); }710
});@@ -6,7 +6,7 @@ import {
6
6
tierTintColor,
7
7
resolveItemTint
8
8
} from "../../shared/render/tint.js";
9
import { MaterialTier, GatherMaterialId } from "../../shared/definitions/materialTiers.js";
9
import { MaterialTier, GatherMaterialId, hexToRgb01, MATERIAL_TINT_HEX, rgb } from "../../shared/definitions/materialTiers.js";
10
10
import { ItemId } from "../../shared/definitions/items.js";
11
11
12
12
test("magenta tintable when R==B and G < R", () =>
@@ -14,6 +14,9 @@ test("magenta tintable when R==B and G < R", () =>
14
14
assert.equal(isMagentaTintable(1, 0, 1), true);
15
15
assert.equal(isMagentaTintable(50 / 255, 0, 50 / 255), true);
16
16
assert.equal(isMagentaTintable(120 / 255, 50 / 255, 120 / 255), true);
17
// Near-magenta drift (R = B ± 2) from AA / export — still tintable.
18
assert.equal(isMagentaTintable(173 / 255, 67 / 255, 171 / 255), true);
19
assert.equal(isMagentaTintable(87 / 255, 60 / 255, 85 / 255), true);
17
20
assert.equal(isMagentaTintable(200 / 255, 100 / 255, 50 / 255), false);
18
21
assert.equal(isMagentaTintable(0.5, 0.5, 0.5), false);
19
22
});
@@ -29,6 +32,16 @@ test("magenta tint preserves lightness and desaturates with G", () =>
29
32
assert.ok(desat.r > pure.r);
30
33
});
31
34
35
test("dark target tints stay dark even on high-G magenta highlights", () =>
36
{
37
const coal = { r: 23 / 255, g: 23 / 255, b: 24 / 255 };
38
const pure = magentaTintedRgb(1, 0, 1, coal);
39
const highlight = magentaTintedRgb(1, 179 / 255, 1, coal);
40
assert.ok(pure.r < 0.12);
41
assert.ok(highlight.r < 0.15, `highlight washed out: ${highlight.r}`);
42
assert.ok(Math.abs(highlight.r - pure.r) < 0.05);
43
});
44
32
45
test("resolveItemTint uses potion instance color and tier tints", () =>
33
46
{
34
47
const potionTint = resolveItemTint({
@@ -41,5 +54,27 @@ test("resolveItemTint uses potion instance color and tier tints", () =>
41
54
const barTint = resolveItemTint({ itemId: ItemId.bronzeBar });
42
55
assert.deepEqual(barTint, bronze);
43
56
const copper = tierTintColor(GatherMaterialId.copper);
44
assert.deepEqual(resolveItemTint({ itemId: ItemId.copperOre }), copper);
57
const copperOre = tierTintColor(GatherMaterialId.copper, { ore: true });
58
assert.notDeepEqual(copperOre, copper);
59
assert.deepEqual(resolveItemTint({ itemId: ItemId.copperOre }), copperOre);
60
const iron = tierTintColor(MaterialTier.iron);
61
const ironOre = tierTintColor(MaterialTier.iron, { ore: true });
62
assert.notDeepEqual(ironOre, iron);
63
assert.deepEqual(resolveItemTint({ itemId: ItemId.ironOre }), ironOre);
64
assert.deepEqual(resolveItemTint({ itemId: ItemId.ironBar }), iron);
65
});
66
67
test("material tint hex converts to 0-1 rgb at load", () =>
68
{
69
assert.deepEqual(MATERIAL_TINT_HEX[MaterialTier.bronze], rgb(184, 122, 71));
70
assert.deepEqual(hexToRgb01(0xB87A47), {
71
r: 184 / 255,
72
g: 122 / 255,
73
b: 71 / 255
74
});
75
assert.deepEqual(hexToRgb01("#B87A47"), hexToRgb01(0xB87A47));
76
assert.deepEqual(hexToRgb01("#abc"), hexToRgb01("#AABBCC"));
77
assert.deepEqual(tierTintColor(MaterialTier.bronze), rgb(184, 122, 71));
78
assert.deepEqual(MATERIAL_TINT_HEX[MaterialTier.mithril], rgb(3, 120, 255));
79
assert.deepEqual(hexToRgb01("rgb(3, 120, 255)"), rgb(3, 120, 255));
45
80
});
@@ -6,7 +6,7 @@ import {6
tierTintColor,6
tierTintColor,7
resolveItemTint7
resolveItemTint8
} from "../../shared/render/tint.js";8
} from "../../shared/render/tint.js";9
import { MaterialTier, GatherMaterialId } from "../../shared/definitions/materialTiers.js";9
import { MaterialTier, GatherMaterialId, hexToRgb01, MATERIAL_TINT_HEX, rgb } from "../../shared/definitions/materialTiers.js";10
import { ItemId } from "../../shared/definitions/items.js";10
import { ItemId } from "../../shared/definitions/items.js";11
11
12
test("magenta tintable when R==B and G < R", () =>12
test("magenta tintable when R==B and G < R", () =>@@ -14,6 +14,9 @@ test("magenta tintable when R==B and G < R", () =>14
assert.equal(isMagentaTintable(1, 0, 1), true);14
assert.equal(isMagentaTintable(1, 0, 1), true);15
assert.equal(isMagentaTintable(50 / 255, 0, 50 / 255), true);15
assert.equal(isMagentaTintable(50 / 255, 0, 50 / 255), true);16
assert.equal(isMagentaTintable(120 / 255, 50 / 255, 120 / 255), true);16
assert.equal(isMagentaTintable(120 / 255, 50 / 255, 120 / 255), true);17
// Near-magenta drift (R = B ± 2) from AA / export — still tintable.18
assert.equal(isMagentaTintable(173 / 255, 67 / 255, 171 / 255), true);19
assert.equal(isMagentaTintable(87 / 255, 60 / 255, 85 / 255), true);17
assert.equal(isMagentaTintable(200 / 255, 100 / 255, 50 / 255), false);20
assert.equal(isMagentaTintable(200 / 255, 100 / 255, 50 / 255), false);18
assert.equal(isMagentaTintable(0.5, 0.5, 0.5), false);21
assert.equal(isMagentaTintable(0.5, 0.5, 0.5), false);19
});22
});@@ -29,6 +32,16 @@ test("magenta tint preserves lightness and desaturates with G", () =>29
assert.ok(desat.r > pure.r);32
assert.ok(desat.r > pure.r);30
});33
});31
34
35
test("dark target tints stay dark even on high-G magenta highlights", () =>36
{37
const coal = { r: 23 / 255, g: 23 / 255, b: 24 / 255 };38
const pure = magentaTintedRgb(1, 0, 1, coal);39
const highlight = magentaTintedRgb(1, 179 / 255, 1, coal);40
assert.ok(pure.r < 0.12);41
assert.ok(highlight.r < 0.15, `highlight washed out: ${highlight.r}`);42
assert.ok(Math.abs(highlight.r - pure.r) < 0.05);43
});44
32
test("resolveItemTint uses potion instance color and tier tints", () =>45
test("resolveItemTint uses potion instance color and tier tints", () =>33
{46
{34
const potionTint = resolveItemTint({47
const potionTint = resolveItemTint({@@ -41,5 +54,27 @@ test("resolveItemTint uses potion instance color and tier tints", () =>41
const barTint = resolveItemTint({ itemId: ItemId.bronzeBar });54
const barTint = resolveItemTint({ itemId: ItemId.bronzeBar });42
assert.deepEqual(barTint, bronze);55
assert.deepEqual(barTint, bronze);43
const copper = tierTintColor(GatherMaterialId.copper);56
const copper = tierTintColor(GatherMaterialId.copper);44
assert.deepEqual(resolveItemTint({ itemId: ItemId.copperOre }), copper);57
const copperOre = tierTintColor(GatherMaterialId.copper, { ore: true });58
assert.notDeepEqual(copperOre, copper);59
assert.deepEqual(resolveItemTint({ itemId: ItemId.copperOre }), copperOre);60
const iron = tierTintColor(MaterialTier.iron);61
const ironOre = tierTintColor(MaterialTier.iron, { ore: true });62
assert.notDeepEqual(ironOre, iron);63
assert.deepEqual(resolveItemTint({ itemId: ItemId.ironOre }), ironOre);64
assert.deepEqual(resolveItemTint({ itemId: ItemId.ironBar }), iron);65
});66
67
test("material tint hex converts to 0-1 rgb at load", () =>68
{69
assert.deepEqual(MATERIAL_TINT_HEX[MaterialTier.bronze], rgb(184, 122, 71));70
assert.deepEqual(hexToRgb01(0xB87A47), {71
r: 184 / 255,72
g: 122 / 255,73
b: 71 / 25574
});75
assert.deepEqual(hexToRgb01("#B87A47"), hexToRgb01(0xB87A47));76
assert.deepEqual(hexToRgb01("#abc"), hexToRgb01("#AABBCC"));77
assert.deepEqual(tierTintColor(MaterialTier.bronze), rgb(184, 122, 71));78
assert.deepEqual(MATERIAL_TINT_HEX[MaterialTier.mithril], rgb(3, 120, 255));79
assert.deepEqual(hexToRgb01("rgb(3, 120, 255)"), rgb(3, 120, 255));45
});80
});@@ -2638,8 +2638,16 @@ Engaging sets `Combat.targetEntityId`. The weapon supplies a single
2638
2638
`AttackProfile` that repeats until cancel, death, or the target leaves
2639
2639
reachable range (then re-path / re-close).
2640
2640
2641
When a combatant is hit, if it has `Combat` it **immediately engages** the
2642
attacker (players and mobs). Peaceful NPCs without `Combat` do not retaliate.
2641
`ATTACK` engages **only the attacker**. A fightable target **retaliates on the
2642
first resolved melee swing** against it (hit, miss, or block) — not when the
2643
player merely clicks Attack or begins pathing. Peaceful NPCs without combat
2644
(`canFight: false`) do not retaliate.
2645
2646
**Aggressive** mobs (`aggressive: true`, optional `aggroRangeTiles`, default 5)
2647
additionally auto-engage the nearest living player character within Chebyshev
2648
range when they have line of sight through enterable tiles (same occlusion
2649
rule as lighting rays: intermediate tiles must be enterable). Passive does not
2650
override an existing engage target.
2643
2651
2644
2652
- **Melee:** pathfind to an 8-neighbour tile, swing when Chebyshev distance is
2645
2653
exactly 1.
@@ -2638,8 +2638,16 @@ Engaging sets `Combat.targetEntityId`. The weapon supplies a single2638
`AttackProfile` that repeats until cancel, death, or the target leaves2638
`AttackProfile` that repeats until cancel, death, or the target leaves2639
reachable range (then re-path / re-close).2639
reachable range (then re-path / re-close).2640
2640
2641
When a combatant is hit, if it has `Combat` it **immediately engages** the2641
`ATTACK` engages **only the attacker**. A fightable target **retaliates on the2642
attacker (players and mobs). Peaceful NPCs without `Combat` do not retaliate.2642
first resolved melee swing** against it (hit, miss, or block) — not when the2643
player merely clicks Attack or begins pathing. Peaceful NPCs without combat2644
(`canFight: false`) do not retaliate.2645
2646
**Aggressive** mobs (`aggressive: true`, optional `aggroRangeTiles`, default 5)2647
additionally auto-engage the nearest living player character within Chebyshev2648
range when they have line of sight through enterable tiles (same occlusion2649
rule as lighting rays: intermediate tiles must be enterable). Passive does not2650
override an existing engage target.2643
2651
2644
- **Melee:** pathfind to an 8-neighbour tile, swing when Chebyshev distance is2652
- **Melee:** pathfind to an 8-neighbour tile, swing when Chebyshev distance is2645
exactly 1.2653
exactly 1.