Add fishing and firestarting, plus lighting and combat pathing fixes.
Fishing with spots, bait, net, pole/rod crafting and line breaks; firestarting, campfires, ovens, and cooking. Dynamic lights reach the outer map ring from the 3×3 sim zone. Combatants share stance tiles instead of sidestepping forever.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#8a3a18"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">FS</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#8a3a18"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">FS</text></svg>@@ -517,18 +517,28 @@ function paintAt (localX, localY)
else
{
const def = BLOCK_DEFINITIONS[tool.typeId];
if (def?.id === BlockType.fishingSpot)
{
const groundType = draft.grounds[index]?.typeId;
if (groundType !== GroundType.water && groundType !== GroundType.deepWater)
{ return; }
}
let nextState = definitionUsesNeighborConnect(def)
? composeNeighborConnectState(def, state, 0)
: state;
if (def?.id === BlockType.flower)
{ nextState = flowerBlockState(randomFlowerColorId()); }
if (def?.id === BlockType.fishingSpot && !nextState)
{ nextState = "fishing-spot"; }
const config = def?.id === BlockType.doorway
? {
targetDimensionId: selectedDimensionId,
tileX: chunkX * CHUNK_SIZE + localX,
tileY: chunkY * CHUNK_SIZE + localY
}
: null;
: (def?.id === BlockType.fishingSpot
? { fishes: [] }
: null);
if (def?.id === BlockType.doorway && !nextState)
{ nextState = "door"; }
draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
@@ -984,6 +994,23 @@ async function main ()
afterDraftMutation();
return;
}
if (ctx.kind === "fishing-spot")
{
const index = ctx.localY * CHUNK_SIZE + ctx.localX;
const existing = draft.blocks[index];
draft.blocks[index] = {
typeId: BlockType.fishingSpot,
state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot",
config: { fishes: [...(config.fishes ?? [])] }
};
view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
ground: draft.grounds[index],
block: draft.blocks[index],
light: draft.light[index]
});
afterDraftMutation();
return;
}
draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
@@ -1005,6 +1032,18 @@ async function main ()
afterDraftMutation();
return;
}
if (ctx.kind === "fishing-spot")
{
const index = ctx.localY * CHUNK_SIZE + ctx.localX;
draft.blocks[index] = null;
view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
ground: draft.grounds[index],
block: draft.blocks[index],
light: draft.light[index]
});
afterDraftMutation();
return;
}
draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
afterDraftMutation();
@@ -1456,6 +1495,17 @@ document.addEventListener("contextmenu", (event) =>
state: block.state ?? "door",
config: block.config ? { ...block.config } : {}
});
return;
}
if (block?.typeId === BlockType.fishingSpot)
{
tileConfigModal.openFishingSpot({
localX,
localY,
tileX: tile.tileX,
tileY: tile.tileY,
config: block.config ? { ...block.config } : { fishes: [] }
});
}
});
@@ -517,18 +517,28 @@ function paintAt (localX, localY) else else { { const def = BLOCK_DEFINITIONS[tool.typeId]; const def = BLOCK_DEFINITIONS[tool.typeId]; if (def?.id === BlockType.fishingSpot) { const groundType = draft.grounds[index]?.typeId; if (groundType !== GroundType.water && groundType !== GroundType.deepWater) { return; } } let nextState = definitionUsesNeighborConnect(def) let nextState = definitionUsesNeighborConnect(def) ? composeNeighborConnectState(def, state, 0) ? composeNeighborConnectState(def, state, 0) : state; : state; if (def?.id === BlockType.flower) if (def?.id === BlockType.flower) { nextState = flowerBlockState(randomFlowerColorId()); } { nextState = flowerBlockState(randomFlowerColorId()); } if (def?.id === BlockType.fishingSpot && !nextState) { nextState = "fishing-spot"; } const config = def?.id === BlockType.doorway const config = def?.id === BlockType.doorway ? { ? { targetDimensionId: selectedDimensionId, targetDimensionId: selectedDimensionId, tileX: chunkX * CHUNK_SIZE + localX, tileX: chunkX * CHUNK_SIZE + localX, tileY: chunkY * CHUNK_SIZE + localY tileY: chunkY * CHUNK_SIZE + localY } } : null; : (def?.id === BlockType.fishingSpot ? { fishes: [] } : null); if (def?.id === BlockType.doorway && !nextState) if (def?.id === BlockType.doorway && !nextState) { nextState = "door"; } { nextState = "door"; } draft.blocks[index] = { typeId: tool.typeId, state: nextState, config }; draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };@@ -984,6 +994,23 @@ async function main () afterDraftMutation(); afterDraftMutation(); return; return; } } if (ctx.kind === "fishing-spot") { const index = ctx.localY * CHUNK_SIZE + ctx.localX; const existing = draft.blocks[index]; draft.blocks[index] = { typeId: BlockType.fishingSpot, state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot", config: { fishes: [...(config.fishes ?? [])] } }; view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); afterDraftMutation(); return; } draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY); draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY); draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config }); draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config }); syncSpawnersOverlay(chunkX, chunkY, draft.spawners); syncSpawnersOverlay(chunkX, chunkY, draft.spawners);@@ -1005,6 +1032,18 @@ async function main () afterDraftMutation(); afterDraftMutation(); return; return; } } if (ctx.kind === "fishing-spot") { const index = ctx.localY * CHUNK_SIZE + ctx.localX; draft.blocks[index] = null; view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); afterDraftMutation(); return; } draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY); draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY); syncSpawnersOverlay(chunkX, chunkY, draft.spawners); syncSpawnersOverlay(chunkX, chunkY, draft.spawners); afterDraftMutation(); afterDraftMutation();@@ -1456,6 +1495,17 @@ document.addEventListener("contextmenu", (event) => state: block.state ?? "door", state: block.state ?? "door", config: block.config ? { ...block.config } : {} config: block.config ? { ...block.config } : {} }); }); return; } if (block?.typeId === BlockType.fishingSpot) { tileConfigModal.openFishingSpot({ localX, localY, tileX: tile.tileX, tileY: tile.tileY, config: block.config ? { ...block.config } : { fishes: [] } }); } }});});@@ -13,6 +13,7 @@ import { mobSpellCastChancePercent } from "/shared/definitions/mobCombat.js";
import { SPELL_DEFINITIONS } from "/shared/definitions/spells.js";
import { centralExchangeStaffCount } from "/shared/market/exchange.js";
import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing, listAllItemPickerEntries } from "/shared/definitions/items.js";
import { listRawFishPickerEntries, normalizeFishingSpotConfig } from "/shared/definitions/fishItems.js";
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
import { normalizeRgb } from "/shared/render/tint.js";
import { createDimensionCombobox } from "./dimensionCombobox.js";
@@ -107,11 +108,13 @@ export function initTileConfigModal ({
let context = null;
/** @type {{ itemId: number, quantity: number }[]} */
let sellsDraft = [];
/** @type {number[]} raw fish item ids for fishing spots */
let fishesDraft = [];
/** @type {{ spellId: string, chance: number }[]} */
let spellsDraft = [];
/** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */
let equipmentDraft = {};
/** @type {{ kind: "sells" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */
/** @type {{ kind: "sells" } | { kind: "fishes" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */
let itemSearchMode = null;
/** @type {string|null} */
let dyeEditSlot = null;
@@ -156,6 +159,12 @@ export function initTileConfigModal ({
openItemSearch("Add shop stock");
}
function openFishItemSearch ()
{
itemSearchMode = { kind: "fishes" };
openItemSearch("Add fish to spot");
}
function openEquipItemSearch (slot)
{
itemSearchMode = { kind: "equip", slot };
@@ -173,7 +182,9 @@ export function initTileConfigModal ({
itemSearchMatches = null;
itemSearchInput.placeholder = itemSearchMode?.kind === "equip"
? "Search equipment…"
: "Search all items…";
: itemSearchMode?.kind === "fishes"
? "Search raw fish…"
: "Search all items…";
renderItemSearchResults("");
itemSearchBackdrop.hidden = false;
itemSearchModal.hidden = false;
@@ -184,6 +195,8 @@ export function initTileConfigModal ({
{
if (itemSearchMode?.kind === "equip")
{ return listEquippableItemsForSlot(itemSearchMode.slot); }
if (itemSearchMode?.kind === "fishes")
{ return listRawFishPickerEntries(); }
return listAllItemPickerEntries();
}
@@ -257,6 +270,12 @@ export function initTileConfigModal ({
};
renderEquipmentRows();
}
else if (itemSearchMode?.kind === "fishes")
{
if (!fishesDraft.includes(item.itemId))
{ fishesDraft.push(item.itemId); }
renderFishesList();
}
else
{
sellsDraft.push({ itemId: item.itemId, quantity: 0 });
@@ -350,6 +369,42 @@ export function initTileConfigModal ({
bindDyeChannel(dyeG, dyeGNum);
bindDyeChannel(dyeB, dyeBNum);
function renderFishesList ()
{
const list = form.querySelector("[data-fishes-list]");
if (!list)
{ return; }
list.innerHTML = "";
if (!fishesDraft.length)
{
const empty = document.createElement("p");
empty.className = "hint";
empty.textContent = "No fish yet. Use + to choose species for this spot.";
list.append(empty);
return;
}
for (let index = 0; index < fishesDraft.length; index++)
{
const itemId = fishesDraft[index];
const def = itemDefinition(itemId);
const row = document.createElement("div");
row.className = "spawner-sells-row";
const name = document.createElement("span");
name.className = "spawner-sells-name";
name.textContent = def?.displayName ?? `Item ${itemId}`;
const remove = document.createElement("button");
remove.type = "button";
remove.textContent = "Remove";
remove.addEventListener("click", () =>
{
fishesDraft.splice(index, 1);
renderFishesList();
});
row.append(name, remove);
list.append(row);
}
}
function renderSellsList ()
{
const list = form.querySelector("[data-sells-list]");
@@ -761,6 +816,30 @@ export function initTileConfigModal ({
show(true);
}
function openFishingSpot (ctx)
{
context = { kind: "fishing-spot", ...ctx };
const normalized = normalizeFishingSpotConfig(ctx.config);
fishesDraft = [...normalized.fishes];
title.textContent = `Fishing spot · ${ctx.tileX}, ${ctx.tileY}`;
form.innerHTML = "";
const header = document.createElement("div");
header.className = "spawner-sells-header";
const label = document.createElement("strong");
label.textContent = "Fishes";
const addBtn = document.createElement("button");
addBtn.type = "button";
addBtn.textContent = "+";
addBtn.title = "Add fish";
addBtn.addEventListener("click", () => openFishItemSearch());
header.append(label, addBtn);
const list = document.createElement("div");
list.setAttribute("data-fishes-list", "");
form.append(header, list);
renderFishesList();
show(true);
}
function openDoorway (ctx)
{
context = { kind: "doorway", ...ctx };
@@ -851,6 +930,12 @@ export function initTileConfigModal ({
show(false);
return;
}
if (context.kind === "fishing-spot")
{
onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft }));
show(false);
return;
}
const data = new FormData(form);
const equipment = {};
for (const slot of EQUIPMENT_SLOTS)
@@ -888,6 +973,7 @@ export function initTileConfigModal ({
isOpen: () => open,
openSpawner,
openDoorway,
openFishingSpot,
close: () => show(false),
handleMessage (message)
{
@@ -13,6 +13,7 @@ import { mobSpellCastChancePercent } from "/shared/definitions/mobCombat.js";import { SPELL_DEFINITIONS } from "/shared/definitions/spells.js";import { SPELL_DEFINITIONS } from "/shared/definitions/spells.js";import { centralExchangeStaffCount } from "/shared/market/exchange.js";import { centralExchangeStaffCount } from "/shared/market/exchange.js";import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing, listAllItemPickerEntries } from "/shared/definitions/items.js";import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing, listAllItemPickerEntries } from "/shared/definitions/items.js";import { listRawFishPickerEntries, normalizeFishingSpotConfig } from "/shared/definitions/fishItems.js";import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";import { normalizeRgb } from "/shared/render/tint.js";import { normalizeRgb } from "/shared/render/tint.js";import { createDimensionCombobox } from "./dimensionCombobox.js";import { createDimensionCombobox } from "./dimensionCombobox.js";@@ -107,11 +108,13 @@ export function initTileConfigModal ({ let context = null; let context = null; /** @type {{ itemId: number, quantity: number }[]} */ /** @type {{ itemId: number, quantity: number }[]} */ let sellsDraft = []; let sellsDraft = []; /** @type {number[]} raw fish item ids for fishing spots */ let fishesDraft = []; /** @type {{ spellId: string, chance: number }[]} */ /** @type {{ spellId: string, chance: number }[]} */ let spellsDraft = []; let spellsDraft = []; /** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */ /** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */ let equipmentDraft = {}; let equipmentDraft = {}; /** @type {{ kind: "sells" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */ /** @type {{ kind: "sells" } | { kind: "fishes" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */ let itemSearchMode = null; let itemSearchMode = null; /** @type {string|null} */ /** @type {string|null} */ let dyeEditSlot = null; let dyeEditSlot = null;@@ -156,6 +159,12 @@ export function initTileConfigModal ({ openItemSearch("Add shop stock"); openItemSearch("Add shop stock"); } } function openFishItemSearch () { itemSearchMode = { kind: "fishes" }; openItemSearch("Add fish to spot"); } function openEquipItemSearch (slot) function openEquipItemSearch (slot) { { itemSearchMode = { kind: "equip", slot }; itemSearchMode = { kind: "equip", slot };@@ -173,7 +182,9 @@ export function initTileConfigModal ({ itemSearchMatches = null; itemSearchMatches = null; itemSearchInput.placeholder = itemSearchMode?.kind === "equip" itemSearchInput.placeholder = itemSearchMode?.kind === "equip" ? "Search equipment…" ? "Search equipment…" : "Search all items…"; : itemSearchMode?.kind === "fishes" ? "Search raw fish…" : "Search all items…"; renderItemSearchResults(""); renderItemSearchResults(""); itemSearchBackdrop.hidden = false; itemSearchBackdrop.hidden = false; itemSearchModal.hidden = false; itemSearchModal.hidden = false;@@ -184,6 +195,8 @@ export function initTileConfigModal ({ { { if (itemSearchMode?.kind === "equip") if (itemSearchMode?.kind === "equip") { return listEquippableItemsForSlot(itemSearchMode.slot); } { return listEquippableItemsForSlot(itemSearchMode.slot); } if (itemSearchMode?.kind === "fishes") { return listRawFishPickerEntries(); } return listAllItemPickerEntries(); return listAllItemPickerEntries(); } }@@ -257,6 +270,12 @@ export function initTileConfigModal ({ }; }; renderEquipmentRows(); renderEquipmentRows(); } } else if (itemSearchMode?.kind === "fishes") { if (!fishesDraft.includes(item.itemId)) { fishesDraft.push(item.itemId); } renderFishesList(); } else else { { sellsDraft.push({ itemId: item.itemId, quantity: 0 }); sellsDraft.push({ itemId: item.itemId, quantity: 0 });@@ -350,6 +369,42 @@ export function initTileConfigModal ({ bindDyeChannel(dyeG, dyeGNum); bindDyeChannel(dyeG, dyeGNum); bindDyeChannel(dyeB, dyeBNum); bindDyeChannel(dyeB, dyeBNum); function renderFishesList () { const list = form.querySelector("[data-fishes-list]"); if (!list) { return; } list.innerHTML = ""; if (!fishesDraft.length) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "No fish yet. Use + to choose species for this spot."; list.append(empty); return; } for (let index = 0; index < fishesDraft.length; index++) { const itemId = fishesDraft[index]; const def = itemDefinition(itemId); const row = document.createElement("div"); row.className = "spawner-sells-row"; const name = document.createElement("span"); name.className = "spawner-sells-name"; name.textContent = def?.displayName ?? `Item ${itemId}`; const remove = document.createElement("button"); remove.type = "button"; remove.textContent = "Remove"; remove.addEventListener("click", () => { fishesDraft.splice(index, 1); renderFishesList(); }); row.append(name, remove); list.append(row); } } function renderSellsList () function renderSellsList () { { const list = form.querySelector("[data-sells-list]"); const list = form.querySelector("[data-sells-list]");@@ -761,6 +816,30 @@ export function initTileConfigModal ({ show(true); show(true); } } function openFishingSpot (ctx) { context = { kind: "fishing-spot", ...ctx }; const normalized = normalizeFishingSpotConfig(ctx.config); fishesDraft = [...normalized.fishes]; title.textContent = `Fishing spot · ${ctx.tileX}, ${ctx.tileY}`; form.innerHTML = ""; const header = document.createElement("div"); header.className = "spawner-sells-header"; const label = document.createElement("strong"); label.textContent = "Fishes"; const addBtn = document.createElement("button"); addBtn.type = "button"; addBtn.textContent = "+"; addBtn.title = "Add fish"; addBtn.addEventListener("click", () => openFishItemSearch()); header.append(label, addBtn); const list = document.createElement("div"); list.setAttribute("data-fishes-list", ""); form.append(header, list); renderFishesList(); show(true); } function openDoorway (ctx) function openDoorway (ctx) { { context = { kind: "doorway", ...ctx }; context = { kind: "doorway", ...ctx };@@ -851,6 +930,12 @@ export function initTileConfigModal ({ show(false); show(false); return; return; } } if (context.kind === "fishing-spot") { onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft })); show(false); return; } const data = new FormData(form); const data = new FormData(form); const equipment = {}; const equipment = {}; for (const slot of EQUIPMENT_SLOTS) for (const slot of EQUIPMENT_SLOTS)@@ -888,6 +973,7 @@ export function initTileConfigModal ({ isOpen: () => open, isOpen: () => open, openSpawner, openSpawner, openDoorway, openDoorway, openFishingSpot, close: () => show(false), close: () => show(false), handleMessage (message) handleMessage (message) { {@@ -33,7 +33,9 @@ import { initGraphicsSettings } from "./graphicsSettings.js";
import { CraftingStationId } from "/shared/definitions/craftingStations.js";
import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
import { formatQuantity } from "/shared/items/formatQuantity.js";
import { ItemId } from "/shared/definitions/items.js";
import { ItemId, itemDefinition } from "/shared/definitions/items.js";
import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
import { countCoinsInSlots } from "/shared/items/inventory.js";
const game = new Game();
@@ -350,6 +352,35 @@ function requestOpenCraftStation (stationId, tileX, tileY)
{ approachAdjacentTile(tileX, tileY); }
}
function requestStartFire (ground)
{
if (!ground)
{ return; }
clearAllPendingActions();
pendingInteract = {
kind: "start-fire",
groundItemId: ground.groundItemId,
tileX: ground.tileX,
tileY: ground.tileY
};
const local = view?.entities.get(view.localEntityId);
if (local && chebyshev(local.tileX, local.tileY, ground.tileX, ground.tileY) <= 1)
{ flushPendingInteract(); }
else
{ approachAdjacentTile(ground.tileX, ground.tileY); }
}
function requestFish (tileX, tileY)
{
clearAllPendingActions();
pendingInteract = { kind: "fish", tileX, tileY };
const local = view?.entities.get(view.localEntityId);
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
{ flushPendingInteract(); }
else
{ approachAdjacentTile(tileX, tileY); }
}
function requestMine (tileX, tileY)
{
clearAllPendingActions();
@@ -595,6 +626,31 @@ function flushPendingInteract ()
return;
}
if (pendingInteract.kind === "start-fire")
{
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
{ return; }
socket.send({
type: MessageType.startFire,
groundItemId: pendingInteract.groundItemId
});
clearPendingInteract();
return;
}
if (pendingInteract.kind === "fish")
{
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
{ return; }
socket.send({
type: MessageType.startFish,
tileX: pendingInteract.tileX,
tileY: pendingInteract.tileY
});
clearPendingInteract();
return;
}
if (pendingInteract.kind === "chop")
{
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
@@ -763,6 +819,12 @@ function handleLeftClick (mouseX, mouseY)
{ requestOpenCauldron(tile.tileX, tile.tileY); }
else if (isFurnaceTile(view, tile.tileX, tile.tileY))
{ requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
else if (isOvenTile(view, tile.tileX, tile.tileY))
{ requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY); }
else if (isCampfireTile(view, tile.tileX, tile.tileY))
{ requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY); }
else if (isFishingSpotTile(view, tile.tileX, tile.tileY))
{ requestFish(tile.tileX, tile.tileY); }
else if (isAnvilTile(view, tile.tileX, tile.tileY))
{ requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
@@ -866,6 +928,13 @@ function handleRightClick (event, mouseX, mouseY)
label: `Pick up ${name}`,
onSelect: () => requestPickup(ground)
});
if (playerHasUsableTinderbox() && isGroundWoodLog(ground))
{
items.push({
label: `Start Fire`,
onSelect: () => requestStartFire(ground)
});
}
}
if (isBankTile(view, tile.tileX, tile.tileY))
@@ -928,6 +997,30 @@ function handleRightClick (event, mouseX, mouseY)
});
}
if (isOvenTile(view, tile.tileX, tile.tileY))
{
items.push({
label: "Cook",
onSelect: () => requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY)
});
}
if (isCampfireTile(view, tile.tileX, tile.tileY))
{
items.push({
label: "Cook",
onSelect: () => requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY)
});
}
if (isFishingSpotTile(view, tile.tileX, tile.tileY))
{
items.push({
label: "Fish",
onSelect: () => requestFish(tile.tileX, tile.tileY)
});
}
if (isAnvilTile(view, tile.tileX, tile.tileY))
{
items.push({
@@ -1486,10 +1579,14 @@ async function main ()
{ toasts?.show("Failed to cast spell"); }
break;
case MessageType.spellCastFlash:
// Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*.
break;
case MessageType.spellLightAppear:
case MessageType.spellLightUpdate:
view?.setSpellLight(message);
break;
case MessageType.spellLightRemove:
view?.removeSpellLight(message);
break;
case MessageType.stamina:
staminaUi?.apply(message);
@@ -1920,11 +2017,51 @@ function isFurnaceTile (view, tileX, tileY)
return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
}
function isOvenTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.oven;
}
function isCampfireTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.campfire;
}
function isFishingSpotTile (view, tileX, tileY)
{
const block = blockAt(view, tileX, tileY);
if (!block || block.typeId !== BlockType.fishingSpot)
{ return false; }
return block.state !== "exhausted";
}
function isAnvilTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
}
function isGroundWoodLog (ground)
{
const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
return def?.familyId === ItemFamilyId.log;
}
function playerHasUsableTinderbox ()
{
const slots = inventory?.getInventorySlots?.() ?? [];
for (const slot of slots)
{
if (!slot || slot.itemId !== CraftingItemId.tinderbox)
{ continue; }
const charges = slot.instance?.kind === "tinderbox"
? (slot.instance.charges | 0)
: TINDERBOX_MAX_CHARGES;
if (charges > 0)
{ return true; }
}
return false;
}
function isWoodworkingBenchTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
@@ -33,7 +33,9 @@ import { initGraphicsSettings } from "./graphicsSettings.js";import { CraftingStationId } from "/shared/definitions/craftingStations.js";import { CraftingStationId } from "/shared/definitions/craftingStations.js";import { isOreBoulderState } from "/shared/definitions/materialTiers.js";import { isOreBoulderState } from "/shared/definitions/materialTiers.js";import { formatQuantity } from "/shared/items/formatQuantity.js";import { formatQuantity } from "/shared/items/formatQuantity.js";import { ItemId } from "/shared/definitions/items.js";import { ItemId, itemDefinition } from "/shared/definitions/items.js";import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";import { countCoinsInSlots } from "/shared/items/inventory.js";import { countCoinsInSlots } from "/shared/items/inventory.js";const game = new Game();const game = new Game();@@ -350,6 +352,35 @@ function requestOpenCraftStation (stationId, tileX, tileY) { approachAdjacentTile(tileX, tileY); } { approachAdjacentTile(tileX, tileY); }}}function requestStartFire (ground){ if (!ground) { return; } clearAllPendingActions(); pendingInteract = { kind: "start-fire", groundItemId: ground.groundItemId, tileX: ground.tileX, tileY: ground.tileY }; const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, ground.tileX, ground.tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(ground.tileX, ground.tileY); }}function requestFish (tileX, tileY){ clearAllPendingActions(); pendingInteract = { kind: "fish", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); }}function requestMine (tileX, tileY)function requestMine (tileX, tileY){{ clearAllPendingActions(); clearAllPendingActions();@@ -595,6 +626,31 @@ function flushPendingInteract () return; return; } } if (pendingInteract.kind === "start-fire") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.startFire, groundItemId: pendingInteract.groundItemId }); clearPendingInteract(); return; } if (pendingInteract.kind === "fish") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.startFish, tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); clearPendingInteract(); return; } if (pendingInteract.kind === "chop") if (pendingInteract.kind === "chop") { { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)@@ -763,6 +819,12 @@ function handleLeftClick (mouseX, mouseY) { requestOpenCauldron(tile.tileX, tile.tileY); } { requestOpenCauldron(tile.tileX, tile.tileY); } else if (isFurnaceTile(view, tile.tileX, tile.tileY)) else if (isFurnaceTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); } { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); } else if (isOvenTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY); } else if (isCampfireTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY); } else if (isFishingSpotTile(view, tile.tileX, tile.tileY)) { requestFish(tile.tileX, tile.tileY); } else if (isAnvilTile(view, tile.tileX, tile.tileY)) else if (isAnvilTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); } { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); } else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY)) else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))@@ -866,6 +928,13 @@ function handleRightClick (event, mouseX, mouseY) label: `Pick up ${name}`, label: `Pick up ${name}`, onSelect: () => requestPickup(ground) onSelect: () => requestPickup(ground) }); }); if (playerHasUsableTinderbox() && isGroundWoodLog(ground)) { items.push({ label: `Start Fire`, onSelect: () => requestStartFire(ground) }); } } } if (isBankTile(view, tile.tileX, tile.tileY)) if (isBankTile(view, tile.tileX, tile.tileY))@@ -928,6 +997,30 @@ function handleRightClick (event, mouseX, mouseY) }); }); } } if (isOvenTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Cook", onSelect: () => requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY) }); } if (isCampfireTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Cook", onSelect: () => requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY) }); } if (isFishingSpotTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Fish", onSelect: () => requestFish(tile.tileX, tile.tileY) }); } if (isAnvilTile(view, tile.tileX, tile.tileY)) if (isAnvilTile(view, tile.tileX, tile.tileY)) { { items.push({ items.push({@@ -1486,10 +1579,14 @@ async function main () { toasts?.show("Failed to cast spell"); } { toasts?.show("Failed to cast spell"); } break; break; case MessageType.spellCastFlash: case MessageType.spellCastFlash: // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*. break; break; case MessageType.spellLightAppear: case MessageType.spellLightAppear: case MessageType.spellLightUpdate: case MessageType.spellLightUpdate: view?.setSpellLight(message); break; case MessageType.spellLightRemove: case MessageType.spellLightRemove: view?.removeSpellLight(message); break; break; case MessageType.stamina: case MessageType.stamina: staminaUi?.apply(message); staminaUi?.apply(message);@@ -1920,11 +2017,51 @@ function isFurnaceTile (view, tileX, tileY) return blockTypeAt(view, tileX, tileY) === BlockType.furnace; return blockTypeAt(view, tileX, tileY) === BlockType.furnace;}}function isOvenTile (view, tileX, tileY){ return blockTypeAt(view, tileX, tileY) === BlockType.oven;}function isCampfireTile (view, tileX, tileY){ return blockTypeAt(view, tileX, tileY) === BlockType.campfire;}function isFishingSpotTile (view, tileX, tileY){ const block = blockAt(view, tileX, tileY); if (!block || block.typeId !== BlockType.fishingSpot) { return false; } return block.state !== "exhausted";}function isAnvilTile (view, tileX, tileY)function isAnvilTile (view, tileX, tileY){{ return blockTypeAt(view, tileX, tileY) === BlockType.anvil; return blockTypeAt(view, tileX, tileY) === BlockType.anvil;}}function isGroundWoodLog (ground){ const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId); return def?.familyId === ItemFamilyId.log;}function playerHasUsableTinderbox (){ const slots = inventory?.getInventorySlots?.() ?? []; for (const slot of slots) { if (!slot || slot.itemId !== CraftingItemId.tinderbox) { continue; } const charges = slot.instance?.kind === "tinderbox" ? (slot.instance.charges | 0) : TINDERBOX_MAX_CHARGES; if (charges > 0) { return true; } } return false;}function isWoodworkingBenchTile (view, tileX, tileY)function isWoodworkingBenchTile (view, tileX, tileY){{ return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench; return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;@@ -420,6 +420,8 @@ export class WorldView
this.nightPreview = null;
this.followPlayer = true;
this.dynamicLights = [];
/** Persistent Light-spell tile lights (server-driven). */
this.spellLights = new Map();
this.swipes = [];
this.damageFloats = [];
this.damageNumbersEl = document.getElementById("damage-numbers");
@@ -1520,7 +1522,28 @@ export class WorldView
spawnSpellFizzleFx (_payload)
{
// Visual-only fizzle; no dynamic light (too expensive for lightmap rebakes).
// Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes).
}
/**
* Authoritative Light-spell tile light from the server.
* Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates.
*/
setSpellLight (payload)
{
const key = `${payload.tileX},${payload.tileY}`;
this.spellLights.set(key, {
tileX: payload.tileX,
tileY: payload.tileY,
until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
range: payload.rangeTiles ?? 6,
intensity: payload.intensity ?? 0.88
});
}
removeSpellLight (payload)
{
this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
}
#spellProjectileImage (baseSprite, frameIndex)
@@ -3242,6 +3265,36 @@ export class WorldView
);
}
/** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */
#innerDynamicLights (activeLights)
{
return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY));
}
/**
* Lights to simulate for one chunk: inner chunks get all inner sources; outer ring
* chunks only receive inner sources close enough to reach the chunk bounds.
*/
#dynamicLightsForChunk (chunkX, chunkY, activeLights)
{
const center = this.#activeLightingCenterChunk();
if (!center)
{ return activeLights; }
const inner = this.#innerDynamicLights(activeLights);
if (this.#isActiveLightingChunk(chunkX, chunkY))
{ return inner; }
return inner.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
}
#dynamicLightsForTile (tileX, tileY, activeLights)
{
return this.#dynamicLightsForChunk(
Math.floor(tileX / CHUNK_SIZE),
Math.floor(tileY / CHUNK_SIZE),
activeLights
);
}
#updateShade ()
{
const ambientDark = this.#ambientDarkness();
@@ -3249,6 +3302,22 @@ export class WorldView
this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
const activeLights = [...this.dynamicLights];
for (const light of this.spellLights.values())
{
if (light.until <= now)
{ continue; }
activeLights.push({
tileX: light.tileX,
tileY: light.tileY,
range: light.range,
intensity: light.intensity
});
}
for (const key of [...this.spellLights.keys()])
{
if (this.spellLights.get(key).until <= now)
{ this.spellLights.delete(key); }
}
const tileSize = this.tileSize();
const blindLight = this.#blindVisionLight();
if (blindLight)
@@ -3272,7 +3341,7 @@ export class WorldView
{
if (objects._inViewport === false)
{ continue; }
const lights = this.#isActiveLightingTile(objects.tileX, objects.tileY) ? activeLights : [];
const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, activeLights);
const intensity = this.#tileLightIntensity(objects, lights, lightOcclusion);
objects.shadeAlpha = ambientDark * (1 - intensity);
}
@@ -3281,7 +3350,7 @@ export class WorldView
{
if (baked._inViewport === false)
{ continue; }
const lights = this.#isActiveLightingChunk(baked.chunkX, baked.chunkY) ? activeLights : [];
const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
this.#writeChunkLightmap(baked, lights, lightOcclusion);
if (baked.groundObject?.renderer?.shaderUniforms)
{ baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
@@ -3482,11 +3551,12 @@ export class WorldView
if (!snapshot?.light)
{ return null; }
const bakedHash = this.#hashUint8Array(snapshot.light);
if (!this.#isActiveLightingChunk(baked.chunkX, baked.chunkY))
const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
if (!lights.length)
{ return `i:${bakedHash}`; }
const mode = this.lightingMode === "simple" ? "s" : "f";
let lightsKey = "";
for (const light of activeLights)
for (const light of lights)
{
if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
{ continue; }
@@ -3497,9 +3567,10 @@ export class WorldView
#invalidateNeighborLightmapCaches (chunkX, chunkY)
{
for (let dy = -1; dy <= 1; dy++)
// Halo grid is ±1 tile; outer map ring is ±2 chunks from the player.
for (let dy = -2; dy <= 2; dy++)
{
for (let dx = -1; dx <= 1; dx++)
for (let dx = -2; dx <= 2; dx++)
{
const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
if (baked)
@@ -420,6 +420,8 @@ export class WorldView this.nightPreview = null; this.nightPreview = null; this.followPlayer = true; this.followPlayer = true; this.dynamicLights = []; this.dynamicLights = []; /** Persistent Light-spell tile lights (server-driven). */ this.spellLights = new Map(); this.swipes = []; this.swipes = []; this.damageFloats = []; this.damageFloats = []; this.damageNumbersEl = document.getElementById("damage-numbers"); this.damageNumbersEl = document.getElementById("damage-numbers");@@ -1520,7 +1522,28 @@ export class WorldView spawnSpellFizzleFx (_payload) spawnSpellFizzleFx (_payload) { { // Visual-only fizzle; no dynamic light (too expensive for lightmap rebakes). // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes). } /** * Authoritative Light-spell tile light from the server. * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates. */ setSpellLight (payload) { const key = `${payload.tileX},${payload.tileY}`; this.spellLights.set(key, { tileX: payload.tileX, tileY: payload.tileY, until: performance.now() + Math.max(0, payload.remainingMs ?? 0), range: payload.rangeTiles ?? 6, intensity: payload.intensity ?? 0.88 }); } removeSpellLight (payload) { this.spellLights.delete(`${payload.tileX},${payload.tileY}`); } } #spellProjectileImage (baseSprite, frameIndex) #spellProjectileImage (baseSprite, frameIndex)@@ -3242,6 +3265,36 @@ export class WorldView ); ); } } /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */ #innerDynamicLights (activeLights) { return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY)); } /** * Lights to simulate for one chunk: inner chunks get all inner sources; outer ring * chunks only receive inner sources close enough to reach the chunk bounds. */ #dynamicLightsForChunk (chunkX, chunkY, activeLights) { const center = this.#activeLightingCenterChunk(); if (!center) { return activeLights; } const inner = this.#innerDynamicLights(activeLights); if (this.#isActiveLightingChunk(chunkX, chunkY)) { return inner; } return inner.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY)); } #dynamicLightsForTile (tileX, tileY, activeLights) { return this.#dynamicLightsForChunk( Math.floor(tileX / CHUNK_SIZE), Math.floor(tileY / CHUNK_SIZE), activeLights ); } #updateShade () #updateShade () { { const ambientDark = this.#ambientDarkness(); const ambientDark = this.#ambientDarkness();@@ -3249,6 +3302,22 @@ export class WorldView this.dynamicLights = this.dynamicLights.filter((light) => light.until > now); this.dynamicLights = this.dynamicLights.filter((light) => light.until > now); const activeLights = [...this.dynamicLights]; const activeLights = [...this.dynamicLights]; for (const light of this.spellLights.values()) { if (light.until <= now) { continue; } activeLights.push({ tileX: light.tileX, tileY: light.tileY, range: light.range, intensity: light.intensity }); } for (const key of [...this.spellLights.keys()]) { if (this.spellLights.get(key).until <= now) { this.spellLights.delete(key); } } const tileSize = this.tileSize(); const tileSize = this.tileSize(); const blindLight = this.#blindVisionLight(); const blindLight = this.#blindVisionLight(); if (blindLight) if (blindLight)@@ -3272,7 +3341,7 @@ export class WorldView { { if (objects._inViewport === false) if (objects._inViewport === false) { continue; } { continue; } const lights = this.#isActiveLightingTile(objects.tileX, objects.tileY) ? activeLights : []; const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, activeLights); const intensity = this.#tileLightIntensity(objects, lights, lightOcclusion); const intensity = this.#tileLightIntensity(objects, lights, lightOcclusion); objects.shadeAlpha = ambientDark * (1 - intensity); objects.shadeAlpha = ambientDark * (1 - intensity); } }@@ -3281,7 +3350,7 @@ export class WorldView { { if (baked._inViewport === false) if (baked._inViewport === false) { continue; } { continue; } const lights = this.#isActiveLightingChunk(baked.chunkX, baked.chunkY) ? activeLights : []; const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights); this.#writeChunkLightmap(baked, lights, lightOcclusion); this.#writeChunkLightmap(baked, lights, lightOcclusion); if (baked.groundObject?.renderer?.shaderUniforms) if (baked.groundObject?.renderer?.shaderUniforms) { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; } { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }@@ -3482,11 +3551,12 @@ export class WorldView if (!snapshot?.light) if (!snapshot?.light) { return null; } { return null; } const bakedHash = this.#hashUint8Array(snapshot.light); const bakedHash = this.#hashUint8Array(snapshot.light); if (!this.#isActiveLightingChunk(baked.chunkX, baked.chunkY)) const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights); if (!lights.length) { return `i:${bakedHash}`; } { return `i:${bakedHash}`; } const mode = this.lightingMode === "simple" ? "s" : "f"; const mode = this.lightingMode === "simple" ? "s" : "f"; let lightsKey = ""; let lightsKey = ""; for (const light of activeLights) for (const light of lights) { { if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY)) if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY)) { continue; } { continue; }@@ -3497,9 +3567,10 @@ export class WorldView #invalidateNeighborLightmapCaches (chunkX, chunkY) #invalidateNeighborLightmapCaches (chunkX, chunkY) { { for (let dy = -1; dy <= 1; dy++) // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player. for (let dy = -2; dy <= 2; dy++) { { for (let dx = -1; dx <= 1; dx++) for (let dx = -2; dx <= 2; dx++) { { const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`); const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`); if (baked) if (baked)@@ -237,7 +237,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
for (const def of Object.values(definitions))
{
const folder = join(layerDir, def.key);
const { states: fileStates, blooms, equips, equipBlooms } = listVisualStates(folder);
const { states: fileStates, blooms: fileBlooms, equips, equipBlooms } = listVisualStates(folder);
if (fileStates.length === 0)
{ throw new Error(`No PNG states in ${folder}`); }
@@ -245,6 +245,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
let states = [...fileStates];
let blooms = fileBlooms;
const imagesForType = [];
if (layer === "block" && def.key === "boulder")
@@ -302,6 +303,36 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
}
}
if (layer === "block" && def.key === "campfire")
{
states = [];
const nextBlooms = {};
for (const material of WOOD_TIER_ORDER)
{
states.push(material);
const tint = materialTintColor(material);
imagesForType.push({
name: spriteImageName(layer, def.key, material),
url: `/assets/${urlFolder}/${def.key}/campfire.png`,
subImgTotal: frames,
perRow: framesPerRow,
loop: animationSpeed > 0,
animationSpeed,
tint: { r: tint.r, g: tint.g, b: tint.b }
});
imagesForType.push({
name: bloomImageName(layer, def.key, material),
url: `/assets/${urlFolder}/${def.key}/campfire-bloom.png`,
subImgTotal: frames,
perRow: framesPerRow,
loop: animationSpeed > 0,
animationSpeed
});
nextBlooms[material] = true;
}
blooms = nextBlooms;
}
if (layer === "block" && def.key === "table")
{
// Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.
@@ -332,7 +363,9 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
states,
defaultState: def.key === "boulder" && states.includes("boulder")
? "boulder"
: (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
: def.key === "fishing-spot" && states.includes("fishing-spot")
? "fishing-spot"
: (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
blooms,
equips,
equipBlooms,
@@ -237,7 +237,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder) for (const def of Object.values(definitions)) for (const def of Object.values(definitions)) { { const folder = join(layerDir, def.key); const folder = join(layerDir, def.key); const { states: fileStates, blooms, equips, equipBlooms } = listVisualStates(folder); const { states: fileStates, blooms: fileBlooms, equips, equipBlooms } = listVisualStates(folder); if (fileStates.length === 0) if (fileStates.length === 0) { throw new Error(`No PNG states in ${folder}`); } { throw new Error(`No PNG states in ${folder}`); }@@ -245,6 +245,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder) const framesPerRow = Math.max(1, def.framesPerRow ?? 1); const framesPerRow = Math.max(1, def.framesPerRow ?? 1); const animationSpeed = Math.max(0, def.animationSpeed ?? 0); const animationSpeed = Math.max(0, def.animationSpeed ?? 0); let states = [...fileStates]; let states = [...fileStates]; let blooms = fileBlooms; const imagesForType = []; const imagesForType = []; if (layer === "block" && def.key === "boulder") if (layer === "block" && def.key === "boulder")@@ -302,6 +303,36 @@ function scanLayer (layerDir, definitions, layer, urlFolder) } } } } if (layer === "block" && def.key === "campfire") { states = []; const nextBlooms = {}; for (const material of WOOD_TIER_ORDER) { states.push(material); const tint = materialTintColor(material); imagesForType.push({ name: spriteImageName(layer, def.key, material), url: `/assets/${urlFolder}/${def.key}/campfire.png`, subImgTotal: frames, perRow: framesPerRow, loop: animationSpeed > 0, animationSpeed, tint: { r: tint.r, g: tint.g, b: tint.b } }); imagesForType.push({ name: bloomImageName(layer, def.key, material), url: `/assets/${urlFolder}/${def.key}/campfire-bloom.png`, subImgTotal: frames, perRow: framesPerRow, loop: animationSpeed > 0, animationSpeed }); nextBlooms[material] = true; } blooms = nextBlooms; } if (layer === "block" && def.key === "table") if (layer === "block" && def.key === "table") { { // Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier. // Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.@@ -332,7 +363,9 @@ function scanLayer (layerDir, definitions, layer, urlFolder) states, states, defaultState: def.key === "boulder" && states.includes("boulder") defaultState: def.key === "boulder" && states.includes("boulder") ? "boulder" ? "boulder" : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0], : def.key === "fishing-spot" && states.includes("fishing-spot") ? "fishing-spot" : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0], blooms, blooms, equips, equips, equipBlooms, equipBlooms,@@ -646,6 +646,42 @@ function clearCombatApproachPath (ecs, handle)
{ path.tiles = []; }
}
function combatTileKey (tileX, tileY)
{
return `${tileX},${tileY}`;
}
/** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */
function collectCombatAllyReservations (world, entityId, targetEntityId)
{
const reserved = new Set();
if (targetEntityId == null)
{ return reserved; }
for (const entity of world.ecs.query(Component.combat, Component.position))
{
if (entity.entityId === entityId)
{ continue; }
if (entity.combat.targetEntityId !== targetEntityId)
{ continue; }
reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY));
const allyPath = world.ecs.get(entity.handle, Component.path);
if (!allyPath?.tiles?.length)
{ continue; }
const next = allyPath.tiles[0];
if (next)
{ reserved.add(combatTileKey(next.x, next.y)); }
const dest = allyPath.tiles[allyPath.tiles.length - 1];
if (dest)
{ reserved.add(combatTileKey(dest.x, dest.y)); }
}
return reserved;
}
function combatGoalPreference (entityId, tileX, tileY)
{
return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0;
}
export function queueMeleeApproach (world, entityId, handle, position, targetPos)
{
if (world.frozen?.has?.(entityId))
@@ -662,7 +698,9 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
return;
}
const goal = bestAdjacentGoal(world, entityId, position, targetPos);
const combat = world.ecs.get(handle, Component.combat);
const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved);
if (!goal)
{
path.tiles = [];
@@ -675,7 +713,7 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
return;
}
if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))
if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved))
{ return; }
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
@@ -711,22 +749,6 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
{ movement.walkCarry = 0; }
}
function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist)
{
const dest = path.tiles[path.tiles.length - 1];
if (dest.x !== goal.x || dest.y !== goal.y)
{ return true; }
const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
if (standOff < minStandDist || standOff > maxRange)
{ return true; }
if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
{ return true; }
const next = path.tiles[0];
if (!next)
{ return true; }
return !world.walkableFor(entityId, next.x, next.y);
}
/**
* Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS.
* Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left).
@@ -750,9 +772,11 @@ export function queueStandInRangeApproach (
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }
const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true;
if (
distToTarget <= maxRange
&& distToTarget >= minStandDist
&& aloneHere
&& hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
)
{
@@ -760,6 +784,8 @@ export function queueStandInRangeApproach (
return;
}
const combat = world.ecs.get(handle, Component.combat);
const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null);
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
const isWalkable = (x, y) => world.walkableFor(entityId, x, y);
const isGoal = (x, y) =>
@@ -767,6 +793,11 @@ export function queueStandInRangeApproach (
const standOff = chebyshev(x, y, targetTileX, targetTileY);
if (standOff < minStandDist || standOff > maxRange)
{ return false; }
if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y)))
{ return false; }
const key = combatTileKey(x, y);
if (reserved.has(key) && !(x === position.tileX && y === position.tileY))
{ return false; }
return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY);
};
@@ -794,7 +825,9 @@ export function queueStandInRangeApproach (
targetTileX,
targetTileY,
maxRange,
minStandDist
minStandDist,
reserved,
position
))
{ return; }
path.tiles = tiles;
@@ -899,7 +932,30 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D
return events.concat(hitEvents);
}
function meleePathStale (world, entityId, position, targetPos, path, goal)
function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position)
{
const dest = path.tiles[path.tiles.length - 1];
if (dest.x !== goal.x || dest.y !== goal.y)
{ return true; }
const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
if (standOff < minStandDist || standOff > maxRange)
{ return true; }
if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
{ return true; }
if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
{ return true; }
const destKey = combatTileKey(dest.x, dest.y);
if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
{ return true; }
const next = path.tiles[0];
if (!next)
{ return true; }
if (!world.walkableFor(entityId, next.x, next.y))
{ return true; }
return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
}
function meleePathStale (world, entityId, position, targetPos, path, goal, reserved)
{
const dest = path.tiles[path.tiles.length - 1];
if (dest.x !== goal.x || dest.y !== goal.y)
@@ -908,13 +964,18 @@ function meleePathStale (world, entityId, position, targetPos, path, goal)
{ return true; }
if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
{ return true; }
const destKey = combatTileKey(dest.x, dest.y);
if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY))
{ return true; }
const next = path.tiles[0];
if (!next)
{ return true; }
return !world.walkableFor(entityId, next.x, next.y);
if (!world.walkableFor(entityId, next.x, next.y))
{ return true; }
return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);
}
function bestAdjacentGoal (world, entityId, position, targetPos)
function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null)
{
const dirs = [
{ x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
@@ -922,21 +983,28 @@ function bestAdjacentGoal (world, entityId, position, targetPos)
];
let best = null;
let bestDist = Infinity;
let bestPref = Infinity;
for (const dir of dirs)
{
const x = targetPos.tileX + dir.x;
const y = targetPos.tileY + dir.y;
const isHere = x === position.tileX && y === position.tileY;
const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true;
const key = combatTileKey(x, y);
if (reserved?.has(key) && !(isHere && aloneHere))
{ continue; }
const clear = world.isClearStanding?.(entityId, x, y)
?? world.walkableFor(entityId, x, y);
if (!clear && !isHere)
{ continue; }
if (isHere && !(world.isClearStanding?.(entityId, x, y) ?? true))
if (isHere && !aloneHere)
{ continue; }
const dist = chebyshev(position.tileX, position.tileY, x, y);
if (dist < bestDist)
const pref = combatGoalPreference(entityId, x, y);
if (dist < bestDist || (dist === bestDist && pref < bestPref))
{
bestDist = dist;
bestPref = pref;
best = { x, y };
}
}
@@ -646,6 +646,42 @@ function clearCombatApproachPath (ecs, handle) { path.tiles = []; } { path.tiles = []; }}}function combatTileKey (tileX, tileY){ return `${tileX},${tileY}`;}/** Tiles claimed by other combatants fighting the same target (position, next step, path goal). */function collectCombatAllyReservations (world, entityId, targetEntityId){ const reserved = new Set(); if (targetEntityId == null) { return reserved; } for (const entity of world.ecs.query(Component.combat, Component.position)) { if (entity.entityId === entityId) { continue; } if (entity.combat.targetEntityId !== targetEntityId) { continue; } reserved.add(combatTileKey(entity.position.tileX, entity.position.tileY)); const allyPath = world.ecs.get(entity.handle, Component.path); if (!allyPath?.tiles?.length) { continue; } const next = allyPath.tiles[0]; if (next) { reserved.add(combatTileKey(next.x, next.y)); } const dest = allyPath.tiles[allyPath.tiles.length - 1]; if (dest) { reserved.add(combatTileKey(dest.x, dest.y)); } } return reserved;}function combatGoalPreference (entityId, tileX, tileY){ return ((tileX * 73856093) ^ (tileY * 19349663) ^ (entityId * 83492791)) >>> 0;}export function queueMeleeApproach (world, entityId, handle, position, targetPos)export function queueMeleeApproach (world, entityId, handle, position, targetPos){{ if (world.frozen?.has?.(entityId)) if (world.frozen?.has?.(entityId))@@ -662,7 +698,9 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos return; return; } } const goal = bestAdjacentGoal(world, entityId, position, targetPos); const combat = world.ecs.get(handle, Component.combat); const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); const goal = bestAdjacentGoal(world, entityId, position, targetPos, reserved); if (!goal) if (!goal) { { path.tiles = []; path.tiles = [];@@ -675,7 +713,7 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos return; return; } } if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal)) if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal, reserved)) { return; } { return; } const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);@@ -711,22 +749,6 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos { movement.walkCarry = 0; } { movement.walkCarry = 0; }}}function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist){ const dest = path.tiles[path.tiles.length - 1]; if (dest.x !== goal.x || dest.y !== goal.y) { return true; } const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY); if (standOff < minStandDist || standOff > maxRange) { return true; } if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY)) { return true; } const next = path.tiles[0]; if (!next) { return true; } return !world.walkableFor(entityId, next.x, next.y);}/**/** * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS. * Path toward the nearest reachable tile from which `targetTile` is in Chebyshev range with LOS. * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left). * Goal is chosen by BFS flood from the actor (shortest walk), not min Chebyshev (which biases top-left).@@ -750,9 +772,11 @@ export function queueStandInRangeApproach ( { path = world.ecs.add(handle, Component.path, { tiles: [] }); } { path = world.ecs.add(handle, Component.path, { tiles: [] }); } const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY); const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY); const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY) ?? true; if ( if ( distToTarget <= maxRange distToTarget <= maxRange && distToTarget >= minStandDist && distToTarget >= minStandDist && aloneHere && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY) && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY) ) ) { {@@ -760,6 +784,8 @@ export function queueStandInRangeApproach ( return; return; } } const combat = world.ecs.get(handle, Component.combat); const reserved = collectCombatAllyReservations(world, entityId, combat?.targetEntityId ?? null); const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS); const isWalkable = (x, y) => world.walkableFor(entityId, x, y); const isWalkable = (x, y) => world.walkableFor(entityId, x, y); const isGoal = (x, y) => const isGoal = (x, y) =>@@ -767,6 +793,11 @@ export function queueStandInRangeApproach ( const standOff = chebyshev(x, y, targetTileX, targetTileY); const standOff = chebyshev(x, y, targetTileX, targetTileY); if (standOff < minStandDist || standOff > maxRange) if (standOff < minStandDist || standOff > maxRange) { return false; } { return false; } if (!(world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y))) { return false; } const key = combatTileKey(x, y); if (reserved.has(key) && !(x === position.tileX && y === position.tileY)) { return false; } return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY); return hasCombatLineOfSight(world, x, y, targetTileX, targetTileY); }; };@@ -794,7 +825,9 @@ export function queueStandInRangeApproach ( targetTileX, targetTileX, targetTileY, targetTileY, maxRange, maxRange, minStandDist minStandDist, reserved, position )) )) { return; } { return; } path.tiles = tiles; path.tiles = tiles;@@ -899,7 +932,30 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D return events.concat(hitEvents); return events.concat(hitEvents);}}function meleePathStale (world, entityId, position, targetPos, path, goal)function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist, reserved, position){ const dest = path.tiles[path.tiles.length - 1]; if (dest.x !== goal.x || dest.y !== goal.y) { return true; } const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY); if (standOff < minStandDist || standOff > maxRange) { return true; } if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY)) { return true; } if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) { return true; } const destKey = combatTileKey(dest.x, dest.y); if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) { return true; } const next = path.tiles[0]; if (!next) { return true; } if (!world.walkableFor(entityId, next.x, next.y)) { return true; } return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);}function meleePathStale (world, entityId, position, targetPos, path, goal, reserved){{ const dest = path.tiles[path.tiles.length - 1]; const dest = path.tiles[path.tiles.length - 1]; if (dest.x !== goal.x || dest.y !== goal.y) if (dest.x !== goal.x || dest.y !== goal.y)@@ -908,13 +964,18 @@ function meleePathStale (world, entityId, position, targetPos, path, goal) { return true; } { return true; } if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true)) { return true; } { return true; } const destKey = combatTileKey(dest.x, dest.y); if (reserved?.has(destKey) && !(dest.x === position.tileX && dest.y === position.tileY)) { return true; } const next = path.tiles[0]; const next = path.tiles[0]; if (!next) if (!next) { return true; } { return true; } return !world.walkableFor(entityId, next.x, next.y); if (!world.walkableFor(entityId, next.x, next.y)) { return true; } return !(world.isClearStanding?.(entityId, next.x, next.y) ?? true);}}function bestAdjacentGoal (world, entityId, position, targetPos)function bestAdjacentGoal (world, entityId, position, targetPos, reserved = null){{ const dirs = [ const dirs = [ { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }, { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },@@ -922,21 +983,28 @@ function bestAdjacentGoal (world, entityId, position, targetPos) ]; ]; let best = null; let best = null; let bestDist = Infinity; let bestDist = Infinity; let bestPref = Infinity; for (const dir of dirs) for (const dir of dirs) { { const x = targetPos.tileX + dir.x; const x = targetPos.tileX + dir.x; const y = targetPos.tileY + dir.y; const y = targetPos.tileY + dir.y; const isHere = x === position.tileX && y === position.tileY; const isHere = x === position.tileX && y === position.tileY; const aloneHere = world.isClearStanding?.(entityId, x, y) ?? true; const key = combatTileKey(x, y); if (reserved?.has(key) && !(isHere && aloneHere)) { continue; } const clear = world.isClearStanding?.(entityId, x, y) const clear = world.isClearStanding?.(entityId, x, y) ?? world.walkableFor(entityId, x, y); ?? world.walkableFor(entityId, x, y); if (!clear && !isHere) if (!clear && !isHere) { continue; } { continue; } if (isHere && !(world.isClearStanding?.(entityId, x, y) ?? true)) if (isHere && !aloneHere) { continue; } { continue; } const dist = chebyshev(position.tileX, position.tileY, x, y); const dist = chebyshev(position.tileX, position.tileY, x, y); if (dist < bestDist) const pref = combatGoalPreference(entityId, x, y); if (dist < bestDist || (dist === bestDist && pref < bestPref)) { { bestDist = dist; bestDist = dist; bestPref = pref; best = { x, y }; best = { x, y }; } } } }@@ -1,6 +1,6 @@
import { Component } from "../ecs/components.js";
import { BlockType } from "../../../shared/definitions/tiles.js";
import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
import { CraftingStationId, CRAFT_DURATION_MS, COOK_BURN_CHANCE_OVEN, COOK_BURN_CHANCE_CAMPFIRE } from "../../../shared/definitions/craftingStations.js";
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
@@ -78,9 +78,22 @@ function stationBlockType (stationId)
{ return BlockType.tailorBench; }
if (stationId === CraftingStationId.leatherworkingStation)
{ return BlockType.leatherworkingTable; }
if (stationId === CraftingStationId.oven)
{ return BlockType.oven; }
if (stationId === CraftingStationId.fireplace)
{ return BlockType.campfire; }
return null;
}
function cookBurnChance (stationId)
{
if (stationId === CraftingStationId.fireplace)
{ return COOK_BURN_CHANCE_CAMPFIRE; }
if (stationId === CraftingStationId.oven)
{ return COOK_BURN_CHANCE_OVEN; }
return 0;
}
function takeInputs (slots, inputs)
{
let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
@@ -371,17 +384,23 @@ export function stepCrafting (world, now)
}
slotsAfter = dyeTaken.slots;
}
const outDef = itemDefinition(recipe.output.itemId);
const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
const burnChance = cookBurnChance(session.stationId);
const burned = burnChance > 0
&& recipe.burntOutput?.itemId
&& ((world.rng?.() ?? Math.random()) < burnChance);
const outSpec = burned ? recipe.burntOutput : recipe.output;
const outDef = itemDefinition(outSpec.itemId);
const outQty = Math.max(1, outSpec.quantity | 0 || 1);
const origin = craftOrigin(
craftOriginVerbForStation(session.stationId),
characterDisplayName(world, handle)
);
const outStack = {
itemId: recipe.output.itemId,
itemId: outSpec.itemId,
quantity: outQty,
origins: [{ origin, quantity: outQty }],
...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
...(recipe.dyeColor && !burned ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
};
const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
if (!added.ok || added.remainder > 0)
@@ -399,7 +418,7 @@ export function stepCrafting (world, now)
let skillsChanged = false;
const levelUps = [];
if (skills?.xp && stationDef?.skillId)
if (!burned && skills?.xp && stationDef?.skillId)
{
const result = applySkillXp(
skills,
@@ -425,6 +444,15 @@ export function stepCrafting (world, now)
});
}
if (burned)
{
events.push({
type: "command-error",
sessionId: session.sessionId,
message: "You burn the food."
});
}
let continuing = false;
const batchRemaining = session.batchRemaining ?? 1;
const nextRemaining = batchRemaining === Infinity
@@ -449,8 +477,8 @@ export function stepCrafting (world, now)
events.push({
type: "item-bubble",
entityId,
itemId: recipe.output.itemId,
quantity: Math.max(1, recipe.output.quantity | 0 || 1)
itemId: outSpec.itemId,
quantity: outQty
});
}
events.push({
@@ -1,6 +1,6 @@import { Component } from "../ecs/components.js";import { Component } from "../ecs/components.js";import { BlockType } from "../../../shared/definitions/tiles.js";import { BlockType } from "../../../shared/definitions/tiles.js";import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";import { CraftingStationId, CRAFT_DURATION_MS, COOK_BURN_CHANCE_OVEN, COOK_BURN_CHANCE_CAMPFIRE } from "../../../shared/definitions/craftingStations.js";import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";@@ -78,9 +78,22 @@ function stationBlockType (stationId) { return BlockType.tailorBench; } { return BlockType.tailorBench; } if (stationId === CraftingStationId.leatherworkingStation) if (stationId === CraftingStationId.leatherworkingStation) { return BlockType.leatherworkingTable; } { return BlockType.leatherworkingTable; } if (stationId === CraftingStationId.oven) { return BlockType.oven; } if (stationId === CraftingStationId.fireplace) { return BlockType.campfire; } return null; return null;}}function cookBurnChance (stationId){ if (stationId === CraftingStationId.fireplace) { return COOK_BURN_CHANCE_CAMPFIRE; } if (stationId === CraftingStationId.oven) { return COOK_BURN_CHANCE_OVEN; } return 0;}function takeInputs (slots, inputs)function takeInputs (slots, inputs){{ let next = slots.map((slot) => (slot ? structuredClone(slot) : null)); let next = slots.map((slot) => (slot ? structuredClone(slot) : null));@@ -371,17 +384,23 @@ export function stepCrafting (world, now) } } slotsAfter = dyeTaken.slots; slotsAfter = dyeTaken.slots; } } const outDef = itemDefinition(recipe.output.itemId); const outQty = Math.max(1, recipe.output.quantity | 0 || 1); const burnChance = cookBurnChance(session.stationId); const burned = burnChance > 0 && recipe.burntOutput?.itemId && ((world.rng?.() ?? Math.random()) < burnChance); const outSpec = burned ? recipe.burntOutput : recipe.output; const outDef = itemDefinition(outSpec.itemId); const outQty = Math.max(1, outSpec.quantity | 0 || 1); const origin = craftOrigin( const origin = craftOrigin( craftOriginVerbForStation(session.stationId), craftOriginVerbForStation(session.stationId), characterDisplayName(world, handle) characterDisplayName(world, handle) ); ); const outStack = { const outStack = { itemId: recipe.output.itemId, itemId: outSpec.itemId, quantity: outQty, quantity: outQty, origins: [{ origin, quantity: outQty }], origins: [{ origin, quantity: outQty }], ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {}) ...(recipe.dyeColor && !burned ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {}) }; }; const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef); const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef); if (!added.ok || added.remainder > 0) if (!added.ok || added.remainder > 0)@@ -399,7 +418,7 @@ export function stepCrafting (world, now) let skillsChanged = false; let skillsChanged = false; const levelUps = []; const levelUps = []; if (skills?.xp && stationDef?.skillId) if (!burned && skills?.xp && stationDef?.skillId) { { const result = applySkillXp( const result = applySkillXp( skills, skills,@@ -425,6 +444,15 @@ export function stepCrafting (world, now) }); }); } } if (burned) { events.push({ type: "command-error", sessionId: session.sessionId, message: "You burn the food." }); } let continuing = false; let continuing = false; const batchRemaining = session.batchRemaining ?? 1; const batchRemaining = session.batchRemaining ?? 1; const nextRemaining = batchRemaining === Infinity const nextRemaining = batchRemaining === Infinity@@ -449,8 +477,8 @@ export function stepCrafting (world, now) events.push({ events.push({ type: "item-bubble", type: "item-bubble", entityId, entityId, itemId: recipe.output.itemId, itemId: outSpec.itemId, quantity: Math.max(1, recipe.output.quantity | 0 || 1) quantity: outQty }); }); } } events.push({ events.push({@@ -0,0 +1,481 @@
import { Component } from "../ecs/components.js";
import { BlockType } from "../../../shared/definitions/tiles.js";
import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "../../../shared/definitions/craftingItems.js";
import {
ashItemIdForWood,
logItemIdForWood
} from "../../../shared/definitions/woodItems.js";
import {
campfireDurationMs,
firestartingDifficulty,
woodTierRank
} from "../../../shared/definitions/craftingStations.js";
import { MATERIAL_DISPLAY_NAME, WOOD_TIER_ORDER } from "../../../shared/definitions/materialTiers.js";
import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js";
import { itemDefinition } from "../../../shared/definitions/items.js";
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
import { rollSkill } from "../../../shared/combat/rolls.js";
import { stackQuantity } from "../../../shared/items/inventory.js";
import { attachOrigins } from "../../../shared/items/origin.js";
import { addGroundItem, publicGroundItem, removeGroundItem, bagView } from "../items/bags.js";
import { chebyshev } from "../combat/service.js";
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
const FIRE_ATTEMPT_MS = 1100;
const MAX_LIGHT_ATTEMPTS = 3;
function userError (message)
{
const error = new Error(message);
error.userFacing = true;
return error;
}
function tileKey (tileX, tileY)
{
return `${tileX},${tileY}`;
}
function ensureCampfires (world)
{
if (!world.campfireExpires)
{ world.campfireExpires = new Map(); }
return world.campfireExpires;
}
function ensureFireSessions (world)
{
if (!world.fireSessions)
{ world.fireSessions = new Map(); }
return world.fireSessions;
}
function clearFireSession (world, characterId)
{
ensureFireSessions(world).delete(characterId);
}
function woodTierFromLogItemId (itemId)
{
const def = itemDefinition(itemId);
if (!def || def.familyId !== ItemFamilyId.log)
{ return null; }
return def.tier ?? null;
}
function findTinderboxSlot (slots)
{
for (let i = 0; i < (slots?.length ?? 0); i++)
{
const slot = slots[i];
if (!slot || slot.itemId !== CraftingItemId.tinderbox)
{ continue; }
const charges = slot.instance?.kind === "tinderbox"
? (slot.instance.charges | 0)
: TINDERBOX_MAX_CHARGES;
if (charges > 0)
{ return i; }
}
return -1;
}
/** Consume one tinderbox charge in place; remove item at 0. */
function consumeTinderboxCharge (slots, slotIndex)
{
const next = slots.map((s) => (s ? structuredClone(s) : null));
const slot = next[slotIndex];
if (!slot || slot.itemId !== CraftingItemId.tinderbox)
{ return { ok: false, slots }; }
const charges = slot.instance?.kind === "tinderbox"
? (slot.instance.charges | 0)
: TINDERBOX_MAX_CHARGES;
if (charges <= 0)
{ return { ok: false, slots }; }
if (charges <= 1)
{
next[slotIndex] = null;
return { ok: true, slots: next, exhausted: true };
}
next[slotIndex].instance = {
kind: "tinderbox",
charges: charges - 1
};
return { ok: true, slots: next, exhausted: false };
}
function placeBlock (world, tileX, tileY, typeId, state, config = null)
{
const chunkX = tileToChunk(tileX);
const chunkY = tileToChunk(tileY);
const localX = tileToLocal(tileX);
const localY = tileToLocal(tileY);
const data = world.chunkData(chunkX, chunkY);
const index = localY * CHUNK_SIZE + localX;
const block = { typeId, state, config };
data.blocks[index] = block;
return {
type: "chunk-delta",
chunkX,
chunkY,
tileX,
tileY,
localX,
localY,
block
};
}
function clearBlockAt (world, tileX, tileY)
{
const chunkX = tileToChunk(tileX);
const chunkY = tileToChunk(tileY);
const localX = tileToLocal(tileX);
const localY = tileToLocal(tileY);
const data = world.chunkData(chunkX, chunkY);
const index = localY * CHUNK_SIZE + localX;
if (!data.blocks[index])
{ return null; }
data.blocks[index] = null;
return {
type: "chunk-delta",
chunkX,
chunkY,
tileX,
tileY,
localX,
localY,
block: null
};
}
function blockAt (world, tileX, tileY)
{
const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
return data.blocks[index] ?? null;
}
function consumeOneGroundLog (world, item, events)
{
const qty = stackQuantity(item.stack?.quantity);
if (qty <= 1)
{
removeGroundItem(world, item.groundItemId);
events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
return;
}
item.stack.quantity = qty - 1;
events.push({
type: "ground-item-appear",
...publicGroundItem(item),
stack: item.stack,
droppedAt: item.droppedAt,
source: item.source,
expiresAt: item.expiresAt
});
}
function spawnAsh (world, tileX, tileY, woodTier, now, events)
{
const ashItemId = ashItemIdForWood(woodTier);
if (!ashItemId)
{ return; }
const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
const stack = attachOrigins({
itemId: ashItemId,
quantity: 1,
origins: []
});
const item = {
groundItemId,
tileX,
tileY,
stack,
droppedAt: now,
expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
source: "campfire-ash"
};
addGroundItem(world, item);
events.push({
type: "ground-item-appear",
...publicGroundItem(item),
stack: item.stack,
droppedAt: item.droppedAt,
source: item.source,
expiresAt: item.expiresAt
});
}
/**
* Start lighting a ground log with a tinderbox (up to 3 skill rolls).
*/
export function startFire (world, sessionId, characterId, groundItemId, now)
{
const entityId = world.characterEntities.get(characterId);
if (entityId == null)
{ throw userError("Character is not in the world."); }
const handle = world.ecs.handleOf(entityId);
const identity = world.ecs.get(handle, Component.networkIdentity);
if (!identity || identity.sessionId !== sessionId)
{ throw userError("Character is not in the world."); }
if (world.ecs.has(handle, Component.dead))
{ throw userError("You are dead."); }
const item = world.groundItems.get(groundItemId | 0);
if (!item)
{ throw userError("That item is no longer on the ground."); }
const woodTier = woodTierFromLogItemId(item.stack?.itemId);
if (!woodTier)
{ throw userError("You can only light wood logs."); }
const position = world.ecs.get(handle, Component.position);
if (chebyshev(position.tileX, position.tileY, item.tileX, item.tileY) > 1)
{ throw userError("You need to stand next to the logs."); }
if (blockAt(world, item.tileX, item.tileY))
{ throw userError("There is no room for a fire there."); }
const difficulty = firestartingDifficulty(woodTier);
const skills = world.ecs.get(handle, Component.skills);
const level = skillLevel(skills, SkillId.firestarting);
if (level < difficulty)
{
const label = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
throw userError(`Your Firestarting skill is too low to light ${label} logs.`);
}
const inventory = world.ecs.get(handle, Component.inventory);
const tinderSlot = findTinderboxSlot(inventory?.slots);
if (tinderSlot < 0)
{ throw userError("You need a tinderbox with charges remaining."); }
const consumed = consumeTinderboxCharge(inventory.slots, tinderSlot);
if (!consumed.ok)
{ throw userError("You need a tinderbox with charges remaining."); }
inventory.slots = consumed.slots;
clearFireSession(world, characterId);
if (world.ecs.has(handle, Component.gather))
{ world.ecs.remove(handle, Component.gather); }
const path = world.ecs.get(handle, Component.path);
if (path)
{ path.tiles = []; }
ensureFireSessions(world).set(characterId, {
sessionId,
groundItemId: item.groundItemId,
tileX: item.tileX,
tileY: item.tileY,
woodTier,
difficulty,
attemptsLeft: MAX_LIGHT_ATTEMPTS,
nextAttemptAt: now,
toolItemId: CraftingItemId.tinderbox
});
return {
events: [],
private: bagView(world.ecs, handle)
};
}
export function cancelFirestarting (world, characterId)
{
clearFireSession(world, characterId);
}
export function handleFirestartingCommand (world, sessionId, command, now = Date.now())
{
if (command.type === "start-fire")
{
return startFire(world, sessionId, command.characterId, command.groundItemId, now);
}
if (command.type === "cancel-fire")
{
cancelFirestarting(world, command.characterId);
return { events: [] };
}
return null;
}
function succeedLight (world, handle, entityId, characterId, session, events, privates, now)
{
const item = world.groundItems.get(session.groundItemId);
if (!item || woodTierFromLogItemId(item.stack?.itemId) !== session.woodTier)
{
events.push({
type: "command-error",
sessionId: session.sessionId,
message: "Those logs are gone."
});
clearFireSession(world, characterId);
return;
}
if (blockAt(world, session.tileX, session.tileY))
{
events.push({
type: "command-error",
sessionId: session.sessionId,
message: "There is no room for a fire there."
});
clearFireSession(world, characterId);
return;
}
consumeOneGroundLog(world, item, events);
const expiresAt = now + campfireDurationMs(session.woodTier);
const delta = placeBlock(
world,
session.tileX,
session.tileY,
BlockType.campfire,
session.woodTier,
{ woodTier: session.woodTier, litAt: now, expiresAt }
);
events.push(delta);
ensureCampfires(world).set(tileKey(session.tileX, session.tileY), {
tileX: session.tileX,
tileY: session.tileY,
woodTier: session.woodTier,
expiresAt
});
const skills = world.ecs.get(handle, Component.skills);
let skillsChanged = false;
const levelUps = [];
if (skills?.xp)
{
const result = applySkillXp(skills, SkillId.firestarting, session.difficulty);
if (result.changed)
{ skillsChanged = true; }
if (result.levelUp)
{ levelUps.push(result.levelUp); }
}
if (skillsChanged)
{
events.push({
type: "skills-updated",
entityId,
characterId,
skills: publicSkillsView(skills),
stored: storedSkillXp(skills),
levelUps
});
}
privates.push({ characterId, bag: bagView(world.ecs, handle) });
clearFireSession(world, characterId);
}
/**
* Advance lighting attempts and expire campfires.
*/
export function stepFirestarting (world, now)
{
const events = [];
const privates = [];
events.push(...stepCampfireExpires(world, now).events);
const sessions = ensureFireSessions(world);
for (const [characterId, session] of [...sessions.entries()])
{
if (now < session.nextAttemptAt)
{ continue; }
const entityId = world.characterEntities.get(characterId);
if (entityId == null)
{
clearFireSession(world, characterId);
continue;
}
const handle = world.ecs.handleOf(entityId);
if (world.ecs.has(handle, Component.dead))
{
clearFireSession(world, characterId);
continue;
}
const position = world.ecs.get(handle, Component.position);
if (chebyshev(position.tileX, position.tileY, session.tileX, session.tileY) > 1)
{
clearFireSession(world, characterId);
continue;
}
const item = world.groundItems.get(session.groundItemId);
if (!item)
{
events.push({
type: "command-error",
sessionId: session.sessionId,
message: "Those logs are gone."
});
clearFireSession(world, characterId);
continue;
}
events.push({
type: "gather-swing",
attackerId: entityId,
tileX: session.tileX,
tileY: session.tileY,
fromTileX: position.tileX,
fromTileY: position.tileY,
toolItemId: session.toolItemId,
swipe: false
});
const skills = world.ecs.get(handle, Component.skills);
const level = skillLevel(skills, SkillId.firestarting);
const roll = rollSkill(level, world.rng ?? Math.random);
session.attemptsLeft -= 1;
if (roll >= session.difficulty)
{
succeedLight(world, handle, entityId, characterId, session, events, privates, now);
continue;
}
if (session.attemptsLeft <= 0)
{
events.push({
type: "command-error",
sessionId: session.sessionId,
message: "The sparks fail to catch."
});
clearFireSession(world, characterId);
continue;
}
session.nextAttemptAt = now + FIRE_ATTEMPT_MS;
}
return { events, privates };
}
export function stepCampfireExpires (world, now)
{
const expires = world.campfireExpires;
if (!expires?.size)
{ return { events: [] }; }
const events = [];
for (const [key, entry] of [...expires.entries()])
{
if (now < entry.expiresAt)
{ continue; }
expires.delete(key);
const block = blockAt(world, entry.tileX, entry.tileY);
if (!block || block.typeId !== BlockType.campfire)
{ continue; }
const delta = clearBlockAt(world, entry.tileX, entry.tileY);
if (delta)
{ events.push(delta); }
spawnAsh(world, entry.tileX, entry.tileY, entry.woodTier, now, events);
}
return { events };
}
/** True if itemId is any wood log. */
export function isWoodLogItemId (itemId)
{
return woodTierFromLogItemId(itemId) != null
|| WOOD_TIER_ORDER.some((tier) => logItemIdForWood(tier) === itemId);
}
export { woodTierFromLogItemId, woodTierRank, findTinderboxSlot };
@@ -0,0 +1,481 @@import { Component } from "../ecs/components.js";import { BlockType } from "../../../shared/definitions/tiles.js";import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "../../../shared/definitions/craftingItems.js";import { ashItemIdForWood, logItemIdForWood} from "../../../shared/definitions/woodItems.js";import { campfireDurationMs, firestartingDifficulty, woodTierRank} from "../../../shared/definitions/craftingStations.js";import { MATERIAL_DISPLAY_NAME, WOOD_TIER_ORDER } from "../../../shared/definitions/materialTiers.js";import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js";import { itemDefinition } from "../../../shared/definitions/items.js";import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";import { rollSkill } from "../../../shared/combat/rolls.js";import { stackQuantity } from "../../../shared/items/inventory.js";import { attachOrigins } from "../../../shared/items/origin.js";import { addGroundItem, publicGroundItem, removeGroundItem, bagView } from "../items/bags.js";import { chebyshev } from "../combat/service.js";import { tileToChunk, tileToLocal } from "../world/coordinates.js";import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";const FIRE_ATTEMPT_MS = 1100;const MAX_LIGHT_ATTEMPTS = 3;function userError (message){ const error = new Error(message); error.userFacing = true; return error;}function tileKey (tileX, tileY){ return `${tileX},${tileY}`;}function ensureCampfires (world){ if (!world.campfireExpires) { world.campfireExpires = new Map(); } return world.campfireExpires;}function ensureFireSessions (world){ if (!world.fireSessions) { world.fireSessions = new Map(); } return world.fireSessions;}function clearFireSession (world, characterId){ ensureFireSessions(world).delete(characterId);}function woodTierFromLogItemId (itemId){ const def = itemDefinition(itemId); if (!def || def.familyId !== ItemFamilyId.log) { return null; } return def.tier ?? null;}function findTinderboxSlot (slots){ for (let i = 0; i < (slots?.length ?? 0); i++) { const slot = slots[i]; if (!slot || slot.itemId !== CraftingItemId.tinderbox) { continue; } const charges = slot.instance?.kind === "tinderbox" ? (slot.instance.charges | 0) : TINDERBOX_MAX_CHARGES; if (charges > 0) { return i; } } return -1;}/** Consume one tinderbox charge in place; remove item at 0. */function consumeTinderboxCharge (slots, slotIndex){ const next = slots.map((s) => (s ? structuredClone(s) : null)); const slot = next[slotIndex]; if (!slot || slot.itemId !== CraftingItemId.tinderbox) { return { ok: false, slots }; } const charges = slot.instance?.kind === "tinderbox" ? (slot.instance.charges | 0) : TINDERBOX_MAX_CHARGES; if (charges <= 0) { return { ok: false, slots }; } if (charges <= 1) { next[slotIndex] = null; return { ok: true, slots: next, exhausted: true }; } next[slotIndex].instance = { kind: "tinderbox", charges: charges - 1 }; return { ok: true, slots: next, exhausted: false };}function placeBlock (world, tileX, tileY, typeId, state, config = null){ const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); const localX = tileToLocal(tileX); const localY = tileToLocal(tileY); const data = world.chunkData(chunkX, chunkY); const index = localY * CHUNK_SIZE + localX; const block = { typeId, state, config }; data.blocks[index] = block; return { type: "chunk-delta", chunkX, chunkY, tileX, tileY, localX, localY, block };}function clearBlockAt (world, tileX, tileY){ const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); const localX = tileToLocal(tileX); const localY = tileToLocal(tileY); const data = world.chunkData(chunkX, chunkY); const index = localY * CHUNK_SIZE + localX; if (!data.blocks[index]) { return null; } data.blocks[index] = null; return { type: "chunk-delta", chunkX, chunkY, tileX, tileY, localX, localY, block: null };}function blockAt (world, tileX, tileY){ const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY)); const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX); return data.blocks[index] ?? null;}function consumeOneGroundLog (world, item, events){ const qty = stackQuantity(item.stack?.quantity); if (qty <= 1) { removeGroundItem(world, item.groundItemId); events.push({ type: "ground-item-despawn", ...publicGroundItem(item) }); return; } item.stack.quantity = qty - 1; events.push({ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, expiresAt: item.expiresAt });}function spawnAsh (world, tileX, tileY, woodTier, now, events){ const ashItemId = ashItemIdForWood(woodTier); if (!ashItemId) { return; } const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1); const stack = attachOrigins({ itemId: ashItemId, quantity: 1, origins: [] }); const item = { groundItemId, tileX, tileY, stack, droppedAt: now, expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000), source: "campfire-ash" }; addGroundItem(world, item); events.push({ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, expiresAt: item.expiresAt });}/** * Start lighting a ground log with a tinderbox (up to 3 skill rolls). */export function startFire (world, sessionId, characterId, groundItemId, now){ const entityId = world.characterEntities.get(characterId); if (entityId == null) { throw userError("Character is not in the world."); } const handle = world.ecs.handleOf(entityId); const identity = world.ecs.get(handle, Component.networkIdentity); if (!identity || identity.sessionId !== sessionId) { throw userError("Character is not in the world."); } if (world.ecs.has(handle, Component.dead)) { throw userError("You are dead."); } const item = world.groundItems.get(groundItemId | 0); if (!item) { throw userError("That item is no longer on the ground."); } const woodTier = woodTierFromLogItemId(item.stack?.itemId); if (!woodTier) { throw userError("You can only light wood logs."); } const position = world.ecs.get(handle, Component.position); if (chebyshev(position.tileX, position.tileY, item.tileX, item.tileY) > 1) { throw userError("You need to stand next to the logs."); } if (blockAt(world, item.tileX, item.tileY)) { throw userError("There is no room for a fire there."); } const difficulty = firestartingDifficulty(woodTier); const skills = world.ecs.get(handle, Component.skills); const level = skillLevel(skills, SkillId.firestarting); if (level < difficulty) { const label = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier; throw userError(`Your Firestarting skill is too low to light ${label} logs.`); } const inventory = world.ecs.get(handle, Component.inventory); const tinderSlot = findTinderboxSlot(inventory?.slots); if (tinderSlot < 0) { throw userError("You need a tinderbox with charges remaining."); } const consumed = consumeTinderboxCharge(inventory.slots, tinderSlot); if (!consumed.ok) { throw userError("You need a tinderbox with charges remaining."); } inventory.slots = consumed.slots; clearFireSession(world, characterId); if (world.ecs.has(handle, Component.gather)) { world.ecs.remove(handle, Component.gather); } const path = world.ecs.get(handle, Component.path); if (path) { path.tiles = []; } ensureFireSessions(world).set(characterId, { sessionId, groundItemId: item.groundItemId, tileX: item.tileX, tileY: item.tileY, woodTier, difficulty, attemptsLeft: MAX_LIGHT_ATTEMPTS, nextAttemptAt: now, toolItemId: CraftingItemId.tinderbox }); return { events: [], private: bagView(world.ecs, handle) };}export function cancelFirestarting (world, characterId){ clearFireSession(world, characterId);}export function handleFirestartingCommand (world, sessionId, command, now = Date.now()){ if (command.type === "start-fire") { return startFire(world, sessionId, command.characterId, command.groundItemId, now); } if (command.type === "cancel-fire") { cancelFirestarting(world, command.characterId); return { events: [] }; } return null;}function succeedLight (world, handle, entityId, characterId, session, events, privates, now){ const item = world.groundItems.get(session.groundItemId); if (!item || woodTierFromLogItemId(item.stack?.itemId) !== session.woodTier) { events.push({ type: "command-error", sessionId: session.sessionId, message: "Those logs are gone." }); clearFireSession(world, characterId); return; } if (blockAt(world, session.tileX, session.tileY)) { events.push({ type: "command-error", sessionId: session.sessionId, message: "There is no room for a fire there." }); clearFireSession(world, characterId); return; } consumeOneGroundLog(world, item, events); const expiresAt = now + campfireDurationMs(session.woodTier); const delta = placeBlock( world, session.tileX, session.tileY, BlockType.campfire, session.woodTier, { woodTier: session.woodTier, litAt: now, expiresAt } ); events.push(delta); ensureCampfires(world).set(tileKey(session.tileX, session.tileY), { tileX: session.tileX, tileY: session.tileY, woodTier: session.woodTier, expiresAt }); const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp) { const result = applySkillXp(skills, SkillId.firestarting, session.difficulty); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } if (skillsChanged) { events.push({ type: "skills-updated", entityId, characterId, skills: publicSkillsView(skills), stored: storedSkillXp(skills), levelUps }); } privates.push({ characterId, bag: bagView(world.ecs, handle) }); clearFireSession(world, characterId);}/** * Advance lighting attempts and expire campfires. */export function stepFirestarting (world, now){ const events = []; const privates = []; events.push(...stepCampfireExpires(world, now).events); const sessions = ensureFireSessions(world); for (const [characterId, session] of [...sessions.entries()]) { if (now < session.nextAttemptAt) { continue; } const entityId = world.characterEntities.get(characterId); if (entityId == null) { clearFireSession(world, characterId); continue; } const handle = world.ecs.handleOf(entityId); if (world.ecs.has(handle, Component.dead)) { clearFireSession(world, characterId); continue; } const position = world.ecs.get(handle, Component.position); if (chebyshev(position.tileX, position.tileY, session.tileX, session.tileY) > 1) { clearFireSession(world, characterId); continue; } const item = world.groundItems.get(session.groundItemId); if (!item) { events.push({ type: "command-error", sessionId: session.sessionId, message: "Those logs are gone." }); clearFireSession(world, characterId); continue; } events.push({ type: "gather-swing", attackerId: entityId, tileX: session.tileX, tileY: session.tileY, fromTileX: position.tileX, fromTileY: position.tileY, toolItemId: session.toolItemId, swipe: false }); const skills = world.ecs.get(handle, Component.skills); const level = skillLevel(skills, SkillId.firestarting); const roll = rollSkill(level, world.rng ?? Math.random); session.attemptsLeft -= 1; if (roll >= session.difficulty) { succeedLight(world, handle, entityId, characterId, session, events, privates, now); continue; } if (session.attemptsLeft <= 0) { events.push({ type: "command-error", sessionId: session.sessionId, message: "The sparks fail to catch." }); clearFireSession(world, characterId); continue; } session.nextAttemptAt = now + FIRE_ATTEMPT_MS; } return { events, privates };}export function stepCampfireExpires (world, now){ const expires = world.campfireExpires; if (!expires?.size) { return { events: [] }; } const events = []; for (const [key, entry] of [...expires.entries()]) { if (now < entry.expiresAt) { continue; } expires.delete(key); const block = blockAt(world, entry.tileX, entry.tileY); if (!block || block.typeId !== BlockType.campfire) { continue; } const delta = clearBlockAt(world, entry.tileX, entry.tileY); if (delta) { events.push(delta); } spawnAsh(world, entry.tileX, entry.tileY, entry.woodTier, now, events); } return { events };}/** True if itemId is any wood log. */export function isWoodLogItemId (itemId){ return woodTierFromLogItemId(itemId) != null || WOOD_TIER_ORDER.some((tier) => logItemIdForWood(tier) === itemId);}export { woodTierFromLogItemId, woodTierRank, findTinderboxSlot };@@ -0,0 +1,602 @@
import { Component } from "../ecs/components.js";
import {
BlockType,
GroundType,
isLiquidWaterGround,
normalizeGround
} from "../../../shared/definitions/tiles.js";
import {
FISH_SPECIES,
fishTierRankFromItemId,
fishingDifficulty,
fishingExhaustDurationMs,
baitItemIdForCloth,
BaitItemId,
normalizeFishingSpotConfig,
fishingPoleItemIdForWood,
woodTierFromFishingRodItemId
} from "../../../shared/definitions/fishItems.js";
import { resolveFishingTool } from "../../../shared/definitions/gathering.js";
import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
import {
ClothTier,
tierRank,
clothTierForWood
} from "../../../shared/definitions/materialTiers.js";
import { yarnItemId } from "../../../shared/definitions/clothItems.js";
import { itemDefinition } from "../../../shared/definitions/items.js";
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
import { rollSkill } from "../../../shared/combat/rolls.js";
import {
insertStack,
stackQuantity,
takeMatchingFromSlots,
takeFromSlot
} from "../../../shared/items/inventory.js";
import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";
import { addGroundItem, publicGroundItem, bagView } from "../items/bags.js";
import { chebyshev } from "../combat/service.js";
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
import { tileShoveEvent } from "../simulation/tileInteract.js";
import { seasonIdAt } from "../../../shared/world/season.js";
const FISH_ATTEMPT_MS = 3000;
const FISH_SHOVE_MS = 1000;
const MAX_FISH_ATTEMPTS = 3;
/** Chance the fishing line snaps after a fully failed rod session. */
const LINE_BREAK_CHANCE = 0.05;
function userError (message)
{
const error = new Error(message);
error.userFacing = true;
return error;
}
function tileKey (tileX, tileY)
{
return `${tileX},${tileY}`;
}
function characterDisplayName (world, handle)
{
const appearance = world.ecs.get(handle, Component.appearance);
const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
return name || "someone";
}
function ensureFishSessions (world)
{
if (!world.fishSessions)
{ world.fishSessions = new Map(); }
return world.fishSessions;
}
function ensureFishSpotRespawns (world)
{
if (!world.fishingSpotRespawns)
{ world.fishingSpotRespawns = new Map(); }
return world.fishingSpotRespawns;
}
function clearFishSession (world, characterId)
{
ensureFishSessions(world).delete(characterId);
}
function blockAt (world, tileX, tileY)
{
const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
return data.blocks[index] ?? null;
}
function groundAt (world, tileX, tileY)
{
const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
return normalizeGround(data.grounds[index]).typeId;
}
function setBlockState (world, tileX, tileY, state)
{
const chunkX = tileToChunk(tileX);
const chunkY = tileToChunk(tileY);
const localX = tileToLocal(tileX);
const localY = tileToLocal(tileY);
const data = world.chunkData(chunkX, chunkY);
const index = localY * CHUNK_SIZE + localX;
const existing = data.blocks[index];
if (!existing)
{ return null; }
const block = { ...existing, state };
data.blocks[index] = block;
return {
type: "chunk-delta",
chunkX,
chunkY,
tileX,
tileY,
localX,
localY,
block
};
}
function spotFishItemIds (block)
{
return normalizeFishingSpotConfig(block?.config).fishes;
}
function maxFishTierInList (fishItemIds)
{
let max = 0;
for (const itemId of fishItemIds)
{ max = Math.max(max, fishTierRankFromItemId(itemId)); }
return max;
}
function eligibleFishItemIds (fishItemIds, baitTierRank)
{
return fishItemIds.filter((itemId) => fishTierRankFromItemId(itemId) <= baitTierRank);
}
function findBestBaitSlot (slots, maxRank)
{
let best = null;
for (let i = 0; i < (slots?.length ?? 0); i++)
{
const slot = slots[i];
if (!slot || stackQuantity(slot.quantity) <= 0)
{ continue; }
const def = itemDefinition(slot.itemId);
if (!def?.bait || !def.tier)
{ continue; }
const rank = tierRank(def.tier);
if (rank < 1 || rank > maxRank)
{ continue; }
if (!best || rank > best.rank)
{ best = { slotIndex: i, itemId: slot.itemId, rank, tier: def.tier }; }
}
return best;
}
function toolTierRank (tool)
{
const tier = tool?.def?.equipment?.tier ?? tool?.tier;
return tierRank(tier);
}
/**
* Start fishing at a fishing-spot block tile.
*/
export function startFish (world, sessionId, characterId, tileX, tileY, now = Date.now())
{
const entityId = world.characterEntities.get(characterId);
if (entityId == null)
{ throw userError("Character is not in the world."); }
const handle = world.ecs.handleOf(entityId);
const identity = world.ecs.get(handle, Component.networkIdentity);
if (!identity || identity.sessionId !== sessionId)
{ throw userError("Character is not in the world."); }
if (world.ecs.has(handle, Component.dead))
{ throw userError("You are dead."); }
const position = world.ecs.get(handle, Component.position);
if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
{ throw userError("You need to stand next to the fishing spot."); }
const block = blockAt(world, tileX, tileY);
if (!block || block.typeId !== BlockType.fishingSpot)
{ throw userError("There is no fishing spot there."); }
if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY)))
{ throw userError("The fish have scattered. Wait for them to return."); }
const ground = groundAt(world, tileX, tileY);
const season = seasonIdAt(now);
if (ground !== GroundType.water && ground !== GroundType.deepWater)
{ throw userError("Fishing spots must be on water."); }
if (!isLiquidWaterGround(ground, season))
{ throw userError("The water is frozen solid."); }
const fishList = spotFishItemIds(block);
if (!fishList.length)
{ throw userError("No fish swim here."); }
const inventory = world.ecs.get(handle, Component.inventory);
const equipment = world.ecs.get(handle, Component.equipment);
const skills = world.ecs.get(handle, Component.skills);
const resolved = resolveFishingTool({
inventorySlots: inventory?.slots,
equipmentSlots: equipment?.slots,
skills
});
if (!resolved.ok)
{ throw userError(resolved.reason); }
const isNet = resolved.kind === EquipmentKind.fishingNet;
const rodRank = isNet ? 1 : toolTierRank(resolved.tool);
const maxInSpot = maxFishTierInList(fishList);
const usefulMax = Math.min(rodRank, maxInSpot);
let baitRank = 1;
let baitItemId = null;
let baitConsumedRank = 0;
if (isNet)
{
baitRank = 1;
baitConsumedRank = 0;
}
else
{
const bait = findBestBaitSlot(inventory?.slots, usefulMax);
if (!bait)
{ throw userError("You need suitable bait for this spot."); }
baitRank = bait.rank;
baitItemId = bait.itemId;
baitConsumedRank = bait.rank;
}
const eligible = eligibleFishItemIds(fishList, baitRank);
if (!eligible.length)
{ throw userError("No fish here match your bait."); }
if (!isNet)
{
const taken = takeMatchingFromSlots(inventory.slots, {
itemId: baitItemId,
quantity: 1,
compact: false
});
if (!taken.ok)
{ throw userError("You need suitable bait for this spot."); }
inventory.slots = taken.slots;
}
clearFishSession(world, characterId);
if (world.ecs.has(handle, Component.gather))
{ world.ecs.remove(handle, Component.gather); }
const path = world.ecs.get(handle, Component.path);
if (path)
{ path.tiles = []; }
ensureFishSessions(world).set(characterId, {
sessionId,
tileX,
tileY,
toolItemId: resolved.tool.def.itemId,
isNet,
baitRank,
baitConsumedRank,
baitItemId,
eligible,
difficulty: fishingDifficulty(baitRank),
attemptsLeft: MAX_FISH_ATTEMPTS,
attemptStartedAt: now,
nextShoveAt: now,
attemptEndsAt: now + FISH_ATTEMPT_MS
});
return {
events: [],
private: isNet ? null : bagView(world.ecs, handle)
};
}
export function handleFishingCommand (world, sessionId, command, now = Date.now())
{
if (command.type === "start-fish")
{
return startFish(
world,
sessionId,
command.characterId,
command.tileX | 0,
command.tileY | 0,
now
);
}
if (command.type === "cancel-fish")
{
clearFishSession(world, command.characterId);
return { events: [] };
}
return null;
}
function completeCatch (world, handle, entityId, characterId, session, events, privates, now)
{
const eligible = session.eligible ?? [];
if (!eligible.length)
{
events.push({
type: "command-error",
sessionId: session.sessionId,
message: "The fish got away."
});
clearFishSession(world, characterId);
return;
}
const rng = world.rng ?? Math.random;
const pick = eligible[Math.floor(rng() * eligible.length) % eligible.length];
const fishRank = fishTierRankFromItemId(pick);
const inventory = world.ecs.get(handle, Component.inventory);
const def = itemDefinition(pick);
const origin = gatherOrigin(GatherOriginVerb.caught, characterDisplayName(world, handle));
const stack = attachOrigins({
itemId: pick,
quantity: 1,
origins: [{ origin, quantity: 1 }]
});
const inserted = insertStack(inventory.slots, stack, def);
if (!inserted.ok || inserted.remainder > 0)
{
events.push({
type: "command-error",
sessionId: session.sessionId,
message: "Your inventory is full."
});
clearFishSession(world, characterId);
return;
}
inventory.slots = inserted.slots;
const xpAmount = (session.baitConsumedRank | 0) + fishRank;
const skills = world.ecs.get(handle, Component.skills);
let skillsChanged = false;
const levelUps = [];
if (skills?.xp && xpAmount > 0)
{
const result = applySkillXp(skills, SkillId.fishing, xpAmount);
if (result.changed)
{ skillsChanged = true; }
if (result.levelUp)
{ levelUps.push(result.levelUp); }
}
if (skillsChanged)
{
events.push({
type: "skills-updated",
entityId,
characterId,
skills: publicSkillsView(skills),
stored: storedSkillXp(skills),
levelUps
});
}
const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted");
if (exhausted)
{ events.push(exhausted); }
ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY), {
tileX: session.tileX,
tileY: session.tileY,
respawnsAt: now + fishingExhaustDurationMs(fishRank)
});
privates.push({ characterId, bag: bagView(world.ecs, handle) });
events.push({
type: "item-bubble",
entityId,
itemId: pick,
quantity: 1
});
clearFishSession(world, characterId);
}
export function stepFishing (world, now)
{
const events = [];
const privates = [];
events.push(...stepFishingSpotRespawns(world, now).events);
const sessions = ensureFishSessions(world);
for (const [characterId, session] of [...sessions.entries()])
{
const entityId = world.characterEntities.get(characterId);
if (entityId == null)
{
clearFishSession(world, characterId);
continue;
}
const handle = world.ecs.handleOf(entityId);
if (world.ecs.has(handle, Component.dead))
{
clearFishSession(world, characterId);
continue;
}
const position = world.ecs.get(handle, Component.position);
if (chebyshev(position.tileX, position.tileY, session.tileX, session.tileY) > 1)
{
clearFishSession(world, characterId);
continue;
}
if (now >= session.nextShoveAt && now < session.attemptEndsAt)
{
session.nextShoveAt = now + FISH_SHOVE_MS;
events.push(tileShoveEvent(
entityId,
position.tileX,
position.tileY,
session.tileX,
session.tileY
));
// Also emit gather-swing so tool overlay shows.
events.push({
type: "gather-swing",
attackerId: entityId,
tileX: session.tileX,
tileY: session.tileY,
fromTileX: position.tileX,
fromTileY: position.tileY,
toolItemId: session.toolItemId,
swipe: false
});
}
if (now < session.attemptEndsAt)
{ continue; }
const skills = world.ecs.get(handle, Component.skills);
const level = skillLevel(skills, SkillId.fishing);
const roll = rollSkill(level, world.rng ?? Math.random);
session.attemptsLeft -= 1;
if (roll >= session.difficulty)
{
completeCatch(world, handle, entityId, characterId, session, events, privates, now);
continue;
}
if (session.attemptsLeft <= 0)
{
events.push({
type: "command-error",
sessionId: session.sessionId,
message: "The fish got away."
});
maybeBreakFishingLine(world, handle, entityId, characterId, session, events, privates, now);
clearFishSession(world, characterId);
continue;
}
session.attemptStartedAt = now;
session.nextShoveAt = now;
session.attemptEndsAt = now + FISH_ATTEMPT_MS;
}
return { events, privates };
}
function spawnGroundStack (world, tileX, tileY, itemId, now, events, source = "fishing-line-break")
{
const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
const stack = attachOrigins({
itemId,
quantity: 1,
origins: []
});
const item = {
groundItemId,
tileX,
tileY,
stack,
droppedAt: now,
expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
source
};
addGroundItem(world, item);
events.push({
type: "ground-item-appear",
...publicGroundItem(item),
stack: item.stack,
droppedAt: item.droppedAt,
source: item.source,
expiresAt: item.expiresAt
});
}
/**
* After a fully failed rod session: 5% chance the line snaps → rod becomes pole + 1 yarn.
*/
function maybeBreakFishingLine (world, handle, entityId, characterId, session, events, privates, now)
{
if (session.isNet)
{ return; }
const rng = world.rng ?? Math.random;
if (rng() >= LINE_BREAK_CHANCE)
{ return; }
const rodItemId = session.toolItemId | 0;
const rodDef = itemDefinition(rodItemId);
const woodTier = woodTierFromFishingRodItemId(rodItemId) ?? rodDef?.tier;
const poleItemId = rodDef?.poleItemId ?? fishingPoleItemIdForWood(woodTier);
const clothTier = rodDef?.clothTier ?? clothTierForWood(woodTier);
const yarnId = yarnItemId(clothTier);
if (!poleItemId || !yarnId)
{ return; }
const inventory = world.ecs.get(handle, Component.inventory);
const equipment = world.ecs.get(handle, Component.equipment);
let removed = false;
let appearanceChanged = false;
if (inventory?.slots)
{
const idx = inventory.slots.findIndex((s) => s?.itemId === rodItemId);
if (idx >= 0)
{
const taken = takeFromSlot(inventory.slots, idx, 1);
if (taken.ok)
{
inventory.slots = taken.slots;
removed = true;
}
}
}
if (!removed && equipment?.slots?.weapon?.itemId === rodItemId)
{
equipment.slots.weapon = null;
removed = true;
appearanceChanged = true;
}
if (!removed)
{ return; }
const position = world.ecs.get(handle, Component.position);
const poleDef = itemDefinition(poleItemId);
const yarnDef = itemDefinition(yarnId);
let slots = inventory.slots;
const poleIns = insertStack(slots, attachOrigins({ itemId: poleItemId, quantity: 1, origins: [] }), poleDef);
if (poleIns.ok && poleIns.remainder === 0)
{ slots = poleIns.slots; }
else
{ spawnGroundStack(world, position.tileX, position.tileY, poleItemId, now, events); }
const yarnIns = insertStack(slots, attachOrigins({ itemId: yarnId, quantity: 1, origins: [] }), yarnDef);
if (yarnIns.ok && yarnIns.remainder === 0)
{ slots = yarnIns.slots; }
else
{ spawnGroundStack(world, position.tileX, position.tileY, yarnId, now, events); }
inventory.slots = slots;
events.push({
type: "command-error",
sessionId: session.sessionId,
message: "Your fishing line broke!"
});
privates.push({
characterId,
bag: bagView(world.ecs, handle),
...(appearanceChanged ? { appearanceChanged: true } : {})
});
}
export function stepFishingSpotRespawns (world, now)
{
const respawns = world.fishingSpotRespawns;
if (!respawns?.size)
{ return { events: [] }; }
const events = [];
for (const [key, entry] of [...respawns.entries()])
{
if (now < entry.respawnsAt)
{ continue; }
respawns.delete(key);
const block = blockAt(world, entry.tileX, entry.tileY);
if (!block || block.typeId !== BlockType.fishingSpot)
{ continue; }
const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot");
if (delta)
{ events.push(delta); }
}
return { events };
}
export { ClothTier, BaitItemId, baitItemIdForCloth, FISH_SPECIES };
@@ -0,0 +1,602 @@import { Component } from "../ecs/components.js";import { BlockType, GroundType, isLiquidWaterGround, normalizeGround} from "../../../shared/definitions/tiles.js";import { FISH_SPECIES, fishTierRankFromItemId, fishingDifficulty, fishingExhaustDurationMs, baitItemIdForCloth, BaitItemId, normalizeFishingSpotConfig, fishingPoleItemIdForWood, woodTierFromFishingRodItemId} from "../../../shared/definitions/fishItems.js";import { resolveFishingTool } from "../../../shared/definitions/gathering.js";import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";import { ClothTier, tierRank, clothTierForWood} from "../../../shared/definitions/materialTiers.js";import { yarnItemId } from "../../../shared/definitions/clothItems.js";import { itemDefinition } from "../../../shared/definitions/items.js";import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";import { rollSkill } from "../../../shared/combat/rolls.js";import { insertStack, stackQuantity, takeMatchingFromSlots, takeFromSlot} from "../../../shared/items/inventory.js";import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";import { addGroundItem, publicGroundItem, bagView } from "../items/bags.js";import { chebyshev } from "../combat/service.js";import { tileToChunk, tileToLocal } from "../world/coordinates.js";import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";import { tileShoveEvent } from "../simulation/tileInteract.js";import { seasonIdAt } from "../../../shared/world/season.js";const FISH_ATTEMPT_MS = 3000;const FISH_SHOVE_MS = 1000;const MAX_FISH_ATTEMPTS = 3;/** Chance the fishing line snaps after a fully failed rod session. */const LINE_BREAK_CHANCE = 0.05;function userError (message){ const error = new Error(message); error.userFacing = true; return error;}function tileKey (tileX, tileY){ return `${tileX},${tileY}`;}function characterDisplayName (world, handle){ const appearance = world.ecs.get(handle, Component.appearance); const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim(); return name || "someone";}function ensureFishSessions (world){ if (!world.fishSessions) { world.fishSessions = new Map(); } return world.fishSessions;}function ensureFishSpotRespawns (world){ if (!world.fishingSpotRespawns) { world.fishingSpotRespawns = new Map(); } return world.fishingSpotRespawns;}function clearFishSession (world, characterId){ ensureFishSessions(world).delete(characterId);}function blockAt (world, tileX, tileY){ const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY)); const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX); return data.blocks[index] ?? null;}function groundAt (world, tileX, tileY){ const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY)); const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX); return normalizeGround(data.grounds[index]).typeId;}function setBlockState (world, tileX, tileY, state){ const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); const localX = tileToLocal(tileX); const localY = tileToLocal(tileY); const data = world.chunkData(chunkX, chunkY); const index = localY * CHUNK_SIZE + localX; const existing = data.blocks[index]; if (!existing) { return null; } const block = { ...existing, state }; data.blocks[index] = block; return { type: "chunk-delta", chunkX, chunkY, tileX, tileY, localX, localY, block };}function spotFishItemIds (block){ return normalizeFishingSpotConfig(block?.config).fishes;}function maxFishTierInList (fishItemIds){ let max = 0; for (const itemId of fishItemIds) { max = Math.max(max, fishTierRankFromItemId(itemId)); } return max;}function eligibleFishItemIds (fishItemIds, baitTierRank){ return fishItemIds.filter((itemId) => fishTierRankFromItemId(itemId) <= baitTierRank);}function findBestBaitSlot (slots, maxRank){ let best = null; for (let i = 0; i < (slots?.length ?? 0); i++) { const slot = slots[i]; if (!slot || stackQuantity(slot.quantity) <= 0) { continue; } const def = itemDefinition(slot.itemId); if (!def?.bait || !def.tier) { continue; } const rank = tierRank(def.tier); if (rank < 1 || rank > maxRank) { continue; } if (!best || rank > best.rank) { best = { slotIndex: i, itemId: slot.itemId, rank, tier: def.tier }; } } return best;}function toolTierRank (tool){ const tier = tool?.def?.equipment?.tier ?? tool?.tier; return tierRank(tier);}/** * Start fishing at a fishing-spot block tile. */export function startFish (world, sessionId, characterId, tileX, tileY, now = Date.now()){ const entityId = world.characterEntities.get(characterId); if (entityId == null) { throw userError("Character is not in the world."); } const handle = world.ecs.handleOf(entityId); const identity = world.ecs.get(handle, Component.networkIdentity); if (!identity || identity.sessionId !== sessionId) { throw userError("Character is not in the world."); } if (world.ecs.has(handle, Component.dead)) { throw userError("You are dead."); } const position = world.ecs.get(handle, Component.position); if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1) { throw userError("You need to stand next to the fishing spot."); } const block = blockAt(world, tileX, tileY); if (!block || block.typeId !== BlockType.fishingSpot) { throw userError("There is no fishing spot there."); } if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY))) { throw userError("The fish have scattered. Wait for them to return."); } const ground = groundAt(world, tileX, tileY); const season = seasonIdAt(now); if (ground !== GroundType.water && ground !== GroundType.deepWater) { throw userError("Fishing spots must be on water."); } if (!isLiquidWaterGround(ground, season)) { throw userError("The water is frozen solid."); } const fishList = spotFishItemIds(block); if (!fishList.length) { throw userError("No fish swim here."); } const inventory = world.ecs.get(handle, Component.inventory); const equipment = world.ecs.get(handle, Component.equipment); const skills = world.ecs.get(handle, Component.skills); const resolved = resolveFishingTool({ inventorySlots: inventory?.slots, equipmentSlots: equipment?.slots, skills }); if (!resolved.ok) { throw userError(resolved.reason); } const isNet = resolved.kind === EquipmentKind.fishingNet; const rodRank = isNet ? 1 : toolTierRank(resolved.tool); const maxInSpot = maxFishTierInList(fishList); const usefulMax = Math.min(rodRank, maxInSpot); let baitRank = 1; let baitItemId = null; let baitConsumedRank = 0; if (isNet) { baitRank = 1; baitConsumedRank = 0; } else { const bait = findBestBaitSlot(inventory?.slots, usefulMax); if (!bait) { throw userError("You need suitable bait for this spot."); } baitRank = bait.rank; baitItemId = bait.itemId; baitConsumedRank = bait.rank; } const eligible = eligibleFishItemIds(fishList, baitRank); if (!eligible.length) { throw userError("No fish here match your bait."); } if (!isNet) { const taken = takeMatchingFromSlots(inventory.slots, { itemId: baitItemId, quantity: 1, compact: false }); if (!taken.ok) { throw userError("You need suitable bait for this spot."); } inventory.slots = taken.slots; } clearFishSession(world, characterId); if (world.ecs.has(handle, Component.gather)) { world.ecs.remove(handle, Component.gather); } const path = world.ecs.get(handle, Component.path); if (path) { path.tiles = []; } ensureFishSessions(world).set(characterId, { sessionId, tileX, tileY, toolItemId: resolved.tool.def.itemId, isNet, baitRank, baitConsumedRank, baitItemId, eligible, difficulty: fishingDifficulty(baitRank), attemptsLeft: MAX_FISH_ATTEMPTS, attemptStartedAt: now, nextShoveAt: now, attemptEndsAt: now + FISH_ATTEMPT_MS }); return { events: [], private: isNet ? null : bagView(world.ecs, handle) };}export function handleFishingCommand (world, sessionId, command, now = Date.now()){ if (command.type === "start-fish") { return startFish( world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now ); } if (command.type === "cancel-fish") { clearFishSession(world, command.characterId); return { events: [] }; } return null;}function completeCatch (world, handle, entityId, characterId, session, events, privates, now){ const eligible = session.eligible ?? []; if (!eligible.length) { events.push({ type: "command-error", sessionId: session.sessionId, message: "The fish got away." }); clearFishSession(world, characterId); return; } const rng = world.rng ?? Math.random; const pick = eligible[Math.floor(rng() * eligible.length) % eligible.length]; const fishRank = fishTierRankFromItemId(pick); const inventory = world.ecs.get(handle, Component.inventory); const def = itemDefinition(pick); const origin = gatherOrigin(GatherOriginVerb.caught, characterDisplayName(world, handle)); const stack = attachOrigins({ itemId: pick, quantity: 1, origins: [{ origin, quantity: 1 }] }); const inserted = insertStack(inventory.slots, stack, def); if (!inserted.ok || inserted.remainder > 0) { events.push({ type: "command-error", sessionId: session.sessionId, message: "Your inventory is full." }); clearFishSession(world, characterId); return; } inventory.slots = inserted.slots; const xpAmount = (session.baitConsumedRank | 0) + fishRank; const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp && xpAmount > 0) { const result = applySkillXp(skills, SkillId.fishing, xpAmount); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } if (skillsChanged) { events.push({ type: "skills-updated", entityId, characterId, skills: publicSkillsView(skills), stored: storedSkillXp(skills), levelUps }); } const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted"); if (exhausted) { events.push(exhausted); } ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY), { tileX: session.tileX, tileY: session.tileY, respawnsAt: now + fishingExhaustDurationMs(fishRank) }); privates.push({ characterId, bag: bagView(world.ecs, handle) }); events.push({ type: "item-bubble", entityId, itemId: pick, quantity: 1 }); clearFishSession(world, characterId);}export function stepFishing (world, now){ const events = []; const privates = []; events.push(...stepFishingSpotRespawns(world, now).events); const sessions = ensureFishSessions(world); for (const [characterId, session] of [...sessions.entries()]) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { clearFishSession(world, characterId); continue; } const handle = world.ecs.handleOf(entityId); if (world.ecs.has(handle, Component.dead)) { clearFishSession(world, characterId); continue; } const position = world.ecs.get(handle, Component.position); if (chebyshev(position.tileX, position.tileY, session.tileX, session.tileY) > 1) { clearFishSession(world, characterId); continue; } if (now >= session.nextShoveAt && now < session.attemptEndsAt) { session.nextShoveAt = now + FISH_SHOVE_MS; events.push(tileShoveEvent( entityId, position.tileX, position.tileY, session.tileX, session.tileY )); // Also emit gather-swing so tool overlay shows. events.push({ type: "gather-swing", attackerId: entityId, tileX: session.tileX, tileY: session.tileY, fromTileX: position.tileX, fromTileY: position.tileY, toolItemId: session.toolItemId, swipe: false }); } if (now < session.attemptEndsAt) { continue; } const skills = world.ecs.get(handle, Component.skills); const level = skillLevel(skills, SkillId.fishing); const roll = rollSkill(level, world.rng ?? Math.random); session.attemptsLeft -= 1; if (roll >= session.difficulty) { completeCatch(world, handle, entityId, characterId, session, events, privates, now); continue; } if (session.attemptsLeft <= 0) { events.push({ type: "command-error", sessionId: session.sessionId, message: "The fish got away." }); maybeBreakFishingLine(world, handle, entityId, characterId, session, events, privates, now); clearFishSession(world, characterId); continue; } session.attemptStartedAt = now; session.nextShoveAt = now; session.attemptEndsAt = now + FISH_ATTEMPT_MS; } return { events, privates };}function spawnGroundStack (world, tileX, tileY, itemId, now, events, source = "fishing-line-break"){ const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1); const stack = attachOrigins({ itemId, quantity: 1, origins: [] }); const item = { groundItemId, tileX, tileY, stack, droppedAt: now, expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000), source }; addGroundItem(world, item); events.push({ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, expiresAt: item.expiresAt });}/** * After a fully failed rod session: 5% chance the line snaps → rod becomes pole + 1 yarn. */function maybeBreakFishingLine (world, handle, entityId, characterId, session, events, privates, now){ if (session.isNet) { return; } const rng = world.rng ?? Math.random; if (rng() >= LINE_BREAK_CHANCE) { return; } const rodItemId = session.toolItemId | 0; const rodDef = itemDefinition(rodItemId); const woodTier = woodTierFromFishingRodItemId(rodItemId) ?? rodDef?.tier; const poleItemId = rodDef?.poleItemId ?? fishingPoleItemIdForWood(woodTier); const clothTier = rodDef?.clothTier ?? clothTierForWood(woodTier); const yarnId = yarnItemId(clothTier); if (!poleItemId || !yarnId) { return; } const inventory = world.ecs.get(handle, Component.inventory); const equipment = world.ecs.get(handle, Component.equipment); let removed = false; let appearanceChanged = false; if (inventory?.slots) { const idx = inventory.slots.findIndex((s) => s?.itemId === rodItemId); if (idx >= 0) { const taken = takeFromSlot(inventory.slots, idx, 1); if (taken.ok) { inventory.slots = taken.slots; removed = true; } } } if (!removed && equipment?.slots?.weapon?.itemId === rodItemId) { equipment.slots.weapon = null; removed = true; appearanceChanged = true; } if (!removed) { return; } const position = world.ecs.get(handle, Component.position); const poleDef = itemDefinition(poleItemId); const yarnDef = itemDefinition(yarnId); let slots = inventory.slots; const poleIns = insertStack(slots, attachOrigins({ itemId: poleItemId, quantity: 1, origins: [] }), poleDef); if (poleIns.ok && poleIns.remainder === 0) { slots = poleIns.slots; } else { spawnGroundStack(world, position.tileX, position.tileY, poleItemId, now, events); } const yarnIns = insertStack(slots, attachOrigins({ itemId: yarnId, quantity: 1, origins: [] }), yarnDef); if (yarnIns.ok && yarnIns.remainder === 0) { slots = yarnIns.slots; } else { spawnGroundStack(world, position.tileX, position.tileY, yarnId, now, events); } inventory.slots = slots; events.push({ type: "command-error", sessionId: session.sessionId, message: "Your fishing line broke!" }); privates.push({ characterId, bag: bagView(world.ecs, handle), ...(appearanceChanged ? { appearanceChanged: true } : {}) });}export function stepFishingSpotRespawns (world, now){ const respawns = world.fishingSpotRespawns; if (!respawns?.size) { return { events: [] }; } const events = []; for (const [key, entry] of [...respawns.entries()]) { if (now < entry.respawnsAt) { continue; } respawns.delete(key); const block = blockAt(world, entry.tileX, entry.tileY); if (!block || block.typeId !== BlockType.fishingSpot) { continue; } const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot"); if (delta) { events.push(delta); } } return { events };}export { ClothTier, BaitItemId, baitItemIdForCloth, FISH_SPECIES };@@ -426,6 +426,23 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
batchAll: !!message.batchAll
});
break;
case MessageType.startFire:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "start-fire",
characterId: session.characterId,
groundItemId: message.groundItemId | 0
});
break;
case MessageType.startFish:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "start-fish",
characterId: session.characterId,
tileX: message.tileX | 0,
tileY: message.tileY | 0
});
break;
case MessageType.cancelCraft:
requirePlaying(session);
simulation.enqueue(session.id, {
@@ -426,6 +426,23 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, batchAll: !!message.batchAll batchAll: !!message.batchAll }); }); break; break; case MessageType.startFire: requirePlaying(session); simulation.enqueue(session.id, { type: "start-fire", characterId: session.characterId, groundItemId: message.groundItemId | 0 }); break; case MessageType.startFish: requirePlaying(session); simulation.enqueue(session.id, { type: "start-fish", characterId: session.characterId, tileX: message.tileX | 0, tileY: message.tileY | 0 }); break; case MessageType.cancelCraft: case MessageType.cancelCraft: requirePlaying(session); requirePlaying(session); simulation.enqueue(session.id, { simulation.enqueue(session.id, {@@ -481,10 +481,20 @@ function eatItem (world, sessionId, command)
{ throw userError("That inventory slot is empty."); }
inventory.slots = taken.slots;
health.current = Math.min(health.max | 0, (health.current | 0) + healing);
let statusEffectsChanged = false;
if (def?.eatStatusEffect)
{
let component = world.ecs.get(handle, Component.statusEffects);
if (!component)
{ component = world.ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }
applyStatusEffect(component, def.eatStatusEffect, Date.now());
statusEffectsChanged = true;
}
return {
events: [],
private: bagView(world.ecs, handle),
healthChanged: true
healthChanged: true,
statusEffectsChanged
};
}
@@ -481,10 +481,20 @@ function eatItem (world, sessionId, command) { throw userError("That inventory slot is empty."); } { throw userError("That inventory slot is empty."); } inventory.slots = taken.slots; inventory.slots = taken.slots; health.current = Math.min(health.max | 0, (health.current | 0) + healing); health.current = Math.min(health.max | 0, (health.current | 0) + healing); let statusEffectsChanged = false; if (def?.eatStatusEffect) { let component = world.ecs.get(handle, Component.statusEffects); if (!component) { component = world.ecs.add(handle, Component.statusEffects, emptyStatusEffects()); } applyStatusEffect(component, def.eatStatusEffect, Date.now()); statusEffectsChanged = true; } return { return { events: [], events: [], private: bagView(world.ecs, handle), private: bagView(world.ecs, handle), healthChanged: true healthChanged: true, statusEffectsChanged }; };}}@@ -576,9 +576,13 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId,
else
{
const shopOriginEntry = { kind: ItemOriginKind.shop, displayName };
const defaultInstance = def?.defaultInstance
? structuredClone(def.defaultInstance)
: null;
stack = attachOrigins({
itemId: buyItemId,
quantity: qty,
instance: defaultInstance,
origins: [{ origin: shopOriginEntry, quantity: qty }]
});
}
@@ -576,9 +576,13 @@ export function buyFromShop (world, sessionId, characterId, npcEntityId, itemId, else else { { const shopOriginEntry = { kind: ItemOriginKind.shop, displayName }; const shopOriginEntry = { kind: ItemOriginKind.shop, displayName }; const defaultInstance = def?.defaultInstance ? structuredClone(def.defaultInstance) : null; stack = attachOrigins({ stack = attachOrigins({ itemId: buyItemId, itemId: buyItemId, quantity: qty, quantity: qty, instance: defaultInstance, origins: [{ origin: shopOriginEntry, quantity: qty }] origins: [{ origin: shopOriginEntry, quantity: qty }] }); }); } }@@ -43,6 +43,8 @@ import {
clearPlantRespawnsForChunk
} from "../gathering/service.js";
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
import { handleFishingCommand, stepFishing } from "../fishing/service.js";
import { handleAlchemyCommand } from "../alchemy/service.js";
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
import {
@@ -90,6 +92,10 @@ export class WorkerWorld
this.groundByTile = new Map();
this.oreRespawns = new Map();
this.treeRespawns = new Map();
this.campfireExpires = new Map();
this.fireSessions = new Map();
this.fishingSpotRespawns = new Map();
this.fishSessions = new Map();
this.pendingSpellImpacts = [];
this.settings = { ...DEFAULT_WORLD_SETTINGS };
this.activeRevisionId = 1;
@@ -478,6 +484,12 @@ export class WorkerWorld
const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
if (gather)
{ return gather; }
const fire = handleFirestartingCommand(this, sessionId, command, message.now ?? Date.now());
if (fire)
{ return fire; }
const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());
if (fishing)
{ return fishing; }
const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
if (craft)
{ return craft; }
@@ -1276,6 +1288,26 @@ export class WorkerWorld
...entry.bag
});
}
const fire = stepFirestarting(this, now);
events.push(...fire.events);
for (const entry of fire.privates ?? [])
{
events.push({
type: "inventory",
characterId: entry.characterId,
...entry.bag
});
}
const fishing = stepFishing(this, now);
events.push(...fishing.events);
for (const entry of fishing.privates ?? [])
{
events.push({
type: "inventory",
characterId: entry.characterId,
...entry.bag
});
}
const craft = stepCrafting(this, now);
events.push(...craft.events);
for (const entry of craft.privates ?? [])
@@ -1370,6 +1402,10 @@ export class WorkerWorld
continue;
}
const combat = this.ecs.get(handle, Component.combat);
if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y))
{ continue; }
const fromTileX = position.tileX;
const fromTileY = position.tileY;
const flying = this.#isFlying(handle);
@@ -43,6 +43,8 @@ import { clearPlantRespawnsForChunk clearPlantRespawnsForChunk} from "../gathering/service.js";} from "../gathering/service.js";import { handleCraftCommand, stepCrafting } from "../crafting/service.js";import { handleCraftCommand, stepCrafting } from "../crafting/service.js";import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";import { handleFishingCommand, stepFishing } from "../fishing/service.js";import { handleAlchemyCommand } from "../alchemy/service.js";import { handleAlchemyCommand } from "../alchemy/service.js";import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";import {import {@@ -90,6 +92,10 @@ export class WorkerWorld this.groundByTile = new Map(); this.groundByTile = new Map(); this.oreRespawns = new Map(); this.oreRespawns = new Map(); this.treeRespawns = new Map(); this.treeRespawns = new Map(); this.campfireExpires = new Map(); this.fireSessions = new Map(); this.fishingSpotRespawns = new Map(); this.fishSessions = new Map(); this.pendingSpellImpacts = []; this.pendingSpellImpacts = []; this.settings = { ...DEFAULT_WORLD_SETTINGS }; this.settings = { ...DEFAULT_WORLD_SETTINGS }; this.activeRevisionId = 1; this.activeRevisionId = 1;@@ -478,6 +484,12 @@ export class WorkerWorld const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now()); const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now()); if (gather) if (gather) { return gather; } { return gather; } const fire = handleFirestartingCommand(this, sessionId, command, message.now ?? Date.now()); if (fire) { return fire; } const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now()); if (fishing) { return fishing; } const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now()); const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now()); if (craft) if (craft) { return craft; } { return craft; }@@ -1276,6 +1288,26 @@ export class WorkerWorld ...entry.bag ...entry.bag }); }); } } const fire = stepFirestarting(this, now); events.push(...fire.events); for (const entry of fire.privates ?? []) { events.push({ type: "inventory", characterId: entry.characterId, ...entry.bag }); } const fishing = stepFishing(this, now); events.push(...fishing.events); for (const entry of fishing.privates ?? []) { events.push({ type: "inventory", characterId: entry.characterId, ...entry.bag }); } const craft = stepCrafting(this, now); const craft = stepCrafting(this, now); events.push(...craft.events); events.push(...craft.events); for (const entry of craft.privates ?? []) for (const entry of craft.privates ?? [])@@ -1370,6 +1402,10 @@ export class WorkerWorld continue; continue; } } const combat = this.ecs.get(handle, Component.combat); if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y)) { continue; } const fromTileX = position.tileX; const fromTileX = position.tileX; const fromTileY = position.tileY; const fromTileY = position.tileY; const flying = this.#isFlying(handle); const flying = this.#isFlying(handle);@@ -1025,3 +1025,94 @@ test("blocking a hit awards Defence XP equal to avoided damage", () =>
harness.close();
}
});
test("stacked combatants against the same target spread to different tiles", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const rat1 = harness.simulation.spawnEntity(mobComponents({
tileX: 9,
tileY: 8,
mobTypeId: MobId.rat,
spawnerId: null
}));
const rat2 = harness.simulation.spawnEntity(mobComponents({
tileX: 9,
tileY: 7,
mobTypeId: MobId.rat,
spawnerId: null
}));
const worker = workerOf(harness.simulation, playerId);
teleportEntity(worker, rat2, 9, 8);
for (let i = 0; i < 200; i++)
{
harness.advance(50);
harness.simulation.step();
}
const pos1 = componentsOf(harness.simulation, rat1).position;
const pos2 = componentsOf(harness.simulation, rat2).position;
assert.notEqual(
`${pos1.tileX},${pos1.tileY}`,
`${pos2.tileX},${pos2.tileY}`,
"expected stacked rats to spread apart"
);
assert.equal(componentsOf(harness.simulation, rat1).combat?.targetEntityId, playerId);
assert.equal(componentsOf(harness.simulation, rat2).combat?.targetEntityId, playerId);
}
finally
{ harness.close(); }
});
test("approaching combatants pick different adjacent goals", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const rat1 = harness.simulation.spawnEntity(mobComponents({
tileX: 6,
tileY: 8,
mobTypeId: MobId.rat,
spawnerId: null
}));
const rat2 = harness.simulation.spawnEntity(mobComponents({
tileX: 6,
tileY: 7,
mobTypeId: MobId.rat,
spawnerId: null
}));
const worker = workerOf(harness.simulation, playerId);
teleportEntity(worker, rat2, 6, 8);
for (let i = 0; i < 120; i++)
{
harness.advance(50);
harness.simulation.step();
}
const path1 = componentsOf(harness.simulation, rat1).path?.tiles ?? [];
const path2 = componentsOf(harness.simulation, rat2).path?.tiles ?? [];
const goal1 = path1[path1.length - 1];
const goal2 = path2[path2.length - 1];
if (goal1 && goal2)
{
assert.notEqual(
`${goal1.x},${goal1.y}`,
`${goal2.x},${goal2.y}`,
"expected different approach goals"
);
}
const pos1 = componentsOf(harness.simulation, rat1).position;
const pos2 = componentsOf(harness.simulation, rat2).position;
assert.notEqual(`${pos1.tileX},${pos1.tileY}`, `${pos2.tileX},${pos2.tileY}`);
}
finally
{ harness.close(); }
});
@@ -1025,3 +1025,94 @@ test("blocking a hit awards Defence XP equal to avoided damage", () => harness.close(); harness.close(); } }});});test("stacked combatants against the same target spread to different tiles", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const rat1 = harness.simulation.spawnEntity(mobComponents({ tileX: 9, tileY: 8, mobTypeId: MobId.rat, spawnerId: null })); const rat2 = harness.simulation.spawnEntity(mobComponents({ tileX: 9, tileY: 7, mobTypeId: MobId.rat, spawnerId: null })); const worker = workerOf(harness.simulation, playerId); teleportEntity(worker, rat2, 9, 8); for (let i = 0; i < 200; i++) { harness.advance(50); harness.simulation.step(); } const pos1 = componentsOf(harness.simulation, rat1).position; const pos2 = componentsOf(harness.simulation, rat2).position; assert.notEqual( `${pos1.tileX},${pos1.tileY}`, `${pos2.tileX},${pos2.tileY}`, "expected stacked rats to spread apart" ); assert.equal(componentsOf(harness.simulation, rat1).combat?.targetEntityId, playerId); assert.equal(componentsOf(harness.simulation, rat2).combat?.targetEntityId, playerId); } finally { harness.close(); }});test("approaching combatants pick different adjacent goals", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const rat1 = harness.simulation.spawnEntity(mobComponents({ tileX: 6, tileY: 8, mobTypeId: MobId.rat, spawnerId: null })); const rat2 = harness.simulation.spawnEntity(mobComponents({ tileX: 6, tileY: 7, mobTypeId: MobId.rat, spawnerId: null })); const worker = workerOf(harness.simulation, playerId); teleportEntity(worker, rat2, 6, 8); for (let i = 0; i < 120; i++) { harness.advance(50); harness.simulation.step(); } const path1 = componentsOf(harness.simulation, rat1).path?.tiles ?? []; const path2 = componentsOf(harness.simulation, rat2).path?.tiles ?? []; const goal1 = path1[path1.length - 1]; const goal2 = path2[path2.length - 1]; if (goal1 && goal2) { assert.notEqual( `${goal1.x},${goal1.y}`, `${goal2.x},${goal2.y}`, "expected different approach goals" ); } const pos1 = componentsOf(harness.simulation, rat1).position; const pos2 = componentsOf(harness.simulation, rat2).position; assert.notEqual(`${pos1.tileX},${pos1.tileY}`, `${pos2.tileX},${pos2.tileY}`); } finally { harness.close(); }});@@ -0,0 +1,298 @@
import test from "node:test";
import assert from "node:assert/strict";
import { BlockType } from "../../shared/definitions/tiles.js";
import {
CraftingStationId,
firestartingDifficulty,
campfireDurationMs,
COOK_BURN_CHANCE_OVEN,
COOK_BURN_CHANCE_CAMPFIRE,
CRAFT_DURATION_MS
} from "../../shared/definitions/craftingStations.js";
import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";
import { WoodItemId, ashItemIdForWood } from "../../shared/definitions/woodItems.js";
import { WoodTier } from "../../shared/definitions/materialTiers.js";
import { SkillId } from "../../shared/definitions/skills.js";
import { recipeDefinition } from "../../shared/crafting/stationRecipes.js";
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
import { totalXpForLevel } from "../../shared/skills/progression.js";
import { ashTintColor } from "../../shared/render/tint.js";
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
import { Component } from "../src/ecs/components.js";
import { addGroundItem } from "../src/items/bags.js";
import { StatusEffectType } from "../../shared/statusEffects/rules.js";
function countItem (slots, itemId)
{
return (slots ?? []).reduce((sum, slot) =>
{
if (slot?.itemId === itemId)
{ return sum + (slot.quantity | 0); }
return sum;
}, 0);
}
function workerOf (simulation, playerId)
{
const record = simulation.entityRecord(playerId);
return simulation.workers[record.workerId];
}
function setSkillLevel (worker, playerId, skillId, level)
{
const handle = worker.world.ecs.handleOf(playerId);
const skills = worker.world.ecs.get(handle, Component.skills);
skills.xp[skillId] = totalXpForLevel(level);
}
function giveInventory (harness, playerId, items)
{
const inventory = emptySlots();
items.forEach((stack, index) =>
{
inventory[index] = {
itemId: stack.itemId,
quantity: stack.quantity,
...(stack.instance ? { instance: structuredClone(stack.instance) } : {})
};
});
harness.simulation.applyBag(playerId, {
inventory,
equipment: emptyEquipment(),
vault: [],
vaultReserved: []
});
}
function advanceMs (harness, ms)
{
const ticks = Math.ceil(ms / 50) + 3;
for (let i = 0; i < ticks; i++)
{
harness.advance(50);
harness.simulation.step();
}
}
function placeStation (worker, tileX, tileY, typeId, state)
{
const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
const localX = ((tileX % 16) + 16) % 16;
const localY = ((tileY % 16) + 16) % 16;
data.blocks[localY * 16 + localX] = {
typeId,
state,
config: null
};
}
test("firestarting difficulty and campfire duration scale with wood tier", () =>
{
assert.equal(firestartingDifficulty(WoodTier.pine), 1);
assert.equal(firestartingDifficulty(WoodTier.birch), 10);
assert.equal(firestartingDifficulty(WoodTier.oak), 20);
assert.equal(campfireDurationMs(WoodTier.pine), 3 * 60_000);
assert.equal(campfireDurationMs(WoodTier.oak), 9 * 60_000);
assert.equal(COOK_BURN_CHANCE_OVEN, 0.1);
assert.equal(COOK_BURN_CHANCE_CAMPFIRE, 0.35);
});
test("ash tint sits between dark grey and wood colour", () =>
{
const tint = ashTintColor(WoodTier.pine);
assert.ok(tint.r > 0.12 && tint.r < 0.9);
});
test("cook-venison recipe exists for oven and campfire with burnt output", () =>
{
const recipe = recipeDefinition("cook-venison");
assert.ok(recipe);
assert.deepEqual(recipe.stationIds, [CraftingStationId.oven, CraftingStationId.fireplace]);
assert.equal(recipe.output.itemId, CraftingItemId.cookedMeat);
assert.equal(recipe.burntOutput.itemId, CraftingItemId.burntMeat);
assert.equal(recipe.inputs[0].itemId, CraftingItemId.rawMeat);
});
test("start-fire places campfire and expiry drops ash", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = workerOf(harness.simulation, playerId);
worker.world.rng = () => 0.999;
setSkillLevel(worker, playerId, SkillId.firestarting, 1);
giveInventory(harness, playerId, [
{ itemId: CraftingItemId.tinderbox, quantity: 1, instance: tinderboxItemInstance(20) }
]);
const groundItemId = 9001;
addGroundItem(worker.world, {
groundItemId,
tileX: 9,
tileY: 8,
stack: { itemId: WoodItemId.pineLog, quantity: 1 },
droppedAt: harness.now(),
expiresAt: harness.now() + 600_000,
source: "test"
});
harness.simulation.enqueue(1, {
type: "start-fire",
characterId: character.character_id,
groundItemId
});
advanceMs(harness, 4000);
const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
assert.equal(block?.typeId, BlockType.campfire);
assert.equal(block?.state, WoodTier.pine);
assert.ok(worker.world.campfireExpires.has("9,8"));
const bag = harness.simulation.bagOf(playerId);
const tinder = bag.inventory.find((s) => s?.itemId === CraftingItemId.tinderbox);
assert.equal(tinder?.instance?.charges, 19);
const entry = worker.world.campfireExpires.get("9,8");
entry.expiresAt = 0;
advanceMs(harness, 200);
assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null);
const ashOnGround = [...worker.world.groundItems.values()].some(
(item) => item.stack?.itemId === ashItemIdForWood(WoodTier.pine)
);
assert.equal(ashOnGround, true);
}
finally
{ harness.close(); }
});
test("start-fire rejects too-low Firestarting for birch", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = workerOf(harness.simulation, playerId);
setSkillLevel(worker, playerId, SkillId.firestarting, 1);
giveInventory(harness, playerId, [
{ itemId: CraftingItemId.tinderbox, quantity: 1, instance: tinderboxItemInstance(5) }
]);
addGroundItem(worker.world, {
groundItemId: 9002,
tileX: 9,
tileY: 8,
stack: { itemId: WoodItemId.birchLog, quantity: 1 },
droppedAt: harness.now(),
expiresAt: harness.now() + 600_000,
source: "test"
});
harness.simulation.enqueue(1, {
type: "start-fire",
characterId: character.character_id,
groundItemId: 9002
});
advanceMs(harness, 200);
assert.equal(worker.world.groundItems.has(9002), true);
assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null);
}
finally
{ harness.close(); }
});
test("oven cook can burn to burnt venison with seeded rng", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = workerOf(harness.simulation, playerId);
worker.world.rng = () => 0.01;
setSkillLevel(worker, playerId, SkillId.cooking, 1);
placeStation(worker, 9, 8, BlockType.oven, "oven");
giveInventory(harness, playerId, [
{ itemId: CraftingItemId.rawMeat, quantity: 1 }
]);
harness.simulation.enqueue(1, {
type: "start-craft",
characterId: character.character_id,
stationId: CraftingStationId.oven,
recipeId: "cook-venison"
});
advanceMs(harness, CRAFT_DURATION_MS + 500);
const bag = harness.simulation.bagOf(playerId);
assert.equal(countItem(bag.inventory, CraftingItemId.rawMeat), 0);
assert.equal(countItem(bag.inventory, CraftingItemId.burntMeat), 1);
assert.equal(countItem(bag.inventory, CraftingItemId.cookedMeat), 0);
}
finally
{ harness.close(); }
});
test("oven cook succeeds when rng avoids burn", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = workerOf(harness.simulation, playerId);
worker.world.rng = () => 0.99;
setSkillLevel(worker, playerId, SkillId.cooking, 1);
placeStation(worker, 9, 8, BlockType.oven, "oven");
giveInventory(harness, playerId, [
{ itemId: CraftingItemId.rawMeat, quantity: 1 }
]);
harness.simulation.enqueue(1, {
type: "start-craft",
characterId: character.character_id,
stationId: CraftingStationId.oven,
recipeId: "cook-venison"
});
advanceMs(harness, CRAFT_DURATION_MS + 500);
const bag = harness.simulation.bagOf(playerId);
assert.equal(countItem(bag.inventory, CraftingItemId.cookedMeat), 1);
}
finally
{ harness.close(); }
});
test("eating cooked venison heals and applies health regen", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = workerOf(harness.simulation, playerId);
const handle = worker.world.ecs.handleOf(playerId);
const health = worker.world.ecs.get(handle, Component.health);
health.current = 5;
health.max = 20;
giveInventory(harness, playerId, [
{ itemId: CraftingItemId.cookedMeat, quantity: 1 }
]);
harness.simulation.enqueue(1, {
type: "eat-item",
characterId: character.character_id,
slotIndex: 0
});
harness.simulation.step();
assert.equal(health.current, 10);
const status = worker.world.ecs.get(handle, Component.statusEffects);
const regen = status?.effects?.find((e) => e.type === StatusEffectType.healthRegen);
assert.ok(regen);
assert.equal(regen.amountPerSecond, 1);
}
finally
{ harness.close(); }
});
@@ -0,0 +1,298 @@import test from "node:test";import assert from "node:assert/strict";import { BlockType } from "../../shared/definitions/tiles.js";import { CraftingStationId, firestartingDifficulty, campfireDurationMs, COOK_BURN_CHANCE_OVEN, COOK_BURN_CHANCE_CAMPFIRE, CRAFT_DURATION_MS} from "../../shared/definitions/craftingStations.js";import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";import { WoodItemId, ashItemIdForWood } from "../../shared/definitions/woodItems.js";import { WoodTier } from "../../shared/definitions/materialTiers.js";import { SkillId } from "../../shared/definitions/skills.js";import { recipeDefinition } from "../../shared/crafting/stationRecipes.js";import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";import { totalXpForLevel } from "../../shared/skills/progression.js";import { ashTintColor } from "../../shared/render/tint.js";import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";import { Component } from "../src/ecs/components.js";import { addGroundItem } from "../src/items/bags.js";import { StatusEffectType } from "../../shared/statusEffects/rules.js";function countItem (slots, itemId){ return (slots ?? []).reduce((sum, slot) => { if (slot?.itemId === itemId) { return sum + (slot.quantity | 0); } return sum; }, 0);}function workerOf (simulation, playerId){ const record = simulation.entityRecord(playerId); return simulation.workers[record.workerId];}function setSkillLevel (worker, playerId, skillId, level){ const handle = worker.world.ecs.handleOf(playerId); const skills = worker.world.ecs.get(handle, Component.skills); skills.xp[skillId] = totalXpForLevel(level);}function giveInventory (harness, playerId, items){ const inventory = emptySlots(); items.forEach((stack, index) => { inventory[index] = { itemId: stack.itemId, quantity: stack.quantity, ...(stack.instance ? { instance: structuredClone(stack.instance) } : {}) }; }); harness.simulation.applyBag(playerId, { inventory, equipment: emptyEquipment(), vault: [], vaultReserved: [] });}function advanceMs (harness, ms){ const ticks = Math.ceil(ms / 50) + 3; for (let i = 0; i < ticks; i++) { harness.advance(50); harness.simulation.step(); }}function placeStation (worker, tileX, tileY, typeId, state){ const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16)); const localX = ((tileX % 16) + 16) % 16; const localY = ((tileY % 16) + 16) % 16; data.blocks[localY * 16 + localX] = { typeId, state, config: null };}test("firestarting difficulty and campfire duration scale with wood tier", () =>{ assert.equal(firestartingDifficulty(WoodTier.pine), 1); assert.equal(firestartingDifficulty(WoodTier.birch), 10); assert.equal(firestartingDifficulty(WoodTier.oak), 20); assert.equal(campfireDurationMs(WoodTier.pine), 3 * 60_000); assert.equal(campfireDurationMs(WoodTier.oak), 9 * 60_000); assert.equal(COOK_BURN_CHANCE_OVEN, 0.1); assert.equal(COOK_BURN_CHANCE_CAMPFIRE, 0.35);});test("ash tint sits between dark grey and wood colour", () =>{ const tint = ashTintColor(WoodTier.pine); assert.ok(tint.r > 0.12 && tint.r < 0.9);});test("cook-venison recipe exists for oven and campfire with burnt output", () =>{ const recipe = recipeDefinition("cook-venison"); assert.ok(recipe); assert.deepEqual(recipe.stationIds, [CraftingStationId.oven, CraftingStationId.fireplace]); assert.equal(recipe.output.itemId, CraftingItemId.cookedMeat); assert.equal(recipe.burntOutput.itemId, CraftingItemId.burntMeat); assert.equal(recipe.inputs[0].itemId, CraftingItemId.rawMeat);});test("start-fire places campfire and expiry drops ash", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const worker = workerOf(harness.simulation, playerId); worker.world.rng = () => 0.999; setSkillLevel(worker, playerId, SkillId.firestarting, 1); giveInventory(harness, playerId, [ { itemId: CraftingItemId.tinderbox, quantity: 1, instance: tinderboxItemInstance(20) } ]); const groundItemId = 9001; addGroundItem(worker.world, { groundItemId, tileX: 9, tileY: 8, stack: { itemId: WoodItemId.pineLog, quantity: 1 }, droppedAt: harness.now(), expiresAt: harness.now() + 600_000, source: "test" }); harness.simulation.enqueue(1, { type: "start-fire", characterId: character.character_id, groundItemId }); advanceMs(harness, 4000); const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9]; assert.equal(block?.typeId, BlockType.campfire); assert.equal(block?.state, WoodTier.pine); assert.ok(worker.world.campfireExpires.has("9,8")); const bag = harness.simulation.bagOf(playerId); const tinder = bag.inventory.find((s) => s?.itemId === CraftingItemId.tinderbox); assert.equal(tinder?.instance?.charges, 19); const entry = worker.world.campfireExpires.get("9,8"); entry.expiresAt = 0; advanceMs(harness, 200); assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null); const ashOnGround = [...worker.world.groundItems.values()].some( (item) => item.stack?.itemId === ashItemIdForWood(WoodTier.pine) ); assert.equal(ashOnGround, true); } finally { harness.close(); }});test("start-fire rejects too-low Firestarting for birch", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const worker = workerOf(harness.simulation, playerId); setSkillLevel(worker, playerId, SkillId.firestarting, 1); giveInventory(harness, playerId, [ { itemId: CraftingItemId.tinderbox, quantity: 1, instance: tinderboxItemInstance(5) } ]); addGroundItem(worker.world, { groundItemId: 9002, tileX: 9, tileY: 8, stack: { itemId: WoodItemId.birchLog, quantity: 1 }, droppedAt: harness.now(), expiresAt: harness.now() + 600_000, source: "test" }); harness.simulation.enqueue(1, { type: "start-fire", characterId: character.character_id, groundItemId: 9002 }); advanceMs(harness, 200); assert.equal(worker.world.groundItems.has(9002), true); assert.equal(worker.world.chunkData(0, 0).blocks[8 * 16 + 9], null); } finally { harness.close(); }});test("oven cook can burn to burnt venison with seeded rng", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const worker = workerOf(harness.simulation, playerId); worker.world.rng = () => 0.01; setSkillLevel(worker, playerId, SkillId.cooking, 1); placeStation(worker, 9, 8, BlockType.oven, "oven"); giveInventory(harness, playerId, [ { itemId: CraftingItemId.rawMeat, quantity: 1 } ]); harness.simulation.enqueue(1, { type: "start-craft", characterId: character.character_id, stationId: CraftingStationId.oven, recipeId: "cook-venison" }); advanceMs(harness, CRAFT_DURATION_MS + 500); const bag = harness.simulation.bagOf(playerId); assert.equal(countItem(bag.inventory, CraftingItemId.rawMeat), 0); assert.equal(countItem(bag.inventory, CraftingItemId.burntMeat), 1); assert.equal(countItem(bag.inventory, CraftingItemId.cookedMeat), 0); } finally { harness.close(); }});test("oven cook succeeds when rng avoids burn", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const worker = workerOf(harness.simulation, playerId); worker.world.rng = () => 0.99; setSkillLevel(worker, playerId, SkillId.cooking, 1); placeStation(worker, 9, 8, BlockType.oven, "oven"); giveInventory(harness, playerId, [ { itemId: CraftingItemId.rawMeat, quantity: 1 } ]); harness.simulation.enqueue(1, { type: "start-craft", characterId: character.character_id, stationId: CraftingStationId.oven, recipeId: "cook-venison" }); advanceMs(harness, CRAFT_DURATION_MS + 500); const bag = harness.simulation.bagOf(playerId); assert.equal(countItem(bag.inventory, CraftingItemId.cookedMeat), 1); } finally { harness.close(); }});test("eating cooked venison heals and applies health regen", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const worker = workerOf(harness.simulation, playerId); const handle = worker.world.ecs.handleOf(playerId); const health = worker.world.ecs.get(handle, Component.health); health.current = 5; health.max = 20; giveInventory(harness, playerId, [ { itemId: CraftingItemId.cookedMeat, quantity: 1 } ]); harness.simulation.enqueue(1, { type: "eat-item", characterId: character.character_id, slotIndex: 0 }); harness.simulation.step(); assert.equal(health.current, 10); const status = worker.world.ecs.get(handle, Component.statusEffects); const regen = status?.effects?.find((e) => e.type === StatusEffectType.healthRegen); assert.ok(regen); assert.equal(regen.amountPerSecond, 1); } finally { harness.close(); }});@@ -0,0 +1,299 @@
import test from "node:test";
import assert from "node:assert/strict";
import { BlockType, GroundType } from "../../shared/definitions/tiles.js";
import {
rawFishItemId,
cookedFishItemId,
baitItemIdForCloth,
FishingToolItemId,
fishingDifficulty,
fishingExhaustDurationMs,
normalizeFishingSpotConfig
} from "../../shared/definitions/fishItems.js";
import { ClothTier } from "../../shared/definitions/materialTiers.js";
import { yarnItemId } from "../../shared/definitions/clothItems.js";
import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
import { SkillId } from "../../shared/definitions/skills.js";
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
import { totalXpForLevel } from "../../shared/skills/progression.js";
import { itemDefinition } from "../../shared/definitions/items.js";
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
import { Component } from "../src/ecs/components.js";
function workerOf (simulation, playerId)
{
const record = simulation.entityRecord(playerId);
return simulation.workers[record.workerId];
}
function setSkillLevel (worker, playerId, skillId, level)
{
const handle = worker.world.ecs.handleOf(playerId);
const skills = worker.world.ecs.get(handle, Component.skills);
skills.xp[skillId] = totalXpForLevel(level);
}
function giveInventory (harness, playerId, items)
{
const inventory = emptySlots();
items.forEach((stack, index) =>
{
inventory[index] = { itemId: stack.itemId, quantity: stack.quantity };
});
harness.simulation.applyBag(playerId, {
inventory,
equipment: emptyEquipment(),
vault: [],
vaultReserved: []
});
}
function advanceMs (harness, ms)
{
const ticks = Math.ceil(ms / 50) + 3;
for (let i = 0; i < ticks; i++)
{
harness.advance(50);
harness.simulation.step();
}
}
function placeFishingSpot (worker, tileX, tileY, fishes, groundType = GroundType.deepWater)
{
const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
const localX = ((tileX % 16) + 16) % 16;
const localY = ((tileY % 16) + 16) % 16;
const index = localY * 16 + localX;
data.grounds[index] = { typeId: groundType, state: null };
data.blocks[index] = {
typeId: BlockType.fishingSpot,
state: "fishing-spot",
config: normalizeFishingSpotConfig({ fishes })
};
}
test("fishing difficulty and exhaust scale with tier", () =>
{
assert.equal(fishingDifficulty(1), 1);
assert.equal(fishingDifficulty(2), 10);
assert.equal(fishingExhaustDurationMs(3), 30_000);
});
test("cooked fish healing is tier times 5", () =>
{
assert.equal(itemDefinition(cookedFishItemId("minnow")).healing, 5);
assert.equal(itemDefinition(cookedFishItemId("shark")).healing, 35);
});
test("net catches tier-1 fish without bait and exhausts spot", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = workerOf(harness.simulation, playerId);
worker.world.rng = () => 0.999;
setSkillLevel(worker, playerId, SkillId.fishing, 1);
const minnow = rawFishItemId("minnow");
const trout = rawFishItemId("trout");
placeFishingSpot(worker, 9, 8, [minnow, trout]);
giveInventory(harness, playerId, [
{ itemId: FishingToolItemId.net, quantity: 1 }
]);
harness.simulation.enqueue(1, {
type: "start-fish",
characterId: character.character_id,
tileX: 9,
tileY: 8
});
advanceMs(harness, 10_000);
const bag = harness.simulation.bagOf(playerId);
assert.ok(bag.inventory.some((s) => s?.itemId === minnow), "expected minnow");
assert.equal(bag.inventory.some((s) => s?.itemId === trout), false);
const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9];
assert.equal(block.state, "exhausted");
assert.ok(worker.world.fishingSpotRespawns.has("9,8"));
}
finally
{ harness.close(); }
});
test("rod consumes highest useful bait for spot", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = workerOf(harness.simulation, playerId);
worker.world.rng = () => 0.999;
setSkillLevel(worker, playerId, SkillId.fishing, 20);
const trout = rawFishItemId("trout");
placeFishingSpot(worker, 9, 8, [trout]);
const worms = baitItemIdForCloth(ClothTier.cotton);
const maggots = baitItemIdForCloth(ClothTier.wool);
const crickets = baitItemIdForCloth(ClothTier.linen);
giveInventory(harness, playerId, [
{ itemId: FishingToolItemId.oakRod, quantity: 1 },
{ itemId: worms, quantity: 2 },
{ itemId: maggots, quantity: 2 },
{ itemId: crickets, quantity: 2 }
]);
harness.simulation.enqueue(1, {
type: "start-fish",
characterId: character.character_id,
tileX: 9,
tileY: 8
});
advanceMs(harness, 200);
const bag = harness.simulation.bagOf(playerId);
assert.equal(bag.inventory.find((s) => s?.itemId === crickets)?.quantity ?? 0, 1);
assert.equal(bag.inventory.find((s) => s?.itemId === maggots)?.quantity ?? 0, 2);
}
finally
{ harness.close(); }
});
test("shallow water fishing blocked in winter", () =>
{
const harness = makeSimulation({ workerCount: 1, now: Date.UTC(2026, 0, 15) });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = workerOf(harness.simulation, playerId);
setSkillLevel(worker, playerId, SkillId.fishing, 1);
placeFishingSpot(worker, 9, 8, [rawFishItemId("minnow")], GroundType.water);
giveInventory(harness, playerId, [
{ itemId: FishingToolItemId.net, quantity: 1 }
]);
harness.simulation.enqueue(1, {
type: "start-fish",
characterId: character.character_id,
tileX: 9,
tileY: 8
});
const result = harness.simulation.step();
assert.ok(result.events.some((e) => e.type === "command-error"));
assert.equal(worker.world.fishSessions.size, 0);
}
finally
{ harness.close(); }
});
test("pole + yarn recipes: log makes pole, pole+2 yarn makes rod", () =>
{
const pole = itemDefinition(FishingToolItemId.birchPole);
const rod = itemDefinition(FishingToolItemId.birchRod);
assert.equal(pole?.fishingPole, true);
assert.equal(rod?.poleItemId, FishingToolItemId.birchPole);
assert.equal(rod?.equipment?.kind, EquipmentKind.fishingRod);
assert.equal(pole?.equipment, undefined);
});
test("failed rod fishing can snap the line into pole + yarn", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = workerOf(harness.simulation, playerId);
// Always fail skill rolls (0) and always snap the line (0 < 0.05).
worker.world.rng = () => 0;
setSkillLevel(worker, playerId, SkillId.fishing, 10);
const perch = rawFishItemId("perch");
placeFishingSpot(worker, 9, 8, [perch]);
const maggots = baitItemIdForCloth(ClothTier.wool);
giveInventory(harness, playerId, [
{ itemId: FishingToolItemId.birchRod, quantity: 1 },
{ itemId: maggots, quantity: 1 }
]);
harness.simulation.enqueue(1, {
type: "start-fish",
characterId: character.character_id,
tileX: 9,
tileY: 8
});
const events = [];
const ticks = Math.ceil(12_000 / 50) + 5;
for (let i = 0; i < ticks; i++)
{
harness.advance(50);
const step = harness.simulation.step();
events.push(...(step.events ?? []));
}
assert.ok(events.some((e) => e.type === "command-error" && e.message === "The fish got away."));
assert.ok(events.some((e) => e.type === "command-error" && e.message === "Your fishing line broke!"));
const bag = harness.simulation.bagOf(playerId);
assert.equal(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchRod), false);
assert.ok(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchPole), "expected pole");
assert.ok(bag.inventory.some((s) => s?.itemId === yarnItemId(ClothTier.wool)), "expected wool yarn");
}
finally
{ harness.close(); }
});
test("line-break yarn drops to ground when bag is full", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = workerOf(harness.simulation, playerId);
worker.world.rng = () => 0;
setSkillLevel(worker, playerId, SkillId.fishing, 10);
const perch = rawFishItemId("perch");
placeFishingSpot(worker, 9, 8, [perch]);
const maggots = baitItemIdForCloth(ClothTier.wool);
const yarn = yarnItemId(ClothTier.wool);
// Rod equipped; bag full except bait (consumed on start → one free slot for pole only).
const slots = emptySlots();
slots[0] = { itemId: maggots, quantity: 1 };
for (let i = 1; i < slots.length; i++)
{ slots[i] = { itemId: rawFishItemId("minnow"), quantity: 1 }; }
const equipment = emptyEquipment();
equipment.slots.weapon = { itemId: FishingToolItemId.birchRod, quantity: 1 };
harness.simulation.applyBag(playerId, {
inventory: slots,
equipment,
vault: [],
vaultReserved: []
});
harness.simulation.enqueue(1, {
type: "start-fish",
characterId: character.character_id,
tileX: 9,
tileY: 8
});
const events = [];
const ticks = Math.ceil(12_000 / 50) + 5;
for (let i = 0; i < ticks; i++)
{
harness.advance(50);
const step = harness.simulation.step();
events.push(...(step.events ?? []));
}
assert.ok(events.some((e) => e.message === "Your fishing line broke!"));
const bag = harness.simulation.bagOf(playerId);
assert.ok(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchPole));
assert.equal(bag.equipment?.slots?.weapon, null);
assert.equal(bag.inventory.some((s) => s?.itemId === yarn), false);
assert.ok(events.some((e) =>
e.type === "ground-item-appear" && e.stack?.itemId === yarn
), "yarn should appear on the ground");
}
finally
{ harness.close(); }
});
@@ -0,0 +1,299 @@import test from "node:test";import assert from "node:assert/strict";import { BlockType, GroundType } from "../../shared/definitions/tiles.js";import { rawFishItemId, cookedFishItemId, baitItemIdForCloth, FishingToolItemId, fishingDifficulty, fishingExhaustDurationMs, normalizeFishingSpotConfig} from "../../shared/definitions/fishItems.js";import { ClothTier } from "../../shared/definitions/materialTiers.js";import { yarnItemId } from "../../shared/definitions/clothItems.js";import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";import { SkillId } from "../../shared/definitions/skills.js";import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";import { totalXpForLevel } from "../../shared/skills/progression.js";import { itemDefinition } from "../../shared/definitions/items.js";import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";import { Component } from "../src/ecs/components.js";function workerOf (simulation, playerId){ const record = simulation.entityRecord(playerId); return simulation.workers[record.workerId];}function setSkillLevel (worker, playerId, skillId, level){ const handle = worker.world.ecs.handleOf(playerId); const skills = worker.world.ecs.get(handle, Component.skills); skills.xp[skillId] = totalXpForLevel(level);}function giveInventory (harness, playerId, items){ const inventory = emptySlots(); items.forEach((stack, index) => { inventory[index] = { itemId: stack.itemId, quantity: stack.quantity }; }); harness.simulation.applyBag(playerId, { inventory, equipment: emptyEquipment(), vault: [], vaultReserved: [] });}function advanceMs (harness, ms){ const ticks = Math.ceil(ms / 50) + 3; for (let i = 0; i < ticks; i++) { harness.advance(50); harness.simulation.step(); }}function placeFishingSpot (worker, tileX, tileY, fishes, groundType = GroundType.deepWater){ const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16)); const localX = ((tileX % 16) + 16) % 16; const localY = ((tileY % 16) + 16) % 16; const index = localY * 16 + localX; data.grounds[index] = { typeId: groundType, state: null }; data.blocks[index] = { typeId: BlockType.fishingSpot, state: "fishing-spot", config: normalizeFishingSpotConfig({ fishes }) };}test("fishing difficulty and exhaust scale with tier", () =>{ assert.equal(fishingDifficulty(1), 1); assert.equal(fishingDifficulty(2), 10); assert.equal(fishingExhaustDurationMs(3), 30_000);});test("cooked fish healing is tier times 5", () =>{ assert.equal(itemDefinition(cookedFishItemId("minnow")).healing, 5); assert.equal(itemDefinition(cookedFishItemId("shark")).healing, 35);});test("net catches tier-1 fish without bait and exhausts spot", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const worker = workerOf(harness.simulation, playerId); worker.world.rng = () => 0.999; setSkillLevel(worker, playerId, SkillId.fishing, 1); const minnow = rawFishItemId("minnow"); const trout = rawFishItemId("trout"); placeFishingSpot(worker, 9, 8, [minnow, trout]); giveInventory(harness, playerId, [ { itemId: FishingToolItemId.net, quantity: 1 } ]); harness.simulation.enqueue(1, { type: "start-fish", characterId: character.character_id, tileX: 9, tileY: 8 }); advanceMs(harness, 10_000); const bag = harness.simulation.bagOf(playerId); assert.ok(bag.inventory.some((s) => s?.itemId === minnow), "expected minnow"); assert.equal(bag.inventory.some((s) => s?.itemId === trout), false); const block = worker.world.chunkData(0, 0).blocks[8 * 16 + 9]; assert.equal(block.state, "exhausted"); assert.ok(worker.world.fishingSpotRespawns.has("9,8")); } finally { harness.close(); }});test("rod consumes highest useful bait for spot", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const worker = workerOf(harness.simulation, playerId); worker.world.rng = () => 0.999; setSkillLevel(worker, playerId, SkillId.fishing, 20); const trout = rawFishItemId("trout"); placeFishingSpot(worker, 9, 8, [trout]); const worms = baitItemIdForCloth(ClothTier.cotton); const maggots = baitItemIdForCloth(ClothTier.wool); const crickets = baitItemIdForCloth(ClothTier.linen); giveInventory(harness, playerId, [ { itemId: FishingToolItemId.oakRod, quantity: 1 }, { itemId: worms, quantity: 2 }, { itemId: maggots, quantity: 2 }, { itemId: crickets, quantity: 2 } ]); harness.simulation.enqueue(1, { type: "start-fish", characterId: character.character_id, tileX: 9, tileY: 8 }); advanceMs(harness, 200); const bag = harness.simulation.bagOf(playerId); assert.equal(bag.inventory.find((s) => s?.itemId === crickets)?.quantity ?? 0, 1); assert.equal(bag.inventory.find((s) => s?.itemId === maggots)?.quantity ?? 0, 2); } finally { harness.close(); }});test("shallow water fishing blocked in winter", () =>{ const harness = makeSimulation({ workerCount: 1, now: Date.UTC(2026, 0, 15) }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const worker = workerOf(harness.simulation, playerId); setSkillLevel(worker, playerId, SkillId.fishing, 1); placeFishingSpot(worker, 9, 8, [rawFishItemId("minnow")], GroundType.water); giveInventory(harness, playerId, [ { itemId: FishingToolItemId.net, quantity: 1 } ]); harness.simulation.enqueue(1, { type: "start-fish", characterId: character.character_id, tileX: 9, tileY: 8 }); const result = harness.simulation.step(); assert.ok(result.events.some((e) => e.type === "command-error")); assert.equal(worker.world.fishSessions.size, 0); } finally { harness.close(); }});test("pole + yarn recipes: log makes pole, pole+2 yarn makes rod", () =>{ const pole = itemDefinition(FishingToolItemId.birchPole); const rod = itemDefinition(FishingToolItemId.birchRod); assert.equal(pole?.fishingPole, true); assert.equal(rod?.poleItemId, FishingToolItemId.birchPole); assert.equal(rod?.equipment?.kind, EquipmentKind.fishingRod); assert.equal(pole?.equipment, undefined);});test("failed rod fishing can snap the line into pole + yarn", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const worker = workerOf(harness.simulation, playerId); // Always fail skill rolls (0) and always snap the line (0 < 0.05). worker.world.rng = () => 0; setSkillLevel(worker, playerId, SkillId.fishing, 10); const perch = rawFishItemId("perch"); placeFishingSpot(worker, 9, 8, [perch]); const maggots = baitItemIdForCloth(ClothTier.wool); giveInventory(harness, playerId, [ { itemId: FishingToolItemId.birchRod, quantity: 1 }, { itemId: maggots, quantity: 1 } ]); harness.simulation.enqueue(1, { type: "start-fish", characterId: character.character_id, tileX: 9, tileY: 8 }); const events = []; const ticks = Math.ceil(12_000 / 50) + 5; for (let i = 0; i < ticks; i++) { harness.advance(50); const step = harness.simulation.step(); events.push(...(step.events ?? [])); } assert.ok(events.some((e) => e.type === "command-error" && e.message === "The fish got away.")); assert.ok(events.some((e) => e.type === "command-error" && e.message === "Your fishing line broke!")); const bag = harness.simulation.bagOf(playerId); assert.equal(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchRod), false); assert.ok(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchPole), "expected pole"); assert.ok(bag.inventory.some((s) => s?.itemId === yarnItemId(ClothTier.wool)), "expected wool yarn"); } finally { harness.close(); }});test("line-break yarn drops to ground when bag is full", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const worker = workerOf(harness.simulation, playerId); worker.world.rng = () => 0; setSkillLevel(worker, playerId, SkillId.fishing, 10); const perch = rawFishItemId("perch"); placeFishingSpot(worker, 9, 8, [perch]); const maggots = baitItemIdForCloth(ClothTier.wool); const yarn = yarnItemId(ClothTier.wool); // Rod equipped; bag full except bait (consumed on start → one free slot for pole only). const slots = emptySlots(); slots[0] = { itemId: maggots, quantity: 1 }; for (let i = 1; i < slots.length; i++) { slots[i] = { itemId: rawFishItemId("minnow"), quantity: 1 }; } const equipment = emptyEquipment(); equipment.slots.weapon = { itemId: FishingToolItemId.birchRod, quantity: 1 }; harness.simulation.applyBag(playerId, { inventory: slots, equipment, vault: [], vaultReserved: [] }); harness.simulation.enqueue(1, { type: "start-fish", characterId: character.character_id, tileX: 9, tileY: 8 }); const events = []; const ticks = Math.ceil(12_000 / 50) + 5; for (let i = 0; i < ticks; i++) { harness.advance(50); const step = harness.simulation.step(); events.push(...(step.events ?? [])); } assert.ok(events.some((e) => e.message === "Your fishing line broke!")); const bag = harness.simulation.bagOf(playerId); assert.ok(bag.inventory.some((s) => s?.itemId === FishingToolItemId.birchPole)); assert.equal(bag.equipment?.slots?.weapon, null); assert.equal(bag.inventory.some((s) => s?.itemId === yarn), false); assert.ok(events.some((e) => e.type === "ground-item-appear" && e.stack?.itemId === yarn ), "yarn should appear on the ground"); } finally { harness.close(); }});