BlueGit

timfa questward

Add Item Spawner: ground piles or openable wood containers.

World Editor lists Item Spawner first (chest preview). Config covers items,
respawn delay, range, appearance (item/chest/barrel/crate), wood material,
and door-like conditions. Runtime spawns ground items or tinted containers;
containers open with a 2s shove channel from an adjacent tile.

timfa Tim Falken · pushed by timfa

Authored 2026-09-14 · 2 months ago

Hash
4d19e1e5aba8402ad1feb2fa8de4165791068fcd
Parent
0cb4d413
16 files changed +1664 −31
client/src/editor/main.js +69 −24
@@ -21,6 +21,14 @@ import
21 21 import { loadGraphicsSettings } from "/shared/graphics/settings.js";
22 22 import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
23 23 import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
24 import
25 {
26 isItemSpawnerConfig,
27 defaultItemSpawnerConfig,
28 normalizeItemSpawnerConfig,
29 itemSpawnerPreviewSpriteName,
30 itemSpawnerContainerSpriteName
31 } from "/shared/definitions/itemSpawners.js";
24 32 import
25 33 {
26 34 computeNeighborConnectMask,
@@ -188,6 +196,8 @@ function selectedToolLabel ()
188 196 { return "Erase block"; }
189 197 if (tool.kind === "spawner")
190 198 {
199 if (tool.spawnerKind === "item" || isItemSpawnerConfig(tool))
200 { return "Spawner · Item Spawner"; }
191 201 const def = mobDefinition(tool.mobTypeId);
192 202 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
193 203 }
@@ -218,7 +228,10 @@ function selectTool (next)
218 228 }
219 229 if (next.kind === "spawner")
220 230 {
221 tool = { kind: "spawner", mobTypeId: next.mobTypeId };
231 if (next.spawnerKind === "item")
232 { tool = { kind: "spawner", spawnerKind: "item" }; }
233 else
234 { tool = { kind: "spawner", mobTypeId: next.mobTypeId }; }
222 235 return;
223 236 }
224 237 const layer = next.kind === "ground" ? "ground" : "block";
@@ -690,8 +703,13 @@ function describeWorldTile (tileX, tileY, dimensionId = selectedDimensionId)
690 703 if (spawner)
691 704 {
692 705 const config = normalizeSpawnerConfig(spawner.config, spawner.config?.spawnerId);
693 const mob = mobDefinition(config.mobTypeId);
694 lines.push(`Spawner: ${mob?.displayName ?? config.mobTypeId} (${config.spawnerId})`);
706 if (isItemSpawnerConfig(config))
707 { lines.push(`Spawner: Item Spawner (${config.spawnerId})`); }
708 else
709 {
710 const mob = mobDefinition(config.mobTypeId);
711 lines.push(`Spawner: ${mob?.displayName ?? config.mobTypeId} (${config.spawnerId})`);
712 }
695 713 }
696 714 else
697 715 { lines.push("Spawner: (none)"); }
@@ -1003,16 +1021,19 @@ function paintAt (localX, localY)
1003 1021 const existing = spawnerAt(localX, localY);
1004 1022 const spawnerId = existing?.config?.spawnerId
1005 1023 ?? `${normalizeDimensionId(selectedDimensionId)}:${chunkX}:${chunkY}:${index}`;
1006 const entry = {
1007 localX,
1008 localY,
1009 config: normalizeSpawnerConfig({
1024 const config = tool.spawnerKind === "item"
1025 ? normalizeItemSpawnerConfig({
1026 ...defaultItemSpawnerConfig(spawnerId),
1027 ...(isItemSpawnerConfig(existing?.config) ? existing.config : {}),
1028 spawnerId
1029 }, spawnerId)
1030 : normalizeSpawnerConfig({
1010 1031 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
1011 ...(existing?.config ?? {}),
1032 ...(existing?.config && !isItemSpawnerConfig(existing.config) ? existing.config : {}),
1012 1033 spawnerId,
1013 1034 mobTypeId: tool.mobTypeId
1014 }, spawnerId)
1015 };
1035 }, spawnerId);
1036 const entry = { localX, localY, config };
1016 1037 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
1017 1038 draft.spawners.push(entry);
1018 1039 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
@@ -1388,18 +1409,36 @@ function updateTooltip (local, options = {})
1388 1409 if (spawner)
1389 1410 {
1390 1411 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
1391 const mob = mobDefinition(config.mobTypeId);
1392 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
1393 lines.push(`maxAlive: ${config.maxAlive}`);
1394 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
1395 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
1396 lines.push(`id: ${config.spawnerId}`);
1397 view.setSpawnRangeHighlight(
1398 local.tileX,
1399 local.tileY,
1400 config.spawnRangeTiles,
1401 config.maxWanderRangeTiles
1402 );
1412 if (isItemSpawnerConfig(config))
1413 {
1414 lines.push("Spawner · Item Spawner");
1415 lines.push(`appearance: ${config.appearance}`);
1416 lines.push(`items: ${(config.items ?? []).length}`);
1417 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
1418 lines.push(`respawn: ${config.respawnDelaySeconds}s`);
1419 lines.push(`id: ${config.spawnerId}`);
1420 view.setSpawnRangeHighlight(
1421 local.tileX,
1422 local.tileY,
1423 config.spawnRangeTiles,
1424 config.spawnRangeTiles
1425 );
1426 }
1427 else
1428 {
1429 const mob = mobDefinition(config.mobTypeId);
1430 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
1431 lines.push(`maxAlive: ${config.maxAlive}`);
1432 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
1433 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
1434 lines.push(`id: ${config.spawnerId}`);
1435 view.setSpawnRangeHighlight(
1436 local.tileX,
1437 local.tileY,
1438 config.spawnRangeTiles,
1439 config.maxWanderRangeTiles
1440 );
1441 }
1403 1442 }
1404 1443 else
1405 1444 { view.clearSpawnRangeHighlight(); }
@@ -1958,6 +1997,8 @@ function collectEditorSpawners ()
1958 1997 for (const entry of spawners ?? [])
1959 1998 {
1960 1999 const config = normalizeSpawnerConfig(entry.config, entry.config?.spawnerId);
2000 if (isItemSpawnerConfig(config))
2001 { continue; }
1961 2002 add({
1962 2003 spawnerId: config.spawnerId,
1963 2004 mobTypeId: config.mobTypeId,
@@ -2333,13 +2374,17 @@ document.addEventListener("contextmenu", (event) =>
2333 2374 const spawner = spawnerAt(localX, localY);
2334 2375 if (spawner)
2335 2376 {
2336 tileConfigModal.openSpawner({
2377 const ctx = {
2337 2378 localX,
2338 2379 localY,
2339 2380 tileX: tile.tileX,
2340 2381 tileY: tile.tileY,
2341 2382 config: { ...spawner.config }
2342 });
2383 };
2384 if (isItemSpawnerConfig(spawner.config))
2385 { tileConfigModal.openItemSpawner(ctx); }
2386 else
2387 { tileConfigModal.openSpawner(ctx); }
2343 2388 return;
2344 2389 }
2345 2390 const index = localY * CHUNK_SIZE + localX;
@@ -21,6 +21,14 @@ import
21import { loadGraphicsSettings } from "/shared/graphics/settings.js";
21import { loadGraphicsSettings } from "/shared/graphics/settings.js";
22import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
22import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
23import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
23import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
24import
25 {
26 isItemSpawnerConfig,
27 defaultItemSpawnerConfig,
28 normalizeItemSpawnerConfig,
29 itemSpawnerPreviewSpriteName,
30 itemSpawnerContainerSpriteName
31 } from "/shared/definitions/itemSpawners.js";
24import
32import
25{
33{
26 computeNeighborConnectMask,
34 computeNeighborConnectMask,
@@ -188,6 +196,8 @@ function selectedToolLabel ()
188 { return "Erase block"; }
196 { return "Erase block"; }
189 if (tool.kind === "spawner")
197 if (tool.kind === "spawner")
190 {
198 {
199 if (tool.spawnerKind === "item" || isItemSpawnerConfig(tool))
200 { return "Spawner · Item Spawner"; }
191 const def = mobDefinition(tool.mobTypeId);
201 const def = mobDefinition(tool.mobTypeId);
192 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
202 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
193 }
203 }
@@ -218,7 +228,10 @@ function selectTool (next)
218 }
228 }
219 if (next.kind === "spawner")
229 if (next.kind === "spawner")
220 {
230 {
221 tool = { kind: "spawner", mobTypeId: next.mobTypeId };
231 if (next.spawnerKind === "item")
232 { tool = { kind: "spawner", spawnerKind: "item" }; }
233 else
234 { tool = { kind: "spawner", mobTypeId: next.mobTypeId }; }
222 return;
235 return;
223 }
236 }
224 const layer = next.kind === "ground" ? "ground" : "block";
237 const layer = next.kind === "ground" ? "ground" : "block";
@@ -690,8 +703,13 @@ function describeWorldTile (tileX, tileY, dimensionId = selectedDimensionId)
690 if (spawner)
703 if (spawner)
691 {
704 {
692 const config = normalizeSpawnerConfig(spawner.config, spawner.config?.spawnerId);
705 const config = normalizeSpawnerConfig(spawner.config, spawner.config?.spawnerId);
693 const mob = mobDefinition(config.mobTypeId);
706 if (isItemSpawnerConfig(config))
694 lines.push(`Spawner: ${mob?.displayName ?? config.mobTypeId} (${config.spawnerId})`);
707 { lines.push(`Spawner: Item Spawner (${config.spawnerId})`); }
708 else
709 {
710 const mob = mobDefinition(config.mobTypeId);
711 lines.push(`Spawner: ${mob?.displayName ?? config.mobTypeId} (${config.spawnerId})`);
712 }
695 }
713 }
696 else
714 else
697 { lines.push("Spawner: (none)"); }
715 { lines.push("Spawner: (none)"); }
@@ -1003,16 +1021,19 @@ function paintAt (localX, localY)
1003 const existing = spawnerAt(localX, localY);
1021 const existing = spawnerAt(localX, localY);
1004 const spawnerId = existing?.config?.spawnerId
1022 const spawnerId = existing?.config?.spawnerId
1005 ?? `${normalizeDimensionId(selectedDimensionId)}:${chunkX}:${chunkY}:${index}`;
1023 ?? `${normalizeDimensionId(selectedDimensionId)}:${chunkX}:${chunkY}:${index}`;
1006 const entry = {
1024 const config = tool.spawnerKind === "item"
1007 localX,
1025 ? normalizeItemSpawnerConfig({
1008 localY,
1026 ...defaultItemSpawnerConfig(spawnerId),
1009 config: normalizeSpawnerConfig({
1027 ...(isItemSpawnerConfig(existing?.config) ? existing.config : {}),
1028 spawnerId
1029 }, spawnerId)
1030 : normalizeSpawnerConfig({
1010 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
1031 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
1011 ...(existing?.config ?? {}),
1032 ...(existing?.config && !isItemSpawnerConfig(existing.config) ? existing.config : {}),
1012 spawnerId,
1033 spawnerId,
1013 mobTypeId: tool.mobTypeId
1034 mobTypeId: tool.mobTypeId
1014 }, spawnerId)
1035 }, spawnerId);
1015 };
1036 const entry = { localX, localY, config };
1016 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
1037 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
1017 draft.spawners.push(entry);
1038 draft.spawners.push(entry);
1018 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1039 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
@@ -1388,18 +1409,36 @@ function updateTooltip (local, options = {})
1388 if (spawner)
1409 if (spawner)
1389 {
1410 {
1390 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
1411 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
1391 const mob = mobDefinition(config.mobTypeId);
1412 if (isItemSpawnerConfig(config))
1392 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
1413 {
1393 lines.push(`maxAlive: ${config.maxAlive}`);
1414 lines.push("Spawner · Item Spawner");
1394 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
1415 lines.push(`appearance: ${config.appearance}`);
1395 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
1416 lines.push(`items: ${(config.items ?? []).length}`);
1396 lines.push(`id: ${config.spawnerId}`);
1417 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
1397 view.setSpawnRangeHighlight(
1418 lines.push(`respawn: ${config.respawnDelaySeconds}s`);
1398 local.tileX,
1419 lines.push(`id: ${config.spawnerId}`);
1399 local.tileY,
1420 view.setSpawnRangeHighlight(
1400 config.spawnRangeTiles,
1421 local.tileX,
1401 config.maxWanderRangeTiles
1422 local.tileY,
1402 );
1423 config.spawnRangeTiles,
1424 config.spawnRangeTiles
1425 );
1426 }
1427 else
1428 {
1429 const mob = mobDefinition(config.mobTypeId);
1430 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
1431 lines.push(`maxAlive: ${config.maxAlive}`);
1432 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
1433 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
1434 lines.push(`id: ${config.spawnerId}`);
1435 view.setSpawnRangeHighlight(
1436 local.tileX,
1437 local.tileY,
1438 config.spawnRangeTiles,
1439 config.maxWanderRangeTiles
1440 );
1441 }
1403 }
1442 }
1404 else
1443 else
1405 { view.clearSpawnRangeHighlight(); }
1444 { view.clearSpawnRangeHighlight(); }
@@ -1958,6 +1997,8 @@ function collectEditorSpawners ()
1958 for (const entry of spawners ?? [])
1997 for (const entry of spawners ?? [])
1959 {
1998 {
1960 const config = normalizeSpawnerConfig(entry.config, entry.config?.spawnerId);
1999 const config = normalizeSpawnerConfig(entry.config, entry.config?.spawnerId);
2000 if (isItemSpawnerConfig(config))
2001 { continue; }
1961 add({
2002 add({
1962 spawnerId: config.spawnerId,
2003 spawnerId: config.spawnerId,
1963 mobTypeId: config.mobTypeId,
2004 mobTypeId: config.mobTypeId,
@@ -2333,13 +2374,17 @@ document.addEventListener("contextmenu", (event) =>
2333 const spawner = spawnerAt(localX, localY);
2374 const spawner = spawnerAt(localX, localY);
2334 if (spawner)
2375 if (spawner)
2335 {
2376 {
2336 tileConfigModal.openSpawner({
2377 const ctx = {
2337 localX,
2378 localX,
2338 localY,
2379 localY,
2339 tileX: tile.tileX,
2380 tileX: tile.tileX,
2340 tileY: tile.tileY,
2381 tileY: tile.tileY,
2341 config: { ...spawner.config }
2382 config: { ...spawner.config }
2342 });
2383 };
2384 if (isItemSpawnerConfig(spawner.config))
2385 { tileConfigModal.openItemSpawner(ctx); }
2386 else
2387 { tileConfigModal.openSpawner(ctx); }
2343 return;
2388 return;
2344 }
2389 }
2345 const index = localY * CHUNK_SIZE + localX;
2390 const index = localY * CHUNK_SIZE + localX;
client/src/editor/paletteModal.js +14 −0
@@ -1,6 +1,7 @@
1 1 import { listPlaceableGrounds, listPlaceableBlockPaletteEntries } from "/shared/definitions/tiles.js";
2 2 import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";
3 3 import { defaultStateForType, resolveState, spriteImageName, palettePreviewImageName } from "/shared/definitions/tileSprites.js";
4 import { itemSpawnerPreviewSpriteName } from "/shared/definitions/itemSpawners.js";
4 5
5 6 /**
6 7 * Select-tool modal: Ground / Blocks / Spawners, auto-built from definitions.
@@ -114,6 +115,19 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
114 115 }
115 116 else
116 117 {
118 if (matchesSearch("Item Spawner"))
119 {
120 shown += 1;
121 grid.append(tileCard({
122 label: "Item Spawner",
123 url: imageUrlFor?.(itemSpawnerPreviewSpriteName()),
124 onClick ()
125 {
126 onSelect({ kind: "spawner", spawnerKind: "item" });
127 show(false);
128 }
129 }));
130 }
117 131 for (const def of listSpawnableMobTypes())
118 132 {
119 133 if (!matchesSearch(def.displayName))
@@ -1,6 +1,7 @@
1import { listPlaceableGrounds, listPlaceableBlockPaletteEntries } from "/shared/definitions/tiles.js";
1import { listPlaceableGrounds, listPlaceableBlockPaletteEntries } from "/shared/definitions/tiles.js";
2import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";
2import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";
3import { defaultStateForType, resolveState, spriteImageName, palettePreviewImageName } from "/shared/definitions/tileSprites.js";
3import { defaultStateForType, resolveState, spriteImageName, palettePreviewImageName } from "/shared/definitions/tileSprites.js";
4import { itemSpawnerPreviewSpriteName } from "/shared/definitions/itemSpawners.js";
4
5
5/**
6/**
6 * Select-tool modal: Ground / Blocks / Spawners, auto-built from definitions.
7 * Select-tool modal: Ground / Blocks / Spawners, auto-built from definitions.
@@ -114,6 +115,19 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
114 }
115 }
115 else
116 else
116 {
117 {
118 if (matchesSearch("Item Spawner"))
119 {
120 shown += 1;
121 grid.append(tileCard({
122 label: "Item Spawner",
123 url: imageUrlFor?.(itemSpawnerPreviewSpriteName()),
124 onClick ()
125 {
126 onSelect({ kind: "spawner", spawnerKind: "item" });
127 show(false);
128 }
129 }));
130 }
117 for (const def of listSpawnableMobTypes())
131 for (const def of listSpawnableMobTypes())
118 {
132 {
119 if (!matchesSearch(def.displayName))
133 if (!matchesSearch(def.displayName))
client/src/editor/tileConfigModal.js +228 −0
@@ -24,6 +24,18 @@ import { createDimensionCombobox } from "./dimensionCombobox.js";
24 24 import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
25 25 import { renderConditionSet, emptyConditionSet, normalizeConditionSet } from "./conditionSetEditor.js";
26 26 import { DEFAULT_DOOR_BLOCKED_MESSAGE } from "/shared/world/doorRequirements.js";
27 import
28 {
29 isItemSpawnerConfig,
30 normalizeItemSpawnerConfig,
31 defaultItemSpawnerConfig,
32 ItemSpawnerAppearance,
33 ITEM_SPAWNER_APPEARANCES,
34 ITEM_SPAWNER_CONTAINER_APPEARANCES,
35 isItemSpawnerContainerAppearance,
36 listItemSpawnerMaterials,
37 ITEM_SPAWNER_LOCKED_MESSAGE
38 } from "/shared/definitions/itemSpawners.js";
27 39
28 40 const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]);
29 41 const ITEM_SEARCH_PAGE_SIZE = 40;
@@ -154,6 +166,8 @@ export function initTileConfigModal ({
154 166 let open = false;
155 167 let context = null;
156 168 /** @type {{ itemId: number, quantity: number }[]} */
169 let itemSpawnerItemsDraft = [];
170 let itemSpawnerWhenDraft = emptyConditionSet();
157 171 let sellsDraft = [];
158 172 /** @type {{ itemId: number, chancePercent: number, quantityMin: number, quantityMax: number }[]} */
159 173 let dropsDraft = [];
@@ -226,6 +240,12 @@ export function initTileConfigModal ({
226 240 openItemSearch("Add fish to spot");
227 241 }
228 242
243 function openItemSpawnerItemsSearch ()
244 {
245 itemSearchMode = { kind: "item-spawner-items" };
246 openItemSearch("Add item to spawner");
247 }
248
229 249 function openEquipItemSearch (slot)
230 250 {
231 251 itemSearchMode = { kind: "equip", slot };
@@ -361,6 +381,12 @@ export function initTileConfigModal ({
361 381 });
362 382 renderDropsList();
363 383 }
384 else if (itemSearchMode?.kind === "item-spawner-items")
385 {
386 itemSpawnerItemsDraft.push({ itemId: item.itemId, quantity: 1 });
387 renderItemSpawnerItemsList();
388 syncItemSpawnerAppearanceGates();
389 }
364 390 else
365 391 {
366 392 sellsDraft.push({ itemId: item.itemId, quantity: 0 });
@@ -1137,6 +1163,182 @@ export function initTileConfigModal ({
1137 1163 show(true);
1138 1164 }
1139 1165
1166
1167 function renderItemSpawnerItemsList ()
1168 {
1169 const list = form.querySelector("[data-item-spawner-items]");
1170 if (!list)
1171 { return; }
1172 list.innerHTML = "";
1173 if (!itemSpawnerItemsDraft.length)
1174 {
1175 const empty = document.createElement("p");
1176 empty.className = "hint";
1177 empty.textContent = "No items yet. Use + to choose what this spawner creates.";
1178 list.append(empty);
1179 return;
1180 }
1181 for (let index = 0; index < itemSpawnerItemsDraft.length; index++)
1182 {
1183 const line = itemSpawnerItemsDraft[index];
1184 const def = itemDefinition(line.itemId);
1185 const row = document.createElement("div");
1186 row.className = "spawner-sells-row";
1187 const name = document.createElement("span");
1188 name.className = "spawner-sells-name";
1189 name.textContent = def?.displayName ?? `Item ${line.itemId}`;
1190 const qty = document.createElement("input");
1191 qty.type = "number";
1192 qty.min = "1";
1193 qty.step = "1";
1194 qty.value = String(Math.max(1, line.quantity | 0));
1195 qty.title = "Stack quantity";
1196 qty.addEventListener("input", () =>
1197 {
1198 itemSpawnerItemsDraft[index].quantity = Math.max(1, Number(qty.value) || 1) | 0;
1199 });
1200 const remove = document.createElement("button");
1201 remove.type = "button";
1202 remove.textContent = "Remove";
1203 remove.addEventListener("click", () =>
1204 {
1205 itemSpawnerItemsDraft.splice(index, 1);
1206 renderItemSpawnerItemsList();
1207 syncItemSpawnerAppearanceGates();
1208 });
1209 row.append(name, qty, remove);
1210 list.append(row);
1211 }
1212 }
1213
1214 function syncItemSpawnerAppearanceGates ()
1215 {
1216 const appearanceSelect = form.querySelector('[name="appearance"]');
1217 const materialField = form.querySelector("[data-item-spawner-material]");
1218 const conditionHost = form.querySelector("[data-item-spawner-condition]");
1219 if (!appearanceSelect)
1220 { return; }
1221 const stackCount = itemSpawnerItemsDraft.length;
1222 const itemOpt = appearanceSelect.querySelector('option[value="item"]');
1223 if (itemOpt)
1224 { itemOpt.disabled = stackCount !== 1; }
1225 if (appearanceSelect.value === "item" && stackCount !== 1)
1226 {
1227 appearanceSelect.value = ItemSpawnerAppearance.chest;
1228 }
1229 const appearance = appearanceSelect.value;
1230 const isContainer = isItemSpawnerContainerAppearance(appearance);
1231 if (materialField)
1232 { materialField.hidden = !isContainer; }
1233 if (conditionHost)
1234 { conditionHost.hidden = !isContainer; }
1235 }
1236
1237 function openItemSpawner (ctx)
1238 {
1239 context = { kind: "item-spawner", ...ctx };
1240 const config = normalizeItemSpawnerConfig(ctx.config, ctx.config?.spawnerId);
1241 itemSpawnerItemsDraft = (config.items ?? []).map((line) => ({
1242 itemId: line.itemId,
1243 quantity: Math.max(1, line.quantity | 0)
1244 }));
1245 itemSpawnerWhenDraft = normalizeConditionSet(config.when ?? emptyConditionSet());
1246 title.textContent = `Item Spawner · ${ctx.tileX}, ${ctx.tileY}`;
1247 if (socket && MessageType)
1248 {
1249 socket.send({ type: MessageType.editorLoadQuests });
1250 socket.send({ type: MessageType.editorLoadDialogues });
1251 }
1252 form.innerHTML = "";
1253
1254 const itemsHeader = document.createElement("div");
1255 itemsHeader.className = "spawner-sells-header";
1256 const itemsLabel = document.createElement("strong");
1257 itemsLabel.textContent = "Items";
1258 const addBtn = document.createElement("button");
1259 addBtn.type = "button";
1260 addBtn.textContent = "+";
1261 addBtn.title = "Add item";
1262 addBtn.addEventListener("click", () => openItemSpawnerItemsSearch());
1263 itemsHeader.append(itemsLabel, addBtn);
1264 const itemsList = document.createElement("div");
1265 itemsList.setAttribute("data-item-spawner-items", "");
1266 form.append(itemsHeader, itemsList);
1267
1268 form.append(
1269 field("Respawn time (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)),
1270 field("Range", numberInput("spawnRangeTiles", config.spawnRangeTiles ?? 0, 0, 32)),
1271 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
1272 );
1273
1274 const appearanceSelect = document.createElement("select");
1275 appearanceSelect.name = "appearance";
1276 const appearanceLabels = {
1277 [ItemSpawnerAppearance.item]: "Item",
1278 [ItemSpawnerAppearance.chest]: "Chest",
1279 [ItemSpawnerAppearance.barrel]: "Barrel",
1280 [ItemSpawnerAppearance.crate]: "Crate"
1281 };
1282 for (const value of ITEM_SPAWNER_APPEARANCES)
1283 {
1284 const opt = document.createElement("option");
1285 opt.value = value;
1286 opt.textContent = appearanceLabels[value] ?? value;
1287 if (value === config.appearance)
1288 { opt.selected = true; }
1289 appearanceSelect.append(opt);
1290 }
1291 appearanceSelect.addEventListener("change", () => syncItemSpawnerAppearanceGates());
1292 form.append(field("Appearance", appearanceSelect));
1293
1294 const materialWrap = document.createElement("div");
1295 materialWrap.setAttribute("data-item-spawner-material", "");
1296 const materialSelect = document.createElement("select");
1297 materialSelect.name = "material";
1298 for (const row of listItemSpawnerMaterials())
1299 {
1300 const opt = document.createElement("option");
1301 opt.value = row.id;
1302 opt.textContent = row.displayName;
1303 if (row.id === config.material)
1304 { opt.selected = true; }
1305 materialSelect.append(opt);
1306 }
1307 materialWrap.append(field("Material", materialSelect));
1308 form.append(materialWrap);
1309
1310 const conditionHost = document.createElement("div");
1311 conditionHost.setAttribute("data-item-spawner-condition", "");
1312 conditionHost.className = "door-requirements-when";
1313 const condHint = document.createElement("p");
1314 condHint.className = "tile-config-hint";
1315 condHint.textContent = `Condition gates opening. Fail toast: "${ITEM_SPAWNER_LOCKED_MESSAGE}"`;
1316 conditionHost.append(condHint);
1317 const whenHost = document.createElement("div");
1318 conditionHost.append(whenHost);
1319 form.append(conditionHost);
1320 const remountWhen = () =>
1321 {
1322 whenHost.replaceChildren(renderConditionSet(itemSpawnerWhenDraft, (next, { remount = true } = {}) =>
1323 {
1324 itemSpawnerWhenDraft = normalizeConditionSet(next);
1325 if (remount)
1326 { remountWhen(); }
1327 }, {
1328 quests: typeof getQuests === "function" ? (getQuests() ?? []) : [],
1329 dialogues: typeof getDialogues === "function" ? (getDialogues() ?? []) : [],
1330 describeWorldTile,
1331 centerEditorOnTile,
1332 getDimensionOptions
1333 }));
1334 };
1335 remountWhen();
1336
1337 renderItemSpawnerItemsList();
1338 syncItemSpawnerAppearanceGates();
1339 show(true);
1340 }
1341
1140 1342 function openFishingSpot (ctx)
1141 1343 {
1142 1344 context = { kind: "fishing-spot", ...ctx };
@@ -1318,6 +1520,25 @@ export function initTileConfigModal ({
1318 1520 show(false);
1319 1521 return;
1320 1522 }
1523 if (context.kind === "item-spawner")
1524 {
1525 const data = new FormData(form);
1526 onSave?.(context, normalizeItemSpawnerConfig({
1527 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
1528 items: itemSpawnerItemsDraft,
1529 respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25),
1530 spawnRangeTiles: (() =>
1531 {
1532 const n = Number(data.get("spawnRangeTiles"));
1533 return Number.isFinite(n) ? n : 0;
1534 })(),
1535 appearance: String(data.get("appearance") || ItemSpawnerAppearance.chest),
1536 material: String(data.get("material") || "pine"),
1537 when: normalizeConditionSet(itemSpawnerWhenDraft)
1538 }, context.config.spawnerId));
1539 show(false);
1540 return;
1541 }
1321 1542 if (context.kind === "fishing-spot")
1322 1543 {
1323 1544 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
@@ -1386,6 +1607,12 @@ export function initTileConfigModal ({
1386 1607 if (!window.confirm(`Delete mob spawner "${label}"?`))
1387 1608 { return; }
1388 1609 }
1610 if (context.kind === "item-spawner")
1611 {
1612 const label = context.config?.spawnerId || "this item spawner";
1613 if (!window.confirm(`Delete item spawner "${label}"?`))
1614 { return; }
1615 }
1389 1616 onRemove?.(context);
1390 1617 show(false);
1391 1618 });
@@ -1393,6 +1620,7 @@ export function initTileConfigModal ({
1393 1620 return {
1394 1621 isOpen: () => open,
1395 1622 openSpawner,
1623 openItemSpawner,
1396 1624 openDoorway,
1397 1625 openDoor,
1398 1626 openFishingSpot,
@@ -24,6 +24,18 @@ import { createDimensionCombobox } from "./dimensionCombobox.js";
24import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
24import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
25import { renderConditionSet, emptyConditionSet, normalizeConditionSet } from "./conditionSetEditor.js";
25import { renderConditionSet, emptyConditionSet, normalizeConditionSet } from "./conditionSetEditor.js";
26import { DEFAULT_DOOR_BLOCKED_MESSAGE } from "/shared/world/doorRequirements.js";
26import { DEFAULT_DOOR_BLOCKED_MESSAGE } from "/shared/world/doorRequirements.js";
27import
28 {
29 isItemSpawnerConfig,
30 normalizeItemSpawnerConfig,
31 defaultItemSpawnerConfig,
32 ItemSpawnerAppearance,
33 ITEM_SPAWNER_APPEARANCES,
34 ITEM_SPAWNER_CONTAINER_APPEARANCES,
35 isItemSpawnerContainerAppearance,
36 listItemSpawnerMaterials,
37 ITEM_SPAWNER_LOCKED_MESSAGE
38 } from "/shared/definitions/itemSpawners.js";
27
39
28const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]);
40const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]);
29const ITEM_SEARCH_PAGE_SIZE = 40;
41const ITEM_SEARCH_PAGE_SIZE = 40;
@@ -154,6 +166,8 @@ export function initTileConfigModal ({
154 let open = false;
166 let open = false;
155 let context = null;
167 let context = null;
156 /** @type {{ itemId: number, quantity: number }[]} */
168 /** @type {{ itemId: number, quantity: number }[]} */
169 let itemSpawnerItemsDraft = [];
170 let itemSpawnerWhenDraft = emptyConditionSet();
157 let sellsDraft = [];
171 let sellsDraft = [];
158 /** @type {{ itemId: number, chancePercent: number, quantityMin: number, quantityMax: number }[]} */
172 /** @type {{ itemId: number, chancePercent: number, quantityMin: number, quantityMax: number }[]} */
159 let dropsDraft = [];
173 let dropsDraft = [];
@@ -226,6 +240,12 @@ export function initTileConfigModal ({
226 openItemSearch("Add fish to spot");
240 openItemSearch("Add fish to spot");
227 }
241 }
228
242
243 function openItemSpawnerItemsSearch ()
244 {
245 itemSearchMode = { kind: "item-spawner-items" };
246 openItemSearch("Add item to spawner");
247 }
248
229 function openEquipItemSearch (slot)
249 function openEquipItemSearch (slot)
230 {
250 {
231 itemSearchMode = { kind: "equip", slot };
251 itemSearchMode = { kind: "equip", slot };
@@ -361,6 +381,12 @@ export function initTileConfigModal ({
361 });
381 });
362 renderDropsList();
382 renderDropsList();
363 }
383 }
384 else if (itemSearchMode?.kind === "item-spawner-items")
385 {
386 itemSpawnerItemsDraft.push({ itemId: item.itemId, quantity: 1 });
387 renderItemSpawnerItemsList();
388 syncItemSpawnerAppearanceGates();
389 }
364 else
390 else
365 {
391 {
366 sellsDraft.push({ itemId: item.itemId, quantity: 0 });
392 sellsDraft.push({ itemId: item.itemId, quantity: 0 });
@@ -1137,6 +1163,182 @@ export function initTileConfigModal ({
1137 show(true);
1163 show(true);
1138 }
1164 }
1139
1165
1166
1167 function renderItemSpawnerItemsList ()
1168 {
1169 const list = form.querySelector("[data-item-spawner-items]");
1170 if (!list)
1171 { return; }
1172 list.innerHTML = "";
1173 if (!itemSpawnerItemsDraft.length)
1174 {
1175 const empty = document.createElement("p");
1176 empty.className = "hint";
1177 empty.textContent = "No items yet. Use + to choose what this spawner creates.";
1178 list.append(empty);
1179 return;
1180 }
1181 for (let index = 0; index < itemSpawnerItemsDraft.length; index++)
1182 {
1183 const line = itemSpawnerItemsDraft[index];
1184 const def = itemDefinition(line.itemId);
1185 const row = document.createElement("div");
1186 row.className = "spawner-sells-row";
1187 const name = document.createElement("span");
1188 name.className = "spawner-sells-name";
1189 name.textContent = def?.displayName ?? `Item ${line.itemId}`;
1190 const qty = document.createElement("input");
1191 qty.type = "number";
1192 qty.min = "1";
1193 qty.step = "1";
1194 qty.value = String(Math.max(1, line.quantity | 0));
1195 qty.title = "Stack quantity";
1196 qty.addEventListener("input", () =>
1197 {
1198 itemSpawnerItemsDraft[index].quantity = Math.max(1, Number(qty.value) || 1) | 0;
1199 });
1200 const remove = document.createElement("button");
1201 remove.type = "button";
1202 remove.textContent = "Remove";
1203 remove.addEventListener("click", () =>
1204 {
1205 itemSpawnerItemsDraft.splice(index, 1);
1206 renderItemSpawnerItemsList();
1207 syncItemSpawnerAppearanceGates();
1208 });
1209 row.append(name, qty, remove);
1210 list.append(row);
1211 }
1212 }
1213
1214 function syncItemSpawnerAppearanceGates ()
1215 {
1216 const appearanceSelect = form.querySelector('[name="appearance"]');
1217 const materialField = form.querySelector("[data-item-spawner-material]");
1218 const conditionHost = form.querySelector("[data-item-spawner-condition]");
1219 if (!appearanceSelect)
1220 { return; }
1221 const stackCount = itemSpawnerItemsDraft.length;
1222 const itemOpt = appearanceSelect.querySelector('option[value="item"]');
1223 if (itemOpt)
1224 { itemOpt.disabled = stackCount !== 1; }
1225 if (appearanceSelect.value === "item" && stackCount !== 1)
1226 {
1227 appearanceSelect.value = ItemSpawnerAppearance.chest;
1228 }
1229 const appearance = appearanceSelect.value;
1230 const isContainer = isItemSpawnerContainerAppearance(appearance);
1231 if (materialField)
1232 { materialField.hidden = !isContainer; }
1233 if (conditionHost)
1234 { conditionHost.hidden = !isContainer; }
1235 }
1236
1237 function openItemSpawner (ctx)
1238 {
1239 context = { kind: "item-spawner", ...ctx };
1240 const config = normalizeItemSpawnerConfig(ctx.config, ctx.config?.spawnerId);
1241 itemSpawnerItemsDraft = (config.items ?? []).map((line) => ({
1242 itemId: line.itemId,
1243 quantity: Math.max(1, line.quantity | 0)
1244 }));
1245 itemSpawnerWhenDraft = normalizeConditionSet(config.when ?? emptyConditionSet());
1246 title.textContent = `Item Spawner · ${ctx.tileX}, ${ctx.tileY}`;
1247 if (socket && MessageType)
1248 {
1249 socket.send({ type: MessageType.editorLoadQuests });
1250 socket.send({ type: MessageType.editorLoadDialogues });
1251 }
1252 form.innerHTML = "";
1253
1254 const itemsHeader = document.createElement("div");
1255 itemsHeader.className = "spawner-sells-header";
1256 const itemsLabel = document.createElement("strong");
1257 itemsLabel.textContent = "Items";
1258 const addBtn = document.createElement("button");
1259 addBtn.type = "button";
1260 addBtn.textContent = "+";
1261 addBtn.title = "Add item";
1262 addBtn.addEventListener("click", () => openItemSpawnerItemsSearch());
1263 itemsHeader.append(itemsLabel, addBtn);
1264 const itemsList = document.createElement("div");
1265 itemsList.setAttribute("data-item-spawner-items", "");
1266 form.append(itemsHeader, itemsList);
1267
1268 form.append(
1269 field("Respawn time (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)),
1270 field("Range", numberInput("spawnRangeTiles", config.spawnRangeTiles ?? 0, 0, 32)),
1271 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
1272 );
1273
1274 const appearanceSelect = document.createElement("select");
1275 appearanceSelect.name = "appearance";
1276 const appearanceLabels = {
1277 [ItemSpawnerAppearance.item]: "Item",
1278 [ItemSpawnerAppearance.chest]: "Chest",
1279 [ItemSpawnerAppearance.barrel]: "Barrel",
1280 [ItemSpawnerAppearance.crate]: "Crate"
1281 };
1282 for (const value of ITEM_SPAWNER_APPEARANCES)
1283 {
1284 const opt = document.createElement("option");
1285 opt.value = value;
1286 opt.textContent = appearanceLabels[value] ?? value;
1287 if (value === config.appearance)
1288 { opt.selected = true; }
1289 appearanceSelect.append(opt);
1290 }
1291 appearanceSelect.addEventListener("change", () => syncItemSpawnerAppearanceGates());
1292 form.append(field("Appearance", appearanceSelect));
1293
1294 const materialWrap = document.createElement("div");
1295 materialWrap.setAttribute("data-item-spawner-material", "");
1296 const materialSelect = document.createElement("select");
1297 materialSelect.name = "material";
1298 for (const row of listItemSpawnerMaterials())
1299 {
1300 const opt = document.createElement("option");
1301 opt.value = row.id;
1302 opt.textContent = row.displayName;
1303 if (row.id === config.material)
1304 { opt.selected = true; }
1305 materialSelect.append(opt);
1306 }
1307 materialWrap.append(field("Material", materialSelect));
1308 form.append(materialWrap);
1309
1310 const conditionHost = document.createElement("div");
1311 conditionHost.setAttribute("data-item-spawner-condition", "");
1312 conditionHost.className = "door-requirements-when";
1313 const condHint = document.createElement("p");
1314 condHint.className = "tile-config-hint";
1315 condHint.textContent = `Condition gates opening. Fail toast: "${ITEM_SPAWNER_LOCKED_MESSAGE}"`;
1316 conditionHost.append(condHint);
1317 const whenHost = document.createElement("div");
1318 conditionHost.append(whenHost);
1319 form.append(conditionHost);
1320 const remountWhen = () =>
1321 {
1322 whenHost.replaceChildren(renderConditionSet(itemSpawnerWhenDraft, (next, { remount = true } = {}) =>
1323 {
1324 itemSpawnerWhenDraft = normalizeConditionSet(next);
1325 if (remount)
1326 { remountWhen(); }
1327 }, {
1328 quests: typeof getQuests === "function" ? (getQuests() ?? []) : [],
1329 dialogues: typeof getDialogues === "function" ? (getDialogues() ?? []) : [],
1330 describeWorldTile,
1331 centerEditorOnTile,
1332 getDimensionOptions
1333 }));
1334 };
1335 remountWhen();
1336
1337 renderItemSpawnerItemsList();
1338 syncItemSpawnerAppearanceGates();
1339 show(true);
1340 }
1341
1140 function openFishingSpot (ctx)
1342 function openFishingSpot (ctx)
1141 {
1343 {
1142 context = { kind: "fishing-spot", ...ctx };
1344 context = { kind: "fishing-spot", ...ctx };
@@ -1318,6 +1520,25 @@ export function initTileConfigModal ({
1318 show(false);
1520 show(false);
1319 return;
1521 return;
1320 }
1522 }
1523 if (context.kind === "item-spawner")
1524 {
1525 const data = new FormData(form);
1526 onSave?.(context, normalizeItemSpawnerConfig({
1527 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
1528 items: itemSpawnerItemsDraft,
1529 respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25),
1530 spawnRangeTiles: (() =>
1531 {
1532 const n = Number(data.get("spawnRangeTiles"));
1533 return Number.isFinite(n) ? n : 0;
1534 })(),
1535 appearance: String(data.get("appearance") || ItemSpawnerAppearance.chest),
1536 material: String(data.get("material") || "pine"),
1537 when: normalizeConditionSet(itemSpawnerWhenDraft)
1538 }, context.config.spawnerId));
1539 show(false);
1540 return;
1541 }
1321 if (context.kind === "fishing-spot")
1542 if (context.kind === "fishing-spot")
1322 {
1543 {
1323 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
1544 onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
@@ -1386,6 +1607,12 @@ export function initTileConfigModal ({
1386 if (!window.confirm(`Delete mob spawner "${label}"?`))
1607 if (!window.confirm(`Delete mob spawner "${label}"?`))
1387 { return; }
1608 { return; }
1388 }
1609 }
1610 if (context.kind === "item-spawner")
1611 {
1612 const label = context.config?.spawnerId || "this item spawner";
1613 if (!window.confirm(`Delete item spawner "${label}"?`))
1614 { return; }
1615 }
1389 onRemove?.(context);
1616 onRemove?.(context);
1390 show(false);
1617 show(false);
1391 });
1618 });
@@ -1393,6 +1620,7 @@ export function initTileConfigModal ({
1393 return {
1620 return {
1394 isOpen: () => open,
1621 isOpen: () => open,
1395 openSpawner,
1622 openSpawner,
1623 openItemSpawner,
1396 openDoorway,
1624 openDoorway,
1397 openDoor,
1625 openDoor,
1398 openFishingSpot,
1626 openFishingSpot,
client/src/play/main.js +61 −1
@@ -22,6 +22,7 @@ import { initStamina } from "./stamina.js";
22 22 import { initHealth } from "./health.js";
23 23 import { initStatusEffects } from "./statusEffects.js";
24 24 import { initContextMenu } from "./contextMenu.js";
25 import { itemSpawnerOpenLabel } from "/shared/definitions/itemSpawners.js";
25 26 import { initDeath } from "./death.js";
26 27 import { initToasts } from "./toasts.js";
27 28 import { initTrade } from "./trade.js";
@@ -670,6 +671,25 @@ function requestStartFire (ground)
670 671 { approachAdjacentTile(ground.tileX, ground.tileY); }
671 672 }
672 673
674 function requestOpenItemContainer (container)
675 {
676 if (!container)
677 { return; }
678 clearAllPendingActions();
679 pendingInteract = {
680 kind: "open-item-container",
681 containerId: container.containerId,
682 tileX: container.tileX,
683 tileY: container.tileY
684 };
685 const local = view?.entities.get(view.localEntityId);
686 if (local && isAdjacentTile(local.tileX, local.tileY, container.tileX, container.tileY)
687 && !(local.tileX === container.tileX && local.tileY === container.tileY))
688 { flushPendingInteract(); }
689 else
690 { approachAdjacentTile(container.tileX, container.tileY); }
691 }
692
673 693 function requestDebarkLog (ground)
674 694 {
675 695 if (!ground)
@@ -1178,6 +1198,25 @@ function flushPendingInteract ()
1178 1198 trade?.flushPendingAccept?.(invite);
1179 1199 return;
1180 1200 }
1201 if (pendingInteract.kind === "open-item-container")
1202 {
1203 if (local.tileX === pendingInteract.tileX && local.tileY === pendingInteract.tileY)
1204 {
1205 approachAdjacentTile(pendingInteract.tileX, pendingInteract.tileY);
1206 return;
1207 }
1208 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
1209 {
1210 approachAdjacentTile(pendingInteract.tileX, pendingInteract.tileY);
1211 return;
1212 }
1213 socket.send({
1214 type: MessageType.openItemContainer,
1215 containerId: pendingInteract.containerId
1216 });
1217 clearPendingInteract();
1218 return;
1219 }
1181 1220 if (pendingInteract.kind === "shear")
1182 1221 {
1183 1222 const target = view.entities.get(pendingInteract.targetEntityId);
@@ -1336,6 +1375,12 @@ function handleLeftClick (mouseX, mouseY)
1336 1375 return;
1337 1376 }
1338 1377
1378 const container = view.itemContainerAtTile?.(tile.tileX, tile.tileY);
1379 if (container)
1380 {
1381 requestOpenItemContainer(container);
1382 return;
1383 }
1339 1384 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
1340 1385 if (ground)
1341 1386 { requestPickup(ground); }
@@ -1517,6 +1562,15 @@ function handleRightClick (event, mouseX, mouseY)
1517 1562 { pushAttack(); }
1518 1563 }
1519 1564
1565 const container = view.itemContainerAtTile?.(tile.tileX, tile.tileY);
1566 if (container)
1567 {
1568 items.push({
1569 label: itemSpawnerOpenLabel(container.appearance),
1570 onSelect: () => requestOpenItemContainer(container)
1571 });
1572 }
1573
1520 1574 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
1521 1575 {
1522 1576 const name = groundLabel(ground);
@@ -2346,7 +2400,13 @@ async function main ()
2346 2400 case MessageType.entitySkull:
2347 2401 view?.updateEntitySkull(message.entityId, message.skullValue);
2348 2402 break;
2349 case MessageType.groundItemAppear:
2403 case MessageType.itemContainerAppear:
2404 view?.upsertItemContainer(message);
2405 break;
2406 case MessageType.itemContainerDespawn:
2407 view?.despawnItemContainer(message.containerId);
2408 break;
2409 case MessageType.groundItemAppear:
2350 2410 if (isForeignDimensionMessage(message))
2351 2411 { break; }
2352 2412 view?.upsertGroundItem(message);
@@ -22,6 +22,7 @@ import { initStamina } from "./stamina.js";
22import { initHealth } from "./health.js";
22import { initHealth } from "./health.js";
23import { initStatusEffects } from "./statusEffects.js";
23import { initStatusEffects } from "./statusEffects.js";
24import { initContextMenu } from "./contextMenu.js";
24import { initContextMenu } from "./contextMenu.js";
25import { itemSpawnerOpenLabel } from "/shared/definitions/itemSpawners.js";
25import { initDeath } from "./death.js";
26import { initDeath } from "./death.js";
26import { initToasts } from "./toasts.js";
27import { initToasts } from "./toasts.js";
27import { initTrade } from "./trade.js";
28import { initTrade } from "./trade.js";
@@ -670,6 +671,25 @@ function requestStartFire (ground)
670 { approachAdjacentTile(ground.tileX, ground.tileY); }
671 { approachAdjacentTile(ground.tileX, ground.tileY); }
671}
672}
672
673
674function requestOpenItemContainer (container)
675{
676 if (!container)
677 { return; }
678 clearAllPendingActions();
679 pendingInteract = {
680 kind: "open-item-container",
681 containerId: container.containerId,
682 tileX: container.tileX,
683 tileY: container.tileY
684 };
685 const local = view?.entities.get(view.localEntityId);
686 if (local && isAdjacentTile(local.tileX, local.tileY, container.tileX, container.tileY)
687 && !(local.tileX === container.tileX && local.tileY === container.tileY))
688 { flushPendingInteract(); }
689 else
690 { approachAdjacentTile(container.tileX, container.tileY); }
691}
692
673function requestDebarkLog (ground)
693function requestDebarkLog (ground)
674{
694{
675 if (!ground)
695 if (!ground)
@@ -1178,6 +1198,25 @@ function flushPendingInteract ()
1178 trade?.flushPendingAccept?.(invite);
1198 trade?.flushPendingAccept?.(invite);
1179 return;
1199 return;
1180 }
1200 }
1201 if (pendingInteract.kind === "open-item-container")
1202 {
1203 if (local.tileX === pendingInteract.tileX && local.tileY === pendingInteract.tileY)
1204 {
1205 approachAdjacentTile(pendingInteract.tileX, pendingInteract.tileY);
1206 return;
1207 }
1208 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
1209 {
1210 approachAdjacentTile(pendingInteract.tileX, pendingInteract.tileY);
1211 return;
1212 }
1213 socket.send({
1214 type: MessageType.openItemContainer,
1215 containerId: pendingInteract.containerId
1216 });
1217 clearPendingInteract();
1218 return;
1219 }
1181 if (pendingInteract.kind === "shear")
1220 if (pendingInteract.kind === "shear")
1182 {
1221 {
1183 const target = view.entities.get(pendingInteract.targetEntityId);
1222 const target = view.entities.get(pendingInteract.targetEntityId);
@@ -1336,6 +1375,12 @@ function handleLeftClick (mouseX, mouseY)
1336 return;
1375 return;
1337 }
1376 }
1338
1377
1378 const container = view.itemContainerAtTile?.(tile.tileX, tile.tileY);
1379 if (container)
1380 {
1381 requestOpenItemContainer(container);
1382 return;
1383 }
1339 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
1384 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
1340 if (ground)
1385 if (ground)
1341 { requestPickup(ground); }
1386 { requestPickup(ground); }
@@ -1517,6 +1562,15 @@ function handleRightClick (event, mouseX, mouseY)
1517 { pushAttack(); }
1562 { pushAttack(); }
1518 }
1563 }
1519
1564
1565 const container = view.itemContainerAtTile?.(tile.tileX, tile.tileY);
1566 if (container)
1567 {
1568 items.push({
1569 label: itemSpawnerOpenLabel(container.appearance),
1570 onSelect: () => requestOpenItemContainer(container)
1571 });
1572 }
1573
1520 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
1574 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
1521 {
1575 {
1522 const name = groundLabel(ground);
1576 const name = groundLabel(ground);
@@ -2346,7 +2400,13 @@ async function main ()
2346 case MessageType.entitySkull:
2400 case MessageType.entitySkull:
2347 view?.updateEntitySkull(message.entityId, message.skullValue);
2401 view?.updateEntitySkull(message.entityId, message.skullValue);
2348 break;
2402 break;
2349 case MessageType.groundItemAppear:
2403 case MessageType.itemContainerAppear:
2404 view?.upsertItemContainer(message);
2405 break;
2406 case MessageType.itemContainerDespawn:
2407 view?.despawnItemContainer(message.containerId);
2408 break;
2409case MessageType.groundItemAppear:
2350 if (isForeignDimensionMessage(message))
2410 if (isForeignDimensionMessage(message))
2351 { break; }
2411 { break; }
2352 view?.upsertGroundItem(message);
2412 view?.upsertGroundItem(message);
client/src/render/worldView.js +47 −0
@@ -18,6 +18,7 @@ import
18 18 } from "/shared/render/tint.js";
19 19 import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
20 20 import { normalizeSpawnerConfig } from "/shared/definitions/mobs.js";
21 import { isItemSpawnerConfig, itemSpawnerContainerSpriteName } from "/shared/definitions/itemSpawners.js";
21 22 import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
22 23 import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLavaGround, isLiquidWaterGround, isGroundPassable, isBlockPassable, groundLightOcclusion, LightOcclusion, blockDefinition, blockLightOcclusionForBlock, GroundType, GROUND_DEFINITIONS, fluidCoastContinues } from "/shared/definitions/tiles.js";
23 24 import { doorSortSubOrder, doorRestingState, isDoorTraversable } from "/shared/world/doors.js";
@@ -1130,6 +1131,7 @@ export class WorldView
1130 1131 this.bakedChunks = new Map();
1131 1132 this.tiles = new Map();
1132 1133 this.entities = new Map();
1134 this.itemContainers = new Map();
1133 1135 this.groundItems = new Map();
1134 1136 this.edges = new Map();
1135 1137 this.localEntityId = null;
@@ -1271,6 +1273,8 @@ export class WorldView
1271 1273 }
1272 1274 for (const [id] of [...this.groundItems.entries()])
1273 1275 { this.despawnGroundItem(id); }
1276 for (const [id] of [...this.itemContainers.entries()])
1277 { this.despawnItemContainer(id); }
1274 1278 for (const swipe of this.swipes)
1275 1279 { swipe.object?.destroy(); }
1276 1280 this.swipes = [];
@@ -1299,6 +1303,8 @@ export class WorldView
1299 1303 { this.despawnEntity(id, { immediate: true }); }
1300 1304 for (const [id] of [...this.groundItems.entries()])
1301 1305 { this.despawnGroundItem(id); }
1306 for (const [id] of [...this.itemContainers.entries()])
1307 { this.despawnItemContainer(id); }
1302 1308 }
1303 1309
1304 1310 applySnapshot (snapshot)
@@ -1327,6 +1333,13 @@ export class WorldView
1327 1333 }
1328 1334 for (const item of snapshot.groundItems ?? [])
1329 1335 { this.upsertGroundItem(item); }
1336 for (const [id, entry] of [...this.itemContainers.entries()])
1337 {
1338 if (Math.floor(entry.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(entry.tileY / CHUNK_SIZE) === snapshot.chunkY)
1339 { this.despawnItemContainer(id); }
1340 }
1341 for (const entry of snapshot.itemContainers ?? [])
1342 { this.upsertItemContainer(entry); }
1330 1343 this.#scheduleEdgeRebuild();
1331 1344 }
1332 1345
@@ -1357,6 +1370,11 @@ export class WorldView
1357 1370 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
1358 1371 { this.despawnGroundItem(id); }
1359 1372 }
1373 for (const [id, entry] of [...this.itemContainers.entries()])
1374 {
1375 if (Math.floor(entry.tileX / CHUNK_SIZE) === chunkX && Math.floor(entry.tileY / CHUNK_SIZE) === chunkY)
1376 { this.despawnItemContainer(id); }
1377 }
1360 1378 for (const [id, entity] of [...this.entities.entries()])
1361 1379 {
1362 1380 if (id === this.localEntityId)
@@ -2825,6 +2843,28 @@ export class WorldView
2825 2843 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
2826 2844 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
2827 2845 const config = normalizeSpawnerConfig(spawner.config ?? {});
2846 if (isItemSpawnerConfig(config))
2847 {
2848 const bodySpriteName = itemSpawnerContainerSpriteName(
2849 config.appearance === "item" ? "chest" : config.appearance,
2850 config.material
2851 );
2852 const object = this.#ensureSprite(null, bodySpriteName, SORT_ENTITY);
2853 if (!object)
2854 { continue; }
2855 object.renderer.alpha = 0.85;
2856 this.#markUnlit(object);
2857 const key = `${prefix}${spawner.localX},${spawner.localY}`;
2858 const entry = {
2859 instances: [{ object, overlays: [] }],
2860 tileX,
2861 tileY,
2862 spriteName: bodySpriteName
2863 };
2864 this.#placeEditorSpawnerEntry(entry, size);
2865 this.editorSpawners.set(key, entry);
2866 continue;
2867 }
2828 2868 const layers = layersFromSpawnerConfig(config);
2829 2869 const bodySpriteName = layers?.[0]?.sprite
2830 2870 ?? resolveSprite?.(config.mobTypeId)
@@ -3248,6 +3288,13 @@ export class WorldView
3248 3288 this.#depthLayer(item.tileY * size + size / 2 - 0.01, SORT_BLOCK)
3249 3289 );
3250 3290 }
3291 for (const entry of this.itemContainers.values())
3292 {
3293 this.#setLayer(
3294 entry.object,
3295 this.#depthLayer(entry.tileY * size + size / 2 - 0.02, SORT_BLOCK)
3296 );
3297 }
3251 3298 // Lerping FX are re-placed in #updateSwipes; static ones need the refresh.
3252 3299 for (const swipe of this.swipes)
3253 3300 {
@@ -18,6 +18,7 @@ import
18} from "/shared/render/tint.js";
18} from "/shared/render/tint.js";
19import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
19import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
20import { normalizeSpawnerConfig } from "/shared/definitions/mobs.js";
20import { normalizeSpawnerConfig } from "/shared/definitions/mobs.js";
21import { isItemSpawnerConfig, itemSpawnerContainerSpriteName } from "/shared/definitions/itemSpawners.js";
21import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
22import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
22import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLavaGround, isLiquidWaterGround, isGroundPassable, isBlockPassable, groundLightOcclusion, LightOcclusion, blockDefinition, blockLightOcclusionForBlock, GroundType, GROUND_DEFINITIONS, fluidCoastContinues } from "/shared/definitions/tiles.js";
23import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLavaGround, isLiquidWaterGround, isGroundPassable, isBlockPassable, groundLightOcclusion, LightOcclusion, blockDefinition, blockLightOcclusionForBlock, GroundType, GROUND_DEFINITIONS, fluidCoastContinues } from "/shared/definitions/tiles.js";
23import { doorSortSubOrder, doorRestingState, isDoorTraversable } from "/shared/world/doors.js";
24import { doorSortSubOrder, doorRestingState, isDoorTraversable } from "/shared/world/doors.js";
@@ -1130,6 +1131,7 @@ export class WorldView
1130 this.bakedChunks = new Map();
1131 this.bakedChunks = new Map();
1131 this.tiles = new Map();
1132 this.tiles = new Map();
1132 this.entities = new Map();
1133 this.entities = new Map();
1134 this.itemContainers = new Map();
1133 this.groundItems = new Map();
1135 this.groundItems = new Map();
1134 this.edges = new Map();
1136 this.edges = new Map();
1135 this.localEntityId = null;
1137 this.localEntityId = null;
@@ -1271,6 +1273,8 @@ export class WorldView
1271 }
1273 }
1272 for (const [id] of [...this.groundItems.entries()])
1274 for (const [id] of [...this.groundItems.entries()])
1273 { this.despawnGroundItem(id); }
1275 { this.despawnGroundItem(id); }
1276 for (const [id] of [...this.itemContainers.entries()])
1277 { this.despawnItemContainer(id); }
1274 for (const swipe of this.swipes)
1278 for (const swipe of this.swipes)
1275 { swipe.object?.destroy(); }
1279 { swipe.object?.destroy(); }
1276 this.swipes = [];
1280 this.swipes = [];
@@ -1299,6 +1303,8 @@ export class WorldView
1299 { this.despawnEntity(id, { immediate: true }); }
1303 { this.despawnEntity(id, { immediate: true }); }
1300 for (const [id] of [...this.groundItems.entries()])
1304 for (const [id] of [...this.groundItems.entries()])
1301 { this.despawnGroundItem(id); }
1305 { this.despawnGroundItem(id); }
1306 for (const [id] of [...this.itemContainers.entries()])
1307 { this.despawnItemContainer(id); }
1302 }
1308 }
1303
1309
1304 applySnapshot (snapshot)
1310 applySnapshot (snapshot)
@@ -1327,6 +1333,13 @@ export class WorldView
1327 }
1333 }
1328 for (const item of snapshot.groundItems ?? [])
1334 for (const item of snapshot.groundItems ?? [])
1329 { this.upsertGroundItem(item); }
1335 { this.upsertGroundItem(item); }
1336 for (const [id, entry] of [...this.itemContainers.entries()])
1337 {
1338 if (Math.floor(entry.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(entry.tileY / CHUNK_SIZE) === snapshot.chunkY)
1339 { this.despawnItemContainer(id); }
1340 }
1341 for (const entry of snapshot.itemContainers ?? [])
1342 { this.upsertItemContainer(entry); }
1330 this.#scheduleEdgeRebuild();
1343 this.#scheduleEdgeRebuild();
1331 }
1344 }
1332
1345
@@ -1357,6 +1370,11 @@ export class WorldView
1357 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
1370 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
1358 { this.despawnGroundItem(id); }
1371 { this.despawnGroundItem(id); }
1359 }
1372 }
1373 for (const [id, entry] of [...this.itemContainers.entries()])
1374 {
1375 if (Math.floor(entry.tileX / CHUNK_SIZE) === chunkX && Math.floor(entry.tileY / CHUNK_SIZE) === chunkY)
1376 { this.despawnItemContainer(id); }
1377 }
1360 for (const [id, entity] of [...this.entities.entries()])
1378 for (const [id, entity] of [...this.entities.entries()])
1361 {
1379 {
1362 if (id === this.localEntityId)
1380 if (id === this.localEntityId)
@@ -2825,6 +2843,28 @@ export class WorldView
2825 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
2843 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
2826 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
2844 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
2827 const config = normalizeSpawnerConfig(spawner.config ?? {});
2845 const config = normalizeSpawnerConfig(spawner.config ?? {});
2846 if (isItemSpawnerConfig(config))
2847 {
2848 const bodySpriteName = itemSpawnerContainerSpriteName(
2849 config.appearance === "item" ? "chest" : config.appearance,
2850 config.material
2851 );
2852 const object = this.#ensureSprite(null, bodySpriteName, SORT_ENTITY);
2853 if (!object)
2854 { continue; }
2855 object.renderer.alpha = 0.85;
2856 this.#markUnlit(object);
2857 const key = `${prefix}${spawner.localX},${spawner.localY}`;
2858 const entry = {
2859 instances: [{ object, overlays: [] }],
2860 tileX,
2861 tileY,
2862 spriteName: bodySpriteName
2863 };
2864 this.#placeEditorSpawnerEntry(entry, size);
2865 this.editorSpawners.set(key, entry);
2866 continue;
2867 }
2828 const layers = layersFromSpawnerConfig(config);
2868 const layers = layersFromSpawnerConfig(config);
2829 const bodySpriteName = layers?.[0]?.sprite
2869 const bodySpriteName = layers?.[0]?.sprite
2830 ?? resolveSprite?.(config.mobTypeId)
2870 ?? resolveSprite?.(config.mobTypeId)
@@ -3248,6 +3288,13 @@ export class WorldView
3248 this.#depthLayer(item.tileY * size + size / 2 - 0.01, SORT_BLOCK)
3288 this.#depthLayer(item.tileY * size + size / 2 - 0.01, SORT_BLOCK)
3249 );
3289 );
3250 }
3290 }
3291 for (const entry of this.itemContainers.values())
3292 {
3293 this.#setLayer(
3294 entry.object,
3295 this.#depthLayer(entry.tileY * size + size / 2 - 0.02, SORT_BLOCK)
3296 );
3297 }
3251 // Lerping FX are re-placed in #updateSwipes; static ones need the refresh.
3298 // Lerping FX are re-placed in #updateSwipes; static ones need the refresh.
3252 for (const swipe of this.swipes)
3299 for (const swipe of this.swipes)
3253 {
3300 {
server/src/assets/spriteCatalog.js +57 −1
@@ -29,6 +29,11 @@ import
29 29 } from "../../../shared/definitions/tileSprites.js";
30 30 import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
31 31 import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT, definitionUsesMaterialNeighborConnect } from "../../../shared/world/neighborConnect.js";
32 import
33 {
34 ITEM_SPAWNER_CONTAINER_APPEARANCES,
35 ITEM_SPAWNER_CONTAINER_ASSET_KEY
36 } from "../../../shared/definitions/itemSpawners.js";
32 37
33 38 const CHARACTER_DEFINITIONS = Object.freeze({
34 39 "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
@@ -49,6 +54,8 @@ export function buildSpriteCatalog (assetRoot)
49 54 const mobs = scanMobLayers(assetRoot);
50 55 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
51 56 const fx = scanFx(join(assetRoot, "fx"));
57 const containers = scanContainerSprites(join(assetRoot, "blocks", ITEM_SPAWNER_CONTAINER_ASSET_KEY));
58 Object.assign(blocks.types, containers.blockTypes);
52 59 return {
53 60 grounds: grounds.types,
54 61 blocks: blocks.types,
@@ -63,11 +70,60 @@ export function buildSpriteCatalog (assetRoot)
63 70 ...herbs.images,
64 71 ...mobs.images,
65 72 ...characters.images,
66 ...fx.images
73 ...fx.images,
74 ...containers.images
67 75 ]
68 76 };
69 77 }
70 78
79 /**
80 * Magenta container masks (chest/barrel/crate) expanded per wood tier for item spawners.
81 * Not placeable as authored blocks — used for editor preview + runtime overlays.
82 */
83 function scanContainerSprites (folder)
84 {
85 const stems = new Set(listPngStems(folder));
86 const images = [];
87 const states = [];
88 for (const appearance of ITEM_SPAWNER_CONTAINER_APPEARANCES)
89 {
90 if (!stems.has(appearance))
91 { throw new Error(`Missing container sprite in ${folder}: ${appearance}.png`); }
92 for (const material of WOOD_TIER_ORDER)
93 {
94 const state = `${material}-${appearance}`;
95 states.push(state);
96 const tint = materialTintColor(material);
97 images.push({
98 name: spriteImageName("block", ITEM_SPAWNER_CONTAINER_ASSET_KEY, state),
99 url: `/assets/blocks/${ITEM_SPAWNER_CONTAINER_ASSET_KEY}/${appearance}.png`,
100 subImgTotal: 1,
101 perRow: 1,
102 loop: false,
103 animationSpeed: 0,
104 tint: { r: tint.r, g: tint.g, b: tint.b }
105 });
106 }
107 }
108 const blockTypes = {
109 [ITEM_SPAWNER_CONTAINER_ASSET_KEY]: {
110 key: ITEM_SPAWNER_CONTAINER_ASSET_KEY,
111 typeId: "containers",
112 states,
113 defaultState: states[0] ?? "pine-chest",
114 blooms: {},
115 equips: {},
116 equipBlooms: {},
117 frames: 1,
118 framesPerRow: 1,
119 animationSpeed: 0,
120 outdoor: false,
121 seasonal: false
122 }
123 };
124 return { images, blockTypes };
125 }
126
71 127 /**
72 128 * Shared `assets/herbs/<herbId>.png` — registered as both world block states and item icons.
73 129 */
@@ -29,6 +29,11 @@ import
29 } from "../../../shared/definitions/tileSprites.js";
29 } from "../../../shared/definitions/tileSprites.js";
30import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
30import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
31import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT, definitionUsesMaterialNeighborConnect } from "../../../shared/world/neighborConnect.js";
31import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT, definitionUsesMaterialNeighborConnect } from "../../../shared/world/neighborConnect.js";
32import
33 {
34 ITEM_SPAWNER_CONTAINER_APPEARANCES,
35 ITEM_SPAWNER_CONTAINER_ASSET_KEY
36 } from "../../../shared/definitions/itemSpawners.js";
32
37
33const CHARACTER_DEFINITIONS = Object.freeze({
38const CHARACTER_DEFINITIONS = Object.freeze({
34 "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
39 "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
@@ -49,6 +54,8 @@ export function buildSpriteCatalog (assetRoot)
49 const mobs = scanMobLayers(assetRoot);
54 const mobs = scanMobLayers(assetRoot);
50 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
55 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
51 const fx = scanFx(join(assetRoot, "fx"));
56 const fx = scanFx(join(assetRoot, "fx"));
57 const containers = scanContainerSprites(join(assetRoot, "blocks", ITEM_SPAWNER_CONTAINER_ASSET_KEY));
58 Object.assign(blocks.types, containers.blockTypes);
52 return {
59 return {
53 grounds: grounds.types,
60 grounds: grounds.types,
54 blocks: blocks.types,
61 blocks: blocks.types,
@@ -63,11 +70,60 @@ export function buildSpriteCatalog (assetRoot)
63 ...herbs.images,
70 ...herbs.images,
64 ...mobs.images,
71 ...mobs.images,
65 ...characters.images,
72 ...characters.images,
66 ...fx.images
73 ...fx.images,
74 ...containers.images
67 ]
75 ]
68 };
76 };
69}
77}
70
78
79/**
80 * Magenta container masks (chest/barrel/crate) expanded per wood tier for item spawners.
81 * Not placeable as authored blocks — used for editor preview + runtime overlays.
82 */
83function scanContainerSprites (folder)
84{
85 const stems = new Set(listPngStems(folder));
86 const images = [];
87 const states = [];
88 for (const appearance of ITEM_SPAWNER_CONTAINER_APPEARANCES)
89 {
90 if (!stems.has(appearance))
91 { throw new Error(`Missing container sprite in ${folder}: ${appearance}.png`); }
92 for (const material of WOOD_TIER_ORDER)
93 {
94 const state = `${material}-${appearance}`;
95 states.push(state);
96 const tint = materialTintColor(material);
97 images.push({
98 name: spriteImageName("block", ITEM_SPAWNER_CONTAINER_ASSET_KEY, state),
99 url: `/assets/blocks/${ITEM_SPAWNER_CONTAINER_ASSET_KEY}/${appearance}.png`,
100 subImgTotal: 1,
101 perRow: 1,
102 loop: false,
103 animationSpeed: 0,
104 tint: { r: tint.r, g: tint.g, b: tint.b }
105 });
106 }
107 }
108 const blockTypes = {
109 [ITEM_SPAWNER_CONTAINER_ASSET_KEY]: {
110 key: ITEM_SPAWNER_CONTAINER_ASSET_KEY,
111 typeId: "containers",
112 states,
113 defaultState: states[0] ?? "pine-chest",
114 blooms: {},
115 equips: {},
116 equipBlooms: {},
117 frames: 1,
118 framesPerRow: 1,
119 animationSpeed: 0,
120 outdoor: false,
121 seasonal: false
122 }
123 };
124 return { images, blockTypes };
125}
126
71/**
127/**
72 * Shared `assets/herbs/<herbId>.png` — registered as both world block states and item icons.
128 * Shared `assets/herbs/<herbId>.png` — registered as both world block states and item icons.
73 */
129 */
server/src/gateway/websocket.js +38 −1
@@ -480,6 +480,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
480 480 groundItemId: message.groundItemId | 0
481 481 });
482 482 break;
483 case MessageType.openItemContainer:
484 requirePlaying(session);
485 simulation.enqueue(session.id, {
486 type: "open-item-container",
487 characterId: session.characterId,
488 containerId: message.containerId | 0
489 });
490 break;
483 491 case MessageType.shear:
484 492 requirePlaying(session);
485 493 simulation.enqueue(session.id, {
@@ -2171,7 +2179,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2171 2179 }
2172 2180 continue;
2173 2181 }
2174 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "entity-skull" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
2182 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "item-container-appear" || event.type === "item-container-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "entity-skull" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
2175 2183 { publishEntity(event); }
2176 2184 }
2177 2185 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -2238,6 +2246,35 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2238 2246 });
2239 2247 continue;
2240 2248 }
2249 if (event.type === "item-container-appear")
2250 {
2251 if (!seesTo)
2252 { continue; }
2253 send(session, {
2254 type: MessageType.itemContainerAppear,
2255 containerId: event.containerId,
2256 spawnerId: event.spawnerId,
2257 tileX: event.tileX,
2258 tileY: event.tileY,
2259 dimensionId: event.dimensionId,
2260 appearance: event.appearance,
2261 material: event.material,
2262 displayName: event.displayName,
2263 sprite: event.sprite
2264 });
2265 continue;
2266 }
2267 if (event.type === "item-container-despawn")
2268 {
2269 if (!seesTo)
2270 { continue; }
2271 send(session, {
2272 type: MessageType.itemContainerDespawn,
2273 containerId: event.containerId,
2274 spawnerId: event.spawnerId
2275 });
2276 continue;
2277 }
2241 2278 if (event.type === "ground-item-appear")
2242 2279 {
2243 2280 if (!seesTo)
@@ -480,6 +480,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
480 groundItemId: message.groundItemId | 0
480 groundItemId: message.groundItemId | 0
481 });
481 });
482 break;
482 break;
483 case MessageType.openItemContainer:
484 requirePlaying(session);
485 simulation.enqueue(session.id, {
486 type: "open-item-container",
487 characterId: session.characterId,
488 containerId: message.containerId | 0
489 });
490 break;
483 case MessageType.shear:
491 case MessageType.shear:
484 requirePlaying(session);
492 requirePlaying(session);
485 simulation.enqueue(session.id, {
493 simulation.enqueue(session.id, {
@@ -2171,7 +2179,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2171 }
2179 }
2172 continue;
2180 continue;
2173 }
2181 }
2174 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "entity-skull" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
2182 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "item-container-appear" || event.type === "item-container-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "entity-skull" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "spell-dark-appear" || event.type === "spell-dark-update" || event.type === "spell-dark-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
2175 { publishEntity(event); }
2183 { publishEntity(event); }
2176 }
2184 }
2177 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
2185 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -2238,6 +2246,35 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2238 });
2246 });
2239 continue;
2247 continue;
2240 }
2248 }
2249 if (event.type === "item-container-appear")
2250 {
2251 if (!seesTo)
2252 { continue; }
2253 send(session, {
2254 type: MessageType.itemContainerAppear,
2255 containerId: event.containerId,
2256 spawnerId: event.spawnerId,
2257 tileX: event.tileX,
2258 tileY: event.tileY,
2259 dimensionId: event.dimensionId,
2260 appearance: event.appearance,
2261 material: event.material,
2262 displayName: event.displayName,
2263 sprite: event.sprite
2264 });
2265 continue;
2266 }
2267 if (event.type === "item-container-despawn")
2268 {
2269 if (!seesTo)
2270 { continue; }
2271 send(session, {
2272 type: MessageType.itemContainerDespawn,
2273 containerId: event.containerId,
2274 spawnerId: event.spawnerId
2275 });
2276 continue;
2277 }
2241 if (event.type === "ground-item-appear")
2278 if (event.type === "ground-item-appear")
2242 {
2279 {
2243 if (!seesTo)
2280 if (!seesTo)
server/src/itemSpawners/service.js added +647 −0
@@ -0,0 +1,647 @@
1 /**
2 * Item Spawner runtime: refill ground-item piles or openable containers,
3 * channelled open with shove-every-second, condition gates, respawn delay.
4 */
5 import { Component } from "../ecs/components.js";
6 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
7 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
8 import { tileToChunk, tileToRegion, parseChunkKey } from "../world/coordinates.js";
9 import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";
10 import
11 {
12 isItemSpawnerConfig,
13 normalizeItemSpawnerConfig,
14 isItemSpawnerContainerAppearance,
15 itemSpawnerContainerDisplayName,
16 itemSpawnerContainerSpriteName,
17 ITEM_SPAWNER_LOCKED_MESSAGE,
18 ITEM_SPAWNER_SPACE_TOAST,
19 ITEM_SPAWNER_OPEN_DURATION_MS,
20 ITEM_SPAWNER_SHOVE_MS,
21 ItemSpawnerAppearance
22 } from "../../../shared/definitions/itemSpawners.js";
23 import { emptyConditionSet, evaluateConditionSet } from "../../../shared/quests/conditions.js";
24 import { itemDefinition } from "../../../shared/definitions/items.js";
25 import { insertStack } from "../../../shared/items/inventory.js";
26 import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
27 import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
28 import { buildEntityConditionContext } from "../doors/conditionContext.js";
29 import { tileShoveEvent } from "../simulation/tileInteract.js";
30 import
31 {
32 placeOrMergeGroundStack,
33 removeGroundItem,
34 bagView,
35 publicGroundItem
36 } from "../items/bags.js";
37
38 function userError (message)
39 {
40 const error = new Error(message);
41 error.userFacing = true;
42 return error;
43 }
44
45 function ensureState (world)
46 {
47 if (!world.itemSpawnerState)
48 {
49 world.itemSpawnerState = {
50 /** @type {Map<string, object>} spawnerId → live instance */
51 active: new Map(),
52 /** @type {Map<string, number>} spawnerId → respawnAt ms */
53 pendingRespawn: new Map(),
54 /** @type {Map<number, string>} groundItemId → spawnerId */
55 groundToSpawner: new Map(),
56 /** @type {Map<number, object>} characterId → open session */
57 openSessions: new Map()
58 };
59 }
60 return world.itemSpawnerState;
61 }
62
63 export function itemContainersInChunk (world, chunkX, chunkY, dimensionId = OVERWORLD_ID)
64 {
65 const dim = normalizeDimensionId(dimensionId);
66 const state = ensureState(world);
67 const out = [];
68 for (const entry of state.active.values())
69 {
70 if (entry.mode !== "container")
71 { continue; }
72 if (normalizeDimensionId(entry.dimensionId) !== dim)
73 { continue; }
74 if (tileToChunk(entry.tileX) !== chunkX || tileToChunk(entry.tileY) !== chunkY)
75 { continue; }
76 out.push(publicItemContainer(entry));
77 }
78 return out;
79 }
80
81 export function publicItemContainer (entry)
82 {
83 return {
84 containerId: entry.containerId,
85 spawnerId: entry.spawnerId,
86 tileX: entry.tileX,
87 tileY: entry.tileY,
88 dimensionId: normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID),
89 appearance: entry.appearance,
90 material: entry.material,
91 displayName: itemSpawnerContainerDisplayName(entry.appearance),
92 sprite: itemSpawnerContainerSpriteName(entry.appearance, entry.material)
93 };
94 }
95
96 function allocateContainerId (world)
97 {
98 world.nextItemContainerId = (world.nextItemContainerId ?? 1) + 1;
99 return world.nextItemContainerId;
100 }
101
102 function scopedSpawnerId (rawId, dimensionId, chunkX, chunkY, index)
103 {
104 const dim = normalizeDimensionId(dimensionId);
105 const raw = typeof rawId === "string" && rawId
106 ? rawId
107 : `${chunkX}:${chunkY}:${index}`;
108 return raw.startsWith(`${dim}:`) ? raw : `${dim}:${raw}`;
109 }
110
111 function pickTile (world, originX, originY, range, dimensionId, reserved = null)
112 {
113 const dim = normalizeDimensionId(dimensionId);
114 const radius = Math.max(0, range | 0);
115 const tryTile = (tileX, tileY) =>
116 {
117 const key = `${dim}:${tileX},${tileY}`;
118 if (reserved?.has(key))
119 { return null; }
120 if (!world.ownsRegion?.(tileToRegion(tileX), tileToRegion(tileY), dim))
121 {
122 // Editor / single-worker worlds may lack ownsRegion — fall through.
123 if (typeof world.ownsRegion === "function")
124 { return null; }
125 }
126 if (typeof world.isEnterable === "function")
127 {
128 if (!world.isEnterable(tileX, tileY, dim))
129 { return null; }
130 }
131 return { tileX, tileY, dimensionId: dim };
132 };
133 if (radius === 0)
134 { return tryTile(originX, originY); }
135 for (let attempt = 0; attempt < 48; attempt++)
136 {
137 const tileX = originX + randInt(-radius, radius);
138 const tileY = originY + randInt(-radius, radius);
139 const tile = tryTile(tileX, tileY);
140 if (tile)
141 { return tile; }
142 }
143 return tryTile(originX, originY);
144 }
145
146 function randInt (min, max)
147 {
148 return min + Math.floor(Math.random() * (max - min + 1));
149 }
150
151 function cloneStacks (items)
152 {
153 return (items ?? []).map((line) => ({
154 itemId: line.itemId | 0,
155 quantity: Math.max(1, line.quantity | 0)
156 }));
157 }
158
159 /**
160 * Spawn (or refill) one item spawner instance. Returns events.
161 */
162 function spawnInstance (world, entryMeta, config, now, events)
163 {
164 const state = ensureState(world);
165 const spawnerId = config.spawnerId;
166 if (state.active.has(spawnerId))
167 { return; }
168 if ((state.pendingRespawn.get(spawnerId) ?? 0) > now)
169 { return; }
170 state.pendingRespawn.delete(spawnerId);
171
172 const tile = pickTile(
173 world,
174 entryMeta.originX,
175 entryMeta.originY,
176 config.spawnRangeTiles,
177 entryMeta.dimensionId
178 );
179 if (!tile)
180 { return; }
181
182 if (config.appearance === ItemSpawnerAppearance.item)
183 {
184 const groundIds = [];
185 for (const line of config.items)
186 {
187 const def = itemDefinition(line.itemId);
188 if (!def)
189 { continue; }
190 const stack = attachOrigins({
191 itemId: line.itemId,
192 quantity: line.quantity,
193 origins: [{ origin: godsOrigin(), quantity: line.quantity }]
194 });
195 const placed = placeOrMergeGroundStack(world, {
196 tileX: tile.tileX,
197 tileY: tile.tileY,
198 dimensionId: tile.dimensionId,
199 stack,
200 now,
201 source: "item-spawner",
202 // Never auto-despawn authored spawner loot.
203 despawnDurationMs: Number.MAX_SAFE_INTEGER
204 });
205 for (const ev of placed.events)
206 {
207 events.push(ev);
208 if (ev.type === "ground-item-appear" && ev.groundItemId != null)
209 {
210 const item = world.groundItems.get(ev.groundItemId);
211 if (item)
212 {
213 item.itemSpawnerId = spawnerId;
214 item.source = "item-spawner";
215 // Far-future expiry (DB column is NOT NULL); expireGroundItems also skips these.
216 item.expiresAt = Number.MAX_SAFE_INTEGER;
217 state.groundToSpawner.set(ev.groundItemId, spawnerId);
218 groundIds.push(ev.groundItemId);
219 }
220 }
221 }
222 }
223 if (!groundIds.length)
224 { return; }
225 state.active.set(spawnerId, {
226 mode: "items",
227 spawnerId,
228 dimensionId: tile.dimensionId,
229 originX: entryMeta.originX,
230 originY: entryMeta.originY,
231 spawnRangeTiles: config.spawnRangeTiles,
232 respawnDelaySeconds: config.respawnDelaySeconds,
233 appearance: config.appearance,
234 items: cloneStacks(config.items),
235 groundItemIds: groundIds,
236 when: emptyConditionSet()
237 });
238 return;
239 }
240
241 const containerId = allocateContainerId(world);
242 const live = {
243 mode: "container",
244 containerId,
245 spawnerId,
246 tileX: tile.tileX,
247 tileY: tile.tileY,
248 dimensionId: tile.dimensionId,
249 originX: entryMeta.originX,
250 originY: entryMeta.originY,
251 spawnRangeTiles: config.spawnRangeTiles,
252 respawnDelaySeconds: config.respawnDelaySeconds,
253 appearance: config.appearance,
254 material: config.material,
255 items: cloneStacks(config.items),
256 when: config.when ?? emptyConditionSet()
257 };
258 state.active.set(spawnerId, live);
259 events.push({
260 type: "item-container-appear",
261 ...publicItemContainer(live)
262 });
263 }
264
265 function clearActive (world, spawnerId, events, { scheduleRespawn = true } = {})
266 {
267 const state = ensureState(world);
268 const live = state.active.get(spawnerId);
269 if (!live)
270 { return; }
271 state.active.delete(spawnerId);
272
273 if (live.mode === "items")
274 {
275 for (const id of live.groundItemIds ?? [])
276 { state.groundToSpawner.delete(id); }
277 }
278 else if (live.mode === "container")
279 {
280 events.push({
281 type: "item-container-despawn",
282 containerId: live.containerId,
283 spawnerId,
284 tileX: live.tileX,
285 tileY: live.tileY,
286 dimensionId: live.dimensionId
287 });
288 }
289
290 if (scheduleRespawn)
291 {
292 const delayMs = Math.max(0, (live.respawnDelaySeconds | 0) * 1000);
293 const clock = typeof world.now === "function" ? world.now() : Date.now();
294 state.pendingRespawn.set(spawnerId, clock + delayMs);
295 }
296 }
297
298 /**
299 * Called whenever a ground item leaves the world (pickup, transform, burn, …).
300 */
301 export function notifyGroundItemRemoved (world, groundItemId, events = [])
302 {
303 const state = ensureState(world);
304 const spawnerId = state.groundToSpawner.get(groundItemId);
305 if (!spawnerId)
306 { return events; }
307 state.groundToSpawner.delete(groundItemId);
308 const live = state.active.get(spawnerId);
309 if (!live || live.mode !== "items")
310 { return events; }
311 live.groundItemIds = (live.groundItemIds ?? []).filter((id) => id !== groundItemId);
312 // Remaining piles stay in the world but are unlinked (orphaned normal items).
313 if (live.groundItemIds.length === 0)
314 { clearActive(world, spawnerId, events, { scheduleRespawn: true }); }
315 return events;
316 }
317
318 /**
319 * Wrap removeGroundItem so item-spawner tracking stays in sync.
320 */
321 export function removeGroundItemTracked (world, groundItemId)
322 {
323 const events = [];
324 notifyGroundItemRemoved(world, groundItemId, events);
325 removeGroundItem(world, groundItemId);
326 return events;
327 }
328
329 function listAuthoredItemSpawners (world)
330 {
331 const list = [];
332 for (const [key, chunk] of world.chunks)
333 {
334 if (chunk.replica || !chunk.simulating || !chunk.data?.open)
335 { continue; }
336 const { chunkX, chunkY, dimensionId: keyDimensionId } = parseChunkKey(key);
337 const dimensionId = normalizeDimensionId(chunk.dimensionId ?? keyDimensionId ?? OVERWORLD_ID);
338 for (const entry of chunk.data.spawners ?? [])
339 {
340 if (!isItemSpawnerConfig(entry.config))
341 { continue; }
342 const localX = entry.localX;
343 const localY = entry.localY;
344 const index = localY * CHUNK_SIZE + localX;
345 const config = normalizeItemSpawnerConfig(
346 entry.config,
347 scopedSpawnerId(entry.config?.spawnerId, dimensionId, chunkX, chunkY, index)
348 );
349 config.spawnerId = scopedSpawnerId(config.spawnerId, dimensionId, chunkX, chunkY, index);
350 list.push({
351 config,
352 originX: chunkX * CHUNK_SIZE + localX,
353 originY: chunkY * CHUNK_SIZE + localY,
354 dimensionId
355 });
356 }
357 }
358 return list;
359 }
360
361 /**
362 * Tick: refill empty spawners whose respawn timer elapsed; advance open channels.
363 */
364 export function stepItemSpawners (world, now = Date.now())
365 {
366 const state = ensureState(world);
367 const events = [];
368 const privates = [];
369
370 // Drop active entries whose authored spawner vanished.
371 const authoredIds = new Set(listAuthoredItemSpawners(world).map((row) => row.config.spawnerId));
372 for (const spawnerId of [...state.active.keys()])
373 {
374 if (!authoredIds.has(spawnerId))
375 { clearActive(world, spawnerId, events, { scheduleRespawn: false }); }
376 }
377
378 for (const row of listAuthoredItemSpawners(world))
379 {
380 const { config } = row;
381 if (state.active.has(config.spawnerId))
382 { continue; }
383 const readyAt = state.pendingRespawn.get(config.spawnerId) ?? 0;
384 if (readyAt > now)
385 { continue; }
386 spawnInstance(world, row, config, now, events);
387 }
388
389 const openResult = stepOpenSessions(world, now);
390 events.push(...openResult.events);
391 privates.push(...openResult.privates);
392
393 return { events, privates };
394 }
395
396 function clearOpenSession (world, characterId)
397 {
398 ensureState(world).openSessions.delete(characterId);
399 }
400
401 export function cancelItemContainerOpen (world, characterId)
402 {
403 clearOpenSession(world, characterId);
404 }
405
406 /**
407 * Start a 2s shove channel to open a container (adjacent tile required).
408 */
409 export function startOpenItemContainer (world, sessionId, characterId, containerId, now = Date.now())
410 {
411 const entityId = world.characterEntities.get(characterId);
412 if (entityId == null)
413 { throw userError("Character is not in the world."); }
414 const handle = world.ecs.handleOf(entityId);
415 const identity = world.ecs.get(handle, Component.networkIdentity);
416 if (!identity || identity.sessionId !== sessionId)
417 { throw userError("Character is not in the world."); }
418 if (world.ecs.has(handle, Component.dead))
419 { throw userError("You are dead."); }
420
421 const state = ensureState(world);
422 let live = null;
423 for (const entry of state.active.values())
424 {
425 if (entry.mode === "container" && entry.containerId === (containerId | 0))
426 {
427 live = entry;
428 break;
429 }
430 }
431 if (!live)
432 { throw userError("That container is gone."); }
433
434 const position = world.ecs.get(handle, Component.position);
435 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
436 if (normalizeDimensionId(live.dimensionId) !== dim)
437 { throw userError("That container is gone."); }
438 if (position.tileX === live.tileX && position.tileY === live.tileY)
439 { throw userError("Stand next to the container."); }
440 if (!isAdjacentTile(position.tileX, position.tileY, live.tileX, live.tileY))
441 { throw userError("Stand next to the container."); }
442
443 if (world.ecs.has(handle, Component.gather))
444 { world.ecs.remove(handle, Component.gather); }
445 const path = world.ecs.get(handle, Component.path);
446 if (path)
447 { path.tiles = []; }
448
449 clearOpenSession(world, characterId);
450 state.openSessions.set(characterId, {
451 sessionId,
452 containerId: live.containerId,
453 spawnerId: live.spawnerId,
454 tileX: live.tileX,
455 tileY: live.tileY,
456 dimensionId: live.dimensionId,
457 appearance: live.appearance,
458 startedAt: now,
459 endsAt: now + ITEM_SPAWNER_OPEN_DURATION_MS,
460 nextShoveAt: now
461 });
462
463 return { events: [] };
464 }
465
466 function containerConditionsMet (world, entityId, live)
467 {
468 const when = live.when ?? emptyConditionSet();
469 if (!(when.all?.length > 0))
470 { return true; }
471 const ctx = buildEntityConditionContext(world, entityId);
472 if (!ctx)
473 { return false; }
474 return evaluateConditionSet(when, ctx);
475 }
476
477 function giveStacksToPlayer (world, handle, entityId, stacks, now, events)
478 {
479 const inventory = world.ecs.get(handle, Component.inventory);
480 if (!inventory)
481 { return { dropped: false }; }
482 let dropped = false;
483 const position = world.ecs.get(handle, Component.position);
484 const dim = normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
485 for (const line of stacks)
486 {
487 const def = itemDefinition(line.itemId);
488 if (!def)
489 { continue; }
490 let remaining = Math.max(1, line.quantity | 0);
491 const stack = attachOrigins({
492 itemId: line.itemId,
493 quantity: remaining,
494 origins: [{ origin: godsOrigin(), quantity: remaining }]
495 });
496 const inserted = insertStack(inventory.slots, stack, def);
497 inventory.slots = inserted.slots;
498 remaining = inserted.remainder | 0;
499 if (remaining > 0)
500 {
501 dropped = true;
502 const leftover = attachOrigins({
503 itemId: line.itemId,
504 quantity: remaining,
505 origins: [{ origin: godsOrigin(), quantity: remaining }]
506 });
507 const placed = placeOrMergeGroundStack(world, {
508 tileX: position.tileX,
509 tileY: position.tileY,
510 dimensionId: dim,
511 stack: leftover,
512 now,
513 source: "item-spawner-overflow"
514 });
515 events.push(...placed.events);
516 }
517 }
518 return { dropped };
519 }
520
521 function completeOpen (world, handle, entityId, characterId, session, events, privates, now)
522 {
523 const state = ensureState(world);
524 const live = state.active.get(session.spawnerId);
525 clearOpenSession(world, characterId);
526 if (!live || live.mode !== "container" || live.containerId !== session.containerId)
527 { return; }
528
529 if (!containerConditionsMet(world, entityId, live))
530 {
531 events.push({
532 type: "toast",
533 sessionId: session.sessionId,
534 characterId,
535 message: ITEM_SPAWNER_LOCKED_MESSAGE
536 });
537 return;
538 }
539
540 const stacks = cloneStacks(live.items);
541 const { dropped } = giveStacksToPlayer(world, handle, entityId, stacks, now, events);
542 privates.push({ characterId, bag: bagView(world.ecs, handle) });
543 if (dropped)
544 {
545 events.push({
546 type: "toast",
547 sessionId: session.sessionId,
548 characterId,
549 message: ITEM_SPAWNER_SPACE_TOAST
550 });
551 }
552 clearActive(world, live.spawnerId, events, { scheduleRespawn: true });
553 }
554
555 function stepOpenSessions (world, now)
556 {
557 const state = ensureState(world);
558 const events = [];
559 const privates = [];
560 for (const [characterId, session] of [...state.openSessions.entries()])
561 {
562 const entityId = world.characterEntities.get(characterId);
563 if (entityId == null)
564 {
565 clearOpenSession(world, characterId);
566 continue;
567 }
568 const handle = world.ecs.handleOf(entityId);
569 if (world.ecs.has(handle, Component.dead))
570 {
571 clearOpenSession(world, characterId);
572 continue;
573 }
574 const live = state.active.get(session.spawnerId);
575 if (!live || live.mode !== "container" || live.containerId !== session.containerId)
576 {
577 clearOpenSession(world, characterId);
578 continue;
579 }
580 const position = world.ecs.get(handle, Component.position);
581 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
582 if (normalizeDimensionId(live.dimensionId) !== dim
583 || position.tileX === live.tileX && position.tileY === live.tileY
584 || !isAdjacentTile(position.tileX, position.tileY, live.tileX, live.tileY))
585 {
586 clearOpenSession(world, characterId);
587 continue;
588 }
589
590 if (now >= session.nextShoveAt && now < session.endsAt)
591 {
592 session.nextShoveAt = now + ITEM_SPAWNER_SHOVE_MS;
593 events.push(tileShoveEvent(
594 entityId,
595 position.tileX,
596 position.tileY,
597 live.tileX,
598 live.tileY,
599 dim
600 ));
601 }
602
603 if (now < session.endsAt)
604 { continue; }
605
606 completeOpen(world, handle, entityId, characterId, session, events, privates, now);
607 }
608 return { events, privates };
609 }
610
611 export function handleItemSpawnerCommand (world, sessionId, command, now = Date.now())
612 {
613 if (command.type === "open-item-container")
614 {
615 return startOpenItemContainer(
616 world,
617 sessionId,
618 command.characterId,
619 command.containerId,
620 now
621 );
622 }
623 if (command.type === "cancel-open-item-container")
624 {
625 cancelItemContainerOpen(world, command.characterId);
626 return { events: [] };
627 }
628 return null;
629 }
630
631 /** Find container at a world tile (for client click helpers / tests). */
632 export function itemContainerAtTile (world, tileX, tileY, dimensionId = OVERWORLD_ID)
633 {
634 const dim = normalizeDimensionId(dimensionId);
635 const state = ensureState(world);
636 for (const entry of state.active.values())
637 {
638 if (entry.mode !== "container")
639 { continue; }
640 if (entry.tileX === tileX && entry.tileY === tileY
641 && normalizeDimensionId(entry.dimensionId) === dim)
642 { return entry; }
643 }
644 return null;
645 }
646
647 export { ensureState as ensureItemSpawnerState };
@@ -0,0 +1,647 @@
1/**
2 * Item Spawner runtime: refill ground-item piles or openable containers,
3 * channelled open with shove-every-second, condition gates, respawn delay.
4 */
5import { Component } from "../ecs/components.js";
6import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
7import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
8import { tileToChunk, tileToRegion, parseChunkKey } from "../world/coordinates.js";
9import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";
10import
11 {
12 isItemSpawnerConfig,
13 normalizeItemSpawnerConfig,
14 isItemSpawnerContainerAppearance,
15 itemSpawnerContainerDisplayName,
16 itemSpawnerContainerSpriteName,
17 ITEM_SPAWNER_LOCKED_MESSAGE,
18 ITEM_SPAWNER_SPACE_TOAST,
19 ITEM_SPAWNER_OPEN_DURATION_MS,
20 ITEM_SPAWNER_SHOVE_MS,
21 ItemSpawnerAppearance
22 } from "../../../shared/definitions/itemSpawners.js";
23import { emptyConditionSet, evaluateConditionSet } from "../../../shared/quests/conditions.js";
24import { itemDefinition } from "../../../shared/definitions/items.js";
25import { insertStack } from "../../../shared/items/inventory.js";
26import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
27import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
28import { buildEntityConditionContext } from "../doors/conditionContext.js";
29import { tileShoveEvent } from "../simulation/tileInteract.js";
30import
31 {
32 placeOrMergeGroundStack,
33 removeGroundItem,
34 bagView,
35 publicGroundItem
36 } from "../items/bags.js";
37
38function userError (message)
39{
40 const error = new Error(message);
41 error.userFacing = true;
42 return error;
43}
44
45function ensureState (world)
46{
47 if (!world.itemSpawnerState)
48 {
49 world.itemSpawnerState = {
50 /** @type {Map<string, object>} spawnerId → live instance */
51 active: new Map(),
52 /** @type {Map<string, number>} spawnerId → respawnAt ms */
53 pendingRespawn: new Map(),
54 /** @type {Map<number, string>} groundItemId → spawnerId */
55 groundToSpawner: new Map(),
56 /** @type {Map<number, object>} characterId → open session */
57 openSessions: new Map()
58 };
59 }
60 return world.itemSpawnerState;
61}
62
63export function itemContainersInChunk (world, chunkX, chunkY, dimensionId = OVERWORLD_ID)
64{
65 const dim = normalizeDimensionId(dimensionId);
66 const state = ensureState(world);
67 const out = [];
68 for (const entry of state.active.values())
69 {
70 if (entry.mode !== "container")
71 { continue; }
72 if (normalizeDimensionId(entry.dimensionId) !== dim)
73 { continue; }
74 if (tileToChunk(entry.tileX) !== chunkX || tileToChunk(entry.tileY) !== chunkY)
75 { continue; }
76 out.push(publicItemContainer(entry));
77 }
78 return out;
79}
80
81export function publicItemContainer (entry)
82{
83 return {
84 containerId: entry.containerId,
85 spawnerId: entry.spawnerId,
86 tileX: entry.tileX,
87 tileY: entry.tileY,
88 dimensionId: normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID),
89 appearance: entry.appearance,
90 material: entry.material,
91 displayName: itemSpawnerContainerDisplayName(entry.appearance),
92 sprite: itemSpawnerContainerSpriteName(entry.appearance, entry.material)
93 };
94}
95
96function allocateContainerId (world)
97{
98 world.nextItemContainerId = (world.nextItemContainerId ?? 1) + 1;
99 return world.nextItemContainerId;
100}
101
102function scopedSpawnerId (rawId, dimensionId, chunkX, chunkY, index)
103{
104 const dim = normalizeDimensionId(dimensionId);
105 const raw = typeof rawId === "string" && rawId
106 ? rawId
107 : `${chunkX}:${chunkY}:${index}`;
108 return raw.startsWith(`${dim}:`) ? raw : `${dim}:${raw}`;
109}
110
111function pickTile (world, originX, originY, range, dimensionId, reserved = null)
112{
113 const dim = normalizeDimensionId(dimensionId);
114 const radius = Math.max(0, range | 0);
115 const tryTile = (tileX, tileY) =>
116 {
117 const key = `${dim}:${tileX},${tileY}`;
118 if (reserved?.has(key))
119 { return null; }
120 if (!world.ownsRegion?.(tileToRegion(tileX), tileToRegion(tileY), dim))
121 {
122 // Editor / single-worker worlds may lack ownsRegion — fall through.
123 if (typeof world.ownsRegion === "function")
124 { return null; }
125 }
126 if (typeof world.isEnterable === "function")
127 {
128 if (!world.isEnterable(tileX, tileY, dim))
129 { return null; }
130 }
131 return { tileX, tileY, dimensionId: dim };
132 };
133 if (radius === 0)
134 { return tryTile(originX, originY); }
135 for (let attempt = 0; attempt < 48; attempt++)
136 {
137 const tileX = originX + randInt(-radius, radius);
138 const tileY = originY + randInt(-radius, radius);
139 const tile = tryTile(tileX, tileY);
140 if (tile)
141 { return tile; }
142 }
143 return tryTile(originX, originY);
144}
145
146function randInt (min, max)
147{
148 return min + Math.floor(Math.random() * (max - min + 1));
149}
150
151function cloneStacks (items)
152{
153 return (items ?? []).map((line) => ({
154 itemId: line.itemId | 0,
155 quantity: Math.max(1, line.quantity | 0)
156 }));
157}
158
159/**
160 * Spawn (or refill) one item spawner instance. Returns events.
161 */
162function spawnInstance (world, entryMeta, config, now, events)
163{
164 const state = ensureState(world);
165 const spawnerId = config.spawnerId;
166 if (state.active.has(spawnerId))
167 { return; }
168 if ((state.pendingRespawn.get(spawnerId) ?? 0) > now)
169 { return; }
170 state.pendingRespawn.delete(spawnerId);
171
172 const tile = pickTile(
173 world,
174 entryMeta.originX,
175 entryMeta.originY,
176 config.spawnRangeTiles,
177 entryMeta.dimensionId
178 );
179 if (!tile)
180 { return; }
181
182 if (config.appearance === ItemSpawnerAppearance.item)
183 {
184 const groundIds = [];
185 for (const line of config.items)
186 {
187 const def = itemDefinition(line.itemId);
188 if (!def)
189 { continue; }
190 const stack = attachOrigins({
191 itemId: line.itemId,
192 quantity: line.quantity,
193 origins: [{ origin: godsOrigin(), quantity: line.quantity }]
194 });
195 const placed = placeOrMergeGroundStack(world, {
196 tileX: tile.tileX,
197 tileY: tile.tileY,
198 dimensionId: tile.dimensionId,
199 stack,
200 now,
201 source: "item-spawner",
202 // Never auto-despawn authored spawner loot.
203 despawnDurationMs: Number.MAX_SAFE_INTEGER
204 });
205 for (const ev of placed.events)
206 {
207 events.push(ev);
208 if (ev.type === "ground-item-appear" && ev.groundItemId != null)
209 {
210 const item = world.groundItems.get(ev.groundItemId);
211 if (item)
212 {
213 item.itemSpawnerId = spawnerId;
214 item.source = "item-spawner";
215 // Far-future expiry (DB column is NOT NULL); expireGroundItems also skips these.
216 item.expiresAt = Number.MAX_SAFE_INTEGER;
217 state.groundToSpawner.set(ev.groundItemId, spawnerId);
218 groundIds.push(ev.groundItemId);
219 }
220 }
221 }
222 }
223 if (!groundIds.length)
224 { return; }
225 state.active.set(spawnerId, {
226 mode: "items",
227 spawnerId,
228 dimensionId: tile.dimensionId,
229 originX: entryMeta.originX,
230 originY: entryMeta.originY,
231 spawnRangeTiles: config.spawnRangeTiles,
232 respawnDelaySeconds: config.respawnDelaySeconds,
233 appearance: config.appearance,
234 items: cloneStacks(config.items),
235 groundItemIds: groundIds,
236 when: emptyConditionSet()
237 });
238 return;
239 }
240
241 const containerId = allocateContainerId(world);
242 const live = {
243 mode: "container",
244 containerId,
245 spawnerId,
246 tileX: tile.tileX,
247 tileY: tile.tileY,
248 dimensionId: tile.dimensionId,
249 originX: entryMeta.originX,
250 originY: entryMeta.originY,
251 spawnRangeTiles: config.spawnRangeTiles,
252 respawnDelaySeconds: config.respawnDelaySeconds,
253 appearance: config.appearance,
254 material: config.material,
255 items: cloneStacks(config.items),
256 when: config.when ?? emptyConditionSet()
257 };
258 state.active.set(spawnerId, live);
259 events.push({
260 type: "item-container-appear",
261 ...publicItemContainer(live)
262 });
263}
264
265function clearActive (world, spawnerId, events, { scheduleRespawn = true } = {})
266{
267 const state = ensureState(world);
268 const live = state.active.get(spawnerId);
269 if (!live)
270 { return; }
271 state.active.delete(spawnerId);
272
273 if (live.mode === "items")
274 {
275 for (const id of live.groundItemIds ?? [])
276 { state.groundToSpawner.delete(id); }
277 }
278 else if (live.mode === "container")
279 {
280 events.push({
281 type: "item-container-despawn",
282 containerId: live.containerId,
283 spawnerId,
284 tileX: live.tileX,
285 tileY: live.tileY,
286 dimensionId: live.dimensionId
287 });
288 }
289
290 if (scheduleRespawn)
291 {
292 const delayMs = Math.max(0, (live.respawnDelaySeconds | 0) * 1000);
293 const clock = typeof world.now === "function" ? world.now() : Date.now();
294 state.pendingRespawn.set(spawnerId, clock + delayMs);
295 }
296}
297
298/**
299 * Called whenever a ground item leaves the world (pickup, transform, burn, …).
300 */
301export function notifyGroundItemRemoved (world, groundItemId, events = [])
302{
303 const state = ensureState(world);
304 const spawnerId = state.groundToSpawner.get(groundItemId);
305 if (!spawnerId)
306 { return events; }
307 state.groundToSpawner.delete(groundItemId);
308 const live = state.active.get(spawnerId);
309 if (!live || live.mode !== "items")
310 { return events; }
311 live.groundItemIds = (live.groundItemIds ?? []).filter((id) => id !== groundItemId);
312 // Remaining piles stay in the world but are unlinked (orphaned normal items).
313 if (live.groundItemIds.length === 0)
314 { clearActive(world, spawnerId, events, { scheduleRespawn: true }); }
315 return events;
316}
317
318/**
319 * Wrap removeGroundItem so item-spawner tracking stays in sync.
320 */
321export function removeGroundItemTracked (world, groundItemId)
322{
323 const events = [];
324 notifyGroundItemRemoved(world, groundItemId, events);
325 removeGroundItem(world, groundItemId);
326 return events;
327}
328
329function listAuthoredItemSpawners (world)
330{
331 const list = [];
332 for (const [key, chunk] of world.chunks)
333 {
334 if (chunk.replica || !chunk.simulating || !chunk.data?.open)
335 { continue; }
336 const { chunkX, chunkY, dimensionId: keyDimensionId } = parseChunkKey(key);
337 const dimensionId = normalizeDimensionId(chunk.dimensionId ?? keyDimensionId ?? OVERWORLD_ID);
338 for (const entry of chunk.data.spawners ?? [])
339 {
340 if (!isItemSpawnerConfig(entry.config))
341 { continue; }
342 const localX = entry.localX;
343 const localY = entry.localY;
344 const index = localY * CHUNK_SIZE + localX;
345 const config = normalizeItemSpawnerConfig(
346 entry.config,
347 scopedSpawnerId(entry.config?.spawnerId, dimensionId, chunkX, chunkY, index)
348 );
349 config.spawnerId = scopedSpawnerId(config.spawnerId, dimensionId, chunkX, chunkY, index);
350 list.push({
351 config,
352 originX: chunkX * CHUNK_SIZE + localX,
353 originY: chunkY * CHUNK_SIZE + localY,
354 dimensionId
355 });
356 }
357 }
358 return list;
359}
360
361/**
362 * Tick: refill empty spawners whose respawn timer elapsed; advance open channels.
363 */
364export function stepItemSpawners (world, now = Date.now())
365{
366 const state = ensureState(world);
367 const events = [];
368 const privates = [];
369
370 // Drop active entries whose authored spawner vanished.
371 const authoredIds = new Set(listAuthoredItemSpawners(world).map((row) => row.config.spawnerId));
372 for (const spawnerId of [...state.active.keys()])
373 {
374 if (!authoredIds.has(spawnerId))
375 { clearActive(world, spawnerId, events, { scheduleRespawn: false }); }
376 }
377
378 for (const row of listAuthoredItemSpawners(world))
379 {
380 const { config } = row;
381 if (state.active.has(config.spawnerId))
382 { continue; }
383 const readyAt = state.pendingRespawn.get(config.spawnerId) ?? 0;
384 if (readyAt > now)
385 { continue; }
386 spawnInstance(world, row, config, now, events);
387 }
388
389 const openResult = stepOpenSessions(world, now);
390 events.push(...openResult.events);
391 privates.push(...openResult.privates);
392
393 return { events, privates };
394}
395
396function clearOpenSession (world, characterId)
397{
398 ensureState(world).openSessions.delete(characterId);
399}
400
401export function cancelItemContainerOpen (world, characterId)
402{
403 clearOpenSession(world, characterId);
404}
405
406/**
407 * Start a 2s shove channel to open a container (adjacent tile required).
408 */
409export function startOpenItemContainer (world, sessionId, characterId, containerId, now = Date.now())
410{
411 const entityId = world.characterEntities.get(characterId);
412 if (entityId == null)
413 { throw userError("Character is not in the world."); }
414 const handle = world.ecs.handleOf(entityId);
415 const identity = world.ecs.get(handle, Component.networkIdentity);
416 if (!identity || identity.sessionId !== sessionId)
417 { throw userError("Character is not in the world."); }
418 if (world.ecs.has(handle, Component.dead))
419 { throw userError("You are dead."); }
420
421 const state = ensureState(world);
422 let live = null;
423 for (const entry of state.active.values())
424 {
425 if (entry.mode === "container" && entry.containerId === (containerId | 0))
426 {
427 live = entry;
428 break;
429 }
430 }
431 if (!live)
432 { throw userError("That container is gone."); }
433
434 const position = world.ecs.get(handle, Component.position);
435 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
436 if (normalizeDimensionId(live.dimensionId) !== dim)
437 { throw userError("That container is gone."); }
438 if (position.tileX === live.tileX && position.tileY === live.tileY)
439 { throw userError("Stand next to the container."); }
440 if (!isAdjacentTile(position.tileX, position.tileY, live.tileX, live.tileY))
441 { throw userError("Stand next to the container."); }
442
443 if (world.ecs.has(handle, Component.gather))
444 { world.ecs.remove(handle, Component.gather); }
445 const path = world.ecs.get(handle, Component.path);
446 if (path)
447 { path.tiles = []; }
448
449 clearOpenSession(world, characterId);
450 state.openSessions.set(characterId, {
451 sessionId,
452 containerId: live.containerId,
453 spawnerId: live.spawnerId,
454 tileX: live.tileX,
455 tileY: live.tileY,
456 dimensionId: live.dimensionId,
457 appearance: live.appearance,
458 startedAt: now,
459 endsAt: now + ITEM_SPAWNER_OPEN_DURATION_MS,
460 nextShoveAt: now
461 });
462
463 return { events: [] };
464}
465
466function containerConditionsMet (world, entityId, live)
467{
468 const when = live.when ?? emptyConditionSet();
469 if (!(when.all?.length > 0))
470 { return true; }
471 const ctx = buildEntityConditionContext(world, entityId);
472 if (!ctx)
473 { return false; }
474 return evaluateConditionSet(when, ctx);
475}
476
477function giveStacksToPlayer (world, handle, entityId, stacks, now, events)
478{
479 const inventory = world.ecs.get(handle, Component.inventory);
480 if (!inventory)
481 { return { dropped: false }; }
482 let dropped = false;
483 const position = world.ecs.get(handle, Component.position);
484 const dim = normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
485 for (const line of stacks)
486 {
487 const def = itemDefinition(line.itemId);
488 if (!def)
489 { continue; }
490 let remaining = Math.max(1, line.quantity | 0);
491 const stack = attachOrigins({
492 itemId: line.itemId,
493 quantity: remaining,
494 origins: [{ origin: godsOrigin(), quantity: remaining }]
495 });
496 const inserted = insertStack(inventory.slots, stack, def);
497 inventory.slots = inserted.slots;
498 remaining = inserted.remainder | 0;
499 if (remaining > 0)
500 {
501 dropped = true;
502 const leftover = attachOrigins({
503 itemId: line.itemId,
504 quantity: remaining,
505 origins: [{ origin: godsOrigin(), quantity: remaining }]
506 });
507 const placed = placeOrMergeGroundStack(world, {
508 tileX: position.tileX,
509 tileY: position.tileY,
510 dimensionId: dim,
511 stack: leftover,
512 now,
513 source: "item-spawner-overflow"
514 });
515 events.push(...placed.events);
516 }
517 }
518 return { dropped };
519}
520
521function completeOpen (world, handle, entityId, characterId, session, events, privates, now)
522{
523 const state = ensureState(world);
524 const live = state.active.get(session.spawnerId);
525 clearOpenSession(world, characterId);
526 if (!live || live.mode !== "container" || live.containerId !== session.containerId)
527 { return; }
528
529 if (!containerConditionsMet(world, entityId, live))
530 {
531 events.push({
532 type: "toast",
533 sessionId: session.sessionId,
534 characterId,
535 message: ITEM_SPAWNER_LOCKED_MESSAGE
536 });
537 return;
538 }
539
540 const stacks = cloneStacks(live.items);
541 const { dropped } = giveStacksToPlayer(world, handle, entityId, stacks, now, events);
542 privates.push({ characterId, bag: bagView(world.ecs, handle) });
543 if (dropped)
544 {
545 events.push({
546 type: "toast",
547 sessionId: session.sessionId,
548 characterId,
549 message: ITEM_SPAWNER_SPACE_TOAST
550 });
551 }
552 clearActive(world, live.spawnerId, events, { scheduleRespawn: true });
553}
554
555function stepOpenSessions (world, now)
556{
557 const state = ensureState(world);
558 const events = [];
559 const privates = [];
560 for (const [characterId, session] of [...state.openSessions.entries()])
561 {
562 const entityId = world.characterEntities.get(characterId);
563 if (entityId == null)
564 {
565 clearOpenSession(world, characterId);
566 continue;
567 }
568 const handle = world.ecs.handleOf(entityId);
569 if (world.ecs.has(handle, Component.dead))
570 {
571 clearOpenSession(world, characterId);
572 continue;
573 }
574 const live = state.active.get(session.spawnerId);
575 if (!live || live.mode !== "container" || live.containerId !== session.containerId)
576 {
577 clearOpenSession(world, characterId);
578 continue;
579 }
580 const position = world.ecs.get(handle, Component.position);
581 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
582 if (normalizeDimensionId(live.dimensionId) !== dim
583 || position.tileX === live.tileX && position.tileY === live.tileY
584 || !isAdjacentTile(position.tileX, position.tileY, live.tileX, live.tileY))
585 {
586 clearOpenSession(world, characterId);
587 continue;
588 }
589
590 if (now >= session.nextShoveAt && now < session.endsAt)
591 {
592 session.nextShoveAt = now + ITEM_SPAWNER_SHOVE_MS;
593 events.push(tileShoveEvent(
594 entityId,
595 position.tileX,
596 position.tileY,
597 live.tileX,
598 live.tileY,
599 dim
600 ));
601 }
602
603 if (now < session.endsAt)
604 { continue; }
605
606 completeOpen(world, handle, entityId, characterId, session, events, privates, now);
607 }
608 return { events, privates };
609}
610
611export function handleItemSpawnerCommand (world, sessionId, command, now = Date.now())
612{
613 if (command.type === "open-item-container")
614 {
615 return startOpenItemContainer(
616 world,
617 sessionId,
618 command.characterId,
619 command.containerId,
620 now
621 );
622 }
623 if (command.type === "cancel-open-item-container")
624 {
625 cancelItemContainerOpen(world, command.characterId);
626 return { events: [] };
627 }
628 return null;
629}
630
631/** Find container at a world tile (for client click helpers / tests). */
632export function itemContainerAtTile (world, tileX, tileY, dimensionId = OVERWORLD_ID)
633{
634 const dim = normalizeDimensionId(dimensionId);
635 const state = ensureState(world);
636 for (const entry of state.active.values())
637 {
638 if (entry.mode !== "container")
639 { continue; }
640 if (entry.tileX === tileX && entry.tileY === tileY
641 && normalizeDimensionId(entry.dimensionId) === dim)
642 { return entry; }
643 }
644 return null;
645}
646
647export { ensureState as ensureItemSpawnerState };
server/src/items/bags.js +6 −1
@@ -199,7 +199,10 @@ export function expireGroundItems (world, now)
199 199 const events = [];
200 200 for (const item of [...world.groundItems.values()])
201 201 {
202 if (item.expiresAt > now)
202 // Authored item-spawner piles never time out.
203 if (item.itemSpawnerId || item.source === "item-spawner")
204 { continue; }
205 if (item.expiresAt == null || item.expiresAt > now)
203 206 { continue; }
204 207 // Destroyed paper frees reserved vault goods; a live ground cheque keeps them reserved.
205 208 if (item.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque")
@@ -253,6 +256,8 @@ export function removeGroundItem (world, groundItemId)
253 256 world.groundByTile.get(key)?.delete(groundItemId);
254 257 if (world.groundByTile.get(key)?.size === 0)
255 258 { world.groundByTile.delete(key); }
259 // Item-spawner tracking (pickup, debark, burn, …) — optional hook avoids cycles.
260 world.onGroundItemRemoved?.(item);
256 261 return item;
257 262 }
258 263
@@ -199,7 +199,10 @@ export function expireGroundItems (world, now)
199 const events = [];
199 const events = [];
200 for (const item of [...world.groundItems.values()])
200 for (const item of [...world.groundItems.values()])
201 {
201 {
202 if (item.expiresAt > now)
202 // Authored item-spawner piles never time out.
203 if (item.itemSpawnerId || item.source === "item-spawner")
204 { continue; }
205 if (item.expiresAt == null || item.expiresAt > now)
203 { continue; }
206 { continue; }
204 // Destroyed paper frees reserved vault goods; a live ground cheque keeps them reserved.
207 // Destroyed paper frees reserved vault goods; a live ground cheque keeps them reserved.
205 if (item.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque")
208 if (item.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque")
@@ -253,6 +256,8 @@ export function removeGroundItem (world, groundItemId)
253 world.groundByTile.get(key)?.delete(groundItemId);
256 world.groundByTile.get(key)?.delete(groundItemId);
254 if (world.groundByTile.get(key)?.size === 0)
257 if (world.groundByTile.get(key)?.size === 0)
255 { world.groundByTile.delete(key); }
258 { world.groundByTile.delete(key); }
259 // Item-spawner tracking (pickup, debark, burn, …) — optional hook avoids cycles.
260 world.onGroundItemRemoved?.(item);
256 return item;
261 return item;
257}
262}
258
263
server/src/simulation/simulation.js +2 −1
@@ -3395,7 +3395,8 @@ export class Simulation
3395 3395 };
3396 3396 this.stateDb.upsertGroundItem(item);
3397 3397 }
3398 if (item.expiresAt > this.now)
3398 if (item.itemSpawnerId || item.source === "item-spawner"
3399 || item.expiresAt == null || item.expiresAt > this.now)
3399 3400 {
3400 3401 items.push(item);
3401 3402 continue;
@@ -3395,7 +3395,8 @@ export class Simulation
3395 };
3395 };
3396 this.stateDb.upsertGroundItem(item);
3396 this.stateDb.upsertGroundItem(item);
3397 }
3397 }
3398 if (item.expiresAt > this.now)
3398 if (item.itemSpawnerId || item.source === "item-spawner"
3399 || item.expiresAt == null || item.expiresAt > this.now)
3399 {
3400 {
3400 items.push(item);
3401 items.push(item);
3401 continue;
3402 continue;
server/src/simulation/spawners.js +3 −0
@@ -17,6 +17,7 @@ import
17 17 isTownGuardMob,
18 18 isHumanoidMob
19 19 } from "../../../shared/definitions/mobs.js";
20 import { isItemSpawnerConfig } from "../../../shared/definitions/itemSpawners.js";
20 21 import { spellDefinition, spellMinMagicLevel, SPRITE_BOLT_SPELL_BY_ELEMENT } from "../../../shared/definitions/spells.js";
21 22 import { MAGIC_ELEMENT_ORDER, magicElementTint } from "../../../shared/definitions/attackTypes.js";
22 23 import { essenceElementDisplayName } from "../../../shared/definitions/essenceItems.js";
@@ -56,6 +57,8 @@ export function collectSpawnRequests (world, now = Date.now())
56 57 : `${dimensionId}:${rawSpawnerId}`;
57 58 const config = normalizeSpawnerConfig(entry.config, scopedSpawnerId);
58 59 config.spawnerId = scopedSpawnerId;
60 if (isItemSpawnerConfig(config))
61 { continue; }
59 62 const flying = !!mobDefinition(config.mobTypeId)?.flying;
60 63 const originX = chunkX * CHUNK_SIZE + localX;
61 64 const originY = chunkY * CHUNK_SIZE + localY;
@@ -17,6 +17,7 @@ import
17 isTownGuardMob,
17 isTownGuardMob,
18 isHumanoidMob
18 isHumanoidMob
19 } from "../../../shared/definitions/mobs.js";
19 } from "../../../shared/definitions/mobs.js";
20import { isItemSpawnerConfig } from "../../../shared/definitions/itemSpawners.js";
20import { spellDefinition, spellMinMagicLevel, SPRITE_BOLT_SPELL_BY_ELEMENT } from "../../../shared/definitions/spells.js";
21import { spellDefinition, spellMinMagicLevel, SPRITE_BOLT_SPELL_BY_ELEMENT } from "../../../shared/definitions/spells.js";
21import { MAGIC_ELEMENT_ORDER, magicElementTint } from "../../../shared/definitions/attackTypes.js";
22import { MAGIC_ELEMENT_ORDER, magicElementTint } from "../../../shared/definitions/attackTypes.js";
22import { essenceElementDisplayName } from "../../../shared/definitions/essenceItems.js";
23import { essenceElementDisplayName } from "../../../shared/definitions/essenceItems.js";
@@ -56,6 +57,8 @@ export function collectSpawnRequests (world, now = Date.now())
56 : `${dimensionId}:${rawSpawnerId}`;
57 : `${dimensionId}:${rawSpawnerId}`;
57 const config = normalizeSpawnerConfig(entry.config, scopedSpawnerId);
58 const config = normalizeSpawnerConfig(entry.config, scopedSpawnerId);
58 config.spawnerId = scopedSpawnerId;
59 config.spawnerId = scopedSpawnerId;
60 if (isItemSpawnerConfig(config))
61 { continue; }
59 const flying = !!mobDefinition(config.mobTypeId)?.flying;
62 const flying = !!mobDefinition(config.mobTypeId)?.flying;
60 const originX = chunkX * CHUNK_SIZE + localX;
63 const originX = chunkX * CHUNK_SIZE + localX;
61 const originY = chunkY * CHUNK_SIZE + localY;
64 const originY = chunkY * CHUNK_SIZE + localY;
server/src/simulation/workerWorld.js +31 −2
@@ -63,6 +63,13 @@ import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
63 63 import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
64 64 import { handleFishingCommand, stepFishing } from "../fishing/service.js";
65 65 import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js";
66 import
67 {
68 handleItemSpawnerCommand,
69 stepItemSpawners,
70 notifyGroundItemRemoved,
71 itemContainersInChunk
72 } from "../itemSpawners/service.js";
66 73 import { handleAlchemyCommand } from "../alchemy/service.js";
67 74 import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
68 75 import {
@@ -139,6 +146,12 @@ export class WorkerWorld
139 146 this.jewelryTeleportSessions = new Map();
140 147 this.settings = { ...DEFAULT_WORLD_SETTINGS };
141 148 this.activeRevisionId = 1;
149 this.onGroundItemRemoved = (item) =>
150 {
151 if (!item?.groundItemId)
152 { return; }
153 notifyGroundItemRemoved(this, item.groundItemId);
154 };
142 155 }
143 156
144 157 handle (message)
@@ -579,6 +592,9 @@ export class WorkerWorld
579 592 const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now());
580 593 if (shearing)
581 594 { return shearing; }
595 const itemSpawner = handleItemSpawnerCommand(this, sessionId, command, message.now ?? Date.now());
596 if (itemSpawner)
597 { return itemSpawner; }
582 598 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
583 599 if (craft)
584 600 { return craft; }
@@ -1540,6 +1556,7 @@ export class WorkerWorld
1540 1556
1541 1557 #stepSystems (now = Date.now(), dt = 1 / 20)
1542 1558 {
1559 this.now = () => now;
1543 1560 const events = [];
1544 1561 const transferRequests = [];
1545 1562 this.#regenStamina(dt, events);
@@ -1646,6 +1663,16 @@ export class WorkerWorld
1646 1663 ...entry.bag
1647 1664 });
1648 1665 }
1666 const itemSpawners = stepItemSpawners(this, now);
1667 events.push(...itemSpawners.events);
1668 for (const entry of itemSpawners.privates ?? [])
1669 {
1670 events.push({
1671 type: "inventory",
1672 characterId: entry.characterId,
1673 ...entry.bag
1674 });
1675 }
1649 1676 const craft = stepCrafting(this, now);
1650 1677 events.push(...craft.events);
1651 1678 for (const entry of craft.privates ?? [])
@@ -2366,7 +2393,8 @@ export class WorkerWorld
2366 2393 enclosed: data.enclosed,
2367 2394 occlusion: data.occlusion,
2368 2395 entities: [],
2369 groundItems: []
2396 groundItems: [],
2397 itemContainers: []
2370 2398 };
2371 2399 }
2372 2400 const entities = [];
@@ -2393,7 +2421,8 @@ export class WorkerWorld
2393 2421 enclosed: data.enclosed,
2394 2422 occlusion: data.occlusion,
2395 2423 entities,
2396 groundItems: groundItemsInChunk(this, chunkX, chunkY, dim)
2424 groundItems: groundItemsInChunk(this, chunkX, chunkY, dim),
2425 itemContainers: itemContainersInChunk(this, chunkX, chunkY, dim)
2397 2426 };
2398 2427 }
2399 2428
@@ -63,6 +63,13 @@ import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
63import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
63import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
64import { handleFishingCommand, stepFishing } from "../fishing/service.js";
64import { handleFishingCommand, stepFishing } from "../fishing/service.js";
65import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js";
65import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js";
66import
67 {
68 handleItemSpawnerCommand,
69 stepItemSpawners,
70 notifyGroundItemRemoved,
71 itemContainersInChunk
72 } from "../itemSpawners/service.js";
66import { handleAlchemyCommand } from "../alchemy/service.js";
73import { handleAlchemyCommand } from "../alchemy/service.js";
67import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
74import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
68import {
75import {
@@ -139,6 +146,12 @@ export class WorkerWorld
139 this.jewelryTeleportSessions = new Map();
146 this.jewelryTeleportSessions = new Map();
140 this.settings = { ...DEFAULT_WORLD_SETTINGS };
147 this.settings = { ...DEFAULT_WORLD_SETTINGS };
141 this.activeRevisionId = 1;
148 this.activeRevisionId = 1;
149 this.onGroundItemRemoved = (item) =>
150 {
151 if (!item?.groundItemId)
152 { return; }
153 notifyGroundItemRemoved(this, item.groundItemId);
154 };
142 }
155 }
143
156
144 handle (message)
157 handle (message)
@@ -579,6 +592,9 @@ export class WorkerWorld
579 const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now());
592 const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now());
580 if (shearing)
593 if (shearing)
581 { return shearing; }
594 { return shearing; }
595 const itemSpawner = handleItemSpawnerCommand(this, sessionId, command, message.now ?? Date.now());
596 if (itemSpawner)
597 { return itemSpawner; }
582 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
598 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
583 if (craft)
599 if (craft)
584 { return craft; }
600 { return craft; }
@@ -1540,6 +1556,7 @@ export class WorkerWorld
1540
1556
1541 #stepSystems (now = Date.now(), dt = 1 / 20)
1557 #stepSystems (now = Date.now(), dt = 1 / 20)
1542 {
1558 {
1559 this.now = () => now;
1543 const events = [];
1560 const events = [];
1544 const transferRequests = [];
1561 const transferRequests = [];
1545 this.#regenStamina(dt, events);
1562 this.#regenStamina(dt, events);
@@ -1646,6 +1663,16 @@ export class WorkerWorld
1646 ...entry.bag
1663 ...entry.bag
1647 });
1664 });
1648 }
1665 }
1666 const itemSpawners = stepItemSpawners(this, now);
1667 events.push(...itemSpawners.events);
1668 for (const entry of itemSpawners.privates ?? [])
1669 {
1670 events.push({
1671 type: "inventory",
1672 characterId: entry.characterId,
1673 ...entry.bag
1674 });
1675 }
1649 const craft = stepCrafting(this, now);
1676 const craft = stepCrafting(this, now);
1650 events.push(...craft.events);
1677 events.push(...craft.events);
1651 for (const entry of craft.privates ?? [])
1678 for (const entry of craft.privates ?? [])
@@ -2366,7 +2393,8 @@ export class WorkerWorld
2366 enclosed: data.enclosed,
2393 enclosed: data.enclosed,
2367 occlusion: data.occlusion,
2394 occlusion: data.occlusion,
2368 entities: [],
2395 entities: [],
2369 groundItems: []
2396 groundItems: [],
2397 itemContainers: []
2370 };
2398 };
2371 }
2399 }
2372 const entities = [];
2400 const entities = [];
@@ -2393,7 +2421,8 @@ export class WorkerWorld
2393 enclosed: data.enclosed,
2421 enclosed: data.enclosed,
2394 occlusion: data.occlusion,
2422 occlusion: data.occlusion,
2395 entities,
2423 entities,
2396 groundItems: groundItemsInChunk(this, chunkX, chunkY, dim)
2424 groundItems: groundItemsInChunk(this, chunkX, chunkY, dim),
2425 itemContainers: itemContainersInChunk(this, chunkX, chunkY, dim)
2397 };
2426 };
2398 }
2427 }
2399
2428
server/tests/item-spawners.test.js added +260 −0
@@ -0,0 +1,260 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
4 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
5 import { ItemId } from "../../shared/definitions/items.js";
6 import { Component } from "../src/ecs/components.js";
7 import
8 {
9 normalizeItemSpawnerConfig,
10 isItemSpawnerConfig,
11 ItemSpawnerAppearance,
12 ITEM_SPAWNER_LOCKED_MESSAGE,
13 ITEM_SPAWNER_OPEN_DURATION_MS
14 } from "../../shared/definitions/itemSpawners.js";
15 import { normalizeSpawnerConfig } from "../../shared/definitions/mobs.js";
16 import { emptySlots, emptyEquipment, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
17 import { ConditionKind } from "../../shared/quests/conditions.js";
18 import
19 {
20 itemContainerAtTile,
21 ensureItemSpawnerState
22 } from "../src/itemSpawners/service.js";
23
24 function workerOf (simulation, playerId)
25 {
26 const record = simulation.entityRecord(playerId);
27 return simulation.workers[record.workerId];
28 }
29
30 function advanceMs (harness, ms)
31 {
32 const ticks = Math.ceil(ms / 50) + 3;
33 for (let i = 0; i < ticks; i++)
34 {
35 harness.advance(50);
36 harness.simulation.step();
37 }
38 }
39
40 function placeItemSpawner (harness, localX, localY, config)
41 {
42 const data = createEmptyChunkData();
43 data.open = true;
44 data.spawners = [{
45 localX,
46 localY,
47 config: normalizeItemSpawnerConfig({
48 spawnerId: `item-${localX}-${localY}`,
49 ...config
50 })
51 }];
52 harness.worldDb.saveChunkVersion(
53 0,
54 0,
55 harness.worldDb.getActiveRevisionId(),
56 true,
57 encodeChunkBlob(data)
58 );
59 harness.simulation.reloadWorld();
60 }
61
62 test("normalizeItemSpawnerConfig auto-switches Appearance Item when multiple stacks", () =>
63 {
64 const config = normalizeSpawnerConfig({
65 spawnerKind: "item",
66 items: [
67 { itemId: ItemId.stick, quantity: 1 },
68 { itemId: ItemId.apple, quantity: 2 }
69 ],
70 appearance: ItemSpawnerAppearance.item
71 }, "t1");
72 assert.equal(isItemSpawnerConfig(config), true);
73 assert.equal(config.appearance, ItemSpawnerAppearance.chest);
74 assert.equal(config.items.length, 2);
75 assert.equal(config.spawnRangeTiles, 0);
76 });
77
78 test("item appearance spawns ground piles that refill after pickup", () =>
79 {
80 const harness = makeSimulation({ workerCount: 1 });
81 try
82 {
83 placeItemSpawner(harness, 9, 8, {
84 appearance: ItemSpawnerAppearance.item,
85 items: [{ itemId: ItemId.stick, quantity: 3 }],
86 respawnDelaySeconds: 1,
87 spawnRangeTiles: 0
88 });
89 const character = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8 });
90 harness.stateDb.saveBag(character.character_id, {
91 inventory: emptySlots(),
92 equipment: emptyEquipment(),
93 vault: [],
94 vaultReserved: []
95 });
96 const playerId = harness.simulation.spawnCharacter(1, character);
97 advanceMs(harness, 200);
98
99 const worker = workerOf(harness.simulation, playerId);
100 const ground = [...worker.world.groundItems.values()].filter(
101 (item) => item.source === "item-spawner" || item.itemSpawnerId
102 );
103 assert.ok(ground.length >= 1, "expected spawner ground item");
104 const groundItemId = ground[0].groundItemId;
105 assert.equal(ground[0].stack.itemId, ItemId.stick);
106
107 harness.simulation.enqueue(1, {
108 type: "pickup-item",
109 characterId: character.character_id,
110 groundItemId
111 });
112 harness.simulation.step();
113 assert.equal(
114 [...worker.world.groundItems.values()].filter((i) => i.itemSpawnerId).length,
115 0
116 );
117
118 advanceMs(harness, 1500);
119 const again = [...worker.world.groundItems.values()].filter(
120 (item) => item.source === "item-spawner" || item.itemSpawnerId
121 );
122 assert.ok(again.length >= 1, "expected respawned ground item");
123 }
124 finally
125 { harness.close(); }
126 });
127
128 test("chest container opens after channel and gives loot", () =>
129 {
130 const harness = makeSimulation({ workerCount: 1 });
131 try
132 {
133 placeItemSpawner(harness, 9, 8, {
134 appearance: ItemSpawnerAppearance.chest,
135 material: "oak",
136 items: [{ itemId: ItemId.apple, quantity: 2 }],
137 respawnDelaySeconds: 60,
138 spawnRangeTiles: 0
139 });
140 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
141 harness.stateDb.saveBag(character.character_id, {
142 inventory: emptySlots(),
143 equipment: emptyEquipment(),
144 vault: [],
145 vaultReserved: []
146 });
147 const playerId = harness.simulation.spawnCharacter(1, character);
148 advanceMs(harness, 200);
149
150 const worker = workerOf(harness.simulation, playerId);
151 const container = itemContainerAtTile(worker.world, 9, 8);
152 assert.ok(container, "expected chest container");
153 assert.equal(container.appearance, "chest");
154 assert.equal(container.material, "oak");
155
156 harness.simulation.enqueue(1, {
157 type: "open-item-container",
158 characterId: character.character_id,
159 containerId: container.containerId
160 });
161 const start = harness.simulation.step();
162 assert.ok(
163 start.events.some((e) => e.type === "tile-shove")
164 || ensureItemSpawnerState(worker.world).openSessions.has(character.character_id),
165 "expected open session or shove"
166 );
167
168 advanceMs(harness, ITEM_SPAWNER_OPEN_DURATION_MS + 200);
169 assert.equal(itemContainerAtTile(worker.world, 9, 8), null);
170
171 const handle = worker.world.ecs.handleOf(playerId);
172 const inventory = worker.world.ecs.get(handle, Component.inventory);
173 const apples = (inventory?.slots ?? []).filter((s) => s?.itemId === ItemId.apple);
174 const qty = apples.reduce((n, s) => n + (s.quantity | 0), 0);
175 assert.equal(qty, 2);
176 }
177 finally
178 { harness.close(); }
179 });
180
181 test("locked container toast when condition fails", () =>
182 {
183 const harness = makeSimulation({ workerCount: 1 });
184 try
185 {
186 placeItemSpawner(harness, 9, 8, {
187 appearance: ItemSpawnerAppearance.barrel,
188 items: [{ itemId: ItemId.stick, quantity: 1 }],
189 when: {
190 mode: "allOf",
191 all: [{ kind: ConditionKind.hasItem, itemId: ItemId.apple, quantity: 1 }]
192 }
193 });
194 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
195 harness.stateDb.saveBag(character.character_id, {
196 inventory: emptySlots(),
197 equipment: emptyEquipment(),
198 vault: [],
199 vaultReserved: []
200 });
201 const playerId = harness.simulation.spawnCharacter(1, character);
202 advanceMs(harness, 200);
203 const worker = workerOf(harness.simulation, playerId);
204 const container = itemContainerAtTile(worker.world, 9, 8);
205 assert.ok(container);
206
207 harness.simulation.enqueue(1, {
208 type: "open-item-container",
209 characterId: character.character_id,
210 containerId: container.containerId
211 });
212 harness.simulation.step();
213 const result = (() =>
214 {
215 const events = [];
216 const ticks = Math.ceil(ITEM_SPAWNER_OPEN_DURATION_MS / 50) + 5;
217 for (let i = 0; i < ticks; i++)
218 {
219 harness.advance(50);
220 events.push(...(harness.simulation.step().events ?? []));
221 }
222 return events;
223 })();
224 const toast = result.find((e) => e.type === "toast" && e.message === ITEM_SPAWNER_LOCKED_MESSAGE);
225 assert.ok(toast, JSON.stringify(result.filter((e) => e.type === "toast")));
226 assert.ok(itemContainerAtTile(worker.world, 9, 8), "locked open must not despawn container");
227 }
228 finally
229 { harness.close(); }
230 });
231
232 test("opening on the container tile is rejected", () =>
233 {
234 const harness = makeSimulation({ workerCount: 1 });
235 try
236 {
237 placeItemSpawner(harness, 9, 8, {
238 appearance: ItemSpawnerAppearance.crate,
239 items: [{ itemId: ItemId.stick, quantity: 1 }]
240 });
241 const character = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8 });
242 const playerId = harness.simulation.spawnCharacter(1, character);
243 advanceMs(harness, 200);
244 const worker = workerOf(harness.simulation, playerId);
245 const container = itemContainerAtTile(worker.world, 9, 8);
246 assert.ok(container);
247
248 harness.simulation.enqueue(1, {
249 type: "open-item-container",
250 characterId: character.character_id,
251 containerId: container.containerId
252 });
253 const step = harness.simulation.step();
254 const err = step.events.find((e) => e.type === "command-error");
255 assert.ok(err, JSON.stringify(step.events));
256 assert.match(err.message, /next to the container/i);
257 }
258 finally
259 { harness.close(); }
260 });
@@ -0,0 +1,260 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
4import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
5import { ItemId } from "../../shared/definitions/items.js";
6import { Component } from "../src/ecs/components.js";
7import
8 {
9 normalizeItemSpawnerConfig,
10 isItemSpawnerConfig,
11 ItemSpawnerAppearance,
12 ITEM_SPAWNER_LOCKED_MESSAGE,
13 ITEM_SPAWNER_OPEN_DURATION_MS
14 } from "../../shared/definitions/itemSpawners.js";
15import { normalizeSpawnerConfig } from "../../shared/definitions/mobs.js";
16import { emptySlots, emptyEquipment, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
17import { ConditionKind } from "../../shared/quests/conditions.js";
18import
19 {
20 itemContainerAtTile,
21 ensureItemSpawnerState
22 } from "../src/itemSpawners/service.js";
23
24function workerOf (simulation, playerId)
25{
26 const record = simulation.entityRecord(playerId);
27 return simulation.workers[record.workerId];
28}
29
30function advanceMs (harness, ms)
31{
32 const ticks = Math.ceil(ms / 50) + 3;
33 for (let i = 0; i < ticks; i++)
34 {
35 harness.advance(50);
36 harness.simulation.step();
37 }
38}
39
40function placeItemSpawner (harness, localX, localY, config)
41{
42 const data = createEmptyChunkData();
43 data.open = true;
44 data.spawners = [{
45 localX,
46 localY,
47 config: normalizeItemSpawnerConfig({
48 spawnerId: `item-${localX}-${localY}`,
49 ...config
50 })
51 }];
52 harness.worldDb.saveChunkVersion(
53 0,
54 0,
55 harness.worldDb.getActiveRevisionId(),
56 true,
57 encodeChunkBlob(data)
58 );
59 harness.simulation.reloadWorld();
60}
61
62test("normalizeItemSpawnerConfig auto-switches Appearance Item when multiple stacks", () =>
63{
64 const config = normalizeSpawnerConfig({
65 spawnerKind: "item",
66 items: [
67 { itemId: ItemId.stick, quantity: 1 },
68 { itemId: ItemId.apple, quantity: 2 }
69 ],
70 appearance: ItemSpawnerAppearance.item
71 }, "t1");
72 assert.equal(isItemSpawnerConfig(config), true);
73 assert.equal(config.appearance, ItemSpawnerAppearance.chest);
74 assert.equal(config.items.length, 2);
75 assert.equal(config.spawnRangeTiles, 0);
76});
77
78test("item appearance spawns ground piles that refill after pickup", () =>
79{
80 const harness = makeSimulation({ workerCount: 1 });
81 try
82 {
83 placeItemSpawner(harness, 9, 8, {
84 appearance: ItemSpawnerAppearance.item,
85 items: [{ itemId: ItemId.stick, quantity: 3 }],
86 respawnDelaySeconds: 1,
87 spawnRangeTiles: 0
88 });
89 const character = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8 });
90 harness.stateDb.saveBag(character.character_id, {
91 inventory: emptySlots(),
92 equipment: emptyEquipment(),
93 vault: [],
94 vaultReserved: []
95 });
96 const playerId = harness.simulation.spawnCharacter(1, character);
97 advanceMs(harness, 200);
98
99 const worker = workerOf(harness.simulation, playerId);
100 const ground = [...worker.world.groundItems.values()].filter(
101 (item) => item.source === "item-spawner" || item.itemSpawnerId
102 );
103 assert.ok(ground.length >= 1, "expected spawner ground item");
104 const groundItemId = ground[0].groundItemId;
105 assert.equal(ground[0].stack.itemId, ItemId.stick);
106
107 harness.simulation.enqueue(1, {
108 type: "pickup-item",
109 characterId: character.character_id,
110 groundItemId
111 });
112 harness.simulation.step();
113 assert.equal(
114 [...worker.world.groundItems.values()].filter((i) => i.itemSpawnerId).length,
115 0
116 );
117
118 advanceMs(harness, 1500);
119 const again = [...worker.world.groundItems.values()].filter(
120 (item) => item.source === "item-spawner" || item.itemSpawnerId
121 );
122 assert.ok(again.length >= 1, "expected respawned ground item");
123 }
124 finally
125 { harness.close(); }
126});
127
128test("chest container opens after channel and gives loot", () =>
129{
130 const harness = makeSimulation({ workerCount: 1 });
131 try
132 {
133 placeItemSpawner(harness, 9, 8, {
134 appearance: ItemSpawnerAppearance.chest,
135 material: "oak",
136 items: [{ itemId: ItemId.apple, quantity: 2 }],
137 respawnDelaySeconds: 60,
138 spawnRangeTiles: 0
139 });
140 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
141 harness.stateDb.saveBag(character.character_id, {
142 inventory: emptySlots(),
143 equipment: emptyEquipment(),
144 vault: [],
145 vaultReserved: []
146 });
147 const playerId = harness.simulation.spawnCharacter(1, character);
148 advanceMs(harness, 200);
149
150 const worker = workerOf(harness.simulation, playerId);
151 const container = itemContainerAtTile(worker.world, 9, 8);
152 assert.ok(container, "expected chest container");
153 assert.equal(container.appearance, "chest");
154 assert.equal(container.material, "oak");
155
156 harness.simulation.enqueue(1, {
157 type: "open-item-container",
158 characterId: character.character_id,
159 containerId: container.containerId
160 });
161 const start = harness.simulation.step();
162 assert.ok(
163 start.events.some((e) => e.type === "tile-shove")
164 || ensureItemSpawnerState(worker.world).openSessions.has(character.character_id),
165 "expected open session or shove"
166 );
167
168 advanceMs(harness, ITEM_SPAWNER_OPEN_DURATION_MS + 200);
169 assert.equal(itemContainerAtTile(worker.world, 9, 8), null);
170
171 const handle = worker.world.ecs.handleOf(playerId);
172 const inventory = worker.world.ecs.get(handle, Component.inventory);
173 const apples = (inventory?.slots ?? []).filter((s) => s?.itemId === ItemId.apple);
174 const qty = apples.reduce((n, s) => n + (s.quantity | 0), 0);
175 assert.equal(qty, 2);
176 }
177 finally
178 { harness.close(); }
179});
180
181test("locked container toast when condition fails", () =>
182{
183 const harness = makeSimulation({ workerCount: 1 });
184 try
185 {
186 placeItemSpawner(harness, 9, 8, {
187 appearance: ItemSpawnerAppearance.barrel,
188 items: [{ itemId: ItemId.stick, quantity: 1 }],
189 when: {
190 mode: "allOf",
191 all: [{ kind: ConditionKind.hasItem, itemId: ItemId.apple, quantity: 1 }]
192 }
193 });
194 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
195 harness.stateDb.saveBag(character.character_id, {
196 inventory: emptySlots(),
197 equipment: emptyEquipment(),
198 vault: [],
199 vaultReserved: []
200 });
201 const playerId = harness.simulation.spawnCharacter(1, character);
202 advanceMs(harness, 200);
203 const worker = workerOf(harness.simulation, playerId);
204 const container = itemContainerAtTile(worker.world, 9, 8);
205 assert.ok(container);
206
207 harness.simulation.enqueue(1, {
208 type: "open-item-container",
209 characterId: character.character_id,
210 containerId: container.containerId
211 });
212 harness.simulation.step();
213 const result = (() =>
214 {
215 const events = [];
216 const ticks = Math.ceil(ITEM_SPAWNER_OPEN_DURATION_MS / 50) + 5;
217 for (let i = 0; i < ticks; i++)
218 {
219 harness.advance(50);
220 events.push(...(harness.simulation.step().events ?? []));
221 }
222 return events;
223 })();
224 const toast = result.find((e) => e.type === "toast" && e.message === ITEM_SPAWNER_LOCKED_MESSAGE);
225 assert.ok(toast, JSON.stringify(result.filter((e) => e.type === "toast")));
226 assert.ok(itemContainerAtTile(worker.world, 9, 8), "locked open must not despawn container");
227 }
228 finally
229 { harness.close(); }
230});
231
232test("opening on the container tile is rejected", () =>
233{
234 const harness = makeSimulation({ workerCount: 1 });
235 try
236 {
237 placeItemSpawner(harness, 9, 8, {
238 appearance: ItemSpawnerAppearance.crate,
239 items: [{ itemId: ItemId.stick, quantity: 1 }]
240 });
241 const character = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8 });
242 const playerId = harness.simulation.spawnCharacter(1, character);
243 advanceMs(harness, 200);
244 const worker = workerOf(harness.simulation, playerId);
245 const container = itemContainerAtTile(worker.world, 9, 8);
246 assert.ok(container);
247
248 harness.simulation.enqueue(1, {
249 type: "open-item-container",
250 characterId: character.character_id,
251 containerId: container.containerId
252 });
253 const step = harness.simulation.step();
254 const err = step.events.find((e) => e.type === "command-error");
255 assert.ok(err, JSON.stringify(step.events));
256 assert.match(err.message, /next to the container/i);
257 }
258 finally
259 { harness.close(); }
260});
shared/definitions/itemSpawners.js added +195 −0
@@ -0,0 +1,195 @@
1 /**
2 * Item Spawner — authored world-editor spawner that creates ground items or
3 * openable wooden containers (chest / barrel / crate) with optional conditions.
4 */
5 import { WOOD_TIER_ORDER, WoodTier, MATERIAL_DISPLAY_NAME } from "./materialTiers.js";
6 import { itemDefinition } from "./items.js";
7 import { normalizeConditionSet, emptyConditionSet } from "../quests/conditions.js";
8 import { spriteImageName } from "./tileSprites.js";
9
10 export const ItemSpawnerKind = "item";
11
12 export const ItemSpawnerAppearance = Object.freeze({
13 item: "item",
14 chest: "chest",
15 barrel: "barrel",
16 crate: "crate"
17 });
18
19 export const ITEM_SPAWNER_APPEARANCES = Object.freeze([
20 ItemSpawnerAppearance.item,
21 ItemSpawnerAppearance.chest,
22 ItemSpawnerAppearance.barrel,
23 ItemSpawnerAppearance.crate
24 ]);
25
26 export const ITEM_SPAWNER_CONTAINER_APPEARANCES = Object.freeze([
27 ItemSpawnerAppearance.chest,
28 ItemSpawnerAppearance.barrel,
29 ItemSpawnerAppearance.crate
30 ]);
31
32 /** Fail toast when container ConditionSet fails (British English). */
33 export const ITEM_SPAWNER_LOCKED_MESSAGE = "The container is locked.";
34
35 /** Partial-loot toast when inventory cannot hold everything. */
36 export const ITEM_SPAWNER_SPACE_TOAST = "Not enough space -- some items were dropped!";
37
38 export const ITEM_SPAWNER_OPEN_DURATION_MS = 2000;
39 export const ITEM_SPAWNER_SHOVE_MS = 1000;
40
41 /** Magenta container art folder under assets/blocks/. */
42 export const ITEM_SPAWNER_CONTAINER_ASSET_KEY = "containers";
43
44 export function isItemSpawnerConfig (config)
45 {
46 if (!config || typeof config !== "object")
47 { return false; }
48 if (config.spawnerKind === ItemSpawnerKind)
49 { return true; }
50 // Legacy / explicit sentinel without mobTypeId.
51 if (config.kind === ItemSpawnerKind)
52 { return true; }
53 return false;
54 }
55
56 export function isItemSpawnerContainerAppearance (appearance)
57 {
58 return ITEM_SPAWNER_CONTAINER_APPEARANCES.includes(appearance);
59 }
60
61 /** British English display name for Open / context menu. */
62 export function itemSpawnerContainerDisplayName (appearance)
63 {
64 switch (appearance)
65 {
66 case ItemSpawnerAppearance.barrel:
67 return "Barrel";
68 case ItemSpawnerAppearance.crate:
69 return "Crate";
70 case ItemSpawnerAppearance.chest:
71 default:
72 return "Chest";
73 }
74 }
75
76 export function itemSpawnerOpenLabel (appearance)
77 {
78 return `Open ${itemSpawnerContainerDisplayName(appearance)}`;
79 }
80
81 /**
82 * Catalog image name for a wood-tinted container (`block:containers:pine-chest`).
83 */
84 export function itemSpawnerContainerSpriteName (appearance, material = WoodTier.pine)
85 {
86 const look = isItemSpawnerContainerAppearance(appearance)
87 ? appearance
88 : ItemSpawnerAppearance.chest;
89 const wood = WOOD_TIER_ORDER.includes(material) ? material : WoodTier.pine;
90 return spriteImageName("block", ITEM_SPAWNER_CONTAINER_ASSET_KEY, `${wood}-${look}`);
91 }
92
93 /** Editor palette / overlay preview — default pine chest. */
94 export function itemSpawnerPreviewSpriteName ()
95 {
96 return itemSpawnerContainerSpriteName(ItemSpawnerAppearance.chest, WoodTier.pine);
97 }
98
99 function normalizeItemStacks (raw)
100 {
101 if (!Array.isArray(raw))
102 { return []; }
103 const lines = [];
104 for (const entry of raw)
105 {
106 if (!entry || typeof entry !== "object")
107 { continue; }
108 const itemId = Number(entry.itemId) | 0;
109 if (!Number.isFinite(itemId) || itemId <= 0 || !itemDefinition(itemId))
110 { continue; }
111 const quantity = Math.max(1, Math.min(10_000, Math.floor(Number(entry.quantity) || 1)));
112 lines.push({ itemId, quantity });
113 }
114 return lines;
115 }
116
117 /** Distinct item types/stacks count for Appearance=Item gating. */
118 export function itemSpawnerStackCount (items)
119 {
120 return Array.isArray(items) ? items.length : 0;
121 }
122
123 export function defaultItemSpawnerConfig (spawnerId = "item-spawner")
124 {
125 return {
126 spawnerKind: ItemSpawnerKind,
127 spawnerId: String(spawnerId || "item-spawner"),
128 items: [],
129 respawnDelaySeconds: 25,
130 spawnRangeTiles: 0,
131 appearance: ItemSpawnerAppearance.chest,
132 material: WoodTier.pine,
133 when: emptyConditionSet()
134 };
135 }
136
137 /**
138 * Clamp / coerce item-spawner fields. Auto-switches Appearance away from Item
139 * when more than one item stack is selected.
140 */
141 export function normalizeItemSpawnerConfig (config, spawnerId = "item-spawner")
142 {
143 const base = defaultItemSpawnerConfig(spawnerId);
144 const merged = { ...base, ...(config ?? {}) };
145 const id = String(merged.spawnerId || config?.spawnerId || spawnerId || "item-spawner");
146 const items = normalizeItemStacks(merged.items);
147 let appearance = String(merged.appearance ?? base.appearance);
148 if (!ITEM_SPAWNER_APPEARANCES.includes(appearance))
149 { appearance = ItemSpawnerAppearance.chest; }
150 if (appearance === ItemSpawnerAppearance.item && items.length !== 1)
151 { appearance = ItemSpawnerAppearance.chest; }
152 const material = WOOD_TIER_ORDER.includes(merged.material)
153 ? merged.material
154 : WoodTier.pine;
155 const respawnDelaySeconds = Math.max(
156 0,
157 Math.min(
158 86_400,
159 Math.floor(
160 Number(
161 merged.respawnDelaySeconds != null && merged.respawnDelaySeconds !== ""
162 ? merged.respawnDelaySeconds
163 : base.respawnDelaySeconds
164 ) || 0
165 )
166 )
167 );
168 const rawRange = Number(merged.spawnRangeTiles);
169 const spawnRangeTiles = Math.max(
170 0,
171 Math.min(32, Number.isFinite(rawRange) ? (rawRange | 0) : base.spawnRangeTiles)
172 );
173 const when = isItemSpawnerContainerAppearance(appearance)
174 ? normalizeConditionSet(merged.when ?? merged.requirements ?? emptyConditionSet())
175 : emptyConditionSet();
176 return {
177 spawnerKind: ItemSpawnerKind,
178 spawnerId: id,
179 items,
180 respawnDelaySeconds,
181 spawnRangeTiles,
182 appearance,
183 material,
184 when
185 };
186 }
187
188 /** Wood material options for the editor Material dropdown. */
189 export function listItemSpawnerMaterials ()
190 {
191 return WOOD_TIER_ORDER.map((id) => ({
192 id,
193 displayName: MATERIAL_DISPLAY_NAME[id] ?? id
194 }));
195 }
@@ -0,0 +1,195 @@
1/**
2 * Item Spawner — authored world-editor spawner that creates ground items or
3 * openable wooden containers (chest / barrel / crate) with optional conditions.
4 */
5import { WOOD_TIER_ORDER, WoodTier, MATERIAL_DISPLAY_NAME } from "./materialTiers.js";
6import { itemDefinition } from "./items.js";
7import { normalizeConditionSet, emptyConditionSet } from "../quests/conditions.js";
8import { spriteImageName } from "./tileSprites.js";
9
10export const ItemSpawnerKind = "item";
11
12export const ItemSpawnerAppearance = Object.freeze({
13 item: "item",
14 chest: "chest",
15 barrel: "barrel",
16 crate: "crate"
17});
18
19export const ITEM_SPAWNER_APPEARANCES = Object.freeze([
20 ItemSpawnerAppearance.item,
21 ItemSpawnerAppearance.chest,
22 ItemSpawnerAppearance.barrel,
23 ItemSpawnerAppearance.crate
24]);
25
26export const ITEM_SPAWNER_CONTAINER_APPEARANCES = Object.freeze([
27 ItemSpawnerAppearance.chest,
28 ItemSpawnerAppearance.barrel,
29 ItemSpawnerAppearance.crate
30]);
31
32/** Fail toast when container ConditionSet fails (British English). */
33export const ITEM_SPAWNER_LOCKED_MESSAGE = "The container is locked.";
34
35/** Partial-loot toast when inventory cannot hold everything. */
36export const ITEM_SPAWNER_SPACE_TOAST = "Not enough space -- some items were dropped!";
37
38export const ITEM_SPAWNER_OPEN_DURATION_MS = 2000;
39export const ITEM_SPAWNER_SHOVE_MS = 1000;
40
41/** Magenta container art folder under assets/blocks/. */
42export const ITEM_SPAWNER_CONTAINER_ASSET_KEY = "containers";
43
44export function isItemSpawnerConfig (config)
45{
46 if (!config || typeof config !== "object")
47 { return false; }
48 if (config.spawnerKind === ItemSpawnerKind)
49 { return true; }
50 // Legacy / explicit sentinel without mobTypeId.
51 if (config.kind === ItemSpawnerKind)
52 { return true; }
53 return false;
54}
55
56export function isItemSpawnerContainerAppearance (appearance)
57{
58 return ITEM_SPAWNER_CONTAINER_APPEARANCES.includes(appearance);
59}
60
61/** British English display name for Open / context menu. */
62export function itemSpawnerContainerDisplayName (appearance)
63{
64 switch (appearance)
65 {
66 case ItemSpawnerAppearance.barrel:
67 return "Barrel";
68 case ItemSpawnerAppearance.crate:
69 return "Crate";
70 case ItemSpawnerAppearance.chest:
71 default:
72 return "Chest";
73 }
74}
75
76export function itemSpawnerOpenLabel (appearance)
77{
78 return `Open ${itemSpawnerContainerDisplayName(appearance)}`;
79}
80
81/**
82 * Catalog image name for a wood-tinted container (`block:containers:pine-chest`).
83 */
84export function itemSpawnerContainerSpriteName (appearance, material = WoodTier.pine)
85{
86 const look = isItemSpawnerContainerAppearance(appearance)
87 ? appearance
88 : ItemSpawnerAppearance.chest;
89 const wood = WOOD_TIER_ORDER.includes(material) ? material : WoodTier.pine;
90 return spriteImageName("block", ITEM_SPAWNER_CONTAINER_ASSET_KEY, `${wood}-${look}`);
91}
92
93/** Editor palette / overlay preview — default pine chest. */
94export function itemSpawnerPreviewSpriteName ()
95{
96 return itemSpawnerContainerSpriteName(ItemSpawnerAppearance.chest, WoodTier.pine);
97}
98
99function normalizeItemStacks (raw)
100{
101 if (!Array.isArray(raw))
102 { return []; }
103 const lines = [];
104 for (const entry of raw)
105 {
106 if (!entry || typeof entry !== "object")
107 { continue; }
108 const itemId = Number(entry.itemId) | 0;
109 if (!Number.isFinite(itemId) || itemId <= 0 || !itemDefinition(itemId))
110 { continue; }
111 const quantity = Math.max(1, Math.min(10_000, Math.floor(Number(entry.quantity) || 1)));
112 lines.push({ itemId, quantity });
113 }
114 return lines;
115}
116
117/** Distinct item types/stacks count for Appearance=Item gating. */
118export function itemSpawnerStackCount (items)
119{
120 return Array.isArray(items) ? items.length : 0;
121}
122
123export function defaultItemSpawnerConfig (spawnerId = "item-spawner")
124{
125 return {
126 spawnerKind: ItemSpawnerKind,
127 spawnerId: String(spawnerId || "item-spawner"),
128 items: [],
129 respawnDelaySeconds: 25,
130 spawnRangeTiles: 0,
131 appearance: ItemSpawnerAppearance.chest,
132 material: WoodTier.pine,
133 when: emptyConditionSet()
134 };
135}
136
137/**
138 * Clamp / coerce item-spawner fields. Auto-switches Appearance away from Item
139 * when more than one item stack is selected.
140 */
141export function normalizeItemSpawnerConfig (config, spawnerId = "item-spawner")
142{
143 const base = defaultItemSpawnerConfig(spawnerId);
144 const merged = { ...base, ...(config ?? {}) };
145 const id = String(merged.spawnerId || config?.spawnerId || spawnerId || "item-spawner");
146 const items = normalizeItemStacks(merged.items);
147 let appearance = String(merged.appearance ?? base.appearance);
148 if (!ITEM_SPAWNER_APPEARANCES.includes(appearance))
149 { appearance = ItemSpawnerAppearance.chest; }
150 if (appearance === ItemSpawnerAppearance.item && items.length !== 1)
151 { appearance = ItemSpawnerAppearance.chest; }
152 const material = WOOD_TIER_ORDER.includes(merged.material)
153 ? merged.material
154 : WoodTier.pine;
155 const respawnDelaySeconds = Math.max(
156 0,
157 Math.min(
158 86_400,
159 Math.floor(
160 Number(
161 merged.respawnDelaySeconds != null && merged.respawnDelaySeconds !== ""
162 ? merged.respawnDelaySeconds
163 : base.respawnDelaySeconds
164 ) || 0
165 )
166 )
167 );
168 const rawRange = Number(merged.spawnRangeTiles);
169 const spawnRangeTiles = Math.max(
170 0,
171 Math.min(32, Number.isFinite(rawRange) ? (rawRange | 0) : base.spawnRangeTiles)
172 );
173 const when = isItemSpawnerContainerAppearance(appearance)
174 ? normalizeConditionSet(merged.when ?? merged.requirements ?? emptyConditionSet())
175 : emptyConditionSet();
176 return {
177 spawnerKind: ItemSpawnerKind,
178 spawnerId: id,
179 items,
180 respawnDelaySeconds,
181 spawnRangeTiles,
182 appearance,
183 material,
184 when
185 };
186}
187
188/** Wood material options for the editor Material dropdown. */
189export function listItemSpawnerMaterials ()
190{
191 return WOOD_TIER_ORDER.map((id) => ({
192 id,
193 displayName: MATERIAL_DISPLAY_NAME[id] ?? id
194 }));
195}
shared/definitions/mobs.js +3 −0
@@ -8,6 +8,7 @@ import { WoodItemId } from "./woodItems.js";
8 8 import { ItemId } from "./items.js";
9 9 import { EQUIPMENT_SLOTS } from "../items/inventory.js";
10 10 import { spellDefinition } from "./spells.js";
11 import { isItemSpawnerConfig, normalizeItemSpawnerConfig } from "./itemSpawners.js";
11 12 import { ClothTier } from "./materialTiers.js";
12 13 import { ClothItemId } from "./clothItems.js";
13 14 import { EssenceItemId } from "./essenceItems.js";
@@ -701,6 +702,8 @@ function normalizeSpells (raw)
701 702 /** Clamp wander ≥ spawn; coerce numeric fields; keep humanoid shop/appearance options. */
702 703 export function normalizeSpawnerConfig (config, spawnerId = "spawner")
703 704 {
705 if (isItemSpawnerConfig(config))
706 { return normalizeItemSpawnerConfig(config, spawnerId); }
704 707 const mobTypeId = config?.mobTypeId ?? MobId.deer;
705 708 const centralExchange = mobTypeId === MobId.centralExchange || !!config?.centralExchange;
706 709 const townGuard = !centralExchange && (mobTypeId === MobId.townGuard || !!config?.townGuard);
@@ -8,6 +8,7 @@ import { WoodItemId } from "./woodItems.js";
8import { ItemId } from "./items.js";
8import { ItemId } from "./items.js";
9import { EQUIPMENT_SLOTS } from "../items/inventory.js";
9import { EQUIPMENT_SLOTS } from "../items/inventory.js";
10import { spellDefinition } from "./spells.js";
10import { spellDefinition } from "./spells.js";
11import { isItemSpawnerConfig, normalizeItemSpawnerConfig } from "./itemSpawners.js";
11import { ClothTier } from "./materialTiers.js";
12import { ClothTier } from "./materialTiers.js";
12import { ClothItemId } from "./clothItems.js";
13import { ClothItemId } from "./clothItems.js";
13import { EssenceItemId } from "./essenceItems.js";
14import { EssenceItemId } from "./essenceItems.js";
@@ -701,6 +702,8 @@ function normalizeSpells (raw)
701/** Clamp wander ≥ spawn; coerce numeric fields; keep humanoid shop/appearance options. */
702/** Clamp wander ≥ spawn; coerce numeric fields; keep humanoid shop/appearance options. */
702export function normalizeSpawnerConfig (config, spawnerId = "spawner")
703export function normalizeSpawnerConfig (config, spawnerId = "spawner")
703{
704{
705 if (isItemSpawnerConfig(config))
706 { return normalizeItemSpawnerConfig(config, spawnerId); }
704 const mobTypeId = config?.mobTypeId ?? MobId.deer;
707 const mobTypeId = config?.mobTypeId ?? MobId.deer;
705 const centralExchange = mobTypeId === MobId.centralExchange || !!config?.centralExchange;
708 const centralExchange = mobTypeId === MobId.centralExchange || !!config?.centralExchange;
706 const townGuard = !centralExchange && (mobTypeId === MobId.townGuard || !!config?.townGuard);
709 const townGuard = !centralExchange && (mobTypeId === MobId.townGuard || !!config?.townGuard);
shared/protocol/constants.js +3 −0
@@ -200,6 +200,9 @@ export const MessageType = Object.freeze({
200 200 debarkLog: "DEBARK_LOG",
201 201 startFish: "START_FISH",
202 202 shear: "SHEAR",
203 openItemContainer: "OPEN_ITEM_CONTAINER",
204 itemContainerAppear: "ITEM_CONTAINER_APPEAR",
205 itemContainerDespawn: "ITEM_CONTAINER_DESPAWN",
203 206 cancelCraft: "CANCEL_CRAFT",
204 207 craftResult: "CRAFT_RESULT",
205 208 openCauldron: "OPEN_CAULDRON",
@@ -200,6 +200,9 @@ export const MessageType = Object.freeze({
200 debarkLog: "DEBARK_LOG",
200 debarkLog: "DEBARK_LOG",
201 startFish: "START_FISH",
201 startFish: "START_FISH",
202 shear: "SHEAR",
202 shear: "SHEAR",
203 openItemContainer: "OPEN_ITEM_CONTAINER",
204 itemContainerAppear: "ITEM_CONTAINER_APPEAR",
205 itemContainerDespawn: "ITEM_CONTAINER_DESPAWN",
203 cancelCraft: "CANCEL_CRAFT",
206 cancelCraft: "CANCEL_CRAFT",
204 craftResult: "CRAFT_RESULT",
207 craftResult: "CRAFT_RESULT",
205 openCauldron: "OPEN_CAULDRON",
208 openCauldron: "OPEN_CAULDRON",