BlueGit

timfa questward

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.

timfa Tim Falken · pushed by timfa

Authored 2026-08-25 · 2 months ago

Hash
c9ca64d1672744df3ffca088b796da482b5a117f
Parent
7c6cd068
56 files changed +4014 −401
client/assets/blocks/crafting-bench/crafting-bench.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/fx/melee-swipe/melee-swipe.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/axe/axe-equip.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/axe/axe-head.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/axe/axe.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bar/bar.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/ore/ore.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/pickaxe/pickaxe-head.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/wood/handle.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/wood/log.png Binary file +0 −0

The contents of this binary file are not shown.

client/editor.html +12 −0
@@ -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>
client/index.html +40 −3
@@ -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">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 </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>
client/src/editor/settingsModal.js +329 −53
@@ -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("&", "&amp;")
494 .replaceAll("<", "&lt;")
495 .replaceAll(">", "&gt;")
496 .replaceAll("\"", "&quot;");
497 }
@@ -1,4 +1,18 @@
1import { WORLD_SETTING_CATEGORIES, coerceSettingValue, formatSettingValue, settingsValuesEqual } from "/shared/definitions/worldSettings.js";
1import {
2 WORLD_SETTING_CATEGORIES,
3 coerceSettingValue,
4 formatSettingValue,
5 settingsValuesEqual,
6 itemSeedMapsEqual
7} from "/shared/definitions/worldSettings.js";
8import {
9 listPricedItems,
10 itemPriceSnapshot,
11 normalizeItemSeedValues,
12 effectiveSeedValue
13} from "/shared/shop/pricing.js";
14
15const SEED_PAGE_SIZE = 20;
2
16
3export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })
17export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })
4{
18{
@@ -11,6 +25,13 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
11 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, onPreviewNi
18 {
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, onPreviewNi
52 {
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: 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 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.itemLastSales
281 : {};
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
75function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput })
292function 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 else
329 {
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
373function 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
139function syncTabs (form, activeCategory)
420function 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
159function dirtyValues (form, baseline)
440function 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
173function 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
187function renderLog (log, changelog)
454function 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
490function escapeHtml (text)
491{
492 return String(text)
493 .replaceAll("&", "&amp;")
494 .replaceAll("<", "&lt;")
495 .replaceAll(">", "&gt;")
496 .replaceAll("\"", "&quot;");
497}
client/src/editor/tileConfigModal.js +161 −31
@@ -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";
10import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
10import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
11import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
11import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
12
12import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
13const 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
23const EQUIP_PRESETS = Object.freeze([
14const 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.humanoid
220 mobTypeId: MobId.humanoid
95 }, "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);
client/src/play/contextMenu.js +14 −1
@@ -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 @@
1export function initContextMenu ({ root = document.body } = {})
1export 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 });
client/src/play/main.js +167 −15
@@ -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 @@
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2import { BlockType } from "/shared/definitions/tiles.js";
2import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName } from "/shared/definitions/tiles.js";
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
4import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
5import { WorldView } from "../render/worldView.js";
5import { WorldView } from "../render/worldView.js";
@@ -26,6 +26,7 @@ const overlay = document.getElementById("overlay");
26const statusEl = document.getElementById("status");
26const statusEl = document.getElementById("status");
27const characterList = document.getElementById("character-list");
27const characterList = document.getElementById("character-list");
28const errorEl = document.getElementById("error");
28const errorEl = document.getElementById("error");
29const worldTooltip = document.getElementById("world-tooltip");
29
30
30let socket;
31let socket;
31let session = null;
32let session = null;
@@ -48,9 +49,16 @@ let shop;
48let pendingPickup = null;
49let 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 } */
50let pendingInteract = null;
51let pendingInteract = null;
52/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
53let 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. */
52let leftClickConsumed = false;
55let leftClickConsumed = false;
53
56
57function consumeWorldClick ()
58{
59 leftClickConsumed = true;
60}
61
54function showError (message)
62function showError (message)
55{
63{
56 errorEl.textContent = message ?? "";
64 errorEl.textContent = message ?? "";
@@ -88,7 +96,8 @@ function renderCharacters (characters)
88function uiBlocked ()
96function 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
94function clearPendingPickup ()
103function clearPendingPickup ()
@@ -99,6 +108,7 @@ function clearPendingPickup ()
99function clearPendingInteract ()
108function clearPendingInteract ()
100{
109{
101 pendingInteract = null;
110 pendingInteract = null;
111 approachMove = null;
102}
112}
103
113
104function clearAllPendingActions ()
114function 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 = local
140 const dist = local
126 ? 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 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 return false;
173 return false;
138}
174}
139
175
@@ -188,9 +224,9 @@ function requestMine (tileX, tileY)
188
224
189function requestTalk (targetEntityId)
225function 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 else
410 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 else
625 { 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 MessageType
674 MessageType
619 });
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
1001function isCraftingBenchTile (view, tileX, tileY)
1002{
1003 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
1004}
1005
935function isOreBoulderTile (view, tileX, tileY)
1006function 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
1012function hideWorldTooltip ()
1013{
1014 if (worldTooltip)
1015 { worldTooltip.hidden = true; }
1016}
1017
1018/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
1019function 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
941function blockTypeAt (view, tileX, tileY)
1054function 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
1071function 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). */
1084function 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
958function chebyshev (ax, ay, bx, by)
1110function 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));
client/src/play/shop.js +352 −36
@@ -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 formatQuantity
5 formatQuantity
6} from "/shared/definitions/items.js";
6} from "/shared/definitions/items.js";
7import { insertStack } from "/shared/items/inventory.js";
8import {
9 canPlayerSellToNpc,
10 resolveShopSellQuote
11} from "/shared/shop/pricing.js";
12import { subjectPronoun } from "/shared/speech/pronouns.js";
7import { applyItemIcon } from "../render/potionIcon.js";
13import { applyItemIcon } from "../render/potionIcon.js";
8
14
9export function initShop ({
15export function initShop ({
10 socket,
16 socket,
11 MessageType,
17 MessageType,
12 getCoinCount,
18 getCoinCount,
13 onError
19 getInventorySlots,
20 onSuppressWorldClick
14})
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: 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 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: 1
84 });
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 == 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 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.hidden
422 isOpen: () => !panel.hidden
107 };
423 };
108}
424}
client/src/render/worldView.js +59 −4
@@ -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_BO
2import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
2import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
3import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5import { itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
5import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
6import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";
6import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";
7import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";
7import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";
8import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
8import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
@@ -27,6 +27,8 @@ const WALK_TILT_DEG = 6;
27const RUN_TILT_DEG = 8;
27const RUN_TILT_DEG = 8;
28const SHOVE_TILE_FRACTION = 0.25;
28const SHOVE_TILE_FRACTION = 0.25;
29const SHOVE_MS = 280;
29const SHOVE_MS = 280;
30/** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */
31const GATHER_TOOL_HOLD_MS = 1100;
30const DAMAGE_FLASH_MS = 180;
32const DAMAGE_FLASH_MS = 180;
31const DAMAGE_FLOAT_MS = 900;
33const 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 WorldView
571 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 WorldView
643 { 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 WorldView
912 ? !!payload.canFight
917 ? !!payload.canFight
913 : !!(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 WorldView
951
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]?.sprite
1009 const base = layers[0]?.sprite
955 ?? bodySpriteName(entity.sex);
1010 ?? bodySpriteName(entity.sex);
956 if (this.game.images[base])
1011 if (this.game.images[base])
client/ui/editor.css +234 −2
@@ -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 {
client/ui/play.css +163 −17
@@ -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 {
docs/FEATURES.md +17 −17
@@ -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 fi
52## World settings
52## World settings
53
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 lighting
58## Baked lighting
59
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 fi
178## Spawners
178## Spawners
179
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 fi
208## Combat, skills, groups, pigeons
208## Combat, skills, groups, pigeons
209
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 respawn
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## Equipment tiers and worn stat bonuses
228## Equipment tiers and worn stat bonuses
229
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 skills
236## Gathering, crafting, and production skills
237
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 stations
242## Crafting stations
243
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 running
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## Banking, cheques, shops, player-driven marketplace
294## Banking, cheques, shops, player-driven marketplace
295
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 hooks
300## Player scripting hooks
server/src/assets/spriteCatalog.js +1 −1
@@ -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`,
server/src/combat/service.js +72 −1
@@ -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";
4import {
4import {
5 mobCanFightType,
5 mobCanFightType,
6 mobMeleeAttackProfile,
6 mobMeleeAttackProfile,
7 mobSkillLevels
7 mobSkillLevels,
8 mobIsAggressive,
9 mobAggroRangeTiles
8} from "../../../shared/definitions/mobCombat.js";
10} from "../../../shared/definitions/mobCombat.js";
9import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
11import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
10import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
12import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
@@ -15,6 +17,7 @@ import {
15import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
17import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
16import { chunkBoundsAround, findPath } from "../navigation/astar.js";
18import { chunkBoundsAround, findPath } from "../navigation/astar.js";
17import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
19import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
20import { rayReaches } from "../../../shared/lighting/raycast.js";
18
21
19export function chebyshev (ax, ay, bx, by)
22export 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
125export 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 */
134export 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/** 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. */
123export function resolveCombatTarget (world, targetId)
193export 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 }
server/src/crafting/service.js +2 −0
@@ -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
server/src/ecs/serialize.js +4 −1
@@ -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 } from
3import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
3import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4import { mobDefinition } from "../../../shared/definitions/mobs.js";
4import { mobDefinition } from "../../../shared/definitions/mobs.js";
5import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
5import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
6import { shopHasInterface } from "../shop/service.js";
6
7
7function bodySprite (sex)
8function 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,
server/src/editor/service.js +37 −4
@@ -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,
5import { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";
5import { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";
6import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
6import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
7import { closedNeighborEdges } from "../world/chunkFlags.js";
7import { closedNeighborEdges } from "../world/chunkFlags.js";
8import { coerceSettingValue, diffSettings, allSettingFields } from "../../../shared/definitions/worldSettings.js";
8import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js";
9import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
10import { itemDefinition } from "../../../shared/definitions/items.js";
11import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
9
12
10export class EditorService
13export class EditorService
11{
14{
@@ -100,7 +103,14 @@ export class EditorService
100 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.itemSeedValues
111 : {})
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 EditorService
110 { 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 ?? 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 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 EditorService
119 changed: {}
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 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 {
server/src/gateway/websocket.js +39 −1
@@ -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 : 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 quantity: message.quantity | 0 || 1
417 quantity: message.quantity | 0 || 1
406 });
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 | 0
426 });
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.npcEntityId
888 });
889 }
890 continue;
891 }
854 if (event.type === "item-bubble")
892 if (event.type === "item-bubble")
855 {
893 {
856 broadcastItemBubble(
894 broadcastItemBubble(
server/src/gathering/service.js +4 −0
@@ -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: now
175 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: false
187 swipe: false
185 }]
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: false
231 swipe: false
228 });
232 });
229 }
233 }
server/src/shop/service.js +515 −73
@@ -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 @@
1import { Component } from "../ecs/components.js";
1import { Component } from "../ecs/components.js";
2import { bagView } from "../items/bags.js";
2import { bagView, findReservedChequeIndex } from "../items/bags.js";
3import { itemDefinition } from "../../../shared/definitions/items.js";
3import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4import { ItemOriginKind, attachOrigins } from "../../../shared/items/origin.js";
4import { ItemOriginKind, attachOrigins } from "../../../shared/items/origin.js";
5import {
5import {
6 addCoinsToSlots,
7 cloneStack,
6 countCoinsInSlots,
8 countCoinsInSlots,
7 insertStack,
9 insertStack,
8 takeCoinsFromSlots
10 insertStackGrowable,
11 takeCoinsFromSlots,
12 takeFromSlot
9} from "../../../shared/items/inventory.js";
13} from "../../../shared/items/inventory.js";
10import { canSellInNpcShop, shopUnitPrice } from "../../../shared/shop/pricing.js";
14import {
15 canSellInNpcShop,
16 canPlayerSellToNpc,
17 resolveShopSellQuote,
18 shopUnitPrice,
19 shopBoughtResalePrice,
20 shopRestockDayKey
21} from "../../../shared/shop/pricing.js";
11import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
22import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
12import { chebyshev } from "../combat/service.js";
23import { chebyshev } from "../combat/service.js";
24import { objectPronoun } from "../../../shared/speech/pronouns.js";
13
25
14function userError (message)
26function userError (message)
15{
27{
@@ -18,38 +30,259 @@ function userError (message)
18 return error;
30 return error;
19}
31}
20
32
33function 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. */
40function 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
47export 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
55function stopNpcMovement (world, npcHandle)
56{
57 const path = world.ecs.get(npcHandle, Component.path);
58 if (path)
59 { path.tiles = []; }
60}
61
62function addShopBrowser (world, shop, npcHandle, characterId)
63{
64 ensureBrowsers(shop)[characterId] = true;
65 stopNpcMovement(world, npcHandle);
66}
67
68function removeShopBrowser (shop, characterId)
69{
70 if (!shop?.browsers)
71 { return; }
72 delete shop.browsers[characterId];
73}
74
75export 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 */
87export 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
21function lastSaleFor (world, itemId)
133function lastSaleFor (world, itemId)
22{
134{
23 return world.itemLastSales?.get(itemId) ?? null;
135 return world.itemLastSales?.get(itemId) ?? null;
24}
136}
25
137
26function shopStockView (world, shop, now)
138function lerpDuration (world)
27{
139{
28 const lerpDurationMs = world.settings?.shopPriceLerpDurationMs
140 return world.settings?.shopPriceLerpDurationMs
29 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
141 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
142}
143
144function 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
152function 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. */
165export 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
196function catalogLine (shop, itemId)
197{
198 return (shop.catalog ?? []).find((line) => (line.itemId | 0) === (itemId | 0)) ?? null;
199}
200
201function 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
211function boughtAvailable (shop, itemId)
212{
213 return Math.max(0, shop.boughtStock?.[itemId] | 0 || 0);
214}
215
216function 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 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 ?? 1
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 return stock;
267 return stock;
50}
268}
51
269
52export function openShop (world, sessionId, characterId, npcEntityId, now = Date.now())
270function 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
285function 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 = Date
65 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.displayName
314}
78 || [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ")
79 || "Shopkeeper";
80
315
316export 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
93export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, quantity = 1, now = Date.now())
327export 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);
344function 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
356export 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?.shopPriceLerpDurationMs
370 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 ?? 1
376 const unitPrice = listing.source === "bought"
131 });
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 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.displayName
402 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: qty
153 }]
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 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 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 boughtStock
448 * (cleared at midnight). Infinite catalog lines absorb goods without resale stock.
449 */
450export 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 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 ?? 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 now
609 now
186 );
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
618export 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}
server/src/simulation/simulation.js +18 −0
@@ -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 Simulation
104 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();
server/src/simulation/spawners.js +22 −6
@@ -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.hiddenDiscount
56 hiddenDiscount: config.hiddenDiscount
56 });
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.length
137 const catalog = Array.isArray(request.sells)
137 ? request.sells
138 ? 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 displayName
157 displayName,
158 remaining: Object.create(null),
159 boughtStock: Object.create(null),
160 restockDay: null
145 };
161 };
146 }
162 }
147 return components;
163 return components;
server/src/simulation/workerWorld.js +78 −29
@@ -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 @@
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";
2import {
2import {
3 chunkKey,
3 chunkKey,
4 chunkToRegion,
4 chunkToRegion,
@@ -38,7 +38,7 @@ import {
38 clearOreRespawnsForChunk
38 clearOreRespawnsForChunk
39} from "../gathering/service.js";
39} from "../gathering/service.js";
40import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
40import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
41import { handleShopCommand, openShop } from "../shop/service.js";
41import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
42import {
42import {
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 stepCombat
50 stepCombat
50} from "../combat/service.js";
51} from "../combat/service.js";
51import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
52import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
@@ -346,6 +347,7 @@ export class WorkerWorld
346
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 WorkerWorld
660 { 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 WorkerWorld
677
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 WorkerWorld
750 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 WorkerWorld
954 }
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 WorkerWorld
983 {
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 WorkerWorld
995 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 WorkerWorld
1011 }
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 WorkerWorld
1057 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 WorkerWorld
1066 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 == 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 #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 WorkerWorld
1108 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; }
server/tests/combat.test.js +80 −10
@@ -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";
3import { mobComponents } from "../src/simulation/spawners.js";
3import { mobComponents } from "../src/simulation/spawners.js";
4import { MobId } from "../../shared/definitions/mobs.js";
4import { MobId } from "../../shared/definitions/mobs.js";
5import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
5import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6import { BlockType } from "../../shared/definitions/tiles.js";
6import { Component } from "../src/ecs/components.js";
7import { Component } from "../src/ecs/components.js";
7import { tileKey } from "../src/world/coordinates.js";
8import { tileKey } from "../src/world/coordinates.js";
8import { WorkerMessage } from "../src/simulation/protocol.js";
9import { 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
349test("attack engages both combatants and retaliates", () =>
350test("attack engages the attacker; target retaliates on first swing", () =>
350{
351{
351 const harness = makeSimulation({ workerCount: 1 });
352 const harness = makeSimulation({ workerCount: 1 });
352 try
353 try
353 {
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: null
362 spawnerId: null
361 }));
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: ratId
368 targetEntityId: deerId
367 });
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 finally
389 finally
376 { 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: deerId
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 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
515test("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
536test("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
500test("attacker keeps pursuing and can swing after the target moves", () =>
570test("attacker keeps pursuing and can swing after the target moves", () =>
501{
571{
502 const harness = makeSimulation({ workerCount: 1 });
572 const harness = makeSimulation({ workerCount: 1 });
server/tests/crafting.test.js +39 −2
@@ -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
75test("furnace recipes: bronze is tin+copper; steel is iron+coal", () =>
75test("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.ironOre
91 ItemId.ironOre
92 ].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
96test("tin copper coal map to associated bar tiers for smelt duration", () =>
126test("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
109test("open furnace near station emits shove and station-open", () =>
145test("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));
server/tests/craftingStations.test.js +17 −1
@@ -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
89test("woodworking and anvil expose pickaxe chain recipes", () =>
89test("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.bronzePickaxeHead
106 ItemId.bronzePickaxeHead
105 ].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.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});
server/tests/live-settings.test.js +36 −0
@@ -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";
5import { join } from "node:path";
5import { join } from "node:path";
6import { WorldDatabase } from "../src/persistence/worldDb.js";
6import { WorldDatabase } from "../src/persistence/worldDb.js";
7import { EditorService } from "../src/editor/service.js";
7import { EditorService } from "../src/editor/service.js";
8import { ItemId } from "../../shared/definitions/items.js";
9import { effectiveSeedValue, shopUnitPrice, undiscountedMarketValue } from "../../shared/shop/pricing.js";
8
10
9function tempWorld ()
11function tempWorld ()
10{
12{
@@ -35,3 +37,37 @@ test("live settings save writes only changed fields and appends a log", () =>
35 finally
37 finally
36 { worldDb.close(); }
38 { worldDb.close(); }
37});
39});
40
41test("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
62test("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});
server/tests/mining.test.js +14 −0
@@ -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
112test("boulder block exists", () =>
124test("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
server/tests/navigationStuck.test.js added +65 −0
@@ -0,0 +1,65 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { NAV_STUCK_MS } from "../../shared/protocol/constants.js";
4 import { MobId } from "../../shared/definitions/mobs.js";
5 import { Component } from "../src/ecs/components.js";
6 import { mobComponents } from "../src/simulation/spawners.js";
7 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
8
9 function workerOf (simulation, entityId)
10 {
11 const record = simulation.entityRecord(entityId);
12 assert.ok(record);
13 return simulation.workers[record.workerId];
14 }
15
16 test("navigation stuck for 5s repaths around a blocker", () =>
17 {
18 const harness = makeSimulation({ workerCount: 1 });
19 try
20 {
21 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
22 harness.simulation.spawnCharacter(1, character);
23 const moverId = harness.simulation.spawnEntity(mobComponents({
24 tileX: 8,
25 tileY: 9,
26 mobTypeId: MobId.deer
27 }));
28 harness.simulation.spawnEntity(mobComponents({
29 tileX: 9,
30 tileY: 9,
31 mobTypeId: MobId.deer
32 }));
33 harness.simulation.step();
34
35 const worker = workerOf(harness.simulation, moverId);
36 const handle = worker.world.ecs.handleOf(moverId);
37 const path = worker.world.ecs.get(handle, Component.path);
38 const position = worker.world.ecs.get(handle, Component.position);
39 path.tiles = [
40 { x: 9, y: 9 },
41 { x: 10, y: 9 },
42 { x: 11, y: 9 }
43 ];
44 path.stuckSince = harness.now();
45 path.stuckTileX = position.tileX;
46 path.stuckTileY = position.tileY;
47
48 harness.advance(1_000);
49 harness.simulation.step();
50 assert.equal(position.tileX, 8);
51 assert.equal(position.tileY, 9);
52 assert.equal(path.tiles[0]?.x, 9);
53 assert.equal(path.tiles[0]?.y, 9);
54
55 harness.advance(NAV_STUCK_MS);
56 harness.simulation.step();
57 assert.equal(position.tileX, 8);
58 assert.equal(position.tileY, 9);
59 const next = path.tiles[0];
60 assert.ok(next, "expected a repath with remaining steps");
61 assert.ok(!(next.x === 9 && next.y === 9), "repath should not keep stepping into the blocker");
62 }
63 finally
64 { harness.close(); }
65 });
@@ -0,0 +1,65 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { NAV_STUCK_MS } from "../../shared/protocol/constants.js";
4import { MobId } from "../../shared/definitions/mobs.js";
5import { Component } from "../src/ecs/components.js";
6import { mobComponents } from "../src/simulation/spawners.js";
7import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
8
9function workerOf (simulation, entityId)
10{
11 const record = simulation.entityRecord(entityId);
12 assert.ok(record);
13 return simulation.workers[record.workerId];
14}
15
16test("navigation stuck for 5s repaths around a blocker", () =>
17{
18 const harness = makeSimulation({ workerCount: 1 });
19 try
20 {
21 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
22 harness.simulation.spawnCharacter(1, character);
23 const moverId = harness.simulation.spawnEntity(mobComponents({
24 tileX: 8,
25 tileY: 9,
26 mobTypeId: MobId.deer
27 }));
28 harness.simulation.spawnEntity(mobComponents({
29 tileX: 9,
30 tileY: 9,
31 mobTypeId: MobId.deer
32 }));
33 harness.simulation.step();
34
35 const worker = workerOf(harness.simulation, moverId);
36 const handle = worker.world.ecs.handleOf(moverId);
37 const path = worker.world.ecs.get(handle, Component.path);
38 const position = worker.world.ecs.get(handle, Component.position);
39 path.tiles = [
40 { x: 9, y: 9 },
41 { x: 10, y: 9 },
42 { x: 11, y: 9 }
43 ];
44 path.stuckSince = harness.now();
45 path.stuckTileX = position.tileX;
46 path.stuckTileY = position.tileY;
47
48 harness.advance(1_000);
49 harness.simulation.step();
50 assert.equal(position.tileX, 8);
51 assert.equal(position.tileY, 9);
52 assert.equal(path.tiles[0]?.x, 9);
53 assert.equal(path.tiles[0]?.y, 9);
54
55 harness.advance(NAV_STUCK_MS);
56 harness.simulation.step();
57 assert.equal(position.tileX, 8);
58 assert.equal(position.tileY, 9);
59 const next = path.tiles[0];
60 assert.ok(next, "expected a repath with remaining steps");
61 assert.ok(!(next.x === 9 && next.y === 9), "repath should not keep stepping into the blocker");
62 }
63 finally
64 { harness.close(); }
65});
server/tests/shop.test.js +593 −10
@@ -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 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { shopUnitPrice, undiscountedMarketValue, canSellInNpcShop, lerp } from "../../shared/shop/pricing.js";
3import {
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";
4import { ItemId } from "../../shared/definitions/items.js";
15import { ItemId } from "../../shared/definitions/items.js";
5import { MobId, normalizeSpawnerConfig, isHumanoidMob } from "../../shared/definitions/mobs.js";
16import { MobId, normalizeSpawnerConfig, isHumanoidMob } from "../../shared/definitions/mobs.js";
6import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
17import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
7import { Component } from "../src/ecs/components.js";
18import { Component } from "../src/ecs/components.js";
8import { emptyEquipment, emptySlots, addCoinsToSlots } from "../../shared/items/inventory.js";
19import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
9import { ItemOriginKind } from "../../shared/items/origin.js";
20import { ItemOriginKind } from "../../shared/items/origin.js";
10import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
21import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
22import { ensureShopRestocked } from "../src/shop/service.js";
23import { BlockType } from "../../shared/definitions/tiles.js";
11
24
12test("shop prices fall back to seedValue and apply hidden discount", () =>
25test("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
23test("humanoid spawner config keeps sex equipment and sells", () =>
60test("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.copperOre
72 ],
73 buysItems: true,
32 hiddenDiscount: 0.85
74 hiddenDiscount: 0.85
33 }, "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: 1
165 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 finally
175 finally
126 { harness.close(); }
176 { harness.close(); }
127});
177});
178
179test("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
204test("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
284test("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
382test("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
446test("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
528test("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
604test("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});
server/tests/tint.test.js +37 −2
@@ -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 resolveItemTint
7 resolveItemTint
8} from "../../shared/render/tint.js";
8} from "../../shared/render/tint.js";
9import { MaterialTier, GatherMaterialId } from "../../shared/definitions/materialTiers.js";
9import { MaterialTier, GatherMaterialId, hexToRgb01, MATERIAL_TINT_HEX, rgb } from "../../shared/definitions/materialTiers.js";
10import { ItemId } from "../../shared/definitions/items.js";
10import { ItemId } from "../../shared/definitions/items.js";
11
11
12test("magenta tintable when R==B and G < R", () =>
12test("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
35test("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
32test("resolveItemTint uses potion instance color and tier tints", () =>
45test("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
67test("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});
shared/crafting/stationRecipes.js +70 −6
@@ -4,11 +4,14 @@ import { CraftingItemId } from "../definitions/craftingItems.js";
4 4 import {
5 5 MetalItemId,
6 6 PICKAXE_HEAD_ITEM_BY_METAL,
7 PICKAXE_ITEM_BY_METAL
7 PICKAXE_ITEM_BY_METAL,
8 AXE_HEAD_ITEM_BY_METAL,
9 AXE_ITEM_BY_METAL
8 10 } from "../definitions/metalItems.js";
9 11 import {
10 12 WOOD_TIER_ORDER,
11 13 MaterialTier,
14 GatherMaterialId,
12 15 MATERIAL_TIER_ORDER,
13 16 woodTierForMetal,
14 17 tierSmeltSkillLevel,
@@ -75,7 +78,7 @@ function pickaxeAssembleRecipe (metalTier, handleItemId, headItemId, pickaxeItem
75 78 {
76 79 return Object.freeze({
77 80 recipeId: `pickaxe-${metalTier}`,
78 stationId: CraftingStationId.woodworkingBench,
81 stationId: CraftingStationId.craftingBench,
79 82 output: { itemId: pickaxeItemId, quantity: 1 },
80 83 inputs: [
81 84 { itemId: handleItemId, quantity: 1 },
@@ -87,6 +90,35 @@ function pickaxeAssembleRecipe (metalTier, handleItemId, headItemId, pickaxeItem
87 90 });
88 91 }
89 92
93 function axeHeadRecipe (metalTier, barItemId, headItemId)
94 {
95 return Object.freeze({
96 recipeId: `axe-head-${metalTier}`,
97 stationId: CraftingStationId.anvil,
98 output: { itemId: headItemId, quantity: 1 },
99 inputs: [{ itemId: barItemId, quantity: 1 }],
100 minSkillLevel: tierSmeltSkillLevel(metalTier),
101 skillId: "smithing",
102 xpMaterial: metalTier
103 });
104 }
105
106 function axeAssembleRecipe (metalTier, handleItemId, headItemId, axeItemId)
107 {
108 return Object.freeze({
109 recipeId: `axe-${metalTier}`,
110 stationId: CraftingStationId.craftingBench,
111 output: { itemId: axeItemId, quantity: 1 },
112 inputs: [
113 { itemId: handleItemId, quantity: 1 },
114 { itemId: headItemId, quantity: 1 }
115 ],
116 minSkillLevel: tierCraftSkillLevel(metalTier),
117 skillId: "crafting",
118 xpMaterial: metalTier
119 });
120 }
121
90 122 const BAR_BY_METAL = Object.freeze({
91 123 [MaterialTier.bronze]: CraftingItemId.bronzeBar,
92 124 [MaterialTier.iron]: MetalItemId.ironBar,
@@ -102,6 +134,11 @@ const PICKAXE_BY_METAL = Object.freeze({
102 134 ...PICKAXE_ITEM_BY_METAL
103 135 });
104 136
137 const AXE_BY_METAL = Object.freeze({
138 [MaterialTier.bronze]: CraftingItemId.bronzeAxe,
139 ...AXE_ITEM_BY_METAL
140 });
141
105 142 const WOOD_HANDLE_RECIPES = WOOD_TIER_ORDER.map((tier) => handleRecipe(tier));
106 143
107 144 const PICKAXE_HEAD_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
@@ -118,6 +155,20 @@ const PICKAXE_ASSEMBLE_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
118 155 );
119 156 });
120 157
158 const AXE_HEAD_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
159 axeHeadRecipe(tier, BAR_BY_METAL[tier], AXE_HEAD_ITEM_BY_METAL[tier]));
160
161 const AXE_ASSEMBLE_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
162 {
163 const wood = woodTierForMetal(tier);
164 return axeAssembleRecipe(
165 tier,
166 handleItemIdForWood(wood),
167 AXE_HEAD_ITEM_BY_METAL[tier],
168 AXE_BY_METAL[tier]
169 );
170 });
171
121 172 /** @type {ReadonlyArray<object>} */
122 173 export const CRAFT_RECIPES = Object.freeze([
123 174 Object.freeze({
@@ -142,25 +193,38 @@ export const CRAFT_RECIPES = Object.freeze([
142 193 { itemId: MetalItemId.coal, quantity: 1 }
143 194 ], MetalItemId.steelBar),
144 195
196 smelt(GatherMaterialId.silver, "smelt-silver", [
197 { itemId: MetalItemId.silverOre, quantity: 1 }
198 ], MetalItemId.silverBar),
199
200 smelt(GatherMaterialId.gold, "smelt-gold", [
201 { itemId: MetalItemId.goldOre, quantity: 1 }
202 ], MetalItemId.goldBar),
203
145 204 smelt(MaterialTier.mithril, "smelt-mithril", [
146 205 { itemId: MetalItemId.mithrilOre, quantity: 1 }
147 206 ], MetalItemId.mithrilBar),
148 207
149 208 smelt(MaterialTier.adamantium, "smelt-adamantium", [
150 { itemId: MetalItemId.adamantiumOre, quantity: 1 }
209 { itemId: MetalItemId.adamantiumOre, quantity: 1 },
210 { itemId: MetalItemId.coal, quantity: 1 }
151 211 ], MetalItemId.adamantiumBar),
152 212
153 213 smelt(MaterialTier.orichalcum, "smelt-orichalcum", [
154 { itemId: MetalItemId.orichalcumOre, quantity: 1 }
214 { itemId: MetalItemId.orichalcumOre, quantity: 1 },
215 { itemId: MetalItemId.coal, quantity: 3 }
155 216 ], MetalItemId.orichalcumBar),
156 217
157 218 smelt(MaterialTier.dragon, "smelt-dragon", [
158 { itemId: MetalItemId.dragonOre, quantity: 1 }
219 { itemId: MetalItemId.dragonOre, quantity: 1 },
220 { itemId: MetalItemId.coal, quantity: 5 }
159 221 ], MetalItemId.dragonBar),
160 222
161 223 ...WOOD_HANDLE_RECIPES,
162 224 ...PICKAXE_HEAD_RECIPES,
163 ...PICKAXE_ASSEMBLE_RECIPES
225 ...PICKAXE_ASSEMBLE_RECIPES,
226 ...AXE_HEAD_RECIPES,
227 ...AXE_ASSEMBLE_RECIPES
164 228 ]);
165 229
166 230 const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
@@ -4,11 +4,14 @@ import { CraftingItemId } from "../definitions/craftingItems.js";
4import {
4import {
5 MetalItemId,
5 MetalItemId,
6 PICKAXE_HEAD_ITEM_BY_METAL,
6 PICKAXE_HEAD_ITEM_BY_METAL,
7 PICKAXE_ITEM_BY_METAL
7 PICKAXE_ITEM_BY_METAL,
8 AXE_HEAD_ITEM_BY_METAL,
9 AXE_ITEM_BY_METAL
8} from "../definitions/metalItems.js";
10} from "../definitions/metalItems.js";
9import {
11import {
10 WOOD_TIER_ORDER,
12 WOOD_TIER_ORDER,
11 MaterialTier,
13 MaterialTier,
14 GatherMaterialId,
12 MATERIAL_TIER_ORDER,
15 MATERIAL_TIER_ORDER,
13 woodTierForMetal,
16 woodTierForMetal,
14 tierSmeltSkillLevel,
17 tierSmeltSkillLevel,
@@ -75,7 +78,7 @@ function pickaxeAssembleRecipe (metalTier, handleItemId, headItemId, pickaxeItem
75{
78{
76 return Object.freeze({
79 return Object.freeze({
77 recipeId: `pickaxe-${metalTier}`,
80 recipeId: `pickaxe-${metalTier}`,
78 stationId: CraftingStationId.woodworkingBench,
81 stationId: CraftingStationId.craftingBench,
79 output: { itemId: pickaxeItemId, quantity: 1 },
82 output: { itemId: pickaxeItemId, quantity: 1 },
80 inputs: [
83 inputs: [
81 { itemId: handleItemId, quantity: 1 },
84 { itemId: handleItemId, quantity: 1 },
@@ -87,6 +90,35 @@ function pickaxeAssembleRecipe (metalTier, handleItemId, headItemId, pickaxeItem
87 });
90 });
88}
91}
89
92
93function axeHeadRecipe (metalTier, barItemId, headItemId)
94{
95 return Object.freeze({
96 recipeId: `axe-head-${metalTier}`,
97 stationId: CraftingStationId.anvil,
98 output: { itemId: headItemId, quantity: 1 },
99 inputs: [{ itemId: barItemId, quantity: 1 }],
100 minSkillLevel: tierSmeltSkillLevel(metalTier),
101 skillId: "smithing",
102 xpMaterial: metalTier
103 });
104}
105
106function axeAssembleRecipe (metalTier, handleItemId, headItemId, axeItemId)
107{
108 return Object.freeze({
109 recipeId: `axe-${metalTier}`,
110 stationId: CraftingStationId.craftingBench,
111 output: { itemId: axeItemId, quantity: 1 },
112 inputs: [
113 { itemId: handleItemId, quantity: 1 },
114 { itemId: headItemId, quantity: 1 }
115 ],
116 minSkillLevel: tierCraftSkillLevel(metalTier),
117 skillId: "crafting",
118 xpMaterial: metalTier
119 });
120}
121
90const BAR_BY_METAL = Object.freeze({
122const BAR_BY_METAL = Object.freeze({
91 [MaterialTier.bronze]: CraftingItemId.bronzeBar,
123 [MaterialTier.bronze]: CraftingItemId.bronzeBar,
92 [MaterialTier.iron]: MetalItemId.ironBar,
124 [MaterialTier.iron]: MetalItemId.ironBar,
@@ -102,6 +134,11 @@ const PICKAXE_BY_METAL = Object.freeze({
102 ...PICKAXE_ITEM_BY_METAL
134 ...PICKAXE_ITEM_BY_METAL
103});
135});
104
136
137const AXE_BY_METAL = Object.freeze({
138 [MaterialTier.bronze]: CraftingItemId.bronzeAxe,
139 ...AXE_ITEM_BY_METAL
140});
141
105const WOOD_HANDLE_RECIPES = WOOD_TIER_ORDER.map((tier) => handleRecipe(tier));
142const WOOD_HANDLE_RECIPES = WOOD_TIER_ORDER.map((tier) => handleRecipe(tier));
106
143
107const PICKAXE_HEAD_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
144const PICKAXE_HEAD_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
@@ -118,6 +155,20 @@ const PICKAXE_ASSEMBLE_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
118 );
155 );
119});
156});
120
157
158const AXE_HEAD_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
159 axeHeadRecipe(tier, BAR_BY_METAL[tier], AXE_HEAD_ITEM_BY_METAL[tier]));
160
161const AXE_ASSEMBLE_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
162{
163 const wood = woodTierForMetal(tier);
164 return axeAssembleRecipe(
165 tier,
166 handleItemIdForWood(wood),
167 AXE_HEAD_ITEM_BY_METAL[tier],
168 AXE_BY_METAL[tier]
169 );
170});
171
121/** @type {ReadonlyArray<object>} */
172/** @type {ReadonlyArray<object>} */
122export const CRAFT_RECIPES = Object.freeze([
173export const CRAFT_RECIPES = Object.freeze([
123 Object.freeze({
174 Object.freeze({
@@ -142,25 +193,38 @@ export const CRAFT_RECIPES = Object.freeze([
142 { itemId: MetalItemId.coal, quantity: 1 }
193 { itemId: MetalItemId.coal, quantity: 1 }
143 ], MetalItemId.steelBar),
194 ], MetalItemId.steelBar),
144
195
196 smelt(GatherMaterialId.silver, "smelt-silver", [
197 { itemId: MetalItemId.silverOre, quantity: 1 }
198 ], MetalItemId.silverBar),
199
200 smelt(GatherMaterialId.gold, "smelt-gold", [
201 { itemId: MetalItemId.goldOre, quantity: 1 }
202 ], MetalItemId.goldBar),
203
145 smelt(MaterialTier.mithril, "smelt-mithril", [
204 smelt(MaterialTier.mithril, "smelt-mithril", [
146 { itemId: MetalItemId.mithrilOre, quantity: 1 }
205 { itemId: MetalItemId.mithrilOre, quantity: 1 }
147 ], MetalItemId.mithrilBar),
206 ], MetalItemId.mithrilBar),
148
207
149 smelt(MaterialTier.adamantium, "smelt-adamantium", [
208 smelt(MaterialTier.adamantium, "smelt-adamantium", [
150 { itemId: MetalItemId.adamantiumOre, quantity: 1 }
209 { itemId: MetalItemId.adamantiumOre, quantity: 1 },
210 { itemId: MetalItemId.coal, quantity: 1 }
151 ], MetalItemId.adamantiumBar),
211 ], MetalItemId.adamantiumBar),
152
212
153 smelt(MaterialTier.orichalcum, "smelt-orichalcum", [
213 smelt(MaterialTier.orichalcum, "smelt-orichalcum", [
154 { itemId: MetalItemId.orichalcumOre, quantity: 1 }
214 { itemId: MetalItemId.orichalcumOre, quantity: 1 },
215 { itemId: MetalItemId.coal, quantity: 3 }
155 ], MetalItemId.orichalcumBar),
216 ], MetalItemId.orichalcumBar),
156
217
157 smelt(MaterialTier.dragon, "smelt-dragon", [
218 smelt(MaterialTier.dragon, "smelt-dragon", [
158 { itemId: MetalItemId.dragonOre, quantity: 1 }
219 { itemId: MetalItemId.dragonOre, quantity: 1 },
220 { itemId: MetalItemId.coal, quantity: 5 }
159 ], MetalItemId.dragonBar),
221 ], MetalItemId.dragonBar),
160
222
161 ...WOOD_HANDLE_RECIPES,
223 ...WOOD_HANDLE_RECIPES,
162 ...PICKAXE_HEAD_RECIPES,
224 ...PICKAXE_HEAD_RECIPES,
163 ...PICKAXE_ASSEMBLE_RECIPES
225 ...PICKAXE_ASSEMBLE_RECIPES,
226 ...AXE_HEAD_RECIPES,
227 ...AXE_ASSEMBLE_RECIPES
164]);
228]);
165
229
166const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
230const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
shared/definitions/craftingItems.js +8 −2
@@ -119,10 +119,16 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
119 119 [CraftingItemId.arrow]: stub(CraftingItemId.arrow, "arrow", "Arrow", ItemCategory.finished, {
120 120 description: "Ammunition for bows."
121 121 }),
122 [CraftingItemId.bronzeAxe]: stub(CraftingItemId.bronzeAxe, "bronze-axe", "Bronze axe", ItemCategory.tool, {
122 [CraftingItemId.bronzeAxe]: Object.freeze({
123 itemId: CraftingItemId.bronzeAxe,
124 key: "bronze-axe",
125 displayName: "Bronze axe",
126 description: "Woodcutting tool. Bronze may be equipped at any Woodcutting level.",
127 seedValue: 8,
123 128 stackable: false,
124 129 maxStackSize: 1,
125 description: "Woodcutting tool.",
130 uniqueInstance: false,
131 category: ItemCategory.tool,
126 132 iconKey: "axe",
127 133 defaultState: "axe",
128 134 tintFromTier: true,
@@ -119,10 +119,16 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
119 [CraftingItemId.arrow]: stub(CraftingItemId.arrow, "arrow", "Arrow", ItemCategory.finished, {
119 [CraftingItemId.arrow]: stub(CraftingItemId.arrow, "arrow", "Arrow", ItemCategory.finished, {
120 description: "Ammunition for bows."
120 description: "Ammunition for bows."
121 }),
121 }),
122 [CraftingItemId.bronzeAxe]: stub(CraftingItemId.bronzeAxe, "bronze-axe", "Bronze axe", ItemCategory.tool, {
122 [CraftingItemId.bronzeAxe]: Object.freeze({
123 itemId: CraftingItemId.bronzeAxe,
124 key: "bronze-axe",
125 displayName: "Bronze axe",
126 description: "Woodcutting tool. Bronze may be equipped at any Woodcutting level.",
127 seedValue: 8,
123 stackable: false,
128 stackable: false,
124 maxStackSize: 1,
129 maxStackSize: 1,
125 description: "Woodcutting tool.",
130 uniqueInstance: false,
131 category: ItemCategory.tool,
126 iconKey: "axe",
132 iconKey: "axe",
127 defaultState: "axe",
133 defaultState: "axe",
128 tintFromTier: true,
134 tintFromTier: true,
shared/definitions/craftingStations.js +2 −2
@@ -54,13 +54,13 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
54 54 stationId: CraftingStationId.craftingBench,
55 55 displayName: "Crafting bench",
56 56 skillId: SkillId.crafting,
57 description: "General crafting (e.g. fletching arrows from smithed tips)."
57 description: "Assemble finished parts (handles + pickaxe/axe heads, later similar kits)."
58 58 }),
59 59 [CraftingStationId.woodworkingBench]: Object.freeze({
60 60 stationId: CraftingStationId.woodworkingBench,
61 61 displayName: "Woodworking bench",
62 62 skillId: SkillId.crafting,
63 description: "Shape logs into handles and assemble hafted tools."
63 description: "Shape logs into handles and other wood components."
64 64 }),
65 65 [CraftingStationId.oven]: Object.freeze({
66 66 stationId: CraftingStationId.oven,
@@ -54,13 +54,13 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
54 stationId: CraftingStationId.craftingBench,
54 stationId: CraftingStationId.craftingBench,
55 displayName: "Crafting bench",
55 displayName: "Crafting bench",
56 skillId: SkillId.crafting,
56 skillId: SkillId.crafting,
57 description: "General crafting (e.g. fletching arrows from smithed tips)."
57 description: "Assemble finished parts (handles + pickaxe/axe heads, later similar kits)."
58 }),
58 }),
59 [CraftingStationId.woodworkingBench]: Object.freeze({
59 [CraftingStationId.woodworkingBench]: Object.freeze({
60 stationId: CraftingStationId.woodworkingBench,
60 stationId: CraftingStationId.woodworkingBench,
61 displayName: "Woodworking bench",
61 displayName: "Woodworking bench",
62 skillId: SkillId.crafting,
62 skillId: SkillId.crafting,
63 description: "Shape logs into handles and assemble hafted tools."
63 description: "Shape logs into handles and other wood components."
64 }),
64 }),
65 [CraftingStationId.oven]: Object.freeze({
65 [CraftingStationId.oven]: Object.freeze({
66 stationId: CraftingStationId.oven,
66 stationId: CraftingStationId.oven,
shared/definitions/gathering.js +4 −0
@@ -43,6 +43,8 @@ export const ORE_ITEM_BY_MATERIAL = Object.freeze({
43 43 [GatherMaterialId.tin]: CraftingItemId.tinOre,
44 44 [GatherMaterialId.copper]: CraftingItemId.copperOre,
45 45 [MaterialTier.iron]: MetalItemId.ironOre,
46 [GatherMaterialId.silver]: MetalItemId.silverOre,
47 [GatherMaterialId.gold]: MetalItemId.goldOre,
46 48 [MaterialTier.mithril]: MetalItemId.mithrilOre,
47 49 [MaterialTier.adamantium]: MetalItemId.adamantiumOre,
48 50 [MaterialTier.orichalcum]: MetalItemId.orichalcumOre,
@@ -54,6 +56,8 @@ export const BAR_ITEM_BY_MATERIAL = Object.freeze({
54 56 [MaterialTier.bronze]: CraftingItemId.bronzeBar,
55 57 [MaterialTier.iron]: MetalItemId.ironBar,
56 58 [MaterialTier.steel]: MetalItemId.steelBar,
59 [GatherMaterialId.silver]: MetalItemId.silverBar,
60 [GatherMaterialId.gold]: MetalItemId.goldBar,
57 61 [MaterialTier.mithril]: MetalItemId.mithrilBar,
58 62 [MaterialTier.adamantium]: MetalItemId.adamantiumBar,
59 63 [MaterialTier.orichalcum]: MetalItemId.orichalcumBar,
@@ -43,6 +43,8 @@ export const ORE_ITEM_BY_MATERIAL = Object.freeze({
43 [GatherMaterialId.tin]: CraftingItemId.tinOre,
43 [GatherMaterialId.tin]: CraftingItemId.tinOre,
44 [GatherMaterialId.copper]: CraftingItemId.copperOre,
44 [GatherMaterialId.copper]: CraftingItemId.copperOre,
45 [MaterialTier.iron]: MetalItemId.ironOre,
45 [MaterialTier.iron]: MetalItemId.ironOre,
46 [GatherMaterialId.silver]: MetalItemId.silverOre,
47 [GatherMaterialId.gold]: MetalItemId.goldOre,
46 [MaterialTier.mithril]: MetalItemId.mithrilOre,
48 [MaterialTier.mithril]: MetalItemId.mithrilOre,
47 [MaterialTier.adamantium]: MetalItemId.adamantiumOre,
49 [MaterialTier.adamantium]: MetalItemId.adamantiumOre,
48 [MaterialTier.orichalcum]: MetalItemId.orichalcumOre,
50 [MaterialTier.orichalcum]: MetalItemId.orichalcumOre,
@@ -54,6 +56,8 @@ export const BAR_ITEM_BY_MATERIAL = Object.freeze({
54 [MaterialTier.bronze]: CraftingItemId.bronzeBar,
56 [MaterialTier.bronze]: CraftingItemId.bronzeBar,
55 [MaterialTier.iron]: MetalItemId.ironBar,
57 [MaterialTier.iron]: MetalItemId.ironBar,
56 [MaterialTier.steel]: MetalItemId.steelBar,
58 [MaterialTier.steel]: MetalItemId.steelBar,
59 [GatherMaterialId.silver]: MetalItemId.silverBar,
60 [GatherMaterialId.gold]: MetalItemId.goldBar,
57 [MaterialTier.mithril]: MetalItemId.mithrilBar,
61 [MaterialTier.mithril]: MetalItemId.mithrilBar,
58 [MaterialTier.adamantium]: MetalItemId.adamantiumBar,
62 [MaterialTier.adamantium]: MetalItemId.adamantiumBar,
59 [MaterialTier.orichalcum]: MetalItemId.orichalcumBar,
63 [MaterialTier.orichalcum]: MetalItemId.orichalcumBar,
shared/definitions/materialTiers.js +141 −25
@@ -50,14 +50,17 @@ export const WOOD_TIER_ORDER = Object.freeze([
50 50
51 51 /**
52 52 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
53 * Tin + copper smelt into bronze; coal fuels steel. Their mine/smelt timing
54 * uses {@link associatedBarTier}.
53 * Tin + copper smelt into bronze; coal fuels steel. Gold and silver have ore +
54 * bars but no tools (jewelry / future recipes). Mine/smelt timing uses
55 * {@link associatedBarTier}.
55 56 */
56 57 export const GatherMaterialId = Object.freeze({
57 58 ...MaterialTier,
58 59 tin: "tin",
59 60 copper: "copper",
60 coal: "coal"
61 coal: "coal",
62 silver: "silver",
63 gold: "gold"
61 64 });
62 65
63 66 /** Minimum relevant skill level required to equip tools/gear of this tier. */
@@ -69,6 +72,8 @@ export const TIER_MIN_SKILL_LEVEL = Object.freeze({
69 72 [MaterialTier.adamantium]: 50,
70 73 [MaterialTier.orichalcum]: 70,
71 74 [MaterialTier.dragon]: 90,
75 [GatherMaterialId.silver]: 10,
76 [GatherMaterialId.gold]: 20,
72 77 [WoodTier.pine]: 1,
73 78 [WoodTier.birch]: 10,
74 79 [WoodTier.oak]: 20,
@@ -87,6 +92,8 @@ export const TIER_RANK = Object.freeze({
87 92 [MaterialTier.adamantium]: 5,
88 93 [MaterialTier.orichalcum]: 6,
89 94 [MaterialTier.dragon]: 7,
95 [GatherMaterialId.silver]: 2,
96 [GatherMaterialId.gold]: 3,
90 97 [WoodTier.pine]: 1,
91 98 [WoodTier.birch]: 2,
92 99 [WoodTier.oak]: 3,
@@ -126,6 +133,8 @@ export const MATERIAL_DISPLAY_NAME = Object.freeze({
126 133 [GatherMaterialId.tin]: "Tin",
127 134 [GatherMaterialId.copper]: "Copper",
128 135 [GatherMaterialId.coal]: "Coal",
136 [GatherMaterialId.silver]: "Silver",
137 [GatherMaterialId.gold]: "Gold",
129 138 [WoodTier.pine]: "Pine",
130 139 [WoodTier.birch]: "Birch",
131 140 [WoodTier.oak]: "Oak",
@@ -136,29 +145,123 @@ export const MATERIAL_DISPLAY_NAME = Object.freeze({
136 145 });
137 146
138 147 /**
139 * Display tint colors (0–1 RGB) for magenta-tinted sprites.
140 * Steel is slightly darker than iron; orichalcum is coppery-gold; dragon is red.
148 * Author tint swatches via {@link rgb} (0–255) so editors can offer a colour picker.
149 * Also accepts `0xRRGGBB` / `"#RRGGBB"`; all forms become 0–1 RGB at module load.
150 * Steel is slightly darker than iron; silver is bright gray; gold is yellow;
151 * orichalcum is coppery; dragon is red.
141 152 */
142 export const MATERIAL_TINT_COLOR = Object.freeze({
143 [MaterialTier.bronze]: Object.freeze({ r: 0.72, g: 0.48, b: 0.28 }),
144 [MaterialTier.iron]: Object.freeze({ r: 0.62, g: 0.64, b: 0.68 }),
145 [MaterialTier.steel]: Object.freeze({ r: 0.48, g: 0.50, b: 0.54 }),
146 [MaterialTier.mithril]: Object.freeze({ r: 0.40, g: 0.55, b: 0.88 }),
147 [MaterialTier.adamantium]: Object.freeze({ r: 0.35, g: 0.75, b: 0.45 }),
148 [MaterialTier.orichalcum]: Object.freeze({ r: 0.90, g: 0.55, b: 0.22 }),
149 [MaterialTier.dragon]: Object.freeze({ r: 0.88, g: 0.18, b: 0.16 }),
150 [GatherMaterialId.tin]: Object.freeze({ r: 0.78, g: 0.80, b: 0.82 }),
151 [GatherMaterialId.copper]: Object.freeze({ r: 0.85, g: 0.45, b: 0.22 }),
152 [GatherMaterialId.coal]: Object.freeze({ r: 0.22, g: 0.22, b: 0.25 }),
153 [WoodTier.pine]: Object.freeze({ r: 0.78, g: 0.62, b: 0.38 }),
154 [WoodTier.birch]: Object.freeze({ r: 0.88, g: 0.82, b: 0.68 }),
155 [WoodTier.oak]: Object.freeze({ r: 0.62, g: 0.42, b: 0.24 }),
156 [WoodTier.ebony]: Object.freeze({ r: 0.22, g: 0.16, b: 0.20 }),
157 [WoodTier.lignum]: Object.freeze({ r: 0.42, g: 0.38, b: 0.22 }),
158 [WoodTier.heartwood]: Object.freeze({ r: 0.72, g: 0.28, b: 0.22 }),
159 [WoodTier.elder]: Object.freeze({ r: 0.72, g: 0.74, b: 0.78 })
153 export function rgb (r, g, b)
154 {
155 return Object.freeze({
156 r: clampByte(r) / 255,
157 g: clampByte(g) / 255,
158 b: clampByte(b) / 255
159 });
160 }
161
162 function clampByte (n)
163 {
164 return Math.min(255, Math.max(0, Math.round(Number(n) || 0)));
165 }
166
167 export const MATERIAL_TINT_HEX = Object.freeze({
168 [MaterialTier.bronze]: rgb(184, 122, 71),
169 [MaterialTier.iron]: rgb(158, 163, 173),
170 [MaterialTier.steel]: rgb(75, 76, 80),
171 [MaterialTier.mithril]: rgb(3, 120, 255),
172 [MaterialTier.adamantium]: rgb(37, 233, 86),
173 [MaterialTier.orichalcum]: rgb(230, 140, 31),
174 [MaterialTier.dragon]: rgb(228, 19, 15),
175 [GatherMaterialId.tin]: rgb(221, 221, 221),
176 [GatherMaterialId.copper]: rgb(255, 94, 0),
177 [GatherMaterialId.coal]: rgb(23, 23, 24),
178 [GatherMaterialId.silver]: rgb(214, 220, 230),
179 [GatherMaterialId.gold]: rgb(255, 200, 0),
180 [WoodTier.pine]: rgb(199, 158, 97),
181 [WoodTier.birch]: rgb(224, 209, 173),
182 [WoodTier.oak]: rgb(158, 107, 61),
183 [WoodTier.ebony]: rgb(56, 41, 51),
184 [WoodTier.lignum]: rgb(107, 97, 56),
185 [WoodTier.heartwood]: rgb(184, 71, 56),
186 [WoodTier.elder]: rgb(184, 189, 199)
187 });
188
189 /**
190 * Optional ore-only tint overrides (boulders + ore items).
191 * Missing entries fall back to {@link MATERIAL_TINT_HEX}.
192 */
193 export const MATERIAL_ORE_TINT_HEX = Object.freeze({
194 [MaterialTier.iron]: rgb(210, 118, 48),
195 [GatherMaterialId.copper]: rgb(1, 128, 58)
160 196 });
161 197
198 /**
199 * Normalize tint authoring forms to frozen 0–1 `{ r, g, b }`:
200 * - number `0xRRGGBB`
201 * - string `"#RGB"` / `"#RRGGBB"` / `"rgb(r,g,b)"`
202 * - object from {@link rgb}
203 */
204 export function hexToRgb01 (hex)
205 {
206 if (hex && typeof hex === "object" && "r" in hex && "g" in hex && "b" in hex)
207 {
208 return Object.freeze({
209 r: clamp01Channel(hex.r),
210 g: clamp01Channel(hex.g),
211 b: clamp01Channel(hex.b)
212 });
213 }
214 if (typeof hex === "number" && Number.isFinite(hex))
215 {
216 const value = hex >>> 0;
217 return Object.freeze({
218 r: ((value >> 16) & 255) / 255,
219 g: ((value >> 8) & 255) / 255,
220 b: (value & 255) / 255
221 });
222 }
223 const text = String(hex ?? "").trim();
224 const rgbMatch = /^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i.exec(text);
225 if (rgbMatch)
226 { return rgb(rgbMatch[1], rgbMatch[2], rgbMatch[3]); }
227 const raw = text.replace(/^#/, "");
228 const full = raw.length === 3
229 ? raw.split("").map((ch) => ch + ch).join("")
230 : raw;
231 if (!/^[0-9a-fA-F]{6}$/.test(full))
232 { return Object.freeze({ r: 0.7, g: 0.7, b: 0.7 }); }
233 const value = Number.parseInt(full, 16);
234 return Object.freeze({
235 r: ((value >> 16) & 255) / 255,
236 g: ((value >> 8) & 255) / 255,
237 b: (value & 255) / 255
238 });
239 }
240
241 function clamp01Channel (n)
242 {
243 const value = Number(n);
244 if (!Number.isFinite(value))
245 { return 0; }
246 if (value > 1)
247 { return clampByte(value) / 255; }
248 return Math.min(1, Math.max(0, value));
249 }
250
251 /** 0–1 RGB map derived from {@link MATERIAL_TINT_HEX}. */
252 export const MATERIAL_TINT_COLOR = Object.freeze(
253 Object.fromEntries(
254 Object.entries(MATERIAL_TINT_HEX).map(([id, hex]) => [id, hexToRgb01(hex)])
255 )
256 );
257
258 /** 0–1 RGB map derived from {@link MATERIAL_ORE_TINT_HEX}. */
259 export const MATERIAL_ORE_TINT_COLOR = Object.freeze(
260 Object.fromEntries(
261 Object.entries(MATERIAL_ORE_TINT_HEX).map(([id, hex]) => [id, hexToRgb01(hex)])
262 )
263 );
264
162 265 /** Wood tier that matches a metal tier's rank (for tool hafts). */
163 266 export const WOOD_TIER_FOR_METAL = Object.freeze({
164 267 [MaterialTier.bronze]: WoodTier.pine,
@@ -176,7 +279,7 @@ export const METAL_TIER_FOR_WOOD = Object.freeze(Object.fromEntries(
176 279
177 280 /**
178 281 * Bar tier that drives mine/smelt duration and gates for a gatherable.
179 * Tin/copper → bronze; coal → steel; other metals map to themselves.
282 * Tin/copper → bronze; coal → steel; gold/silver and gear metals map to themselves.
180 283 */
181 284 export function associatedBarTier (materialId)
182 285 {
@@ -192,8 +295,18 @@ export function materialDisplayName (materialId)
192 295 return MATERIAL_DISPLAY_NAME[materialId] ?? materialId;
193 296 }
194 297
195 export function materialTintColor (materialId)
298 /**
299 * Tint for a material. When `ore` is true, prefer {@link MATERIAL_ORE_TINT_COLOR}
300 * if defined for that material; otherwise the normal material tint.
301 */
302 export function materialTintColor (materialId, { ore = false } = {})
196 303 {
304 if (ore)
305 {
306 const oreTint = MATERIAL_ORE_TINT_COLOR[materialId];
307 if (oreTint)
308 { return oreTint; }
309 }
197 310 return MATERIAL_TINT_COLOR[materialId] ?? MATERIAL_TINT_COLOR[MaterialTier.bronze];
198 311 }
199 312
@@ -277,11 +390,14 @@ export const EXHAUSTED_ORE_BOULDER_STATE = "boulder";
277 390 /**
278 391 * Materials that have an ore boulder node.
279 392 * Bronze has no ore (tin + copper); steel has no ore (iron + coal).
393 * Gold and silver are precious only (ore + bars, no tools).
280 394 */
281 395 export const ORE_BEARING_MATERIALS = Object.freeze([
282 396 GatherMaterialId.tin,
283 397 GatherMaterialId.copper,
284 398 MaterialTier.iron,
399 GatherMaterialId.silver,
400 GatherMaterialId.gold,
285 401 MaterialTier.mithril,
286 402 MaterialTier.adamantium,
287 403 MaterialTier.orichalcum,
@@ -50,14 +50,17 @@ export const WOOD_TIER_ORDER = Object.freeze([
50
50
51/**
51/**
52 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
52 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
53 * Tin + copper smelt into bronze; coal fuels steel. Their mine/smelt timing
53 * Tin + copper smelt into bronze; coal fuels steel. Gold and silver have ore +
54 * uses {@link associatedBarTier}.
54 * bars but no tools (jewelry / future recipes). Mine/smelt timing uses
55 * {@link associatedBarTier}.
55 */
56 */
56export const GatherMaterialId = Object.freeze({
57export const GatherMaterialId = Object.freeze({
57 ...MaterialTier,
58 ...MaterialTier,
58 tin: "tin",
59 tin: "tin",
59 copper: "copper",
60 copper: "copper",
60 coal: "coal"
61 coal: "coal",
62 silver: "silver",
63 gold: "gold"
61});
64});
62
65
63/** Minimum relevant skill level required to equip tools/gear of this tier. */
66/** Minimum relevant skill level required to equip tools/gear of this tier. */
@@ -69,6 +72,8 @@ export const TIER_MIN_SKILL_LEVEL = Object.freeze({
69 [MaterialTier.adamantium]: 50,
72 [MaterialTier.adamantium]: 50,
70 [MaterialTier.orichalcum]: 70,
73 [MaterialTier.orichalcum]: 70,
71 [MaterialTier.dragon]: 90,
74 [MaterialTier.dragon]: 90,
75 [GatherMaterialId.silver]: 10,
76 [GatherMaterialId.gold]: 20,
72 [WoodTier.pine]: 1,
77 [WoodTier.pine]: 1,
73 [WoodTier.birch]: 10,
78 [WoodTier.birch]: 10,
74 [WoodTier.oak]: 20,
79 [WoodTier.oak]: 20,
@@ -87,6 +92,8 @@ export const TIER_RANK = Object.freeze({
87 [MaterialTier.adamantium]: 5,
92 [MaterialTier.adamantium]: 5,
88 [MaterialTier.orichalcum]: 6,
93 [MaterialTier.orichalcum]: 6,
89 [MaterialTier.dragon]: 7,
94 [MaterialTier.dragon]: 7,
95 [GatherMaterialId.silver]: 2,
96 [GatherMaterialId.gold]: 3,
90 [WoodTier.pine]: 1,
97 [WoodTier.pine]: 1,
91 [WoodTier.birch]: 2,
98 [WoodTier.birch]: 2,
92 [WoodTier.oak]: 3,
99 [WoodTier.oak]: 3,
@@ -126,6 +133,8 @@ export const MATERIAL_DISPLAY_NAME = Object.freeze({
126 [GatherMaterialId.tin]: "Tin",
133 [GatherMaterialId.tin]: "Tin",
127 [GatherMaterialId.copper]: "Copper",
134 [GatherMaterialId.copper]: "Copper",
128 [GatherMaterialId.coal]: "Coal",
135 [GatherMaterialId.coal]: "Coal",
136 [GatherMaterialId.silver]: "Silver",
137 [GatherMaterialId.gold]: "Gold",
129 [WoodTier.pine]: "Pine",
138 [WoodTier.pine]: "Pine",
130 [WoodTier.birch]: "Birch",
139 [WoodTier.birch]: "Birch",
131 [WoodTier.oak]: "Oak",
140 [WoodTier.oak]: "Oak",
@@ -136,29 +145,123 @@ export const MATERIAL_DISPLAY_NAME = Object.freeze({
136});
145});
137
146
138/**
147/**
139 * Display tint colors (0–1 RGB) for magenta-tinted sprites.
148 * Author tint swatches via {@link rgb} (0–255) so editors can offer a colour picker.
140 * Steel is slightly darker than iron; orichalcum is coppery-gold; dragon is red.
149 * Also accepts `0xRRGGBB` / `"#RRGGBB"`; all forms become 0–1 RGB at module load.
150 * Steel is slightly darker than iron; silver is bright gray; gold is yellow;
151 * orichalcum is coppery; dragon is red.
141 */
152 */
142export const MATERIAL_TINT_COLOR = Object.freeze({
153export function rgb (r, g, b)
143 [MaterialTier.bronze]: Object.freeze({ r: 0.72, g: 0.48, b: 0.28 }),
154{
144 [MaterialTier.iron]: Object.freeze({ r: 0.62, g: 0.64, b: 0.68 }),
155 return Object.freeze({
145 [MaterialTier.steel]: Object.freeze({ r: 0.48, g: 0.50, b: 0.54 }),
156 r: clampByte(r) / 255,
146 [MaterialTier.mithril]: Object.freeze({ r: 0.40, g: 0.55, b: 0.88 }),
157 g: clampByte(g) / 255,
147 [MaterialTier.adamantium]: Object.freeze({ r: 0.35, g: 0.75, b: 0.45 }),
158 b: clampByte(b) / 255
148 [MaterialTier.orichalcum]: Object.freeze({ r: 0.90, g: 0.55, b: 0.22 }),
159 });
149 [MaterialTier.dragon]: Object.freeze({ r: 0.88, g: 0.18, b: 0.16 }),
160}
150 [GatherMaterialId.tin]: Object.freeze({ r: 0.78, g: 0.80, b: 0.82 }),
161
151 [GatherMaterialId.copper]: Object.freeze({ r: 0.85, g: 0.45, b: 0.22 }),
162function clampByte (n)
152 [GatherMaterialId.coal]: Object.freeze({ r: 0.22, g: 0.22, b: 0.25 }),
163{
153 [WoodTier.pine]: Object.freeze({ r: 0.78, g: 0.62, b: 0.38 }),
164 return Math.min(255, Math.max(0, Math.round(Number(n) || 0)));
154 [WoodTier.birch]: Object.freeze({ r: 0.88, g: 0.82, b: 0.68 }),
165}
155 [WoodTier.oak]: Object.freeze({ r: 0.62, g: 0.42, b: 0.24 }),
166
156 [WoodTier.ebony]: Object.freeze({ r: 0.22, g: 0.16, b: 0.20 }),
167export const MATERIAL_TINT_HEX = Object.freeze({
157 [WoodTier.lignum]: Object.freeze({ r: 0.42, g: 0.38, b: 0.22 }),
168 [MaterialTier.bronze]: rgb(184, 122, 71),
158 [WoodTier.heartwood]: Object.freeze({ r: 0.72, g: 0.28, b: 0.22 }),
169 [MaterialTier.iron]: rgb(158, 163, 173),
159 [WoodTier.elder]: Object.freeze({ r: 0.72, g: 0.74, b: 0.78 })
170 [MaterialTier.steel]: rgb(75, 76, 80),
171 [MaterialTier.mithril]: rgb(3, 120, 255),
172 [MaterialTier.adamantium]: rgb(37, 233, 86),
173 [MaterialTier.orichalcum]: rgb(230, 140, 31),
174 [MaterialTier.dragon]: rgb(228, 19, 15),
175 [GatherMaterialId.tin]: rgb(221, 221, 221),
176 [GatherMaterialId.copper]: rgb(255, 94, 0),
177 [GatherMaterialId.coal]: rgb(23, 23, 24),
178 [GatherMaterialId.silver]: rgb(214, 220, 230),
179 [GatherMaterialId.gold]: rgb(255, 200, 0),
180 [WoodTier.pine]: rgb(199, 158, 97),
181 [WoodTier.birch]: rgb(224, 209, 173),
182 [WoodTier.oak]: rgb(158, 107, 61),
183 [WoodTier.ebony]: rgb(56, 41, 51),
184 [WoodTier.lignum]: rgb(107, 97, 56),
185 [WoodTier.heartwood]: rgb(184, 71, 56),
186 [WoodTier.elder]: rgb(184, 189, 199)
187});
188
189/**
190 * Optional ore-only tint overrides (boulders + ore items).
191 * Missing entries fall back to {@link MATERIAL_TINT_HEX}.
192 */
193export const MATERIAL_ORE_TINT_HEX = Object.freeze({
194 [MaterialTier.iron]: rgb(210, 118, 48),
195 [GatherMaterialId.copper]: rgb(1, 128, 58)
160});
196});
161
197
198/**
199 * Normalize tint authoring forms to frozen 0–1 `{ r, g, b }`:
200 * - number `0xRRGGBB`
201 * - string `"#RGB"` / `"#RRGGBB"` / `"rgb(r,g,b)"`
202 * - object from {@link rgb}
203 */
204export function hexToRgb01 (hex)
205{
206 if (hex && typeof hex === "object" && "r" in hex && "g" in hex && "b" in hex)
207 {
208 return Object.freeze({
209 r: clamp01Channel(hex.r),
210 g: clamp01Channel(hex.g),
211 b: clamp01Channel(hex.b)
212 });
213 }
214 if (typeof hex === "number" && Number.isFinite(hex))
215 {
216 const value = hex >>> 0;
217 return Object.freeze({
218 r: ((value >> 16) & 255) / 255,
219 g: ((value >> 8) & 255) / 255,
220 b: (value & 255) / 255
221 });
222 }
223 const text = String(hex ?? "").trim();
224 const rgbMatch = /^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i.exec(text);
225 if (rgbMatch)
226 { return rgb(rgbMatch[1], rgbMatch[2], rgbMatch[3]); }
227 const raw = text.replace(/^#/, "");
228 const full = raw.length === 3
229 ? raw.split("").map((ch) => ch + ch).join("")
230 : raw;
231 if (!/^[0-9a-fA-F]{6}$/.test(full))
232 { return Object.freeze({ r: 0.7, g: 0.7, b: 0.7 }); }
233 const value = Number.parseInt(full, 16);
234 return Object.freeze({
235 r: ((value >> 16) & 255) / 255,
236 g: ((value >> 8) & 255) / 255,
237 b: (value & 255) / 255
238 });
239}
240
241function clamp01Channel (n)
242{
243 const value = Number(n);
244 if (!Number.isFinite(value))
245 { return 0; }
246 if (value > 1)
247 { return clampByte(value) / 255; }
248 return Math.min(1, Math.max(0, value));
249}
250
251/** 0–1 RGB map derived from {@link MATERIAL_TINT_HEX}. */
252export const MATERIAL_TINT_COLOR = Object.freeze(
253 Object.fromEntries(
254 Object.entries(MATERIAL_TINT_HEX).map(([id, hex]) => [id, hexToRgb01(hex)])
255 )
256);
257
258/** 0–1 RGB map derived from {@link MATERIAL_ORE_TINT_HEX}. */
259export const MATERIAL_ORE_TINT_COLOR = Object.freeze(
260 Object.fromEntries(
261 Object.entries(MATERIAL_ORE_TINT_HEX).map(([id, hex]) => [id, hexToRgb01(hex)])
262 )
263);
264
162/** Wood tier that matches a metal tier's rank (for tool hafts). */
265/** Wood tier that matches a metal tier's rank (for tool hafts). */
163export const WOOD_TIER_FOR_METAL = Object.freeze({
266export const WOOD_TIER_FOR_METAL = Object.freeze({
164 [MaterialTier.bronze]: WoodTier.pine,
267 [MaterialTier.bronze]: WoodTier.pine,
@@ -176,7 +279,7 @@ export const METAL_TIER_FOR_WOOD = Object.freeze(Object.fromEntries(
176
279
177/**
280/**
178 * Bar tier that drives mine/smelt duration and gates for a gatherable.
281 * Bar tier that drives mine/smelt duration and gates for a gatherable.
179 * Tin/copper → bronze; coal → steel; other metals map to themselves.
282 * Tin/copper → bronze; coal → steel; gold/silver and gear metals map to themselves.
180 */
283 */
181export function associatedBarTier (materialId)
284export function associatedBarTier (materialId)
182{
285{
@@ -192,8 +295,18 @@ export function materialDisplayName (materialId)
192 return MATERIAL_DISPLAY_NAME[materialId] ?? materialId;
295 return MATERIAL_DISPLAY_NAME[materialId] ?? materialId;
193}
296}
194
297
195export function materialTintColor (materialId)
298/**
299 * Tint for a material. When `ore` is true, prefer {@link MATERIAL_ORE_TINT_COLOR}
300 * if defined for that material; otherwise the normal material tint.
301 */
302export function materialTintColor (materialId, { ore = false } = {})
196{
303{
304 if (ore)
305 {
306 const oreTint = MATERIAL_ORE_TINT_COLOR[materialId];
307 if (oreTint)
308 { return oreTint; }
309 }
197 return MATERIAL_TINT_COLOR[materialId] ?? MATERIAL_TINT_COLOR[MaterialTier.bronze];
310 return MATERIAL_TINT_COLOR[materialId] ?? MATERIAL_TINT_COLOR[MaterialTier.bronze];
198}
311}
199
312
@@ -277,11 +390,14 @@ export const EXHAUSTED_ORE_BOULDER_STATE = "boulder";
277/**
390/**
278 * Materials that have an ore boulder node.
391 * Materials that have an ore boulder node.
279 * Bronze has no ore (tin + copper); steel has no ore (iron + coal).
392 * Bronze has no ore (tin + copper); steel has no ore (iron + coal).
393 * Gold and silver are precious only (ore + bars, no tools).
280 */
394 */
281export const ORE_BEARING_MATERIALS = Object.freeze([
395export const ORE_BEARING_MATERIALS = Object.freeze([
282 GatherMaterialId.tin,
396 GatherMaterialId.tin,
283 GatherMaterialId.copper,
397 GatherMaterialId.copper,
284 MaterialTier.iron,
398 MaterialTier.iron,
399 GatherMaterialId.silver,
400 GatherMaterialId.gold,
285 MaterialTier.mithril,
401 MaterialTier.mithril,
286 MaterialTier.adamantium,
402 MaterialTier.adamantium,
287 MaterialTier.orichalcum,
403 MaterialTier.orichalcum,
shared/definitions/metalItems.js +109 −6
@@ -7,8 +7,9 @@ import {
7 7 import { EquipmentKind } from "./equipmentKinds.js";
8 8
9 9 /**
10 * Metal ores, bars, pickaxes, and coal.
11 * Shared magenta base sprites under items/metal: states ore / bar; pickaxes stay in items/pickaxe.
10 * Metal ores, bars, pickaxes/axes, and coal.
11 * Shared magenta base sprites under items/metal: states ore / bar;
12 * pickaxes in items/pickaxe; axes in items/axe.
12 13 */
13 14 export const MetalItemId = Object.freeze({
14 15 coal: 35,
@@ -29,13 +30,30 @@ export const MetalItemId = Object.freeze({
29 30 dragonOre: 50,
30 31 dragonBar: 51,
31 32 dragonPickaxe: 52,
33 goldOre: 74,
34 goldBar: 75,
35 silverOre: 76,
36 silverBar: 77,
32 37 bronzePickaxeHead: 67,
33 38 ironPickaxeHead: 68,
34 39 steelPickaxeHead: 69,
35 40 mithrilPickaxeHead: 70,
36 41 adamantiumPickaxeHead: 71,
37 42 orichalcumPickaxeHead: 72,
38 dragonPickaxeHead: 73
43 dragonPickaxeHead: 73,
44 bronzeAxeHead: 78,
45 ironAxeHead: 79,
46 steelAxeHead: 80,
47 mithrilAxeHead: 81,
48 adamantiumAxeHead: 82,
49 orichalcumAxeHead: 83,
50 dragonAxeHead: 84,
51 ironAxe: 85,
52 steelAxe: 86,
53 mithrilAxe: 87,
54 adamantiumAxe: 88,
55 orichalcumAxe: 89,
56 dragonAxe: 90
39 57 });
40 58
41 59 const DEFAULT_STACK = 99;
@@ -87,14 +105,14 @@ function pickaxeHeadDef (itemId, tier, key)
87 105 itemId,
88 106 key,
89 107 displayName: `${name} pickaxe head`,
90 description: `Smithed ${name.toLowerCase()} head. Attach a matching handle at a woodworking bench.`,
108 description: `Smithed ${name.toLowerCase()} head. Attach a matching handle at a crafting bench.`,
91 109 seedValue: 5,
92 110 stackable: true,
93 111 maxStackSize: DEFAULT_STACK,
94 112 uniqueInstance: false,
95 113 category: ItemCategory.intermediate,
96 114 iconKey: "pickaxe",
97 defaultState: "pickaxe",
115 defaultState: "pickaxe-head",
98 116 tier,
99 117 tintFromTier: true
100 118 });
@@ -124,6 +142,50 @@ function pickaxeDef (itemId, tier, key)
124 142 });
125 143 }
126 144
145 function axeHeadDef (itemId, tier, key)
146 {
147 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
148 return Object.freeze({
149 itemId,
150 key,
151 displayName: `${name} axe head`,
152 description: `Smithed ${name.toLowerCase()} head. Attach a matching handle at a crafting bench.`,
153 seedValue: 5,
154 stackable: true,
155 maxStackSize: DEFAULT_STACK,
156 uniqueInstance: false,
157 category: ItemCategory.intermediate,
158 iconKey: "axe",
159 defaultState: "axe-head",
160 tier,
161 tintFromTier: true
162 });
163 }
164
165 function axeDef (itemId, tier, key)
166 {
167 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
168 return Object.freeze({
169 itemId,
170 key,
171 displayName: `${name} axe`,
172 description: `Woodcutting tool (${name}).`,
173 seedValue: 8,
174 stackable: false,
175 maxStackSize: 1,
176 uniqueInstance: false,
177 category: ItemCategory.tool,
178 iconKey: "axe",
179 defaultState: "axe",
180 tintFromTier: true,
181 equipment: Object.freeze({
182 slot: "weapon",
183 tier,
184 kind: EquipmentKind.axeTool
185 })
186 });
187 }
188
127 189 /** Full defs for metal family (merged into ITEM_DEFINITIONS). */
128 190 export const METAL_ITEM_DEFINITIONS = Object.freeze({
129 191 [MetalItemId.coal]: Object.freeze({
@@ -146,29 +208,50 @@ export const METAL_ITEM_DEFINITIONS = Object.freeze({
146 208 MaterialTier.bronze,
147 209 "bronze-pickaxe-head"
148 210 ),
211 [MetalItemId.bronzeAxeHead]: axeHeadDef(
212 MetalItemId.bronzeAxeHead,
213 MaterialTier.bronze,
214 "bronze-axe-head"
215 ),
149 216 [MetalItemId.ironOre]: oreDef(MetalItemId.ironOre, MaterialTier.iron, "iron-ore"),
150 217 [MetalItemId.ironBar]: barDef(MetalItemId.ironBar, MaterialTier.iron, "iron-bar"),
151 218 [MetalItemId.ironPickaxe]: pickaxeDef(MetalItemId.ironPickaxe, MaterialTier.iron, "iron-pickaxe"),
152 219 [MetalItemId.ironPickaxeHead]: pickaxeHeadDef(MetalItemId.ironPickaxeHead, MaterialTier.iron, "iron-pickaxe-head"),
220 [MetalItemId.ironAxe]: axeDef(MetalItemId.ironAxe, MaterialTier.iron, "iron-axe"),
221 [MetalItemId.ironAxeHead]: axeHeadDef(MetalItemId.ironAxeHead, MaterialTier.iron, "iron-axe-head"),
222 [MetalItemId.goldOre]: oreDef(MetalItemId.goldOre, GatherMaterialId.gold, "gold-ore"),
223 [MetalItemId.goldBar]: barDef(MetalItemId.goldBar, GatherMaterialId.gold, "gold-bar"),
224 [MetalItemId.silverOre]: oreDef(MetalItemId.silverOre, GatherMaterialId.silver, "silver-ore"),
225 [MetalItemId.silverBar]: barDef(MetalItemId.silverBar, GatherMaterialId.silver, "silver-bar"),
153 226 [MetalItemId.steelBar]: barDef(MetalItemId.steelBar, MaterialTier.steel, "steel-bar"),
154 227 [MetalItemId.steelPickaxe]: pickaxeDef(MetalItemId.steelPickaxe, MaterialTier.steel, "steel-pickaxe"),
155 228 [MetalItemId.steelPickaxeHead]: pickaxeHeadDef(MetalItemId.steelPickaxeHead, MaterialTier.steel, "steel-pickaxe-head"),
229 [MetalItemId.steelAxe]: axeDef(MetalItemId.steelAxe, MaterialTier.steel, "steel-axe"),
230 [MetalItemId.steelAxeHead]: axeHeadDef(MetalItemId.steelAxeHead, MaterialTier.steel, "steel-axe-head"),
156 231 [MetalItemId.mithrilOre]: oreDef(MetalItemId.mithrilOre, MaterialTier.mithril, "mithril-ore"),
157 232 [MetalItemId.mithrilBar]: barDef(MetalItemId.mithrilBar, MaterialTier.mithril, "mithril-bar"),
158 233 [MetalItemId.mithrilPickaxe]: pickaxeDef(MetalItemId.mithrilPickaxe, MaterialTier.mithril, "mithril-pickaxe"),
159 234 [MetalItemId.mithrilPickaxeHead]: pickaxeHeadDef(MetalItemId.mithrilPickaxeHead, MaterialTier.mithril, "mithril-pickaxe-head"),
235 [MetalItemId.mithrilAxe]: axeDef(MetalItemId.mithrilAxe, MaterialTier.mithril, "mithril-axe"),
236 [MetalItemId.mithrilAxeHead]: axeHeadDef(MetalItemId.mithrilAxeHead, MaterialTier.mithril, "mithril-axe-head"),
160 237 [MetalItemId.adamantiumOre]: oreDef(MetalItemId.adamantiumOre, MaterialTier.adamantium, "adamantium-ore"),
161 238 [MetalItemId.adamantiumBar]: barDef(MetalItemId.adamantiumBar, MaterialTier.adamantium, "adamantium-bar"),
162 239 [MetalItemId.adamantiumPickaxe]: pickaxeDef(MetalItemId.adamantiumPickaxe, MaterialTier.adamantium, "adamantium-pickaxe"),
163 240 [MetalItemId.adamantiumPickaxeHead]: pickaxeHeadDef(MetalItemId.adamantiumPickaxeHead, MaterialTier.adamantium, "adamantium-pickaxe-head"),
241 [MetalItemId.adamantiumAxe]: axeDef(MetalItemId.adamantiumAxe, MaterialTier.adamantium, "adamantium-axe"),
242 [MetalItemId.adamantiumAxeHead]: axeHeadDef(MetalItemId.adamantiumAxeHead, MaterialTier.adamantium, "adamantium-axe-head"),
164 243 [MetalItemId.orichalcumOre]: oreDef(MetalItemId.orichalcumOre, MaterialTier.orichalcum, "orichalcum-ore"),
165 244 [MetalItemId.orichalcumBar]: barDef(MetalItemId.orichalcumBar, MaterialTier.orichalcum, "orichalcum-bar"),
166 245 [MetalItemId.orichalcumPickaxe]: pickaxeDef(MetalItemId.orichalcumPickaxe, MaterialTier.orichalcum, "orichalcum-pickaxe"),
167 246 [MetalItemId.orichalcumPickaxeHead]: pickaxeHeadDef(MetalItemId.orichalcumPickaxeHead, MaterialTier.orichalcum, "orichalcum-pickaxe-head"),
247 [MetalItemId.orichalcumAxe]: axeDef(MetalItemId.orichalcumAxe, MaterialTier.orichalcum, "orichalcum-axe"),
248 [MetalItemId.orichalcumAxeHead]: axeHeadDef(MetalItemId.orichalcumAxeHead, MaterialTier.orichalcum, "orichalcum-axe-head"),
168 249 [MetalItemId.dragonOre]: oreDef(MetalItemId.dragonOre, MaterialTier.dragon, "dragon-ore"),
169 250 [MetalItemId.dragonBar]: barDef(MetalItemId.dragonBar, MaterialTier.dragon, "dragon-bar"),
170 251 [MetalItemId.dragonPickaxe]: pickaxeDef(MetalItemId.dragonPickaxe, MaterialTier.dragon, "dragon-pickaxe"),
171 [MetalItemId.dragonPickaxeHead]: pickaxeHeadDef(MetalItemId.dragonPickaxeHead, MaterialTier.dragon, "dragon-pickaxe-head")
252 [MetalItemId.dragonPickaxeHead]: pickaxeHeadDef(MetalItemId.dragonPickaxeHead, MaterialTier.dragon, "dragon-pickaxe-head"),
253 [MetalItemId.dragonAxe]: axeDef(MetalItemId.dragonAxe, MaterialTier.dragon, "dragon-axe"),
254 [MetalItemId.dragonAxeHead]: axeHeadDef(MetalItemId.dragonAxeHead, MaterialTier.dragon, "dragon-axe-head")
172 255 });
173 256
174 257 /** Pickaxe head item id by metal tier. */
@@ -190,3 +273,23 @@ export const PICKAXE_ITEM_BY_METAL = Object.freeze({
190 273 [MaterialTier.orichalcum]: MetalItemId.orichalcumPickaxe,
191 274 [MaterialTier.dragon]: MetalItemId.dragonPickaxe
192 275 });
276
277 /** Axe head item id by metal tier. */
278 export const AXE_HEAD_ITEM_BY_METAL = Object.freeze({
279 [MaterialTier.bronze]: MetalItemId.bronzeAxeHead,
280 [MaterialTier.iron]: MetalItemId.ironAxeHead,
281 [MaterialTier.steel]: MetalItemId.steelAxeHead,
282 [MaterialTier.mithril]: MetalItemId.mithrilAxeHead,
283 [MaterialTier.adamantium]: MetalItemId.adamantiumAxeHead,
284 [MaterialTier.orichalcum]: MetalItemId.orichalcumAxeHead,
285 [MaterialTier.dragon]: MetalItemId.dragonAxeHead
286 });
287
288 export const AXE_ITEM_BY_METAL = Object.freeze({
289 [MaterialTier.iron]: MetalItemId.ironAxe,
290 [MaterialTier.steel]: MetalItemId.steelAxe,
291 [MaterialTier.mithril]: MetalItemId.mithrilAxe,
292 [MaterialTier.adamantium]: MetalItemId.adamantiumAxe,
293 [MaterialTier.orichalcum]: MetalItemId.orichalcumAxe,
294 [MaterialTier.dragon]: MetalItemId.dragonAxe
295 });
@@ -7,8 +7,9 @@ import {
7import { EquipmentKind } from "./equipmentKinds.js";
7import { EquipmentKind } from "./equipmentKinds.js";
8
8
9/**
9/**
10 * Metal ores, bars, pickaxes, and coal.
10 * Metal ores, bars, pickaxes/axes, and coal.
11 * Shared magenta base sprites under items/metal: states ore / bar; pickaxes stay in items/pickaxe.
11 * Shared magenta base sprites under items/metal: states ore / bar;
12 * pickaxes in items/pickaxe; axes in items/axe.
12 */
13 */
13export const MetalItemId = Object.freeze({
14export const MetalItemId = Object.freeze({
14 coal: 35,
15 coal: 35,
@@ -29,13 +30,30 @@ export const MetalItemId = Object.freeze({
29 dragonOre: 50,
30 dragonOre: 50,
30 dragonBar: 51,
31 dragonBar: 51,
31 dragonPickaxe: 52,
32 dragonPickaxe: 52,
33 goldOre: 74,
34 goldBar: 75,
35 silverOre: 76,
36 silverBar: 77,
32 bronzePickaxeHead: 67,
37 bronzePickaxeHead: 67,
33 ironPickaxeHead: 68,
38 ironPickaxeHead: 68,
34 steelPickaxeHead: 69,
39 steelPickaxeHead: 69,
35 mithrilPickaxeHead: 70,
40 mithrilPickaxeHead: 70,
36 adamantiumPickaxeHead: 71,
41 adamantiumPickaxeHead: 71,
37 orichalcumPickaxeHead: 72,
42 orichalcumPickaxeHead: 72,
38 dragonPickaxeHead: 73
43 dragonPickaxeHead: 73,
44 bronzeAxeHead: 78,
45 ironAxeHead: 79,
46 steelAxeHead: 80,
47 mithrilAxeHead: 81,
48 adamantiumAxeHead: 82,
49 orichalcumAxeHead: 83,
50 dragonAxeHead: 84,
51 ironAxe: 85,
52 steelAxe: 86,
53 mithrilAxe: 87,
54 adamantiumAxe: 88,
55 orichalcumAxe: 89,
56 dragonAxe: 90
39});
57});
40
58
41const DEFAULT_STACK = 99;
59const DEFAULT_STACK = 99;
@@ -87,14 +105,14 @@ function pickaxeHeadDef (itemId, tier, key)
87 itemId,
105 itemId,
88 key,
106 key,
89 displayName: `${name} pickaxe head`,
107 displayName: `${name} pickaxe head`,
90 description: `Smithed ${name.toLowerCase()} head. Attach a matching handle at a woodworking bench.`,
108 description: `Smithed ${name.toLowerCase()} head. Attach a matching handle at a crafting bench.`,
91 seedValue: 5,
109 seedValue: 5,
92 stackable: true,
110 stackable: true,
93 maxStackSize: DEFAULT_STACK,
111 maxStackSize: DEFAULT_STACK,
94 uniqueInstance: false,
112 uniqueInstance: false,
95 category: ItemCategory.intermediate,
113 category: ItemCategory.intermediate,
96 iconKey: "pickaxe",
114 iconKey: "pickaxe",
97 defaultState: "pickaxe",
115 defaultState: "pickaxe-head",
98 tier,
116 tier,
99 tintFromTier: true
117 tintFromTier: true
100 });
118 });
@@ -124,6 +142,50 @@ function pickaxeDef (itemId, tier, key)
124 });
142 });
125}
143}
126
144
145function axeHeadDef (itemId, tier, key)
146{
147 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
148 return Object.freeze({
149 itemId,
150 key,
151 displayName: `${name} axe head`,
152 description: `Smithed ${name.toLowerCase()} head. Attach a matching handle at a crafting bench.`,
153 seedValue: 5,
154 stackable: true,
155 maxStackSize: DEFAULT_STACK,
156 uniqueInstance: false,
157 category: ItemCategory.intermediate,
158 iconKey: "axe",
159 defaultState: "axe-head",
160 tier,
161 tintFromTier: true
162 });
163}
164
165function axeDef (itemId, tier, key)
166{
167 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
168 return Object.freeze({
169 itemId,
170 key,
171 displayName: `${name} axe`,
172 description: `Woodcutting tool (${name}).`,
173 seedValue: 8,
174 stackable: false,
175 maxStackSize: 1,
176 uniqueInstance: false,
177 category: ItemCategory.tool,
178 iconKey: "axe",
179 defaultState: "axe",
180 tintFromTier: true,
181 equipment: Object.freeze({
182 slot: "weapon",
183 tier,
184 kind: EquipmentKind.axeTool
185 })
186 });
187}
188
127/** Full defs for metal family (merged into ITEM_DEFINITIONS). */
189/** Full defs for metal family (merged into ITEM_DEFINITIONS). */
128export const METAL_ITEM_DEFINITIONS = Object.freeze({
190export const METAL_ITEM_DEFINITIONS = Object.freeze({
129 [MetalItemId.coal]: Object.freeze({
191 [MetalItemId.coal]: Object.freeze({
@@ -146,29 +208,50 @@ export const METAL_ITEM_DEFINITIONS = Object.freeze({
146 MaterialTier.bronze,
208 MaterialTier.bronze,
147 "bronze-pickaxe-head"
209 "bronze-pickaxe-head"
148 ),
210 ),
211 [MetalItemId.bronzeAxeHead]: axeHeadDef(
212 MetalItemId.bronzeAxeHead,
213 MaterialTier.bronze,
214 "bronze-axe-head"
215 ),
149 [MetalItemId.ironOre]: oreDef(MetalItemId.ironOre, MaterialTier.iron, "iron-ore"),
216 [MetalItemId.ironOre]: oreDef(MetalItemId.ironOre, MaterialTier.iron, "iron-ore"),
150 [MetalItemId.ironBar]: barDef(MetalItemId.ironBar, MaterialTier.iron, "iron-bar"),
217 [MetalItemId.ironBar]: barDef(MetalItemId.ironBar, MaterialTier.iron, "iron-bar"),
151 [MetalItemId.ironPickaxe]: pickaxeDef(MetalItemId.ironPickaxe, MaterialTier.iron, "iron-pickaxe"),
218 [MetalItemId.ironPickaxe]: pickaxeDef(MetalItemId.ironPickaxe, MaterialTier.iron, "iron-pickaxe"),
152 [MetalItemId.ironPickaxeHead]: pickaxeHeadDef(MetalItemId.ironPickaxeHead, MaterialTier.iron, "iron-pickaxe-head"),
219 [MetalItemId.ironPickaxeHead]: pickaxeHeadDef(MetalItemId.ironPickaxeHead, MaterialTier.iron, "iron-pickaxe-head"),
220 [MetalItemId.ironAxe]: axeDef(MetalItemId.ironAxe, MaterialTier.iron, "iron-axe"),
221 [MetalItemId.ironAxeHead]: axeHeadDef(MetalItemId.ironAxeHead, MaterialTier.iron, "iron-axe-head"),
222 [MetalItemId.goldOre]: oreDef(MetalItemId.goldOre, GatherMaterialId.gold, "gold-ore"),
223 [MetalItemId.goldBar]: barDef(MetalItemId.goldBar, GatherMaterialId.gold, "gold-bar"),
224 [MetalItemId.silverOre]: oreDef(MetalItemId.silverOre, GatherMaterialId.silver, "silver-ore"),
225 [MetalItemId.silverBar]: barDef(MetalItemId.silverBar, GatherMaterialId.silver, "silver-bar"),
153 [MetalItemId.steelBar]: barDef(MetalItemId.steelBar, MaterialTier.steel, "steel-bar"),
226 [MetalItemId.steelBar]: barDef(MetalItemId.steelBar, MaterialTier.steel, "steel-bar"),
154 [MetalItemId.steelPickaxe]: pickaxeDef(MetalItemId.steelPickaxe, MaterialTier.steel, "steel-pickaxe"),
227 [MetalItemId.steelPickaxe]: pickaxeDef(MetalItemId.steelPickaxe, MaterialTier.steel, "steel-pickaxe"),
155 [MetalItemId.steelPickaxeHead]: pickaxeHeadDef(MetalItemId.steelPickaxeHead, MaterialTier.steel, "steel-pickaxe-head"),
228 [MetalItemId.steelPickaxeHead]: pickaxeHeadDef(MetalItemId.steelPickaxeHead, MaterialTier.steel, "steel-pickaxe-head"),
229 [MetalItemId.steelAxe]: axeDef(MetalItemId.steelAxe, MaterialTier.steel, "steel-axe"),
230 [MetalItemId.steelAxeHead]: axeHeadDef(MetalItemId.steelAxeHead, MaterialTier.steel, "steel-axe-head"),
156 [MetalItemId.mithrilOre]: oreDef(MetalItemId.mithrilOre, MaterialTier.mithril, "mithril-ore"),
231 [MetalItemId.mithrilOre]: oreDef(MetalItemId.mithrilOre, MaterialTier.mithril, "mithril-ore"),
157 [MetalItemId.mithrilBar]: barDef(MetalItemId.mithrilBar, MaterialTier.mithril, "mithril-bar"),
232 [MetalItemId.mithrilBar]: barDef(MetalItemId.mithrilBar, MaterialTier.mithril, "mithril-bar"),
158 [MetalItemId.mithrilPickaxe]: pickaxeDef(MetalItemId.mithrilPickaxe, MaterialTier.mithril, "mithril-pickaxe"),
233 [MetalItemId.mithrilPickaxe]: pickaxeDef(MetalItemId.mithrilPickaxe, MaterialTier.mithril, "mithril-pickaxe"),
159 [MetalItemId.mithrilPickaxeHead]: pickaxeHeadDef(MetalItemId.mithrilPickaxeHead, MaterialTier.mithril, "mithril-pickaxe-head"),
234 [MetalItemId.mithrilPickaxeHead]: pickaxeHeadDef(MetalItemId.mithrilPickaxeHead, MaterialTier.mithril, "mithril-pickaxe-head"),
235 [MetalItemId.mithrilAxe]: axeDef(MetalItemId.mithrilAxe, MaterialTier.mithril, "mithril-axe"),
236 [MetalItemId.mithrilAxeHead]: axeHeadDef(MetalItemId.mithrilAxeHead, MaterialTier.mithril, "mithril-axe-head"),
160 [MetalItemId.adamantiumOre]: oreDef(MetalItemId.adamantiumOre, MaterialTier.adamantium, "adamantium-ore"),
237 [MetalItemId.adamantiumOre]: oreDef(MetalItemId.adamantiumOre, MaterialTier.adamantium, "adamantium-ore"),
161 [MetalItemId.adamantiumBar]: barDef(MetalItemId.adamantiumBar, MaterialTier.adamantium, "adamantium-bar"),
238 [MetalItemId.adamantiumBar]: barDef(MetalItemId.adamantiumBar, MaterialTier.adamantium, "adamantium-bar"),
162 [MetalItemId.adamantiumPickaxe]: pickaxeDef(MetalItemId.adamantiumPickaxe, MaterialTier.adamantium, "adamantium-pickaxe"),
239 [MetalItemId.adamantiumPickaxe]: pickaxeDef(MetalItemId.adamantiumPickaxe, MaterialTier.adamantium, "adamantium-pickaxe"),
163 [MetalItemId.adamantiumPickaxeHead]: pickaxeHeadDef(MetalItemId.adamantiumPickaxeHead, MaterialTier.adamantium, "adamantium-pickaxe-head"),
240 [MetalItemId.adamantiumPickaxeHead]: pickaxeHeadDef(MetalItemId.adamantiumPickaxeHead, MaterialTier.adamantium, "adamantium-pickaxe-head"),
241 [MetalItemId.adamantiumAxe]: axeDef(MetalItemId.adamantiumAxe, MaterialTier.adamantium, "adamantium-axe"),
242 [MetalItemId.adamantiumAxeHead]: axeHeadDef(MetalItemId.adamantiumAxeHead, MaterialTier.adamantium, "adamantium-axe-head"),
164 [MetalItemId.orichalcumOre]: oreDef(MetalItemId.orichalcumOre, MaterialTier.orichalcum, "orichalcum-ore"),
243 [MetalItemId.orichalcumOre]: oreDef(MetalItemId.orichalcumOre, MaterialTier.orichalcum, "orichalcum-ore"),
165 [MetalItemId.orichalcumBar]: barDef(MetalItemId.orichalcumBar, MaterialTier.orichalcum, "orichalcum-bar"),
244 [MetalItemId.orichalcumBar]: barDef(MetalItemId.orichalcumBar, MaterialTier.orichalcum, "orichalcum-bar"),
166 [MetalItemId.orichalcumPickaxe]: pickaxeDef(MetalItemId.orichalcumPickaxe, MaterialTier.orichalcum, "orichalcum-pickaxe"),
245 [MetalItemId.orichalcumPickaxe]: pickaxeDef(MetalItemId.orichalcumPickaxe, MaterialTier.orichalcum, "orichalcum-pickaxe"),
167 [MetalItemId.orichalcumPickaxeHead]: pickaxeHeadDef(MetalItemId.orichalcumPickaxeHead, MaterialTier.orichalcum, "orichalcum-pickaxe-head"),
246 [MetalItemId.orichalcumPickaxeHead]: pickaxeHeadDef(MetalItemId.orichalcumPickaxeHead, MaterialTier.orichalcum, "orichalcum-pickaxe-head"),
247 [MetalItemId.orichalcumAxe]: axeDef(MetalItemId.orichalcumAxe, MaterialTier.orichalcum, "orichalcum-axe"),
248 [MetalItemId.orichalcumAxeHead]: axeHeadDef(MetalItemId.orichalcumAxeHead, MaterialTier.orichalcum, "orichalcum-axe-head"),
168 [MetalItemId.dragonOre]: oreDef(MetalItemId.dragonOre, MaterialTier.dragon, "dragon-ore"),
249 [MetalItemId.dragonOre]: oreDef(MetalItemId.dragonOre, MaterialTier.dragon, "dragon-ore"),
169 [MetalItemId.dragonBar]: barDef(MetalItemId.dragonBar, MaterialTier.dragon, "dragon-bar"),
250 [MetalItemId.dragonBar]: barDef(MetalItemId.dragonBar, MaterialTier.dragon, "dragon-bar"),
170 [MetalItemId.dragonPickaxe]: pickaxeDef(MetalItemId.dragonPickaxe, MaterialTier.dragon, "dragon-pickaxe"),
251 [MetalItemId.dragonPickaxe]: pickaxeDef(MetalItemId.dragonPickaxe, MaterialTier.dragon, "dragon-pickaxe"),
171 [MetalItemId.dragonPickaxeHead]: pickaxeHeadDef(MetalItemId.dragonPickaxeHead, MaterialTier.dragon, "dragon-pickaxe-head")
252 [MetalItemId.dragonPickaxeHead]: pickaxeHeadDef(MetalItemId.dragonPickaxeHead, MaterialTier.dragon, "dragon-pickaxe-head"),
253 [MetalItemId.dragonAxe]: axeDef(MetalItemId.dragonAxe, MaterialTier.dragon, "dragon-axe"),
254 [MetalItemId.dragonAxeHead]: axeHeadDef(MetalItemId.dragonAxeHead, MaterialTier.dragon, "dragon-axe-head")
172});
255});
173
256
174/** Pickaxe head item id by metal tier. */
257/** Pickaxe head item id by metal tier. */
@@ -190,3 +273,23 @@ export const PICKAXE_ITEM_BY_METAL = Object.freeze({
190 [MaterialTier.orichalcum]: MetalItemId.orichalcumPickaxe,
273 [MaterialTier.orichalcum]: MetalItemId.orichalcumPickaxe,
191 [MaterialTier.dragon]: MetalItemId.dragonPickaxe
274 [MaterialTier.dragon]: MetalItemId.dragonPickaxe
192});
275});
276
277/** Axe head item id by metal tier. */
278export const AXE_HEAD_ITEM_BY_METAL = Object.freeze({
279 [MaterialTier.bronze]: MetalItemId.bronzeAxeHead,
280 [MaterialTier.iron]: MetalItemId.ironAxeHead,
281 [MaterialTier.steel]: MetalItemId.steelAxeHead,
282 [MaterialTier.mithril]: MetalItemId.mithrilAxeHead,
283 [MaterialTier.adamantium]: MetalItemId.adamantiumAxeHead,
284 [MaterialTier.orichalcum]: MetalItemId.orichalcumAxeHead,
285 [MaterialTier.dragon]: MetalItemId.dragonAxeHead
286});
287
288export const AXE_ITEM_BY_METAL = Object.freeze({
289 [MaterialTier.iron]: MetalItemId.ironAxe,
290 [MaterialTier.steel]: MetalItemId.steelAxe,
291 [MaterialTier.mithril]: MetalItemId.mithrilAxe,
292 [MaterialTier.adamantium]: MetalItemId.adamantiumAxe,
293 [MaterialTier.orichalcum]: MetalItemId.orichalcumAxe,
294 [MaterialTier.dragon]: MetalItemId.dragonAxe
295});
shared/definitions/mobCombat.js +14 −0
@@ -1,6 +1,8 @@
1 1 import { mobDefinition } from "./mobs.js";
2 2 import { SkillId, UNARMED_ATTACK } from "./skills.js";
3 3
4 export const DEFAULT_AGGRO_RANGE_TILES = 5;
5
4 6 /** Living mobs with health can fight unless explicitly non-combat (pigeon, etc.). */
5 7 export function mobCanFight (def)
6 8 {
@@ -16,6 +18,18 @@ export function mobCanFightType (mobTypeId)
16 18 return mobCanFight(mobDefinition(mobTypeId));
17 19 }
18 20
21 /** Aggressive mobs auto-engage players in range with line of sight. */
22 export function mobIsAggressive (def)
23 {
24 return !!(def?.aggressive && mobCanFight(def));
25 }
26
27 export function mobAggroRangeTiles (def)
28 {
29 const range = def?.aggroRangeTiles | 0;
30 return range > 0 ? range : DEFAULT_AGGRO_RANGE_TILES;
31 }
32
19 33 /** Melee profile for a mob: one attackSkill drives hit chance and damage. */
20 34 export function mobMeleeAttackProfile (def)
21 35 {
@@ -1,6 +1,8 @@
1import { mobDefinition } from "./mobs.js";
1import { mobDefinition } from "./mobs.js";
2import { SkillId, UNARMED_ATTACK } from "./skills.js";
2import { SkillId, UNARMED_ATTACK } from "./skills.js";
3
3
4export const DEFAULT_AGGRO_RANGE_TILES = 5;
5
4/** Living mobs with health can fight unless explicitly non-combat (pigeon, etc.). */
6/** Living mobs with health can fight unless explicitly non-combat (pigeon, etc.). */
5export function mobCanFight (def)
7export function mobCanFight (def)
6{
8{
@@ -16,6 +18,18 @@ export function mobCanFightType (mobTypeId)
16 return mobCanFight(mobDefinition(mobTypeId));
18 return mobCanFight(mobDefinition(mobTypeId));
17}
19}
18
20
21/** Aggressive mobs auto-engage players in range with line of sight. */
22export function mobIsAggressive (def)
23{
24 return !!(def?.aggressive && mobCanFight(def));
25}
26
27export function mobAggroRangeTiles (def)
28{
29 const range = def?.aggroRangeTiles | 0;
30 return range > 0 ? range : DEFAULT_AGGRO_RANGE_TILES;
31}
32
19/** Melee profile for a mob: one attackSkill drives hit chance and damage. */
33/** Melee profile for a mob: one attackSkill drives hit chance and damage. */
20export function mobMeleeAttackProfile (def)
34export function mobMeleeAttackProfile (def)
21{
35{
shared/definitions/mobs.js +20 −4
@@ -41,6 +41,7 @@ export const MOB_DEFINITIONS = Object.freeze({
41 41 ambient: false,
42 42 talkable: false,
43 43 untargetable: false,
44 aggressive: false,
44 45 gait: "walk",
45 46 sex: "male",
46 47 frames: 1,
@@ -64,6 +65,7 @@ export const MOB_DEFINITIONS = Object.freeze({
64 65 ambient: false,
65 66 talkable: false,
66 67 untargetable: true,
68 aggressive: false,
67 69 gait: "walk",
68 70 sex: "male",
69 71 frames: 2,
@@ -91,6 +93,9 @@ export const MOB_DEFINITIONS = Object.freeze({
91 93 ambient: false,
92 94 talkable: false,
93 95 untargetable: false,
96 /** Auto-engage nearby players when in range with line of sight. */
97 aggressive: true,
98 aggroRangeTiles: 5,
94 99 gait: "walk",
95 100 sex: "male",
96 101 frames: 1,
@@ -114,6 +119,7 @@ export const MOB_DEFINITIONS = Object.freeze({
114 119 ambient: false,
115 120 talkable: true,
116 121 untargetable: false,
122 aggressive: false,
117 123 usePlayerBody: true,
118 124 gait: "walk",
119 125 sex: "male",
@@ -156,6 +162,7 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
156 162 displayName: humanoid ? "Shopkeeper" : "",
157 163 equipment: emptySpawnerEquipment(),
158 164 sells: [],
165 buysItems: false,
159 166 hiddenDiscount: 0.9
160 167 };
161 168 }
@@ -195,17 +202,25 @@ function normalizeSells (raw)
195 202 {
196 203 if (!Array.isArray(raw))
197 204 { return []; }
198 const ids = [];
205 const lines = [];
199 206 const seen = new Set();
200 207 for (const entry of raw)
201 208 {
202 const itemId = Number(entry);
209 let itemId;
210 let quantity = 0;
211 if (entry && typeof entry === "object")
212 {
213 itemId = Number(entry.itemId);
214 quantity = Math.max(0, Number(entry.quantity) || 0) | 0;
215 }
216 else
217 { itemId = Number(entry); }
203 218 if (!Number.isFinite(itemId) || itemId <= 0 || seen.has(itemId | 0))
204 219 { continue; }
205 220 seen.add(itemId | 0);
206 ids.push(itemId | 0);
221 lines.push({ itemId: itemId | 0, quantity });
207 222 }
208 return ids;
223 return lines;
209 224 }
210 225
211 226 /** Clamp wander ≥ spawn; coerce numeric fields; keep humanoid shop/appearance options. */
@@ -232,6 +247,7 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
232 247 displayName,
233 248 equipment: normalizeEquipment(merged.equipment),
234 249 sells: normalizeSells(merged.sells),
250 buysItems: !!merged.buysItems,
235 251 hiddenDiscount
236 252 };
237 253 }
@@ -41,6 +41,7 @@ export const MOB_DEFINITIONS = Object.freeze({
41 ambient: false,
41 ambient: false,
42 talkable: false,
42 talkable: false,
43 untargetable: false,
43 untargetable: false,
44 aggressive: false,
44 gait: "walk",
45 gait: "walk",
45 sex: "male",
46 sex: "male",
46 frames: 1,
47 frames: 1,
@@ -64,6 +65,7 @@ export const MOB_DEFINITIONS = Object.freeze({
64 ambient: false,
65 ambient: false,
65 talkable: false,
66 talkable: false,
66 untargetable: true,
67 untargetable: true,
68 aggressive: false,
67 gait: "walk",
69 gait: "walk",
68 sex: "male",
70 sex: "male",
69 frames: 2,
71 frames: 2,
@@ -91,6 +93,9 @@ export const MOB_DEFINITIONS = Object.freeze({
91 ambient: false,
93 ambient: false,
92 talkable: false,
94 talkable: false,
93 untargetable: false,
95 untargetable: false,
96 /** Auto-engage nearby players when in range with line of sight. */
97 aggressive: true,
98 aggroRangeTiles: 5,
94 gait: "walk",
99 gait: "walk",
95 sex: "male",
100 sex: "male",
96 frames: 1,
101 frames: 1,
@@ -114,6 +119,7 @@ export const MOB_DEFINITIONS = Object.freeze({
114 ambient: false,
119 ambient: false,
115 talkable: true,
120 talkable: true,
116 untargetable: false,
121 untargetable: false,
122 aggressive: false,
117 usePlayerBody: true,
123 usePlayerBody: true,
118 gait: "walk",
124 gait: "walk",
119 sex: "male",
125 sex: "male",
@@ -156,6 +162,7 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
156 displayName: humanoid ? "Shopkeeper" : "",
162 displayName: humanoid ? "Shopkeeper" : "",
157 equipment: emptySpawnerEquipment(),
163 equipment: emptySpawnerEquipment(),
158 sells: [],
164 sells: [],
165 buysItems: false,
159 hiddenDiscount: 0.9
166 hiddenDiscount: 0.9
160 };
167 };
161}
168}
@@ -195,17 +202,25 @@ function normalizeSells (raw)
195{
202{
196 if (!Array.isArray(raw))
203 if (!Array.isArray(raw))
197 { return []; }
204 { return []; }
198 const ids = [];
205 const lines = [];
199 const seen = new Set();
206 const seen = new Set();
200 for (const entry of raw)
207 for (const entry of raw)
201 {
208 {
202 const itemId = Number(entry);
209 let itemId;
210 let quantity = 0;
211 if (entry && typeof entry === "object")
212 {
213 itemId = Number(entry.itemId);
214 quantity = Math.max(0, Number(entry.quantity) || 0) | 0;
215 }
216 else
217 { itemId = Number(entry); }
203 if (!Number.isFinite(itemId) || itemId <= 0 || seen.has(itemId | 0))
218 if (!Number.isFinite(itemId) || itemId <= 0 || seen.has(itemId | 0))
204 { continue; }
219 { continue; }
205 seen.add(itemId | 0);
220 seen.add(itemId | 0);
206 ids.push(itemId | 0);
221 lines.push({ itemId: itemId | 0, quantity });
207 }
222 }
208 return ids;
223 return lines;
209}
224}
210
225
211/** Clamp wander ≥ spawn; coerce numeric fields; keep humanoid shop/appearance options. */
226/** Clamp wander ≥ spawn; coerce numeric fields; keep humanoid shop/appearance options. */
@@ -232,6 +247,7 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
232 displayName,
247 displayName,
233 equipment: normalizeEquipment(merged.equipment),
248 equipment: normalizeEquipment(merged.equipment),
234 sells: normalizeSells(merged.sells),
249 sells: normalizeSells(merged.sells),
250 buysItems: !!merged.buysItems,
235 hiddenDiscount
251 hiddenDiscount
236 };
252 };
237}
253}
shared/definitions/skills.js +3 −3
@@ -50,9 +50,9 @@ export const ALL_SKILL_IDS = Object.freeze([
50 50 ]);
51 51
52 52 export const SKILL_DEFINITIONS = Object.freeze({
53 [SkillId.clubfighting]: Object.freeze({ skillId: SkillId.clubfighting, displayName: "Club fighting" }),
54 [SkillId.swordfighting]: Object.freeze({ skillId: SkillId.swordfighting, displayName: "Sword fighting" }),
55 [SkillId.axefighting]: Object.freeze({ skillId: SkillId.axefighting, displayName: "Axe fighting" }),
53 [SkillId.clubfighting]: Object.freeze({ skillId: SkillId.clubfighting, displayName: "Clubs" }),
54 [SkillId.swordfighting]: Object.freeze({ skillId: SkillId.swordfighting, displayName: "Swords" }),
55 [SkillId.axefighting]: Object.freeze({ skillId: SkillId.axefighting, displayName: "Axes" }),
56 56 [SkillId.archery]: Object.freeze({ skillId: SkillId.archery, displayName: "Archery" }),
57 57 [SkillId.unarmed]: Object.freeze({ skillId: SkillId.unarmed, displayName: "Unarmed" }),
58 58 [SkillId.magic]: Object.freeze({ skillId: SkillId.magic, displayName: "Magic" }),
@@ -50,9 +50,9 @@ export const ALL_SKILL_IDS = Object.freeze([
50]);
50]);
51
51
52export const SKILL_DEFINITIONS = Object.freeze({
52export const SKILL_DEFINITIONS = Object.freeze({
53 [SkillId.clubfighting]: Object.freeze({ skillId: SkillId.clubfighting, displayName: "Club fighting" }),
53 [SkillId.clubfighting]: Object.freeze({ skillId: SkillId.clubfighting, displayName: "Clubs" }),
54 [SkillId.swordfighting]: Object.freeze({ skillId: SkillId.swordfighting, displayName: "Sword fighting" }),
54 [SkillId.swordfighting]: Object.freeze({ skillId: SkillId.swordfighting, displayName: "Swords" }),
55 [SkillId.axefighting]: Object.freeze({ skillId: SkillId.axefighting, displayName: "Axe fighting" }),
55 [SkillId.axefighting]: Object.freeze({ skillId: SkillId.axefighting, displayName: "Axes" }),
56 [SkillId.archery]: Object.freeze({ skillId: SkillId.archery, displayName: "Archery" }),
56 [SkillId.archery]: Object.freeze({ skillId: SkillId.archery, displayName: "Archery" }),
57 [SkillId.unarmed]: Object.freeze({ skillId: SkillId.unarmed, displayName: "Unarmed" }),
57 [SkillId.unarmed]: Object.freeze({ skillId: SkillId.unarmed, displayName: "Unarmed" }),
58 [SkillId.magic]: Object.freeze({ skillId: SkillId.magic, displayName: "Magic" }),
58 [SkillId.magic]: Object.freeze({ skillId: SkillId.magic, displayName: "Magic" }),
shared/definitions/tiles.js +40 −5
@@ -1,6 +1,7 @@
1 1 import {
2 2 ORE_BEARING_MATERIALS,
3 3 oreBoulderState,
4 materialFromOreBoulderState,
4 5 MATERIAL_DISPLAY_NAME
5 6 } from "./materialTiers.js";
6 7 import { spriteImageName, resolveState } from "./tileSprites.js";
@@ -23,7 +24,8 @@ export const BlockType = Object.freeze({
23 24 boulder: 7,
24 25 furnace: 8,
25 26 anvil: 9,
26 woodworkingBench: 10
27 woodworkingBench: 10,
28 craftingBench: 11
27 29 });
28 30
29 31 export const GROUND_DEFINITIONS = Object.freeze({
@@ -153,7 +155,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
153 155 key: "furnace",
154 156 displayName: "Furnace",
155 157 passable: false,
156 lightRangeTiles: 0,
158 lightRangeTiles: 4,
157 159 frames: 1,
158 160 framesPerRow: 1,
159 161 animationSpeed: 0,
@@ -180,6 +182,17 @@ export const BLOCK_DEFINITIONS = Object.freeze({
180 182 framesPerRow: 1,
181 183 animationSpeed: 0,
182 184 craftingStationId: "woodworking-bench"
185 }),
186 [BlockType.craftingBench]: Object.freeze({
187 id: BlockType.craftingBench,
188 key: "crafting-bench",
189 displayName: "Crafting bench",
190 passable: false,
191 lightRangeTiles: 0,
192 frames: 1,
193 framesPerRow: 1,
194 animationSpeed: 0,
195 craftingStationId: "crafting-bench"
183 196 })
184 197 });
185 198
@@ -194,6 +207,30 @@ export function listPlaceableBlocks ()
194 207 return Object.values(BLOCK_DEFINITIONS).filter((def) => !def.editorHidden);
195 208 }
196 209
210 /** Display name for an ore boulder state (`copper-ore` → "Copper ore boulder"). */
211 export function oreBoulderDisplayName (state)
212 {
213 const material = materialFromOreBoulderState(state);
214 if (!material)
215 { return null; }
216 const label = MATERIAL_DISPLAY_NAME[material] ?? material;
217 return material === "coal" ? "Coal boulder" : `${label} ore boulder`;
218 }
219
220 /**
221 * Hover / UI label for a gatherable resource node.
222 * Ore boulders today; trees / fishing / herbs can extend this later.
223 * Returns null when the block is not an active resource node.
224 */
225 export function resourceNodeDisplayName (block)
226 {
227 if (!block)
228 { return null; }
229 if (block.typeId === BlockType.boulder)
230 { return oreBoulderDisplayName(block.state); }
231 return null;
232 }
233
197 234 /**
198 235 * Editor palette cards: one entry per placeable, with boulder expanded into
199 236 * plain rock + each ore/coal variant (shared BlockType, distinct state).
@@ -215,13 +252,11 @@ export function listPlaceableBlockPaletteEntries (catalog = null)
215 252 for (const material of ORE_BEARING_MATERIALS)
216 253 {
217 254 const state = oreBoulderState(material);
218 const label = MATERIAL_DISPLAY_NAME[material] ?? material;
219 const isCoal = material === "coal";
220 255 entries.push({
221 256 typeId: def.id,
222 257 state,
223 258 key: def.key,
224 displayName: isCoal ? "Coal boulder" : `${label} ore boulder`,
259 displayName: oreBoulderDisplayName(state) ?? state,
225 260 spriteName: spriteImageName("block", def.key, state)
226 261 });
227 262 }
@@ -1,6 +1,7 @@
1import {
1import {
2 ORE_BEARING_MATERIALS,
2 ORE_BEARING_MATERIALS,
3 oreBoulderState,
3 oreBoulderState,
4 materialFromOreBoulderState,
4 MATERIAL_DISPLAY_NAME
5 MATERIAL_DISPLAY_NAME
5} from "./materialTiers.js";
6} from "./materialTiers.js";
6import { spriteImageName, resolveState } from "./tileSprites.js";
7import { spriteImageName, resolveState } from "./tileSprites.js";
@@ -23,7 +24,8 @@ export const BlockType = Object.freeze({
23 boulder: 7,
24 boulder: 7,
24 furnace: 8,
25 furnace: 8,
25 anvil: 9,
26 anvil: 9,
26 woodworkingBench: 10
27 woodworkingBench: 10,
28 craftingBench: 11
27});
29});
28
30
29export const GROUND_DEFINITIONS = Object.freeze({
31export const GROUND_DEFINITIONS = Object.freeze({
@@ -153,7 +155,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
153 key: "furnace",
155 key: "furnace",
154 displayName: "Furnace",
156 displayName: "Furnace",
155 passable: false,
157 passable: false,
156 lightRangeTiles: 0,
158 lightRangeTiles: 4,
157 frames: 1,
159 frames: 1,
158 framesPerRow: 1,
160 framesPerRow: 1,
159 animationSpeed: 0,
161 animationSpeed: 0,
@@ -180,6 +182,17 @@ export const BLOCK_DEFINITIONS = Object.freeze({
180 framesPerRow: 1,
182 framesPerRow: 1,
181 animationSpeed: 0,
183 animationSpeed: 0,
182 craftingStationId: "woodworking-bench"
184 craftingStationId: "woodworking-bench"
185 }),
186 [BlockType.craftingBench]: Object.freeze({
187 id: BlockType.craftingBench,
188 key: "crafting-bench",
189 displayName: "Crafting bench",
190 passable: false,
191 lightRangeTiles: 0,
192 frames: 1,
193 framesPerRow: 1,
194 animationSpeed: 0,
195 craftingStationId: "crafting-bench"
183 })
196 })
184});
197});
185
198
@@ -194,6 +207,30 @@ export function listPlaceableBlocks ()
194 return Object.values(BLOCK_DEFINITIONS).filter((def) => !def.editorHidden);
207 return Object.values(BLOCK_DEFINITIONS).filter((def) => !def.editorHidden);
195}
208}
196
209
210/** Display name for an ore boulder state (`copper-ore` → "Copper ore boulder"). */
211export function oreBoulderDisplayName (state)
212{
213 const material = materialFromOreBoulderState(state);
214 if (!material)
215 { return null; }
216 const label = MATERIAL_DISPLAY_NAME[material] ?? material;
217 return material === "coal" ? "Coal boulder" : `${label} ore boulder`;
218}
219
220/**
221 * Hover / UI label for a gatherable resource node.
222 * Ore boulders today; trees / fishing / herbs can extend this later.
223 * Returns null when the block is not an active resource node.
224 */
225export function resourceNodeDisplayName (block)
226{
227 if (!block)
228 { return null; }
229 if (block.typeId === BlockType.boulder)
230 { return oreBoulderDisplayName(block.state); }
231 return null;
232}
233
197/**
234/**
198 * Editor palette cards: one entry per placeable, with boulder expanded into
235 * Editor palette cards: one entry per placeable, with boulder expanded into
199 * plain rock + each ore/coal variant (shared BlockType, distinct state).
236 * plain rock + each ore/coal variant (shared BlockType, distinct state).
@@ -215,13 +252,11 @@ export function listPlaceableBlockPaletteEntries (catalog = null)
215 for (const material of ORE_BEARING_MATERIALS)
252 for (const material of ORE_BEARING_MATERIALS)
216 {
253 {
217 const state = oreBoulderState(material);
254 const state = oreBoulderState(material);
218 const label = MATERIAL_DISPLAY_NAME[material] ?? material;
219 const isCoal = material === "coal";
220 entries.push({
255 entries.push({
221 typeId: def.id,
256 typeId: def.id,
222 state,
257 state,
223 key: def.key,
258 key: def.key,
224 displayName: isCoal ? "Coal boulder" : `${label} ore boulder`,
259 displayName: oreBoulderDisplayName(state) ?? state,
225 spriteName: spriteImageName("block", def.key, state)
260 spriteName: spriteImageName("block", def.key, state)
226 });
261 });
227 }
262 }
shared/definitions/worldSettings.js +51 −0
@@ -199,6 +199,13 @@ export const WORLD_SETTING_CATEGORIES = [
199 199 }
200 200 ]
201 201 },
202 {
203 id: "basePrices",
204 label: "Base prices",
205 /** Custom panel (item seed list); not scalar fields. */
206 panel: "itemSeedPrices",
207 fields: []
208 },
202 209 {
203 210 id: "courier",
204 211 label: "Courier",
@@ -277,6 +284,50 @@ export function settingsValuesEqual (a, b)
277 284 return a === b;
278 285 }
279 286
287 export function itemSeedMapsEqual (a, b)
288 {
289 const left = a && typeof a === "object" ? a : {};
290 const right = b && typeof b === "object" ? b : {};
291 const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
292 for (const key of keys)
293 {
294 const lv = left[key];
295 const rv = right[key];
296 if (lv == null && rv == null)
297 { continue; }
298 if (lv == null || rv == null)
299 { return false; }
300 if (!settingsValuesEqual(Number(lv), Number(rv)))
301 { return false; }
302 }
303 return true;
304 }
305
306 /**
307 * Diff sparse itemSeedValues maps. Bullets name the item when possible.
308 * @param {(itemId: number) => string|null} [displayNameFor]
309 */
310 export function diffItemSeedValues (previous, next, displayNameFor = null)
311 {
312 const bullets = [];
313 const prev = previous && typeof previous === "object" ? previous : {};
314 const upcoming = next && typeof next === "object" ? next : {};
315 const keys = new Set([...Object.keys(prev), ...Object.keys(upcoming)]);
316 for (const key of [...keys].sort((a, b) => Number(a) - Number(b)))
317 {
318 const from = prev[key];
319 const to = upcoming[key];
320 if (settingsValuesEqual(Number(from), Number(to)))
321 { continue; }
322 const itemId = Number(key);
323 const name = displayNameFor?.(itemId) || `Item ${key}`;
324 const fromText = from == null ? "default" : formatSettingValue(from);
325 const toText = to == null ? "default" : formatSettingValue(to);
326 bullets.push(`${name} seed value changed from ${fromText} to ${toText}.`);
327 }
328 return bullets;
329 }
330
280 331 export function diffSettings (previous, next, fields = allSettingFields())
281 332 {
282 333 const bullets = [];
@@ -199,6 +199,13 @@ export const WORLD_SETTING_CATEGORIES = [
199 }
199 }
200 ]
200 ]
201 },
201 },
202 {
203 id: "basePrices",
204 label: "Base prices",
205 /** Custom panel (item seed list); not scalar fields. */
206 panel: "itemSeedPrices",
207 fields: []
208 },
202 {
209 {
203 id: "courier",
210 id: "courier",
204 label: "Courier",
211 label: "Courier",
@@ -277,6 +284,50 @@ export function settingsValuesEqual (a, b)
277 return a === b;
284 return a === b;
278}
285}
279
286
287export function itemSeedMapsEqual (a, b)
288{
289 const left = a && typeof a === "object" ? a : {};
290 const right = b && typeof b === "object" ? b : {};
291 const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
292 for (const key of keys)
293 {
294 const lv = left[key];
295 const rv = right[key];
296 if (lv == null && rv == null)
297 { continue; }
298 if (lv == null || rv == null)
299 { return false; }
300 if (!settingsValuesEqual(Number(lv), Number(rv)))
301 { return false; }
302 }
303 return true;
304}
305
306/**
307 * Diff sparse itemSeedValues maps. Bullets name the item when possible.
308 * @param {(itemId: number) => string|null} [displayNameFor]
309 */
310export function diffItemSeedValues (previous, next, displayNameFor = null)
311{
312 const bullets = [];
313 const prev = previous && typeof previous === "object" ? previous : {};
314 const upcoming = next && typeof next === "object" ? next : {};
315 const keys = new Set([...Object.keys(prev), ...Object.keys(upcoming)]);
316 for (const key of [...keys].sort((a, b) => Number(a) - Number(b)))
317 {
318 const from = prev[key];
319 const to = upcoming[key];
320 if (settingsValuesEqual(Number(from), Number(to)))
321 { continue; }
322 const itemId = Number(key);
323 const name = displayNameFor?.(itemId) || `Item ${key}`;
324 const fromText = from == null ? "default" : formatSettingValue(from);
325 const toText = to == null ? "default" : formatSettingValue(to);
326 bullets.push(`${name} seed value changed from ${fromText} to ${toText}.`);
327 }
328 return bullets;
329}
330
280export function diffSettings (previous, next, fields = allSettingFields())
331export function diffSettings (previous, next, fields = allSettingFields())
281{
332{
282 const bullets = [];
333 const bullets = [];
shared/protocol/constants.js +9 −1
@@ -4,6 +4,9 @@ export const SPRITE_SIZE_PX = 16;
4 4 export const PIVOT_FROM_BOTTOM_PX = 8;
5 5 export const VISIBLE_CHUNK_RADIUS = 1;
6 6
7 /** If an entity has a path but has not left its tile for this long, repath. */
8 export const NAV_STUCK_MS = 5000;
9
7 10 export const DEFAULT_CHUNK_LOADER = Object.freeze({
8 11 simulationRadiusChunks: 1,
9 12 regionLoadRadius: 1
@@ -25,6 +28,8 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
25 28 walkTilesPerSecond: 2,
26 29 simulationTickHz: 20,
27 30 shopPriceLerpDurationMs: 60 * 60 * 1000,
31 /** Sparse map of itemId → seed value overrides (string keys). Missing = item def seedValue. */
32 itemSeedValues: Object.freeze({}),
28 33 groundItemDespawnDurationMs: 10 * 60 * 1000,
29 34 regionUnloadGracePeriodMs: 30 * 1000,
30 35 defaultGroundTypeId: 1,
@@ -154,6 +159,9 @@ export const MessageType = Object.freeze({
154 159 tileShove: "TILE_SHOVE",
155 160 itemBubble: "ITEM_BUBBLE",
156 161 shopOpen: "SHOP_OPEN",
157 buyFromShop: "BUY_FROM_SHOP"
162 shopClosed: "SHOP_CLOSED",
163 closeShop: "CLOSE_SHOP",
164 buyFromShop: "BUY_FROM_SHOP",
165 sellToShop: "SELL_TO_SHOP"
158 166 });
159 167
@@ -4,6 +4,9 @@ export const SPRITE_SIZE_PX = 16;
4export const PIVOT_FROM_BOTTOM_PX = 8;
4export const PIVOT_FROM_BOTTOM_PX = 8;
5export const VISIBLE_CHUNK_RADIUS = 1;
5export const VISIBLE_CHUNK_RADIUS = 1;
6
6
7/** If an entity has a path but has not left its tile for this long, repath. */
8export const NAV_STUCK_MS = 5000;
9
7export const DEFAULT_CHUNK_LOADER = Object.freeze({
10export const DEFAULT_CHUNK_LOADER = Object.freeze({
8 simulationRadiusChunks: 1,
11 simulationRadiusChunks: 1,
9 regionLoadRadius: 1
12 regionLoadRadius: 1
@@ -25,6 +28,8 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
25 walkTilesPerSecond: 2,
28 walkTilesPerSecond: 2,
26 simulationTickHz: 20,
29 simulationTickHz: 20,
27 shopPriceLerpDurationMs: 60 * 60 * 1000,
30 shopPriceLerpDurationMs: 60 * 60 * 1000,
31 /** Sparse map of itemId → seed value overrides (string keys). Missing = item def seedValue. */
32 itemSeedValues: Object.freeze({}),
28 groundItemDespawnDurationMs: 10 * 60 * 1000,
33 groundItemDespawnDurationMs: 10 * 60 * 1000,
29 regionUnloadGracePeriodMs: 30 * 1000,
34 regionUnloadGracePeriodMs: 30 * 1000,
30 defaultGroundTypeId: 1,
35 defaultGroundTypeId: 1,
@@ -154,6 +159,9 @@ export const MessageType = Object.freeze({
154 tileShove: "TILE_SHOVE",
159 tileShove: "TILE_SHOVE",
155 itemBubble: "ITEM_BUBBLE",
160 itemBubble: "ITEM_BUBBLE",
156 shopOpen: "SHOP_OPEN",
161 shopOpen: "SHOP_OPEN",
157 buyFromShop: "BUY_FROM_SHOP"
162 shopClosed: "SHOP_CLOSED",
163 closeShop: "CLOSE_SHOP",
164 buyFromShop: "BUY_FROM_SHOP",
165 sellToShop: "SELL_TO_SHOP"
158});
166});
159
167
shared/render/tint.js +38 −16
@@ -1,18 +1,24 @@
1 import { MaterialTier, MATERIAL_TIER_ORDER, MATERIAL_TINT_COLOR, GatherMaterialId } from "../definitions/materialTiers.js";
1 import { MATERIAL_TIER_ORDER, materialTintColor, GatherMaterialId } from "../definitions/materialTiers.js";
2 2 import { itemDefinition } from "../definitions/items.js";
3 3
4 4 /**
5 5 * Artist convention for tintable pixels (source sprites):
6 * - Tintable when R == B and G < R (magenta family).
6 * - Tintable when R ≈ B and G < R (magenta family).
7 * - |R − B| may be up to {@link MAGENTA_CHANNEL_TOLERANCE} (AA / export drift).
7 8 * - Lightness L = R (= B): (50,0,50) dark … (255,0,255) max light.
8 * - G > 0 (still G < R) desaturates toward white/gray: mix(tint, white, G/R) * L.
9 * - G > 0 (still G < R) desaturates toward the tint's own gray (not white),
10 * so dark target colours stay dark: mix(tint, vec3(luma(tint)), G/R) * L.
9 11 * - Otherwise leave RGB as-is. World shaders apply darkness after this pass.
10 12 */
11 13
12 export const MAGENTA_CHANNEL_EPS = 1 / 255;
14 /** Max |R − B| in 0–255 channel units for near-magenta pixels. */
15 export const MAGENTA_CHANNEL_TOLERANCE = 2;
13 16
14 /** @deprecated Prefer MATERIAL_TINT_COLOR — kept as alias for call sites. */
15 export const TIER_TINT_COLOR = MATERIAL_TINT_COLOR;
17 /** @deprecated Float form of tolerance; prefer {@link MAGENTA_CHANNEL_TOLERANCE}. */
18 export const MAGENTA_CHANNEL_EPS = MAGENTA_CHANNEL_TOLERANCE / 255;
19
20 /** @deprecated Prefer materialTintColor / MATERIAL_TINT_COLOR — kept for call sites. */
21 export { MATERIAL_TINT_COLOR as TIER_TINT_COLOR } from "../definitions/materialTiers.js";
16 22
17 23 export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
18 24 {
@@ -25,14 +31,14 @@ export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
25 31 };
26 32 }
27 33
28 export function tierTintColor (tier)
34 export function tierTintColor (tier, { ore = false } = {})
29 35 {
30 return normalizeRgb(MATERIAL_TINT_COLOR[tier] ?? MATERIAL_TINT_COLOR[MaterialTier.bronze]);
36 return normalizeRgb(materialTintColor(tier, { ore }));
31 37 }
32 38
33 39 /**
34 40 * Resolve tint for an inventory/ground stack or item def.
35 * Priority: potion instance.color → def.tint → tintFromTier + tier.
41 * Priority: potion instance.color → def.tint → tintFromTier + tier (ore items use ore overrides).
36 42 */
37 43 export function resolveItemTint (stackOrDef, def = null)
38 44 {
@@ -46,7 +52,7 @@ export function resolveItemTint (stackOrDef, def = null)
46 52 { return normalizeRgb(definition.tint); }
47 53 const tier = resolveTintTier(definition);
48 54 if (tier)
49 { return tierTintColor(tier); }
55 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
50 56 return null;
51 57 }
52 58
@@ -61,10 +67,15 @@ export function resolveEquipTint (itemIdOrDef)
61 67 { return normalizeRgb(definition.tint); }
62 68 const tier = resolveTintTier(definition);
63 69 if (tier)
64 { return tierTintColor(tier); }
70 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
65 71 return null;
66 72 }
67 73
74 function isOreItemDefinition (definition)
75 {
76 return definition?.defaultState === "ore";
77 }
78
68 79 function resolveTintTier (definition)
69 80 {
70 81 if (!definition)
@@ -86,16 +97,21 @@ export function magentaTintedRgb (r, g, b, tintRgb)
86 97 const L = r;
87 98 const gBlend = r > 0 ? Math.min(1, Math.max(0, g / r)) : 0;
88 99 const tint = normalizeRgb(tintRgb);
100 const tintLuma = luminance(tint.r, tint.g, tint.b);
89 101 return {
90 r: clamp01(mix(tint.r, 1, gBlend) * L),
91 g: clamp01(mix(tint.g, 1, gBlend) * L),
92 b: clamp01(mix(tint.b, 1, gBlend) * L)
102 r: clamp01(mix(tint.r, tintLuma, gBlend) * L),
103 g: clamp01(mix(tint.g, tintLuma, gBlend) * L),
104 b: clamp01(mix(tint.b, tintLuma, gBlend) * L)
93 105 };
94 106 }
95 107
96 export function isMagentaTintable (r, g, b, eps = MAGENTA_CHANNEL_EPS)
108 export function isMagentaTintable (r, g, b, tolerance = MAGENTA_CHANNEL_TOLERANCE)
97 109 {
98 return Math.abs(r - b) <= eps && g < r - eps;
110 // Compare in 0–255 ints — float |r-b| vs k/255 fails for some R=B±2 pairs.
111 const R = Math.round(r * 255);
112 const G = Math.round(g * 255);
113 const B = Math.round(b * 255);
114 return Math.abs(R - B) <= tolerance && G < R;
99 115 }
100 116
101 117 /** Mutate ImageData in place with magenta→tint (alpha unchanged). */
@@ -136,3 +152,9 @@ function mix (a, b, t)
136 152 {
137 153 return a + (b - a) * t;
138 154 }
155
156 /** Rec. 709 luminance for desaturating toward the tint's own gray. */
157 function luminance (r, g, b)
158 {
159 return 0.2126 * r + 0.7152 * g + 0.0722 * b;
160 }
@@ -1,18 +1,24 @@
1import { MaterialTier, MATERIAL_TIER_ORDER, MATERIAL_TINT_COLOR, GatherMaterialId } from "../definitions/materialTiers.js";
1import { MATERIAL_TIER_ORDER, materialTintColor, GatherMaterialId } from "../definitions/materialTiers.js";
2import { itemDefinition } from "../definitions/items.js";
2import { itemDefinition } from "../definitions/items.js";
3
3
4/**
4/**
5 * Artist convention for tintable pixels (source sprites):
5 * Artist convention for tintable pixels (source sprites):
6 * - Tintable when R == B and G < R (magenta family).
6 * - Tintable when R ≈ B and G < R (magenta family).
7 * - |R − B| may be up to {@link MAGENTA_CHANNEL_TOLERANCE} (AA / export drift).
7 * - Lightness L = R (= B): (50,0,50) dark … (255,0,255) max light.
8 * - Lightness L = R (= B): (50,0,50) dark … (255,0,255) max light.
8 * - G > 0 (still G < R) desaturates toward white/gray: mix(tint, white, G/R) * L.
9 * - G > 0 (still G < R) desaturates toward the tint's own gray (not white),
10 * so dark target colours stay dark: mix(tint, vec3(luma(tint)), G/R) * L.
9 * - Otherwise leave RGB as-is. World shaders apply darkness after this pass.
11 * - Otherwise leave RGB as-is. World shaders apply darkness after this pass.
10 */
12 */
11
13
12export const MAGENTA_CHANNEL_EPS = 1 / 255;
14/** Max |R − B| in 0–255 channel units for near-magenta pixels. */
15export const MAGENTA_CHANNEL_TOLERANCE = 2;
13
16
14/** @deprecated Prefer MATERIAL_TINT_COLOR — kept as alias for call sites. */
17/** @deprecated Float form of tolerance; prefer {@link MAGENTA_CHANNEL_TOLERANCE}. */
15export const TIER_TINT_COLOR = MATERIAL_TINT_COLOR;
18export const MAGENTA_CHANNEL_EPS = MAGENTA_CHANNEL_TOLERANCE / 255;
19
20/** @deprecated Prefer materialTintColor / MATERIAL_TINT_COLOR — kept for call sites. */
21export { MATERIAL_TINT_COLOR as TIER_TINT_COLOR } from "../definitions/materialTiers.js";
16
22
17export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
23export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
18{
24{
@@ -25,14 +31,14 @@ export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
25 };
31 };
26}
32}
27
33
28export function tierTintColor (tier)
34export function tierTintColor (tier, { ore = false } = {})
29{
35{
30 return normalizeRgb(MATERIAL_TINT_COLOR[tier] ?? MATERIAL_TINT_COLOR[MaterialTier.bronze]);
36 return normalizeRgb(materialTintColor(tier, { ore }));
31}
37}
32
38
33/**
39/**
34 * Resolve tint for an inventory/ground stack or item def.
40 * Resolve tint for an inventory/ground stack or item def.
35 * Priority: potion instance.color → def.tint → tintFromTier + tier.
41 * Priority: potion instance.color → def.tint → tintFromTier + tier (ore items use ore overrides).
36 */
42 */
37export function resolveItemTint (stackOrDef, def = null)
43export function resolveItemTint (stackOrDef, def = null)
38{
44{
@@ -46,7 +52,7 @@ export function resolveItemTint (stackOrDef, def = null)
46 { return normalizeRgb(definition.tint); }
52 { return normalizeRgb(definition.tint); }
47 const tier = resolveTintTier(definition);
53 const tier = resolveTintTier(definition);
48 if (tier)
54 if (tier)
49 { return tierTintColor(tier); }
55 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
50 return null;
56 return null;
51}
57}
52
58
@@ -61,10 +67,15 @@ export function resolveEquipTint (itemIdOrDef)
61 { return normalizeRgb(definition.tint); }
67 { return normalizeRgb(definition.tint); }
62 const tier = resolveTintTier(definition);
68 const tier = resolveTintTier(definition);
63 if (tier)
69 if (tier)
64 { return tierTintColor(tier); }
70 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
65 return null;
71 return null;
66}
72}
67
73
74function isOreItemDefinition (definition)
75{
76 return definition?.defaultState === "ore";
77}
78
68function resolveTintTier (definition)
79function resolveTintTier (definition)
69{
80{
70 if (!definition)
81 if (!definition)
@@ -86,16 +97,21 @@ export function magentaTintedRgb (r, g, b, tintRgb)
86 const L = r;
97 const L = r;
87 const gBlend = r > 0 ? Math.min(1, Math.max(0, g / r)) : 0;
98 const gBlend = r > 0 ? Math.min(1, Math.max(0, g / r)) : 0;
88 const tint = normalizeRgb(tintRgb);
99 const tint = normalizeRgb(tintRgb);
100 const tintLuma = luminance(tint.r, tint.g, tint.b);
89 return {
101 return {
90 r: clamp01(mix(tint.r, 1, gBlend) * L),
102 r: clamp01(mix(tint.r, tintLuma, gBlend) * L),
91 g: clamp01(mix(tint.g, 1, gBlend) * L),
103 g: clamp01(mix(tint.g, tintLuma, gBlend) * L),
92 b: clamp01(mix(tint.b, 1, gBlend) * L)
104 b: clamp01(mix(tint.b, tintLuma, gBlend) * L)
93 };
105 };
94}
106}
95
107
96export function isMagentaTintable (r, g, b, eps = MAGENTA_CHANNEL_EPS)
108export function isMagentaTintable (r, g, b, tolerance = MAGENTA_CHANNEL_TOLERANCE)
97{
109{
98 return Math.abs(r - b) <= eps && g < r - eps;
110 // Compare in 0–255 ints — float |r-b| vs k/255 fails for some R=B±2 pairs.
111 const R = Math.round(r * 255);
112 const G = Math.round(g * 255);
113 const B = Math.round(b * 255);
114 return Math.abs(R - B) <= tolerance && G < R;
99}
115}
100
116
101/** Mutate ImageData in place with magenta→tint (alpha unchanged). */
117/** Mutate ImageData in place with magenta→tint (alpha unchanged). */
@@ -136,3 +152,9 @@ function mix (a, b, t)
136{
152{
137 return a + (b - a) * t;
153 return a + (b - a) * t;
138}
154}
155
156/** Rec. 709 luminance for desaturating toward the tint's own gray. */
157function luminance (r, g, b)
158{
159 return 0.2126 * r + 0.7152 * g + 0.0722 * b;
160}
shared/shop/pricing.js +255 −9
@@ -3,7 +3,7 @@
3 3 * Matches design §27.6 — lerp toward lastTradePrice over shopPriceLerpDurationMs.
4 4 */
5 5
6 import { itemDefinition } from "../definitions/items.js";
6 import { ItemId, itemDefinition, ITEM_DEFINITIONS } from "../definitions/items.js";
7 7 import { ItemCategory } from "../definitions/itemCategories.js";
8 8 import { DEFAULT_WORLD_SETTINGS } from "../protocol/constants.js";
9 9
@@ -12,16 +12,69 @@ export function lerp (a, b, t)
12 12 return a + (b - a) * t;
13 13 }
14 14
15 /** Normalize sparse itemId → seed overrides from world settings. */
16 export function normalizeItemSeedValues (raw)
17 {
18 const out = {};
19 if (!raw || typeof raw !== "object")
20 { return out; }
21 for (const [key, value] of Object.entries(raw))
22 {
23 const itemId = Number(key);
24 if (!Number.isInteger(itemId) || itemId <= 0 || !itemDefinition(itemId))
25 { continue; }
26 const seed = Math.round(Number(value));
27 if (!Number.isFinite(seed))
28 { continue; }
29 const defSeed = Math.max(1, Number(itemDefinition(itemId)?.seedValue) || 1);
30 const next = Math.max(1, seed);
31 // Only store overrides that differ from the item definition default.
32 if (next !== defSeed)
33 { out[String(itemId)] = next; }
34 }
35 return out;
36 }
37
38 /** Effective world seed for an item (override or definition). */
39 export function effectiveSeedValue (itemId, settings = null)
40 {
41 const def = itemDefinition(itemId);
42 const defSeed = Math.max(1, Number(def?.seedValue) || 1);
43 const overrides = settings?.itemSeedValues;
44 if (!overrides || typeof overrides !== "object")
45 { return defSeed; }
46 const key = String(itemId | 0);
47 if (!Object.prototype.hasOwnProperty.call(overrides, key)
48 && !Object.prototype.hasOwnProperty.call(overrides, itemId | 0))
49 { return defSeed; }
50 const raw = overrides[key] ?? overrides[itemId | 0];
51 const seed = Math.round(Number(raw));
52 if (!Number.isFinite(seed))
53 { return defSeed; }
54 return Math.max(1, seed);
55 }
56
15 57 /**
16 58 * @param {object|null} lastSale `{ lastTradePrice, lastTradeAt, priceFrom }`
59 * @param {object|null} settings world settings (reads itemSeedValues + lerp duration)
17 60 */
18 export function undiscountedMarketValue (itemId, lastSale = null, now = Date.now(), lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs)
61 export function undiscountedMarketValue (
62 itemId,
63 lastSale = null,
64 now = Date.now(),
65 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
66 settings = null
67 )
19 68 {
20 const def = itemDefinition(itemId);
21 const seed = Math.max(1, Number(def?.seedValue) || 1);
69 const seed = effectiveSeedValue(itemId, settings);
22 70 if (!lastSale?.lastTradeAt || lastSale.lastTradePrice == null)
23 71 { return seed; }
24 const duration = Math.max(1, Number(lerpDurationMs) || DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs);
72 const duration = Math.max(
73 1,
74 Number(lerpDurationMs)
75 || Number(settings?.shopPriceLerpDurationMs)
76 || DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs
77 );
25 78 const t = Math.min(1, Math.max(0, (now - lastSale.lastTradeAt) / duration));
26 79 const from = lastSale.priceFrom != null ? Number(lastSale.priceFrom) : seed;
27 80 const to = Number(lastSale.lastTradePrice);
@@ -30,20 +83,95 @@ export function undiscountedMarketValue (itemId, lastSale = null, now = Date.now
30 83 return lerp(from, to, t);
31 84 }
32 85
33 /** Integer shop purchase price (server authority). */
86 /** Integer shop purchase price (player buying catalog stock). */
34 87 export function shopUnitPrice (itemId, {
35 88 lastSale = null,
36 89 now = Date.now(),
37 90 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
38 hiddenDiscount = 1
91 hiddenDiscount = 1,
92 settings = null
39 93 } = {})
40 94 {
41 const undiscounted = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs);
95 const undiscounted = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings);
42 96 const discount = Math.min(1, Math.max(0.01, Number(hiddenDiscount) || 1));
43 97 return Math.max(1, Math.round(undiscounted * discount));
44 98 }
45 99
46 /** NPC shops sell ingredients (and items explicitly flagged). */
100 /** NPC pays the player this much when buying (80% of market). */
101 export function shopBuyFromPlayerPrice (itemId, {
102 lastSale = null,
103 now = Date.now(),
104 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
105 settings = null
106 } = {})
107 {
108 return Math.max(1, Math.round(undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 0.8));
109 }
110
111 /** Resale price for goods the NPC bought from players today (120% of market). */
112 export function shopBoughtResalePrice (itemId, {
113 lastSale = null,
114 now = Date.now(),
115 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
116 settings = null
117 } = {})
118 {
119 return Math.max(1, Math.round(undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 1.2));
120 }
121
122 /**
123 * Editor / tooltip snapshot for one item.
124 * `marketKnown` is true when a last-sale record exists; otherwise market equals seed.
125 */
126 export function itemPriceSnapshot (itemId, {
127 settings = null,
128 lastSale = null,
129 now = Date.now(),
130 hiddenDiscount = 1
131 } = {})
132 {
133 const def = itemDefinition(itemId);
134 if (!def)
135 { return null; }
136 const lerpDurationMs = settings?.shopPriceLerpDurationMs
137 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
138 const seedValue = effectiveSeedValue(itemId, settings);
139 const marketKnown = !!(lastSale?.lastTradeAt && lastSale.lastTradePrice != null);
140 const marketValue = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings);
141 const shopPrice = shopUnitPrice(itemId, {
142 lastSale,
143 now,
144 lerpDurationMs,
145 hiddenDiscount,
146 settings
147 });
148 return {
149 itemId: def.itemId,
150 displayName: def.displayName ?? String(def.itemId),
151 key: def.key ?? String(def.itemId),
152 definitionSeedValue: Math.max(1, Number(def.seedValue) || 1),
153 seedValue,
154 marketValue: Math.max(1, Math.round(marketValue)),
155 marketKnown,
156 shopPrice
157 };
158 }
159
160 /** All items with a price row for the base-prices editor. */
161 export function listPricedItems ()
162 {
163 return Object.values(ITEM_DEFINITIONS)
164 .filter((def) => def?.itemId != null && def.seedValue != null)
165 .map((def) => ({
166 itemId: def.itemId,
167 displayName: def.displayName ?? String(def.itemId),
168 key: def.key ?? String(def.itemId),
169 definitionSeedValue: Math.max(1, Number(def.seedValue) || 1)
170 }))
171 .sort((a, b) => a.displayName.localeCompare(b.displayName));
172 }
173
174 /** NPC shops sell ingredients (and items explicitly flagged) in their catalog. */
47 175 export function canSellInNpcShop (itemId)
48 176 {
49 177 const def = itemDefinition(itemId);
@@ -55,3 +183,121 @@ export function canSellInNpcShop (itemId)
55 183 { return true; }
56 184 return def.category === ItemCategory.ingredient || def.category === "ingredient";
57 185 }
186
187 /**
188 * What a buysItems shopkeeper will purchase from a player bag slot.
189 * All transferable goods except blank cheques (and coins).
190 * Filled cheques are sold as their reserved goods (+ admin fee).
191 */
192 export function canPlayerSellToNpc (stack)
193 {
194 if (!stack?.itemId)
195 { return false; }
196 const itemId = stack.itemId | 0;
197 if (itemId === ItemId.blankCheque || itemId === ItemId.coins)
198 { return false; }
199 if (itemId === ItemId.filledCheque)
200 {
201 const instance = stack.instance;
202 if (instance?.kind !== "filled-cheque")
203 { return false; }
204 const goodsId = instance.itemId | 0;
205 return goodsId > 0 && !!itemDefinition(goodsId) && goodsId !== ItemId.coins;
206 }
207 return !!itemDefinition(itemId);
208 }
209
210 /** Administrative fee rate when selling a filled cheque to an NPC. */
211 export const CHEQUE_SHOP_ADMIN_FEE_RATE = 0.05;
212
213 /** Fee deducted from cheque shop payout (5% of base, rounded up). */
214 export function shopChequeAdminFee (basePayout)
215 {
216 const base = Math.max(0, Math.round(Number(basePayout)) || 0);
217 if (base <= 0)
218 { return 0; }
219 return Math.ceil(base * CHEQUE_SHOP_ADMIN_FEE_RATE);
220 }
221
222 /**
223 * Quote for selling one bag unit (or one filled cheque) to a buysItems NPC.
224 * @returns {null | {
225 * isCheque: boolean,
226 * goodsItemId: number,
227 * goodsQuantity: number,
228 * unitPrice: number,
229 * baseTotal: number,
230 * adminFee: number,
231 * payout: number
232 * }}
233 */
234 export function resolveShopSellQuote (stack, {
235 lastSale = null,
236 now = Date.now(),
237 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
238 settings = null,
239 quantity = 1
240 } = {})
241 {
242 if (!canPlayerSellToNpc(stack))
243 { return null; }
244 if ((stack.itemId | 0) === ItemId.filledCheque)
245 {
246 const goodsItemId = stack.instance.itemId | 0;
247 const goodsQuantity = Math.max(1, stack.instance.quantity | 0);
248 const unitPrice = shopBuyFromPlayerPrice(goodsItemId, {
249 lastSale,
250 now,
251 lerpDurationMs,
252 settings
253 });
254 const baseTotal = unitPrice * goodsQuantity;
255 const adminFee = shopChequeAdminFee(baseTotal);
256 return {
257 isCheque: true,
258 goodsItemId,
259 goodsQuantity,
260 unitPrice,
261 baseTotal,
262 adminFee,
263 payout: Math.max(0, baseTotal - adminFee)
264 };
265 }
266 const goodsItemId = stack.itemId | 0;
267 const goodsQuantity = Math.max(1, Math.min(stack.quantity | 0 || 1, quantity | 0 || 1));
268 const unitPrice = shopBuyFromPlayerPrice(goodsItemId, {
269 lastSale,
270 now,
271 lerpDurationMs,
272 settings
273 });
274 const baseTotal = unitPrice * goodsQuantity;
275 return {
276 isCheque: false,
277 goodsItemId,
278 goodsQuantity,
279 unitPrice,
280 baseTotal,
281 adminFee: 0,
282 payout: baseTotal
283 };
284 }
285
286 /** Items the editor may add to a shopkeeper sells list. */
287 export function listNpcShopSellableItems ()
288 {
289 return Object.values(ITEM_DEFINITIONS)
290 .filter((def) => canSellInNpcShop(def.itemId))
291 .map((def) => ({
292 itemId: def.itemId,
293 displayName: def.displayName ?? String(def.itemId),
294 key: def.key ?? String(def.itemId)
295 }))
296 .sort((a, b) => a.displayName.localeCompare(b.displayName));
297 }
298
299 /** Calendar day key used for midnight shop restock (UTC). */
300 export function shopRestockDayKey (now = Date.now())
301 {
302 return new Date(now).toISOString().slice(0, 10);
303 }
@@ -3,7 +3,7 @@
3 * Matches design §27.6 — lerp toward lastTradePrice over shopPriceLerpDurationMs.
3 * Matches design §27.6 — lerp toward lastTradePrice over shopPriceLerpDurationMs.
4 */
4 */
5
5
6import { itemDefinition } from "../definitions/items.js";
6import { ItemId, itemDefinition, ITEM_DEFINITIONS } from "../definitions/items.js";
7import { ItemCategory } from "../definitions/itemCategories.js";
7import { ItemCategory } from "../definitions/itemCategories.js";
8import { DEFAULT_WORLD_SETTINGS } from "../protocol/constants.js";
8import { DEFAULT_WORLD_SETTINGS } from "../protocol/constants.js";
9
9
@@ -12,16 +12,69 @@ export function lerp (a, b, t)
12 return a + (b - a) * t;
12 return a + (b - a) * t;
13}
13}
14
14
15/** Normalize sparse itemId → seed overrides from world settings. */
16export function normalizeItemSeedValues (raw)
17{
18 const out = {};
19 if (!raw || typeof raw !== "object")
20 { return out; }
21 for (const [key, value] of Object.entries(raw))
22 {
23 const itemId = Number(key);
24 if (!Number.isInteger(itemId) || itemId <= 0 || !itemDefinition(itemId))
25 { continue; }
26 const seed = Math.round(Number(value));
27 if (!Number.isFinite(seed))
28 { continue; }
29 const defSeed = Math.max(1, Number(itemDefinition(itemId)?.seedValue) || 1);
30 const next = Math.max(1, seed);
31 // Only store overrides that differ from the item definition default.
32 if (next !== defSeed)
33 { out[String(itemId)] = next; }
34 }
35 return out;
36}
37
38/** Effective world seed for an item (override or definition). */
39export function effectiveSeedValue (itemId, settings = null)
40{
41 const def = itemDefinition(itemId);
42 const defSeed = Math.max(1, Number(def?.seedValue) || 1);
43 const overrides = settings?.itemSeedValues;
44 if (!overrides || typeof overrides !== "object")
45 { return defSeed; }
46 const key = String(itemId | 0);
47 if (!Object.prototype.hasOwnProperty.call(overrides, key)
48 && !Object.prototype.hasOwnProperty.call(overrides, itemId | 0))
49 { return defSeed; }
50 const raw = overrides[key] ?? overrides[itemId | 0];
51 const seed = Math.round(Number(raw));
52 if (!Number.isFinite(seed))
53 { return defSeed; }
54 return Math.max(1, seed);
55}
56
15/**
57/**
16 * @param {object|null} lastSale `{ lastTradePrice, lastTradeAt, priceFrom }`
58 * @param {object|null} lastSale `{ lastTradePrice, lastTradeAt, priceFrom }`
59 * @param {object|null} settings world settings (reads itemSeedValues + lerp duration)
17 */
60 */
18export function undiscountedMarketValue (itemId, lastSale = null, now = Date.now(), lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs)
61export function undiscountedMarketValue (
62 itemId,
63 lastSale = null,
64 now = Date.now(),
65 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
66 settings = null
67)
19{
68{
20 const def = itemDefinition(itemId);
69 const seed = effectiveSeedValue(itemId, settings);
21 const seed = Math.max(1, Number(def?.seedValue) || 1);
22 if (!lastSale?.lastTradeAt || lastSale.lastTradePrice == null)
70 if (!lastSale?.lastTradeAt || lastSale.lastTradePrice == null)
23 { return seed; }
71 { return seed; }
24 const duration = Math.max(1, Number(lerpDurationMs) || DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs);
72 const duration = Math.max(
73 1,
74 Number(lerpDurationMs)
75 || Number(settings?.shopPriceLerpDurationMs)
76 || DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs
77 );
25 const t = Math.min(1, Math.max(0, (now - lastSale.lastTradeAt) / duration));
78 const t = Math.min(1, Math.max(0, (now - lastSale.lastTradeAt) / duration));
26 const from = lastSale.priceFrom != null ? Number(lastSale.priceFrom) : seed;
79 const from = lastSale.priceFrom != null ? Number(lastSale.priceFrom) : seed;
27 const to = Number(lastSale.lastTradePrice);
80 const to = Number(lastSale.lastTradePrice);
@@ -30,20 +83,95 @@ export function undiscountedMarketValue (itemId, lastSale = null, now = Date.now
30 return lerp(from, to, t);
83 return lerp(from, to, t);
31}
84}
32
85
33/** Integer shop purchase price (server authority). */
86/** Integer shop purchase price (player buying catalog stock). */
34export function shopUnitPrice (itemId, {
87export function shopUnitPrice (itemId, {
35 lastSale = null,
88 lastSale = null,
36 now = Date.now(),
89 now = Date.now(),
37 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
90 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
38 hiddenDiscount = 1
91 hiddenDiscount = 1,
92 settings = null
39} = {})
93} = {})
40{
94{
41 const undiscounted = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs);
95 const undiscounted = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings);
42 const discount = Math.min(1, Math.max(0.01, Number(hiddenDiscount) || 1));
96 const discount = Math.min(1, Math.max(0.01, Number(hiddenDiscount) || 1));
43 return Math.max(1, Math.round(undiscounted * discount));
97 return Math.max(1, Math.round(undiscounted * discount));
44}
98}
45
99
46/** NPC shops sell ingredients (and items explicitly flagged). */
100/** NPC pays the player this much when buying (80% of market). */
101export function shopBuyFromPlayerPrice (itemId, {
102 lastSale = null,
103 now = Date.now(),
104 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
105 settings = null
106} = {})
107{
108 return Math.max(1, Math.round(undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 0.8));
109}
110
111/** Resale price for goods the NPC bought from players today (120% of market). */
112export function shopBoughtResalePrice (itemId, {
113 lastSale = null,
114 now = Date.now(),
115 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
116 settings = null
117} = {})
118{
119 return Math.max(1, Math.round(undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 1.2));
120}
121
122/**
123 * Editor / tooltip snapshot for one item.
124 * `marketKnown` is true when a last-sale record exists; otherwise market equals seed.
125 */
126export function itemPriceSnapshot (itemId, {
127 settings = null,
128 lastSale = null,
129 now = Date.now(),
130 hiddenDiscount = 1
131} = {})
132{
133 const def = itemDefinition(itemId);
134 if (!def)
135 { return null; }
136 const lerpDurationMs = settings?.shopPriceLerpDurationMs
137 ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs;
138 const seedValue = effectiveSeedValue(itemId, settings);
139 const marketKnown = !!(lastSale?.lastTradeAt && lastSale.lastTradePrice != null);
140 const marketValue = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings);
141 const shopPrice = shopUnitPrice(itemId, {
142 lastSale,
143 now,
144 lerpDurationMs,
145 hiddenDiscount,
146 settings
147 });
148 return {
149 itemId: def.itemId,
150 displayName: def.displayName ?? String(def.itemId),
151 key: def.key ?? String(def.itemId),
152 definitionSeedValue: Math.max(1, Number(def.seedValue) || 1),
153 seedValue,
154 marketValue: Math.max(1, Math.round(marketValue)),
155 marketKnown,
156 shopPrice
157 };
158}
159
160/** All items with a price row for the base-prices editor. */
161export function listPricedItems ()
162{
163 return Object.values(ITEM_DEFINITIONS)
164 .filter((def) => def?.itemId != null && def.seedValue != null)
165 .map((def) => ({
166 itemId: def.itemId,
167 displayName: def.displayName ?? String(def.itemId),
168 key: def.key ?? String(def.itemId),
169 definitionSeedValue: Math.max(1, Number(def.seedValue) || 1)
170 }))
171 .sort((a, b) => a.displayName.localeCompare(b.displayName));
172}
173
174/** NPC shops sell ingredients (and items explicitly flagged) in their catalog. */
47export function canSellInNpcShop (itemId)
175export function canSellInNpcShop (itemId)
48{
176{
49 const def = itemDefinition(itemId);
177 const def = itemDefinition(itemId);
@@ -55,3 +183,121 @@ export function canSellInNpcShop (itemId)
55 { return true; }
183 { return true; }
56 return def.category === ItemCategory.ingredient || def.category === "ingredient";
184 return def.category === ItemCategory.ingredient || def.category === "ingredient";
57}
185}
186
187/**
188 * What a buysItems shopkeeper will purchase from a player bag slot.
189 * All transferable goods except blank cheques (and coins).
190 * Filled cheques are sold as their reserved goods (+ admin fee).
191 */
192export function canPlayerSellToNpc (stack)
193{
194 if (!stack?.itemId)
195 { return false; }
196 const itemId = stack.itemId | 0;
197 if (itemId === ItemId.blankCheque || itemId === ItemId.coins)
198 { return false; }
199 if (itemId === ItemId.filledCheque)
200 {
201 const instance = stack.instance;
202 if (instance?.kind !== "filled-cheque")
203 { return false; }
204 const goodsId = instance.itemId | 0;
205 return goodsId > 0 && !!itemDefinition(goodsId) && goodsId !== ItemId.coins;
206 }
207 return !!itemDefinition(itemId);
208}
209
210/** Administrative fee rate when selling a filled cheque to an NPC. */
211export const CHEQUE_SHOP_ADMIN_FEE_RATE = 0.05;
212
213/** Fee deducted from cheque shop payout (5% of base, rounded up). */
214export function shopChequeAdminFee (basePayout)
215{
216 const base = Math.max(0, Math.round(Number(basePayout)) || 0);
217 if (base <= 0)
218 { return 0; }
219 return Math.ceil(base * CHEQUE_SHOP_ADMIN_FEE_RATE);
220}
221
222/**
223 * Quote for selling one bag unit (or one filled cheque) to a buysItems NPC.
224 * @returns {null | {
225 * isCheque: boolean,
226 * goodsItemId: number,
227 * goodsQuantity: number,
228 * unitPrice: number,
229 * baseTotal: number,
230 * adminFee: number,
231 * payout: number
232 * }}
233 */
234export function resolveShopSellQuote (stack, {
235 lastSale = null,
236 now = Date.now(),
237 lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs,
238 settings = null,
239 quantity = 1
240} = {})
241{
242 if (!canPlayerSellToNpc(stack))
243 { return null; }
244 if ((stack.itemId | 0) === ItemId.filledCheque)
245 {
246 const goodsItemId = stack.instance.itemId | 0;
247 const goodsQuantity = Math.max(1, stack.instance.quantity | 0);
248 const unitPrice = shopBuyFromPlayerPrice(goodsItemId, {
249 lastSale,
250 now,
251 lerpDurationMs,
252 settings
253 });
254 const baseTotal = unitPrice * goodsQuantity;
255 const adminFee = shopChequeAdminFee(baseTotal);
256 return {
257 isCheque: true,
258 goodsItemId,
259 goodsQuantity,
260 unitPrice,
261 baseTotal,
262 adminFee,
263 payout: Math.max(0, baseTotal - adminFee)
264 };
265 }
266 const goodsItemId = stack.itemId | 0;
267 const goodsQuantity = Math.max(1, Math.min(stack.quantity | 0 || 1, quantity | 0 || 1));
268 const unitPrice = shopBuyFromPlayerPrice(goodsItemId, {
269 lastSale,
270 now,
271 lerpDurationMs,
272 settings
273 });
274 const baseTotal = unitPrice * goodsQuantity;
275 return {
276 isCheque: false,
277 goodsItemId,
278 goodsQuantity,
279 unitPrice,
280 baseTotal,
281 adminFee: 0,
282 payout: baseTotal
283 };
284}
285
286/** Items the editor may add to a shopkeeper sells list. */
287export function listNpcShopSellableItems ()
288{
289 return Object.values(ITEM_DEFINITIONS)
290 .filter((def) => canSellInNpcShop(def.itemId))
291 .map((def) => ({
292 itemId: def.itemId,
293 displayName: def.displayName ?? String(def.itemId),
294 key: def.key ?? String(def.itemId)
295 }))
296 .sort((a, b) => a.displayName.localeCompare(b.displayName));
297}
298
299/** Calendar day key used for midnight shop restock (UTC). */
300export function shopRestockDayKey (now = Date.now())
301{
302 return new Date(now).toISOString().slice(0, 10);
303}
shared/speech/pronouns.js added +19 −0
@@ -0,0 +1,19 @@
1 /**
2 * Binary sex pronouns for humanoids. Never use singular they.
3 * Unknown / missing sex defaults to male forms.
4 */
5
6 export function subjectPronoun (sex)
7 {
8 return sex === "female" ? "she" : "he";
9 }
10
11 export function objectPronoun (sex)
12 {
13 return sex === "female" ? "her" : "him";
14 }
15
16 export function possessiveDeterminer (sex)
17 {
18 return sex === "female" ? "her" : "his";
19 }
@@ -0,0 +1,19 @@
1/**
2 * Binary sex pronouns for humanoids. Never use singular they.
3 * Unknown / missing sex defaults to male forms.
4 */
5
6export function subjectPronoun (sex)
7{
8 return sex === "female" ? "she" : "he";
9}
10
11export function objectPronoun (sex)
12{
13 return sex === "female" ? "her" : "him";
14}
15
16export function possessiveDeterminer (sex)
17{
18 return sex === "female" ? "her" : "his";
19}
tile_mmo_server_technical_design_v0.6.md +10 −2
@@ -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 single
2638`AttackProfile` that repeats until cancel, death, or the target leaves
2638`AttackProfile` that repeats until cancel, death, or the target leaves
2639reachable range (then re-path / re-close).
2639reachable range (then re-path / re-close).
2640
2640
2641When a combatant is hit, if it has `Combat` it **immediately engages** the
2641`ATTACK` engages **only the attacker**. A fightable target **retaliates on the
2642attacker (players and mobs). Peaceful NPCs without `Combat` do not retaliate.
2642first resolved melee swing** against it (hit, miss, or block) — not when the
2643player 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)
2647additionally auto-engage the nearest living player character within Chebyshev
2648range when they have line of sight through enterable tiles (same occlusion
2649rule as lighting rays: intermediate tiles must be enterable). Passive does not
2650override an existing engage target.
2643
2651
2644- **Melee:** pathfind to an 8-neighbour tile, swing when Chebyshev distance is
2652- **Melee:** pathfind to an 8-neighbour tile, swing when Chebyshev distance is
2645 exactly 1.
2653 exactly 1.