Add cloth tiers, dyes, and tailor crafting loop.
Share armour sprites via material tint, and wire cotton/flower gathering through spinning, weaving, dye mixing, and sweater craft.
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.
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.
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.
@@ -158,6 +158,18 @@
<div class="craft-detail">
<p id="craft-detail-empty" class="hint">Select a recipe.</p>
<div id="craft-detail-body" hidden>
<div id="craft-tailor-controls" class="craft-tailor-controls" hidden>
<label class="craft-tailor-field">
<span>Material</span>
<select id="craft-cloth-tier"></select>
</label>
<div class="craft-tailor-dye">
<span>Dye (optional)</span>
<button id="craft-dye-pick" type="button">Choose dye…</button>
<button id="craft-dye-clear" type="button" hidden>Clear dye</button>
<img id="craft-dye-preview" alt="" hidden>
</div>
</div>
<div class="craft-output">
<img id="craft-output-img" alt="">
<h3 id="craft-output-name"></h3>
@@ -173,6 +185,15 @@
</div>
</aside>
<div id="dye-picker-backdrop" class="modal-backdrop" hidden></div>
<aside id="dye-picker-panel" hidden>
<header>
<h2>Choose dye</h2>
<button id="dye-picker-close" type="button">Close</button>
</header>
<div id="dye-picker-grid" class="craft-recipe-grid"></div>
</aside>
<div id="shop-backdrop" class="modal-backdrop" hidden></div>
<aside id="shop-panel" hidden>
<header>
@@ -158,6 +158,18 @@ <div class="craft-detail"> <div class="craft-detail"> <p id="craft-detail-empty" class="hint">Select a recipe.</p> <p id="craft-detail-empty" class="hint">Select a recipe.</p> <div id="craft-detail-body" hidden> <div id="craft-detail-body" hidden> <div id="craft-tailor-controls" class="craft-tailor-controls" hidden> <label class="craft-tailor-field"> <span>Material</span> <select id="craft-cloth-tier"></select> </label> <div class="craft-tailor-dye"> <span>Dye (optional)</span> <button id="craft-dye-pick" type="button">Choose dye…</button> <button id="craft-dye-clear" type="button" hidden>Clear dye</button> <img id="craft-dye-preview" alt="" hidden> </div> </div> <div class="craft-output"> <div class="craft-output"> <img id="craft-output-img" alt=""> <img id="craft-output-img" alt=""> <h3 id="craft-output-name"></h3> <h3 id="craft-output-name"></h3>@@ -173,6 +185,15 @@ </div> </div> </aside> </aside> <div id="dye-picker-backdrop" class="modal-backdrop" hidden></div> <aside id="dye-picker-panel" hidden> <header> <h2>Choose dye</h2> <button id="dye-picker-close" type="button">Close</button> </header> <div id="dye-picker-grid" class="craft-recipe-grid"></div> </aside> <div id="shop-backdrop" class="modal-backdrop" hidden></div> <div id="shop-backdrop" class="modal-backdrop" hidden></div> <aside id="shop-panel" hidden> <aside id="shop-panel" hidden> <header> <header>@@ -30,6 +30,7 @@ export function initAlchemy ({
let state = null;
let pickSlotIndex = null;
let pickItemId = null;
let pickInstance = null;
document.getElementById("cauldron-close")?.addEventListener("click", () => close());
backdrop?.addEventListener("click", () => close());
@@ -119,6 +120,7 @@ export function initAlchemy ({
{
pickSlotIndex = slotIndex;
pickItemId = null;
pickInstance = null;
pickList.replaceChildren();
const counts = new Map();
for (const slot of getInventorySlots?.() ?? [])
@@ -129,24 +131,42 @@ export function initAlchemy ({
if (!def || def.uniqueInstance || def.equipment
|| slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle)
{ continue; }
counts.set(slot.itemId, (counts.get(slot.itemId) ?? 0) + (slot.quantity | 0));
const identity = (slot.itemId === ItemId.flower || slot.itemId === ItemId.dye)
? `${slot.itemId}|${JSON.stringify(slot.instance ?? null)}`
: String(slot.itemId);
const prev = counts.get(identity);
if (prev)
{ prev.quantity += slot.quantity | 0; }
else
{
counts.set(identity, {
itemId: slot.itemId,
quantity: slot.quantity | 0,
instance: slot.instance ? structuredClone(slot.instance) : null
});
}
}
for (const [itemId, quantity] of counts)
for (const entry of counts.values())
{
const stack = { itemId, quantity };
const stack = {
itemId: entry.itemId,
quantity: entry.quantity,
instance: entry.instance
};
const btn = document.createElement("button");
btn.type = "button";
btn.className = "cauldron-pick-item";
const img = document.createElement("img");
applyItemIcon(img, stack, itemAssetPathForStack(stack));
const label = document.createElement("span");
label.textContent = `${itemDisplayName(stack)} (${formatQuantity(quantity)})`;
label.textContent = `${itemDisplayName(stack)} (${formatQuantity(entry.quantity)})`;
btn.append(img, label);
btn.addEventListener("click", () =>
{
pickItemId = itemId;
pickQty.max = String(quantity);
pickQty.value = String(Math.min(quantity, Number(pickQty.value) || 1));
pickItemId = entry.itemId;
pickInstance = entry.instance;
pickQty.max = String(entry.quantity);
pickQty.value = String(Math.min(entry.quantity, Number(pickQty.value) || 1));
for (const child of pickList.children)
{ child.classList.toggle("selected", child === btn); }
});
@@ -163,6 +183,7 @@ export function initAlchemy ({
pickPanel.hidden = true;
pickSlotIndex = null;
pickItemId = null;
pickInstance = null;
}
function confirmPick ()
@@ -174,7 +195,8 @@ export function initAlchemy ({
type: MessageType.cauldronSetSlot,
slotIndex: pickSlotIndex,
itemId: pickItemId,
quantity
quantity,
instance: pickInstance
});
closePick();
}
@@ -30,6 +30,7 @@ export function initAlchemy ({ let state = null; let state = null; let pickSlotIndex = null; let pickSlotIndex = null; let pickItemId = null; let pickItemId = null; let pickInstance = null; document.getElementById("cauldron-close")?.addEventListener("click", () => close()); document.getElementById("cauldron-close")?.addEventListener("click", () => close()); backdrop?.addEventListener("click", () => close()); backdrop?.addEventListener("click", () => close());@@ -119,6 +120,7 @@ export function initAlchemy ({ { { pickSlotIndex = slotIndex; pickSlotIndex = slotIndex; pickItemId = null; pickItemId = null; pickInstance = null; pickList.replaceChildren(); pickList.replaceChildren(); const counts = new Map(); const counts = new Map(); for (const slot of getInventorySlots?.() ?? []) for (const slot of getInventorySlots?.() ?? [])@@ -129,24 +131,42 @@ export function initAlchemy ({ if (!def || def.uniqueInstance || def.equipment if (!def || def.uniqueInstance || def.equipment || slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle) || slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle) { continue; } { continue; } counts.set(slot.itemId, (counts.get(slot.itemId) ?? 0) + (slot.quantity | 0)); const identity = (slot.itemId === ItemId.flower || slot.itemId === ItemId.dye) ? `${slot.itemId}|${JSON.stringify(slot.instance ?? null)}` : String(slot.itemId); const prev = counts.get(identity); if (prev) { prev.quantity += slot.quantity | 0; } else { counts.set(identity, { itemId: slot.itemId, quantity: slot.quantity | 0, instance: slot.instance ? structuredClone(slot.instance) : null }); } } } for (const [itemId, quantity] of counts) for (const entry of counts.values()) { { const stack = { itemId, quantity }; const stack = { itemId: entry.itemId, quantity: entry.quantity, instance: entry.instance }; const btn = document.createElement("button"); const btn = document.createElement("button"); btn.type = "button"; btn.type = "button"; btn.className = "cauldron-pick-item"; btn.className = "cauldron-pick-item"; const img = document.createElement("img"); const img = document.createElement("img"); applyItemIcon(img, stack, itemAssetPathForStack(stack)); applyItemIcon(img, stack, itemAssetPathForStack(stack)); const label = document.createElement("span"); const label = document.createElement("span"); label.textContent = `${itemDisplayName(stack)} (${formatQuantity(quantity)})`; label.textContent = `${itemDisplayName(stack)} (${formatQuantity(entry.quantity)})`; btn.append(img, label); btn.append(img, label); btn.addEventListener("click", () => btn.addEventListener("click", () => { { pickItemId = itemId; pickItemId = entry.itemId; pickQty.max = String(quantity); pickInstance = entry.instance; pickQty.value = String(Math.min(quantity, Number(pickQty.value) || 1)); pickQty.max = String(entry.quantity); pickQty.value = String(Math.min(entry.quantity, Number(pickQty.value) || 1)); for (const child of pickList.children) for (const child of pickList.children) { child.classList.toggle("selected", child === btn); } { child.classList.toggle("selected", child === btn); } }); });@@ -163,6 +183,7 @@ export function initAlchemy ({ pickPanel.hidden = true; pickPanel.hidden = true; pickSlotIndex = null; pickSlotIndex = null; pickItemId = null; pickItemId = null; pickInstance = null; } } function confirmPick () function confirmPick ()@@ -174,7 +195,8 @@ export function initAlchemy ({ type: MessageType.cauldronSetSlot, type: MessageType.cauldronSetSlot, slotIndex: pickSlotIndex, slotIndex: pickSlotIndex, itemId: pickItemId, itemId: pickItemId, quantity quantity, instance: pickInstance }); }); closePick(); closePick(); } }@@ -2,9 +2,10 @@ import {
itemDefinition,
itemDisplayName,
itemAssetPathForStack,
formatQuantity
formatQuantity,
ItemId
} from "/shared/definitions/items.js";
import { craftingStationDefinition } from "/shared/definitions/craftingStations.js";
import { craftingStationDefinition, CraftingStationId } from "/shared/definitions/craftingStations.js";
import {
CRAFT_DURATION_MS,
canStartCraft,
@@ -12,6 +13,8 @@ import {
hasRecipeInputs,
recipesForStation
} from "/shared/crafting/recipes.js";
import { resolveTailorCraft } from "/shared/crafting/tailor.js";
import { CLOTH_TIER_ORDER, CLOTH_DISPLAY_NAME, ClothTier } from "/shared/definitions/materialTiers.js";
import { craftDurationMs } from "/shared/definitions/gathering.js";
import { applyItemIcon } from "../render/potionIcon.js";
@@ -28,6 +31,11 @@ export function initCrafting ({
const recipeGrid = document.getElementById("craft-recipe-grid");
const detailEmpty = document.getElementById("craft-detail-empty");
const detailBody = document.getElementById("craft-detail-body");
const tailorControls = document.getElementById("craft-tailor-controls");
const clothTierSelect = document.getElementById("craft-cloth-tier");
const dyePickBtn = document.getElementById("craft-dye-pick");
const dyeClearBtn = document.getElementById("craft-dye-clear");
const dyePreview = document.getElementById("craft-dye-preview");
const outputImg = document.getElementById("craft-output-img");
const outputName = document.getElementById("craft-output-name");
const inputsList = document.getElementById("craft-inputs");
@@ -35,11 +43,16 @@ export function initCrafting ({
const progressWrap = document.getElementById("craft-progress");
const progressFill = document.getElementById("craft-progress-fill");
const craftButton = document.getElementById("craft-button");
const dyeBackdrop = document.getElementById("dye-picker-backdrop");
const dyePanel = document.getElementById("dye-picker-panel");
const dyeGrid = document.getElementById("dye-picker-grid");
let open = false;
let stationId = null;
let recipes = [];
let selectedRecipeId = null;
let clothTier = ClothTier.cotton;
let dyeSlotIndex = null;
let crafting = false;
let craftTimer = null;
let craftAnimFrame = null;
@@ -48,6 +61,24 @@ export function initCrafting ({
document.getElementById("craft-close").addEventListener("click", () => close());
backdrop.addEventListener("click", () => close());
craftButton.addEventListener("click", () => startCraft());
clothTierSelect?.addEventListener("change", () =>
{
clothTier = clothTierSelect.value || ClothTier.cotton;
renderDetail();
});
dyePickBtn?.addEventListener("click", () => openDyePicker());
dyeClearBtn?.addEventListener("click", () =>
{
dyeSlotIndex = null;
renderDetail();
});
document.getElementById("dye-picker-close")?.addEventListener("click", () => closeDyePicker());
dyeBackdrop?.addEventListener("click", () => closeDyePicker());
function isTailorStation ()
{
return stationId === CraftingStationId.tailorBench;
}
function selectedRecipe ()
{
@@ -60,6 +91,23 @@ export function initCrafting ({
return getSkillLevel?.(def?.skillId) ?? 1;
}
function activeRecipe ()
{
const base = selectedRecipe();
if (!base)
{ return null; }
if (!base.tailorTemplate)
{ return base; }
const slots = getInventorySlots?.() ?? [];
const dyeStack = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
const resolved = resolveTailorCraft({
templateId: base.tailorTemplate,
clothTier,
dyeStack
});
return resolved.ok ? resolved.recipe : base;
}
function refresh ()
{
if (!open)
@@ -68,6 +116,21 @@ export function initCrafting ({
renderDetail();
}
function fillClothTier ()
{
if (!clothTierSelect)
{ return; }
clothTierSelect.replaceChildren();
for (const tier of CLOTH_TIER_ORDER)
{
const option = document.createElement("option");
option.value = tier;
option.textContent = CLOTH_DISPLAY_NAME[tier] ?? tier;
clothTierSelect.append(option);
}
clothTierSelect.value = clothTier;
}
function renderRecipeGrid ()
{
recipeGrid.replaceChildren();
@@ -93,7 +156,9 @@ export function initCrafting ({
const label = document.createElement("span");
label.className = "craft-recipe-name";
label.textContent = def?.displayName ?? "Item";
label.textContent = recipe.tailorTemplate
? (def?.displayName?.replace(/^Cotton\s+/i, "") ?? "Garment")
: (def?.displayName ?? "Item");
cell.append(img, label);
cell.addEventListener("click", () =>
@@ -109,7 +174,7 @@ export function initCrafting ({
function renderDetail ()
{
const recipe = selectedRecipe();
const recipe = activeRecipe();
if (!recipe)
{
detailEmpty.hidden = false;
@@ -119,9 +184,13 @@ export function initCrafting ({
detailEmpty.hidden = true;
detailBody.hidden = false;
if (tailorControls)
{ tailorControls.hidden = !isTailorStation(); }
const outputStack = {
itemId: recipe.output.itemId,
quantity: Math.max(1, recipe.output.quantity | 0 || 1)
quantity: Math.max(1, recipe.output.quantity | 0 || 1),
...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
};
applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
outputImg.alt = itemDisplayName(outputStack);
@@ -134,6 +203,32 @@ export function initCrafting ({
{
inputsList.append(renderInputRow(input, slots));
}
if (recipe.consumeDye)
{
const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
const row = document.createElement("li");
row.className = "craft-input-row";
row.textContent = dye
? `Dye — 1 use (${dye.instance?.fillLevel ?? "?"}/5)`
: "Dye — none selected";
inputsList.append(row);
}
if (dyePreview && dyeClearBtn)
{
const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
if (dye?.itemId === ItemId.dye)
{
dyePreview.hidden = false;
dyeClearBtn.hidden = false;
applyItemIcon(dyePreview, dye, itemAssetPathForStack(dye));
}
else
{
dyePreview.hidden = true;
dyeClearBtn.hidden = true;
}
}
updateCraftState(slots, recipe);
}
@@ -191,9 +286,53 @@ export function initCrafting ({
craftButton.disabled = true;
}
function openDyePicker ()
{
const slots = getInventorySlots?.() ?? [];
dyeGrid.replaceChildren();
let found = false;
slots.forEach((stack, index) =>
{
if (!stack || stack.itemId !== ItemId.dye)
{ return; }
found = true;
const cell = document.createElement("button");
cell.type = "button";
cell.className = "craft-recipe-cell";
const img = document.createElement("img");
applyItemIcon(img, stack, itemAssetPathForStack(stack));
const label = document.createElement("span");
label.className = "craft-recipe-name";
label.textContent = itemDisplayName(stack);
cell.append(img, label);
cell.addEventListener("click", () =>
{
dyeSlotIndex = index;
closeDyePicker();
renderDetail();
});
dyeGrid.append(cell);
});
if (!found)
{
const empty = document.createElement("p");
empty.className = "hint";
empty.textContent = "No dyes in your inventory.";
dyeGrid.append(empty);
}
dyePanel.hidden = false;
dyeBackdrop.hidden = false;
}
function closeDyePicker ()
{
dyePanel.hidden = true;
dyeBackdrop.hidden = true;
}
function startCraft ()
{
const recipe = selectedRecipe();
const recipe = activeRecipe();
if (!recipe || crafting)
{ return; }
const slots = getInventorySlots?.() ?? [];
@@ -209,11 +348,17 @@ export function initCrafting ({
statusEl.textContent = "Crafting…";
craftStartedAt = performance.now();
const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
socket.send({
const payload = {
type: MessageType.startCraft,
stationId,
recipeId: recipe.recipeId
});
recipeId: selectedRecipeId
};
if (isTailorStation())
{
payload.clothTier = clothTier;
payload.dyeSlotIndex = dyeSlotIndex;
}
socket.send(payload);
animateProgress(durationMs);
craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
}
@@ -268,6 +413,9 @@ export function initCrafting ({
stationId = nextStationId;
recipes = recipesForStation(nextStationId);
selectedRecipeId = recipes[0]?.recipeId ?? null;
clothTier = ClothTier.cotton;
dyeSlotIndex = null;
fillClothTier();
stationName.textContent = def.displayName;
open = true;
panel.hidden = false;
@@ -286,10 +434,12 @@ export function initCrafting ({
socket.send({ type: MessageType.cancelCraft });
stopCraftAnimation();
}
closeDyePicker();
open = false;
stationId = null;
recipes = [];
selectedRecipeId = null;
dyeSlotIndex = null;
panel.hidden = true;
backdrop.hidden = true;
detailEmpty.hidden = false;
@@ -2,9 +2,10 @@ import { itemDefinition, itemDefinition, itemDisplayName, itemDisplayName, itemAssetPathForStack, itemAssetPathForStack, formatQuantity formatQuantity, ItemId} from "/shared/definitions/items.js";} from "/shared/definitions/items.js";import { craftingStationDefinition } from "/shared/definitions/craftingStations.js";import { craftingStationDefinition, CraftingStationId } from "/shared/definitions/craftingStations.js";import {import { CRAFT_DURATION_MS, CRAFT_DURATION_MS, canStartCraft, canStartCraft,@@ -12,6 +13,8 @@ import { hasRecipeInputs, hasRecipeInputs, recipesForStation recipesForStation} from "/shared/crafting/recipes.js";} from "/shared/crafting/recipes.js";import { resolveTailorCraft } from "/shared/crafting/tailor.js";import { CLOTH_TIER_ORDER, CLOTH_DISPLAY_NAME, ClothTier } from "/shared/definitions/materialTiers.js";import { craftDurationMs } from "/shared/definitions/gathering.js";import { craftDurationMs } from "/shared/definitions/gathering.js";import { applyItemIcon } from "../render/potionIcon.js";import { applyItemIcon } from "../render/potionIcon.js";@@ -28,6 +31,11 @@ export function initCrafting ({ const recipeGrid = document.getElementById("craft-recipe-grid"); const recipeGrid = document.getElementById("craft-recipe-grid"); const detailEmpty = document.getElementById("craft-detail-empty"); const detailEmpty = document.getElementById("craft-detail-empty"); const detailBody = document.getElementById("craft-detail-body"); const detailBody = document.getElementById("craft-detail-body"); const tailorControls = document.getElementById("craft-tailor-controls"); const clothTierSelect = document.getElementById("craft-cloth-tier"); const dyePickBtn = document.getElementById("craft-dye-pick"); const dyeClearBtn = document.getElementById("craft-dye-clear"); const dyePreview = document.getElementById("craft-dye-preview"); const outputImg = document.getElementById("craft-output-img"); const outputImg = document.getElementById("craft-output-img"); const outputName = document.getElementById("craft-output-name"); const outputName = document.getElementById("craft-output-name"); const inputsList = document.getElementById("craft-inputs"); const inputsList = document.getElementById("craft-inputs");@@ -35,11 +43,16 @@ export function initCrafting ({ const progressWrap = document.getElementById("craft-progress"); const progressWrap = document.getElementById("craft-progress"); const progressFill = document.getElementById("craft-progress-fill"); const progressFill = document.getElementById("craft-progress-fill"); const craftButton = document.getElementById("craft-button"); const craftButton = document.getElementById("craft-button"); const dyeBackdrop = document.getElementById("dye-picker-backdrop"); const dyePanel = document.getElementById("dye-picker-panel"); const dyeGrid = document.getElementById("dye-picker-grid"); let open = false; let open = false; let stationId = null; let stationId = null; let recipes = []; let recipes = []; let selectedRecipeId = null; let selectedRecipeId = null; let clothTier = ClothTier.cotton; let dyeSlotIndex = null; let crafting = false; let crafting = false; let craftTimer = null; let craftTimer = null; let craftAnimFrame = null; let craftAnimFrame = null;@@ -48,6 +61,24 @@ export function initCrafting ({ document.getElementById("craft-close").addEventListener("click", () => close()); document.getElementById("craft-close").addEventListener("click", () => close()); backdrop.addEventListener("click", () => close()); backdrop.addEventListener("click", () => close()); craftButton.addEventListener("click", () => startCraft()); craftButton.addEventListener("click", () => startCraft()); clothTierSelect?.addEventListener("change", () => { clothTier = clothTierSelect.value || ClothTier.cotton; renderDetail(); }); dyePickBtn?.addEventListener("click", () => openDyePicker()); dyeClearBtn?.addEventListener("click", () => { dyeSlotIndex = null; renderDetail(); }); document.getElementById("dye-picker-close")?.addEventListener("click", () => closeDyePicker()); dyeBackdrop?.addEventListener("click", () => closeDyePicker()); function isTailorStation () { return stationId === CraftingStationId.tailorBench; } function selectedRecipe () function selectedRecipe () { {@@ -60,6 +91,23 @@ export function initCrafting ({ return getSkillLevel?.(def?.skillId) ?? 1; return getSkillLevel?.(def?.skillId) ?? 1; } } function activeRecipe () { const base = selectedRecipe(); if (!base) { return null; } if (!base.tailorTemplate) { return base; } const slots = getInventorySlots?.() ?? []; const dyeStack = dyeSlotIndex != null ? slots[dyeSlotIndex] : null; const resolved = resolveTailorCraft({ templateId: base.tailorTemplate, clothTier, dyeStack }); return resolved.ok ? resolved.recipe : base; } function refresh () function refresh () { { if (!open) if (!open)@@ -68,6 +116,21 @@ export function initCrafting ({ renderDetail(); renderDetail(); } } function fillClothTier () { if (!clothTierSelect) { return; } clothTierSelect.replaceChildren(); for (const tier of CLOTH_TIER_ORDER) { const option = document.createElement("option"); option.value = tier; option.textContent = CLOTH_DISPLAY_NAME[tier] ?? tier; clothTierSelect.append(option); } clothTierSelect.value = clothTier; } function renderRecipeGrid () function renderRecipeGrid () { { recipeGrid.replaceChildren(); recipeGrid.replaceChildren();@@ -93,7 +156,9 @@ export function initCrafting ({ const label = document.createElement("span"); const label = document.createElement("span"); label.className = "craft-recipe-name"; label.className = "craft-recipe-name"; label.textContent = def?.displayName ?? "Item"; label.textContent = recipe.tailorTemplate ? (def?.displayName?.replace(/^Cotton\s+/i, "") ?? "Garment") : (def?.displayName ?? "Item"); cell.append(img, label); cell.append(img, label); cell.addEventListener("click", () => cell.addEventListener("click", () =>@@ -109,7 +174,7 @@ export function initCrafting ({ function renderDetail () function renderDetail () { { const recipe = selectedRecipe(); const recipe = activeRecipe(); if (!recipe) if (!recipe) { { detailEmpty.hidden = false; detailEmpty.hidden = false;@@ -119,9 +184,13 @@ export function initCrafting ({ detailEmpty.hidden = true; detailEmpty.hidden = true; detailBody.hidden = false; detailBody.hidden = false; if (tailorControls) { tailorControls.hidden = !isTailorStation(); } const outputStack = { const outputStack = { itemId: recipe.output.itemId, itemId: recipe.output.itemId, quantity: Math.max(1, recipe.output.quantity | 0 || 1) quantity: Math.max(1, recipe.output.quantity | 0 || 1), ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {}) }; }; applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack)); applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack)); outputImg.alt = itemDisplayName(outputStack); outputImg.alt = itemDisplayName(outputStack);@@ -134,6 +203,32 @@ export function initCrafting ({ { { inputsList.append(renderInputRow(input, slots)); inputsList.append(renderInputRow(input, slots)); } } if (recipe.consumeDye) { const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null; const row = document.createElement("li"); row.className = "craft-input-row"; row.textContent = dye ? `Dye — 1 use (${dye.instance?.fillLevel ?? "?"}/5)` : "Dye — none selected"; inputsList.append(row); } if (dyePreview && dyeClearBtn) { const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null; if (dye?.itemId === ItemId.dye) { dyePreview.hidden = false; dyeClearBtn.hidden = false; applyItemIcon(dyePreview, dye, itemAssetPathForStack(dye)); } else { dyePreview.hidden = true; dyeClearBtn.hidden = true; } } updateCraftState(slots, recipe); updateCraftState(slots, recipe); } }@@ -191,9 +286,53 @@ export function initCrafting ({ craftButton.disabled = true; craftButton.disabled = true; } } function openDyePicker () { const slots = getInventorySlots?.() ?? []; dyeGrid.replaceChildren(); let found = false; slots.forEach((stack, index) => { if (!stack || stack.itemId !== ItemId.dye) { return; } found = true; const cell = document.createElement("button"); cell.type = "button"; cell.className = "craft-recipe-cell"; const img = document.createElement("img"); applyItemIcon(img, stack, itemAssetPathForStack(stack)); const label = document.createElement("span"); label.className = "craft-recipe-name"; label.textContent = itemDisplayName(stack); cell.append(img, label); cell.addEventListener("click", () => { dyeSlotIndex = index; closeDyePicker(); renderDetail(); }); dyeGrid.append(cell); }); if (!found) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "No dyes in your inventory."; dyeGrid.append(empty); } dyePanel.hidden = false; dyeBackdrop.hidden = false; } function closeDyePicker () { dyePanel.hidden = true; dyeBackdrop.hidden = true; } function startCraft () function startCraft () { { const recipe = selectedRecipe(); const recipe = activeRecipe(); if (!recipe || crafting) if (!recipe || crafting) { return; } { return; } const slots = getInventorySlots?.() ?? []; const slots = getInventorySlots?.() ?? [];@@ -209,11 +348,17 @@ export function initCrafting ({ statusEl.textContent = "Crafting…"; statusEl.textContent = "Crafting…"; craftStartedAt = performance.now(); craftStartedAt = performance.now(); const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS); const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS); socket.send({ const payload = { type: MessageType.startCraft, type: MessageType.startCraft, stationId, stationId, recipeId: recipe.recipeId recipeId: selectedRecipeId }); }; if (isTailorStation()) { payload.clothTier = clothTier; payload.dyeSlotIndex = dyeSlotIndex; } socket.send(payload); animateProgress(durationMs); animateProgress(durationMs); craftTimer = window.setTimeout(() => finishCraft(true), durationMs); craftTimer = window.setTimeout(() => finishCraft(true), durationMs); } }@@ -268,6 +413,9 @@ export function initCrafting ({ stationId = nextStationId; stationId = nextStationId; recipes = recipesForStation(nextStationId); recipes = recipesForStation(nextStationId); selectedRecipeId = recipes[0]?.recipeId ?? null; selectedRecipeId = recipes[0]?.recipeId ?? null; clothTier = ClothTier.cotton; dyeSlotIndex = null; fillClothTier(); stationName.textContent = def.displayName; stationName.textContent = def.displayName; open = true; open = true; panel.hidden = false; panel.hidden = false;@@ -286,10 +434,12 @@ export function initCrafting ({ socket.send({ type: MessageType.cancelCraft }); socket.send({ type: MessageType.cancelCraft }); stopCraftAnimation(); stopCraftAnimation(); } } closeDyePicker(); open = false; open = false; stationId = null; stationId = null; recipes = []; recipes = []; selectedRecipeId = null; selectedRecipeId = null; dyeSlotIndex = null; panel.hidden = true; panel.hidden = true; backdrop.hidden = true; backdrop.hidden = true; detailEmpty.hidden = false; detailEmpty.hidden = false;@@ -1,5 +1,5 @@
import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock } from "/shared/definitions/tiles.js";
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
import { GameSocket, defaultSocketUrl } from "../net/socket.js";
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
import { WorldView } from "../render/worldView.js";
@@ -246,6 +246,17 @@ function requestChop (tileX, tileY)
{ approachAdjacentTile(tileX, tileY); }
}
function requestPick (tileX, tileY)
{
clearAllPendingActions();
pendingInteract = { kind: "pick", 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 requestTalk (targetEntityId)
{
clearAllPendingActions();
@@ -336,6 +347,19 @@ function flushPendingInteract ()
return;
}
if (pendingInteract.kind === "pick")
{
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
{ return; }
socket.send({
type: MessageType.pick,
tileX: pendingInteract.tileX,
tileY: pendingInteract.tileY
});
clearPendingInteract();
return;
}
if (pendingInteract.kind === "talk")
{
const target = view.entities.get(pendingInteract.targetEntityId);
@@ -453,10 +477,18 @@ function handleLeftClick (mouseX, mouseY)
{ requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
{ requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
else if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
{ requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); }
else if (isLoomTile(view, tile.tileX, tile.tileY))
{ requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); }
else if (isTailorBenchTile(view, tile.tileX, tile.tileY))
{ requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); }
else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
{ requestMine(tile.tileX, tile.tileY); }
else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
{ requestChop(tile.tileX, tile.tileY); }
else if (isPickablePlantTile(view, tile.tileX, tile.tileY))
{ requestPick(tile.tileX, tile.tileY); }
else
{
clearAllPendingActions();
@@ -596,6 +628,30 @@ function handleRightClick (event, mouseX, mouseY)
});
}
if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
{
items.push({
label: "Spin",
onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY)
});
}
if (isLoomTile(view, tile.tileX, tile.tileY))
{
items.push({
label: "Weave",
onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY)
});
}
if (isTailorBenchTile(view, tile.tileX, tile.tileY))
{
items.push({
label: "Tailor",
onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY)
});
}
if (isOreBoulderTile(view, tile.tileX, tile.tileY))
{
items.push({
@@ -612,6 +668,14 @@ function handleRightClick (event, mouseX, mouseY)
});
}
if (isPickablePlantTile(view, tile.tileX, tile.tileY))
{
items.push({
label: "Pick",
onSelect: () => requestPick(tile.tileX, tile.tileY)
});
}
contextMenu.show(event.clientX, event.clientY, items);
}
@@ -1112,6 +1176,21 @@ function isCraftingBenchTile (view, tileX, tileY)
return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
}
function isSpinningWheelTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
}
function isLoomTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.loom;
}
function isTailorBenchTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
}
function isOreBoulderTile (view, tileX, tileY)
{
const block = blockAt(view, tileX, tileY);
@@ -1123,6 +1202,11 @@ function isChopableTreeTile (view, tileX, tileY)
return isChopableTreeBlock(blockAt(view, tileX, tileY));
}
function isPickablePlantTile (view, tileX, tileY)
{
return isPickablePlantBlock(blockAt(view, tileX, tileY));
}
function hideWorldTooltip ()
{
if (worldTooltip)
@@ -1,5 +1,5 @@import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock } from "/shared/definitions/tiles.js";import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";import { GameSocket, defaultSocketUrl } from "../net/socket.js";import { GameSocket, defaultSocketUrl } from "../net/socket.js";import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";import { WorldView } from "../render/worldView.js";import { WorldView } from "../render/worldView.js";@@ -246,6 +246,17 @@ function requestChop (tileX, tileY) { approachAdjacentTile(tileX, tileY); } { approachAdjacentTile(tileX, tileY); }}}function requestPick (tileX, tileY){ clearAllPendingActions(); pendingInteract = { kind: "pick", 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 requestTalk (targetEntityId)function requestTalk (targetEntityId){{ clearAllPendingActions(); clearAllPendingActions();@@ -336,6 +347,19 @@ function flushPendingInteract () return; return; } } if (pendingInteract.kind === "pick") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.pick, tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); clearPendingInteract(); return; } if (pendingInteract.kind === "talk") if (pendingInteract.kind === "talk") { { const target = view.entities.get(pendingInteract.targetEntityId); const target = view.entities.get(pendingInteract.targetEntityId);@@ -453,10 +477,18 @@ function handleLeftClick (mouseX, mouseY) { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); } { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); } else if (isCraftingBenchTile(view, tile.tileX, tile.tileY)) else if (isCraftingBenchTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); } { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); } else if (isSpinningWheelTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); } else if (isLoomTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); } else if (isTailorBenchTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); } else if (isOreBoulderTile(view, tile.tileX, tile.tileY)) else if (isOreBoulderTile(view, tile.tileX, tile.tileY)) { requestMine(tile.tileX, tile.tileY); } { requestMine(tile.tileX, tile.tileY); } else if (isChopableTreeTile(view, tile.tileX, tile.tileY)) else if (isChopableTreeTile(view, tile.tileX, tile.tileY)) { requestChop(tile.tileX, tile.tileY); } { requestChop(tile.tileX, tile.tileY); } else if (isPickablePlantTile(view, tile.tileX, tile.tileY)) { requestPick(tile.tileX, tile.tileY); } else else { { clearAllPendingActions(); clearAllPendingActions();@@ -596,6 +628,30 @@ function handleRightClick (event, mouseX, mouseY) }); }); } } if (isSpinningWheelTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Spin", onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY) }); } if (isLoomTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Weave", onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY) }); } if (isTailorBenchTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Tailor", onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY) }); } if (isOreBoulderTile(view, tile.tileX, tile.tileY)) if (isOreBoulderTile(view, tile.tileX, tile.tileY)) { { items.push({ items.push({@@ -612,6 +668,14 @@ function handleRightClick (event, mouseX, mouseY) }); }); } } if (isPickablePlantTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Pick", onSelect: () => requestPick(tile.tileX, tile.tileY) }); } contextMenu.show(event.clientX, event.clientY, items); contextMenu.show(event.clientX, event.clientY, items);}}@@ -1112,6 +1176,21 @@ function isCraftingBenchTile (view, tileX, tileY) return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench; return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;}}function isSpinningWheelTile (view, tileX, tileY){ return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;}function isLoomTile (view, tileX, tileY){ return blockTypeAt(view, tileX, tileY) === BlockType.loom;}function isTailorBenchTile (view, tileX, tileY){ return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;}function isOreBoulderTile (view, tileX, tileY)function isOreBoulderTile (view, tileX, tileY){{ const block = blockAt(view, tileX, tileY); const block = blockAt(view, tileX, tileY);@@ -1123,6 +1202,11 @@ function isChopableTreeTile (view, tileX, tileY) return isChopableTreeBlock(blockAt(view, tileX, tileY)); return isChopableTreeBlock(blockAt(view, tileX, tileY));}}function isPickablePlantTile (view, tileX, tileY){ return isPickablePlantBlock(blockAt(view, tileX, tileY));}function hideWorldTooltip ()function hideWorldTooltip (){{ if (worldTooltip) if (worldTooltip)@@ -99,7 +99,8 @@ export async function tintedItemIconDataUrl (assetPath, tint)
export function isPotionStack (stack)
{
return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion";
return (stack?.itemId === ItemId.potion && stack.instance?.kind === "potion")
|| (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye");
}
/** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
@@ -99,7 +99,8 @@ export async function tintedItemIconDataUrl (assetPath, tint)export function isPotionStack (stack)export function isPotionStack (stack){{ return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion"; return (stack?.itemId === ItemId.potion && stack.instance?.kind === "potion") || (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye");}}/** Set img.src to tinted icon when the stack/def has a tint; else fallback path. *//** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */@@ -228,23 +228,34 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Equipment tiers and worn stat bonuses
**Status:** partial
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting.
**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
## Gathering, crafting, and production skills
**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting live)
**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower herbalism live)
**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Herbalism (plants):** **Flower** nodes need **plant clippers** (bronze clippers: anvil 1 bronze bar, or NPC shop); success yields a flower with a random dye colour and stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
## Cloth, dyes, and tailoring
**Status:** partial (cotton loop + flower dyes + sweater live; higher cloth sources TBD)
**Spec:** **Cloth tiers** (same skill gates/ranks as metal/wood): Cotton, Wool, Linen, Cashmere, Silk, Fairy silk, Dragonweave. Shared magenta sprites under `items/cloth` (`wool` fibre, `yarn`, `cloth`) and `items/clothing` (`sweater` + equip) tinted per tier (or optional dye colour on clothing instances). **Spinning wheel** (Tailoring): fibre → yarn. **Loom**: yarn → cloth. **Tailor bench** UI is template-first: pick clothing template (sweater today; shirt/robe later) → cloth tier → optional dye from bag → sidebar shows resolved ingredients (sweater = 3 yarn). Crafted clothing can carry `instance.dyeColor`; otherwise material tint. **Flowers** (9 colours) brew 1:1 into **dye** bottles at a cauldron (needs **glass bottles** / `potion-0`). Two different dye colours mix paint-style (weighted by fill); bottle count follows inserted dyes; fill packs with overflow into the next bottle (extra glass only if overflow needs more bottles than inputs). Cannot mix flowers with dyes in one brew. Dye uses on tailor consume one fill level per craft.
**TODO (sources):** shear animals / pick plants for wool–silk; fairy silk + dragonweave as mob drops later.
**Later design (document only for now):**
- **Wizard cloth gear** — robes and similar give Magic skill bonuses (`EquipmentKind.wizardCloth`).
- **Cosmetic cloth gear** — sum equipped cosmetic item tiers as **Style points** (quests / exclusive areas).
- **Warm clothing** — sweaters and other warm pieces reduce cold-season debuffs (e.g. winter halves stamina regen; each warm-equipped slot except hands mitigates; full warm set nullifies cold; summer reverses). **Padding** from cloth + matching-tier plate at a crafting bench → **padded armour** per slot.
**Code:** `shared/definitions/materialTiers.js` (`ClothTier`), `shared/definitions/clothItems.js`, `shared/definitions/dyes.js`, `shared/crafting/tailor.js`, `shared/crafting/stationRecipes.js`, `server/src/alchemy/service.js`, `server/src/crafting/service.js`, `server/src/gathering/service.js`, `client/src/play/crafting.js`, `client/src/play/alchemy.js`
## Crafting stations
**Status:** partial (furnace, anvil, woodworking bench, crafting bench live; UI shell for others)
**Spec:** Furnace / anvil / woodworking-bench / crafting-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle).
**TODO:** oven/campfire burn, spinning wheel once sheep exist; dedicated station sprites where still placeholder.
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace` / `anvil` / `woodworkingBench` / `craftingBench`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
**Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
**Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring.
**TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
## Stamina and running
@@ -254,9 +265,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Alchemy / cauldron
**Status:** partial (scaffolding)
**Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs at a **Cauldron** block. Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules.
**Code:** `shared/definitions/alchemy.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`
**Status:** partial (potion scaffolding + flower→dye + dye mixing live)
**Spec:** **Herbalism** gathers flowers (clippers) and cotton (no tool). **Alchemy** uses herbs at a **Cauldron** block for potions; the same cauldron bottles dyes from flowers and mixes two dye colours (paint-style). Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules. **Glass bottle** (`ItemId.glassBottle`, sprite `potion-0`) is `npcShopAllowed` for vendor catalogs.
**Code:** `shared/definitions/alchemy.js`, `shared/definitions/dyes.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`
## Inventory, items, equipment, ground drops
@@ -228,23 +228,34 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Equipment tiers and worn stat bonuses## Equipment tiers and worn stat bonuses**Status:** partial **Status:** partial **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies). **Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type). **Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type). **TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`## Gathering, crafting, and production skills## Gathering, crafting, and production skills**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting live) **Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower herbalism live) **Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later. **Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Herbalism (plants):** **Flower** nodes need **plant clippers** (bronze clippers: anvil 1 bronze bar, or NPC shop); success yields a flower with a random dye colour and stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later. **Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`## Cloth, dyes, and tailoring**Status:** partial (cotton loop + flower dyes + sweater live; higher cloth sources TBD) **Spec:** **Cloth tiers** (same skill gates/ranks as metal/wood): Cotton, Wool, Linen, Cashmere, Silk, Fairy silk, Dragonweave. Shared magenta sprites under `items/cloth` (`wool` fibre, `yarn`, `cloth`) and `items/clothing` (`sweater` + equip) tinted per tier (or optional dye colour on clothing instances). **Spinning wheel** (Tailoring): fibre → yarn. **Loom**: yarn → cloth. **Tailor bench** UI is template-first: pick clothing template (sweater today; shirt/robe later) → cloth tier → optional dye from bag → sidebar shows resolved ingredients (sweater = 3 yarn). Crafted clothing can carry `instance.dyeColor`; otherwise material tint. **Flowers** (9 colours) brew 1:1 into **dye** bottles at a cauldron (needs **glass bottles** / `potion-0`). Two different dye colours mix paint-style (weighted by fill); bottle count follows inserted dyes; fill packs with overflow into the next bottle (extra glass only if overflow needs more bottles than inputs). Cannot mix flowers with dyes in one brew. Dye uses on tailor consume one fill level per craft. **TODO (sources):** shear animals / pick plants for wool–silk; fairy silk + dragonweave as mob drops later. **Later design (document only for now):**- **Wizard cloth gear** — robes and similar give Magic skill bonuses (`EquipmentKind.wizardCloth`).- **Cosmetic cloth gear** — sum equipped cosmetic item tiers as **Style points** (quests / exclusive areas).- **Warm clothing** — sweaters and other warm pieces reduce cold-season debuffs (e.g. winter halves stamina regen; each warm-equipped slot except hands mitigates; full warm set nullifies cold; summer reverses). **Padding** from cloth + matching-tier plate at a crafting bench → **padded armour** per slot.**Code:** `shared/definitions/materialTiers.js` (`ClothTier`), `shared/definitions/clothItems.js`, `shared/definitions/dyes.js`, `shared/crafting/tailor.js`, `shared/crafting/stationRecipes.js`, `server/src/alchemy/service.js`, `server/src/crafting/service.js`, `server/src/gathering/service.js`, `client/src/play/crafting.js`, `client/src/play/alchemy.js`## Crafting stations## Crafting stations**Status:** partial (furnace, anvil, woodworking bench, crafting bench live; UI shell for others) **Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live) **Spec:** Furnace / anvil / woodworking-bench / crafting-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). **Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. **TODO:** oven/campfire burn, spinning wheel once sheep exist; dedicated station sprites where still placeholder. **TODO:** oven/campfire burn; dedicated station sprites where still placeholder. **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace` / `anvil` / `woodworkingBench` / `craftingBench`), `server/src/crafting/service.js`, `client/src/play/crafting.js`**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`## Stamina and running## Stamina and running@@ -254,9 +265,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Alchemy / cauldron## Alchemy / cauldron**Status:** partial (scaffolding) **Status:** partial (potion scaffolding + flower→dye + dye mixing live) **Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs at a **Cauldron** block. Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules. **Spec:** **Herbalism** gathers flowers (clippers) and cotton (no tool). **Alchemy** uses herbs at a **Cauldron** block for potions; the same cauldron bottles dyes from flowers and mixes two dye colours (paint-style). Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules. **Glass bottle** (`ItemId.glassBottle`, sprite `potion-0`) is `npcShopAllowed` for vendor catalogs. **Code:** `shared/definitions/alchemy.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`**Code:** `shared/definitions/alchemy.js`, `shared/definitions/dyes.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`## Inventory, items, equipment, ground drops## Inventory, items, equipment, ground drops@@ -8,6 +8,11 @@ import {
recipePaperBody,
resolvedAlchemyPotions
} from "../../../shared/alchemy/recipes.js";
import {
dyeItemInstance,
DEFAULT_DYE_FILL,
mixDyeBatches
} from "../../../shared/definitions/dyes.js";
import { bagView } from "../items/bags.js";
import {
countItemInSlots,
@@ -189,13 +194,47 @@ function setSlot (world, sessionId, command)
const def = itemDefinition(itemId);
if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle)
{ throw userError("That cannot go in a cauldron slot."); }
if (itemId === ItemId.dye || itemId === ItemId.flower)
{
// Allowed — instances are captured on insert.
}
else if (def.dye || def.flower)
{ /* ok */ }
const inventory = ensureInventory(world, handle);
const have = countItemInSlots(inventory.slots, itemId);
if (have < quantity)
{ throw userError("Not enough of that item in your inventory."); }
let instance = null;
if (itemId === ItemId.flower || itemId === ItemId.dye)
{
const wanted = command.instance ? structuredClone(command.instance) : null;
if (wanted)
{ instance = wanted; }
else
{
for (const slot of inventory.slots)
{
if (slot?.itemId === itemId && slot.instance)
{
instance = structuredClone(slot.instance);
break;
}
}
}
if (!instance && itemId === ItemId.flower)
{ throw userError("That flower has no colour."); }
if (!instance && itemId === ItemId.dye)
{ throw userError("That dye has no colour."); }
const have = countMatchingInstance(inventory.slots, itemId, instance);
if (have < quantity)
{ throw userError("Not enough of that item in your inventory."); }
}
else
{
const have = countItemInSlots(inventory.slots, itemId);
if (have < quantity)
{ throw userError("Not enough of that item in your inventory."); }
}
session.slots[slotIndex] = { itemId, quantity };
session.slots[slotIndex] = { itemId, quantity, instance };
return {
events: [],
private: bagView(world.ecs, handle),
@@ -218,6 +257,7 @@ function insertFromSlot (world, sessionId, command)
const pulled = takeMatchingFromSlots(inventory.slots, {
itemId: reserved.itemId,
quantity: reserved.quantity,
instance: reserved.instance ?? null,
compact: false
});
if (!pulled.ok)
@@ -225,11 +265,21 @@ function insertFromSlot (world, sessionId, command)
inventory.slots = pulled.slots;
session.slots[slotIndex] = null;
const existing = session.brew.find((row) => row.itemId === reserved.itemId);
const brewRow = {
itemId: reserved.itemId,
quantity: reserved.quantity,
instance: reserved.instance
? structuredClone(reserved.instance)
: (pulled.taken?.instance ? structuredClone(pulled.taken.instance) : null)
};
const existing = session.brew.find((row) =>
row.itemId === brewRow.itemId
&& JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
if (existing)
{ existing.quantity += reserved.quantity; }
{ existing.quantity += brewRow.quantity; }
else
{ session.brew.push({ itemId: reserved.itemId, quantity: reserved.quantity }); }
{ session.brew.push(brewRow); }
session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId });
session.lastSuccessRecipe = null;
@@ -269,6 +319,14 @@ function bottle (world, sessionId, command)
{ throw userError("The cauldron is empty."); }
const inventory = ensureInventory(world, handle);
const dyePath = evaluateDyeBrew(session.brew);
if (dyePath)
{
if (!dyePath.ok)
{ throw userError(dyePath.reason); }
return bottleDyeResult(world, handle, session, inventory, dyePath);
}
const skills = world.ecs.get(handle, Component.skills) ?? {};
const evaluation = evaluateAlchemyBottle({
@@ -336,6 +394,122 @@ function bottle (world, sessionId, command)
};
}
/**
* @returns {null | { ok: false, reason: string } | { ok: true, mode: "flower"|"mix", ... }}
*/
function evaluateDyeBrew (brew)
{
const rows = brew ?? [];
if (!rows.length)
{ return null; }
const hasFlower = rows.some((row) => row.itemId === ItemId.flower);
const hasDye = rows.some((row) => row.itemId === ItemId.dye);
const hasOther = rows.some((row) => row.itemId !== ItemId.flower && row.itemId !== ItemId.dye);
if (!hasFlower && !hasDye)
{ return null; }
if (hasOther)
{ return { ok: false, reason: "Do not mix dyes or flowers with alchemy ingredients." }; }
if (hasFlower && hasDye)
{ return { ok: false, reason: "Cannot mix flowers and dyes together." }; }
if (hasFlower)
{
const colors = new Set(rows.map((row) => row.instance?.colorId).filter(Boolean));
if (colors.size === 0)
{ return { ok: false, reason: "Those flowers have no colour." }; }
if (colors.size > 1)
{ return { ok: false, reason: "Use flowers of a single colour for dye." }; }
const sample = rows.find((row) => row.instance?.color);
const quantity = rows.reduce((sum, row) => sum + (row.quantity | 0), 0);
return {
ok: true,
mode: "flower",
quantity: Math.max(1, quantity),
instance: dyeItemInstance(sample.instance.color, DEFAULT_DYE_FILL, sample.instance.colorId)
};
}
const mixed = mixDyeBatches(rows);
if (!mixed.ok)
{ return { ok: false, reason: mixed.reason }; }
return { ok: true, mode: "mix", ...mixed };
}
function bottleDyeResult (world, handle, session, inventory, dyePath)
{
const outputs = dyePath.mode === "flower"
? Array.from({ length: dyePath.quantity }, () => ({
quantity: 1,
instance: dyePath.instance
}))
: dyePath.outputs;
// Flowers need empty glass bottles. Dye remixes reuse the bottles already
// consumed into the brew; only overflow bottles need extra glass.
const bottleNeed = dyePath.mode === "flower"
? outputs.length
: Math.max(0, dyePath.extraBottles | 0);
if (bottleNeed > 0)
{
const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
if (bottles < bottleNeed)
{
throw userError(
`You need ${bottleNeed} glass bottle${bottleNeed === 1 ? "" : "s"}.`
);
}
const takeBottles = takeMatchingFromSlots(inventory.slots, {
itemId: ItemId.glassBottle,
quantity: bottleNeed,
compact: false
});
if (!takeBottles.ok)
{ throw userError("You need glass bottles to bottle the dye."); }
inventory.slots = takeBottles.slots;
}
const dyeDef = itemDefinition(ItemId.dye);
let slots = inventory.slots;
for (const out of outputs)
{
const inserted = insertStack(slots, {
itemId: ItemId.dye,
quantity: out.quantity,
instance: out.instance
}, dyeDef);
if (!inserted.ok)
{
throw userError("Not enough inventory space for dye.");
}
slots = inserted.slots;
}
inventory.slots = slots;
session.lastSuccessRecipe = null;
clearBrew(session);
const sample = outputs[0]?.instance;
return {
events: [],
private: bagView(world.ecs, handle),
cauldron: true,
cauldronState: sessionView(session),
alchemyResult: {
success: true,
reason: null,
produced: outputs.length,
wanted: outputs.length,
lost: 0,
potion: {
potionKey: "dye",
displayName: "Dye",
unstable: false,
color: sample?.color ?? null,
fillLevel: sample?.fillLevel ?? DEFAULT_DYE_FILL
}
}
};
}
function clear (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -399,3 +573,18 @@ function saveRecipe (world, sessionId, command)
cauldronState: sessionView(session)
};
}
function countMatchingInstance (slots, itemId, instance)
{
let total = 0;
const key = JSON.stringify(instance ?? null);
for (const slot of slots ?? [])
{
if (!slot || slot.itemId !== itemId)
{ continue; }
if (JSON.stringify(slot.instance ?? null) !== key)
{ continue; }
total += stackQuantity(slot.quantity);
}
return total;
}
@@ -8,6 +8,11 @@ import { recipePaperBody, recipePaperBody, resolvedAlchemyPotions resolvedAlchemyPotions} from "../../../shared/alchemy/recipes.js";} from "../../../shared/alchemy/recipes.js";import { dyeItemInstance, DEFAULT_DYE_FILL, mixDyeBatches} from "../../../shared/definitions/dyes.js";import { bagView } from "../items/bags.js";import { bagView } from "../items/bags.js";import {import { countItemInSlots, countItemInSlots,@@ -189,13 +194,47 @@ function setSlot (world, sessionId, command) const def = itemDefinition(itemId); const def = itemDefinition(itemId); if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle) if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle) { throw userError("That cannot go in a cauldron slot."); } { throw userError("That cannot go in a cauldron slot."); } if (itemId === ItemId.dye || itemId === ItemId.flower) { // Allowed — instances are captured on insert. } else if (def.dye || def.flower) { /* ok */ } const inventory = ensureInventory(world, handle); const inventory = ensureInventory(world, handle); const have = countItemInSlots(inventory.slots, itemId); let instance = null; if (have < quantity) if (itemId === ItemId.flower || itemId === ItemId.dye) { throw userError("Not enough of that item in your inventory."); } { const wanted = command.instance ? structuredClone(command.instance) : null; if (wanted) { instance = wanted; } else { for (const slot of inventory.slots) { if (slot?.itemId === itemId && slot.instance) { instance = structuredClone(slot.instance); break; } } } if (!instance && itemId === ItemId.flower) { throw userError("That flower has no colour."); } if (!instance && itemId === ItemId.dye) { throw userError("That dye has no colour."); } const have = countMatchingInstance(inventory.slots, itemId, instance); if (have < quantity) { throw userError("Not enough of that item in your inventory."); } } else { const have = countItemInSlots(inventory.slots, itemId); if (have < quantity) { throw userError("Not enough of that item in your inventory."); } } session.slots[slotIndex] = { itemId, quantity }; session.slots[slotIndex] = { itemId, quantity, instance }; return { return { events: [], events: [], private: bagView(world.ecs, handle), private: bagView(world.ecs, handle),@@ -218,6 +257,7 @@ function insertFromSlot (world, sessionId, command) const pulled = takeMatchingFromSlots(inventory.slots, { const pulled = takeMatchingFromSlots(inventory.slots, { itemId: reserved.itemId, itemId: reserved.itemId, quantity: reserved.quantity, quantity: reserved.quantity, instance: reserved.instance ?? null, compact: false compact: false }); }); if (!pulled.ok) if (!pulled.ok)@@ -225,11 +265,21 @@ function insertFromSlot (world, sessionId, command) inventory.slots = pulled.slots; inventory.slots = pulled.slots; session.slots[slotIndex] = null; session.slots[slotIndex] = null; const existing = session.brew.find((row) => row.itemId === reserved.itemId); const brewRow = { itemId: reserved.itemId, quantity: reserved.quantity, instance: reserved.instance ? structuredClone(reserved.instance) : (pulled.taken?.instance ? structuredClone(pulled.taken.instance) : null) }; const existing = session.brew.find((row) => row.itemId === brewRow.itemId && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null)); if (existing) if (existing) { existing.quantity += reserved.quantity; } { existing.quantity += brewRow.quantity; } else else { session.brew.push({ itemId: reserved.itemId, quantity: reserved.quantity }); } { session.brew.push(brewRow); } session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId }); session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId }); session.lastSuccessRecipe = null; session.lastSuccessRecipe = null;@@ -269,6 +319,14 @@ function bottle (world, sessionId, command) { throw userError("The cauldron is empty."); } { throw userError("The cauldron is empty."); } const inventory = ensureInventory(world, handle); const inventory = ensureInventory(world, handle); const dyePath = evaluateDyeBrew(session.brew); if (dyePath) { if (!dyePath.ok) { throw userError(dyePath.reason); } return bottleDyeResult(world, handle, session, inventory, dyePath); } const skills = world.ecs.get(handle, Component.skills) ?? {}; const skills = world.ecs.get(handle, Component.skills) ?? {}; const evaluation = evaluateAlchemyBottle({ const evaluation = evaluateAlchemyBottle({@@ -336,6 +394,122 @@ function bottle (world, sessionId, command) }; };}}/** * @returns {null | { ok: false, reason: string } | { ok: true, mode: "flower"|"mix", ... }} */function evaluateDyeBrew (brew){ const rows = brew ?? []; if (!rows.length) { return null; } const hasFlower = rows.some((row) => row.itemId === ItemId.flower); const hasDye = rows.some((row) => row.itemId === ItemId.dye); const hasOther = rows.some((row) => row.itemId !== ItemId.flower && row.itemId !== ItemId.dye); if (!hasFlower && !hasDye) { return null; } if (hasOther) { return { ok: false, reason: "Do not mix dyes or flowers with alchemy ingredients." }; } if (hasFlower && hasDye) { return { ok: false, reason: "Cannot mix flowers and dyes together." }; } if (hasFlower) { const colors = new Set(rows.map((row) => row.instance?.colorId).filter(Boolean)); if (colors.size === 0) { return { ok: false, reason: "Those flowers have no colour." }; } if (colors.size > 1) { return { ok: false, reason: "Use flowers of a single colour for dye." }; } const sample = rows.find((row) => row.instance?.color); const quantity = rows.reduce((sum, row) => sum + (row.quantity | 0), 0); return { ok: true, mode: "flower", quantity: Math.max(1, quantity), instance: dyeItemInstance(sample.instance.color, DEFAULT_DYE_FILL, sample.instance.colorId) }; } const mixed = mixDyeBatches(rows); if (!mixed.ok) { return { ok: false, reason: mixed.reason }; } return { ok: true, mode: "mix", ...mixed };}function bottleDyeResult (world, handle, session, inventory, dyePath){ const outputs = dyePath.mode === "flower" ? Array.from({ length: dyePath.quantity }, () => ({ quantity: 1, instance: dyePath.instance })) : dyePath.outputs; // Flowers need empty glass bottles. Dye remixes reuse the bottles already // consumed into the brew; only overflow bottles need extra glass. const bottleNeed = dyePath.mode === "flower" ? outputs.length : Math.max(0, dyePath.extraBottles | 0); if (bottleNeed > 0) { const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle); if (bottles < bottleNeed) { throw userError( `You need ${bottleNeed} glass bottle${bottleNeed === 1 ? "" : "s"}.` ); } const takeBottles = takeMatchingFromSlots(inventory.slots, { itemId: ItemId.glassBottle, quantity: bottleNeed, compact: false }); if (!takeBottles.ok) { throw userError("You need glass bottles to bottle the dye."); } inventory.slots = takeBottles.slots; } const dyeDef = itemDefinition(ItemId.dye); let slots = inventory.slots; for (const out of outputs) { const inserted = insertStack(slots, { itemId: ItemId.dye, quantity: out.quantity, instance: out.instance }, dyeDef); if (!inserted.ok) { throw userError("Not enough inventory space for dye."); } slots = inserted.slots; } inventory.slots = slots; session.lastSuccessRecipe = null; clearBrew(session); const sample = outputs[0]?.instance; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session), alchemyResult: { success: true, reason: null, produced: outputs.length, wanted: outputs.length, lost: 0, potion: { potionKey: "dye", displayName: "Dye", unstable: false, color: sample?.color ?? null, fillLevel: sample?.fillLevel ?? DEFAULT_DYE_FILL } } };}function clear (world, sessionId, command)function clear (world, sessionId, command){{ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const { handle } = world.requireOwnedEntity(sessionId, command.characterId);@@ -399,3 +573,18 @@ function saveRecipe (world, sessionId, command) cauldronState: sessionView(session) cauldronState: sessionView(session) }; };}}function countMatchingInstance (slots, itemId, instance){ let total = 0; const key = JSON.stringify(instance ?? null); for (const slot of slots ?? []) { if (!slot || slot.itemId !== itemId) { continue; } if (JSON.stringify(slot.instance ?? null) !== key) { continue; } total += stackQuantity(slot.quantity); } return total;}@@ -1,7 +1,7 @@
import { Component } from "../ecs/components.js";
import { BlockType } from "../../../shared/definitions/tiles.js";
import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
import { itemDefinition } from "../../../shared/definitions/items.js";
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
import {
@@ -10,6 +10,7 @@ import {
canCraftFitInventory,
hasRecipeInputs
} from "../../../shared/crafting/recipes.js";
import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
import {
@@ -69,6 +70,12 @@ function stationBlockType (stationId)
{ return BlockType.woodworkingBench; }
if (stationId === CraftingStationId.craftingBench)
{ return BlockType.craftingBench; }
if (stationId === CraftingStationId.spinningWheel)
{ return BlockType.spinningWheel; }
if (stationId === CraftingStationId.loom)
{ return BlockType.loom; }
if (stationId === CraftingStationId.tailorBench)
{ return BlockType.tailorBench; }
return null;
}
@@ -96,7 +103,27 @@ function takeInputs (slots, inputs)
return { ok: true, slots: next };
}
export function startCraft (world, sessionId, characterId, stationId, recipeId, now)
/** Spend one fill level of a dye bottle (remove at 0). */
function consumeDyeUse (slots, slotIndex)
{
const next = slots.map((slot) => (slot ? structuredClone(slot) : null));
const slot = next[slotIndex];
if (!slot || slot.itemId !== ItemId.dye || slot.instance?.kind !== "dye")
{ return { ok: false }; }
const fill = Math.max(1, slot.instance.fillLevel | 0 || 4);
if (fill <= 1)
{
next[slotIndex] = null;
return { ok: true, slots: next };
}
slot.instance = {
...slot.instance,
fillLevel: fill - 1
};
return { ok: true, slots: next };
}
export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})
{
const entityId = world.characterEntities.get(characterId);
if (entityId == null)
@@ -111,7 +138,7 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
const stationDef = craftingStationDefinition(stationId);
if (!stationDef)
{ throw userError("Unknown crafting station."); }
const recipe = recipeDefinition(recipeId);
let recipe = recipeDefinition(recipeId);
if (!recipe)
{ throw userError("Unknown recipe."); }
const stationIds = Array.isArray(recipe.stationIds)
@@ -128,6 +155,27 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
const inventory = world.ecs.get(handle, Component.inventory);
const skills = world.ecs.get(handle, Component.skills);
const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
let dyeSlotIndex = null;
if (recipe.tailorTemplate)
{
const dyeIdx = options.dyeSlotIndex;
let dyeStack = null;
if (dyeIdx != null && dyeIdx >= 0)
{
dyeStack = inventory?.slots?.[dyeIdx | 0] ?? null;
dyeSlotIndex = dyeIdx | 0;
}
const resolved = resolveTailorCraft({
templateId: recipe.tailorTemplate,
clothTier: options.clothTier,
dyeStack
});
if (!resolved.ok)
{ throw userError(resolved.reason); }
recipe = resolved.recipe;
}
if (!canStartCraft(inventory?.slots ?? [], recipe, level))
{
if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
@@ -136,6 +184,12 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
{ throw userError("Missing materials."); }
throw userError("Not enough bag space for the result.");
}
if (recipe.consumeDye && dyeSlotIndex != null)
{
const dye = inventory?.slots?.[dyeSlotIndex];
if (!dye || dye.itemId !== ItemId.dye)
{ throw userError("Selected dye is missing."); }
}
const sessions = ensureCraftSessions(world);
const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
@@ -143,6 +197,8 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
sessionId,
stationId,
recipeId,
recipe,
dyeSlotIndex,
finishesAt: now + durationMs
});
const events = [];
@@ -245,7 +301,7 @@ export function stepCrafting (world, now)
continue;
}
const recipe = recipeDefinition(session.recipeId);
const recipe = session.recipe ?? recipeDefinition(session.recipeId);
const stationDef = craftingStationDefinition(session.stationId);
const inventory = world.ecs.get(handle, Component.inventory);
const skills = world.ecs.get(handle, Component.skills);
@@ -280,17 +336,36 @@ export function stepCrafting (world, now)
});
continue;
}
let slotsAfter = taken.slots;
if (recipe.consumeDye && session.dyeSlotIndex != null)
{
const dyeTaken = consumeDyeUse(slotsAfter, session.dyeSlotIndex);
if (!dyeTaken.ok)
{
events.push({
type: "craft-result",
sessionId: session.sessionId,
recipeId: session.recipeId,
ok: false,
error: "Selected dye is missing."
});
continue;
}
slotsAfter = dyeTaken.slots;
}
const outDef = itemDefinition(recipe.output.itemId);
const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
const origin = craftOrigin(
craftOriginVerbForStation(session.stationId),
characterDisplayName(world, handle)
);
const added = insertStack(taken.slots, attachOrigins({
const outStack = {
itemId: recipe.output.itemId,
quantity: outQty,
origins: [{ origin, quantity: outQty }]
}), outDef);
origins: [{ origin, quantity: outQty }],
...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
};
const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
if (!added.ok || added.remainder > 0)
{
events.push({
@@ -354,7 +429,11 @@ export function handleCraftCommand (world, sessionId, command, now)
command.characterId,
command.stationId,
command.recipeId,
now
now,
{
clothTier: command.clothTier ?? null,
dyeSlotIndex: command.dyeSlotIndex ?? null
}
);
case "cancel-craft":
return cancelCraft(world, command.characterId);
@@ -1,7 +1,7 @@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 } from "../../../shared/definitions/craftingStations.js";import { 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";import {import {@@ -10,6 +10,7 @@ import { canCraftFitInventory, canCraftFitInventory, hasRecipeInputs hasRecipeInputs} from "../../../shared/crafting/recipes.js";} from "../../../shared/crafting/recipes.js";import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";import {import {@@ -69,6 +70,12 @@ function stationBlockType (stationId) { return BlockType.woodworkingBench; } { return BlockType.woodworkingBench; } if (stationId === CraftingStationId.craftingBench) if (stationId === CraftingStationId.craftingBench) { return BlockType.craftingBench; } { return BlockType.craftingBench; } if (stationId === CraftingStationId.spinningWheel) { return BlockType.spinningWheel; } if (stationId === CraftingStationId.loom) { return BlockType.loom; } if (stationId === CraftingStationId.tailorBench) { return BlockType.tailorBench; } return null; return null;}}@@ -96,7 +103,27 @@ function takeInputs (slots, inputs) return { ok: true, slots: next }; return { ok: true, slots: next };}}export function startCraft (world, sessionId, characterId, stationId, recipeId, now)/** Spend one fill level of a dye bottle (remove at 0). */function consumeDyeUse (slots, slotIndex){ const next = slots.map((slot) => (slot ? structuredClone(slot) : null)); const slot = next[slotIndex]; if (!slot || slot.itemId !== ItemId.dye || slot.instance?.kind !== "dye") { return { ok: false }; } const fill = Math.max(1, slot.instance.fillLevel | 0 || 4); if (fill <= 1) { next[slotIndex] = null; return { ok: true, slots: next }; } slot.instance = { ...slot.instance, fillLevel: fill - 1 }; return { ok: true, slots: next };}export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {}){{ const entityId = world.characterEntities.get(characterId); const entityId = world.characterEntities.get(characterId); if (entityId == null) if (entityId == null)@@ -111,7 +138,7 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId, const stationDef = craftingStationDefinition(stationId); const stationDef = craftingStationDefinition(stationId); if (!stationDef) if (!stationDef) { throw userError("Unknown crafting station."); } { throw userError("Unknown crafting station."); } const recipe = recipeDefinition(recipeId); let recipe = recipeDefinition(recipeId); if (!recipe) if (!recipe) { throw userError("Unknown recipe."); } { throw userError("Unknown recipe."); } const stationIds = Array.isArray(recipe.stationIds) const stationIds = Array.isArray(recipe.stationIds)@@ -128,6 +155,27 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId, const inventory = world.ecs.get(handle, Component.inventory); const inventory = world.ecs.get(handle, Component.inventory); const skills = world.ecs.get(handle, Component.skills); const skills = world.ecs.get(handle, Component.skills); const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing); const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing); let dyeSlotIndex = null; if (recipe.tailorTemplate) { const dyeIdx = options.dyeSlotIndex; let dyeStack = null; if (dyeIdx != null && dyeIdx >= 0) { dyeStack = inventory?.slots?.[dyeIdx | 0] ?? null; dyeSlotIndex = dyeIdx | 0; } const resolved = resolveTailorCraft({ templateId: recipe.tailorTemplate, clothTier: options.clothTier, dyeStack }); if (!resolved.ok) { throw userError(resolved.reason); } recipe = resolved.recipe; } if (!canStartCraft(inventory?.slots ?? [], recipe, level)) if (!canStartCraft(inventory?.slots ?? [], recipe, level)) { { if ((level | 0) < (recipe.minSkillLevel | 0 || 1)) if ((level | 0) < (recipe.minSkillLevel | 0 || 1))@@ -136,6 +184,12 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId, { throw userError("Missing materials."); } { throw userError("Missing materials."); } throw userError("Not enough bag space for the result."); throw userError("Not enough bag space for the result."); } } if (recipe.consumeDye && dyeSlotIndex != null) { const dye = inventory?.slots?.[dyeSlotIndex]; if (!dye || dye.itemId !== ItemId.dye) { throw userError("Selected dye is missing."); } } const sessions = ensureCraftSessions(world); const sessions = ensureCraftSessions(world); const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS); const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);@@ -143,6 +197,8 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId, sessionId, sessionId, stationId, stationId, recipeId, recipeId, recipe, dyeSlotIndex, finishesAt: now + durationMs finishesAt: now + durationMs }); }); const events = []; const events = [];@@ -245,7 +301,7 @@ export function stepCrafting (world, now) continue; continue; } } const recipe = recipeDefinition(session.recipeId); const recipe = session.recipe ?? recipeDefinition(session.recipeId); const stationDef = craftingStationDefinition(session.stationId); const stationDef = craftingStationDefinition(session.stationId); const inventory = world.ecs.get(handle, Component.inventory); const inventory = world.ecs.get(handle, Component.inventory); const skills = world.ecs.get(handle, Component.skills); const skills = world.ecs.get(handle, Component.skills);@@ -280,17 +336,36 @@ export function stepCrafting (world, now) }); }); continue; continue; } } let slotsAfter = taken.slots; if (recipe.consumeDye && session.dyeSlotIndex != null) { const dyeTaken = consumeDyeUse(slotsAfter, session.dyeSlotIndex); if (!dyeTaken.ok) { events.push({ type: "craft-result", sessionId: session.sessionId, recipeId: session.recipeId, ok: false, error: "Selected dye is missing." }); continue; } slotsAfter = dyeTaken.slots; } const outDef = itemDefinition(recipe.output.itemId); const outDef = itemDefinition(recipe.output.itemId); const outQty = Math.max(1, recipe.output.quantity | 0 || 1); const outQty = Math.max(1, recipe.output.quantity | 0 || 1); const origin = craftOrigin( const origin = craftOrigin( craftOriginVerbForStation(session.stationId), craftOriginVerbForStation(session.stationId), characterDisplayName(world, handle) characterDisplayName(world, handle) ); ); const added = insertStack(taken.slots, attachOrigins({ const outStack = { itemId: recipe.output.itemId, itemId: recipe.output.itemId, quantity: outQty, quantity: outQty, origins: [{ origin, quantity: outQty }] origins: [{ origin, quantity: outQty }], }), outDef); ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {}) }; const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef); if (!added.ok || added.remainder > 0) if (!added.ok || added.remainder > 0) { { events.push({ events.push({@@ -354,7 +429,11 @@ export function handleCraftCommand (world, sessionId, command, now) command.characterId, command.characterId, command.stationId, command.stationId, command.recipeId, command.recipeId, now now, { clothTier: command.clothTier ?? null, dyeSlotIndex: command.dyeSlotIndex ?? null } ); ); case "cancel-craft": case "cancel-craft": return cancelCraft(world, command.characterId); return cancelCraft(world, command.characterId);@@ -1,5 +1,6 @@
import { Component } from "./components.js";
import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";
import { resolveEquipTint } from "../../../shared/render/tint.js";
import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
import { mobDefinition } from "../../../shared/definitions/mobs.js";
import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
@@ -108,7 +109,14 @@ export function appearanceLayers (ecs, handle, appearance)
{ continue; }
const overlay = itemEquipSprite(worn.itemId);
if (overlay)
{ layers.push({ sprite: overlay, itemId: worn.itemId }); }
{
const tint = resolveEquipTint(worn.itemId, worn.instance);
layers.push({
sprite: overlay,
itemId: worn.itemId,
...(tint ? { tint } : {})
});
}
}
return layers;
}
@@ -1,5 +1,6 @@import { Component } from "./components.js";import { Component } from "./components.js";import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";import { resolveEquipTint } from "../../../shared/render/tint.js";import { spriteImageName } from "../../../shared/definitions/tileSprites.js";import { spriteImageName } from "../../../shared/definitions/tileSprites.js";import { mobDefinition } from "../../../shared/definitions/mobs.js";import { mobDefinition } from "../../../shared/definitions/mobs.js";import { mobCanFight } from "../../../shared/definitions/mobCombat.js";import { mobCanFight } from "../../../shared/definitions/mobCombat.js";@@ -108,7 +109,14 @@ export function appearanceLayers (ecs, handle, appearance) { continue; } { continue; } const overlay = itemEquipSprite(worn.itemId); const overlay = itemEquipSprite(worn.itemId); if (overlay) if (overlay) { layers.push({ sprite: overlay, itemId: worn.itemId }); } { const tint = resolveEquipTint(worn.itemId, worn.instance); layers.push({ sprite: overlay, itemId: worn.itemId, ...(tint ? { tint } : {}) }); } } } return layers; return layers;}}@@ -244,6 +244,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
tileY: message.tileY | 0
});
break;
case MessageType.pick:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "pick",
characterId: session.characterId,
tileX: message.tileX | 0,
tileY: message.tileY | 0
});
break;
case MessageType.cancelGather:
requirePlaying(session);
simulation.enqueue(session.id, {
@@ -257,7 +266,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
type: "start-craft",
characterId: session.characterId,
stationId: message.stationId,
recipeId: message.recipeId
recipeId: message.recipeId,
clothTier: message.clothTier ?? null,
dyeSlotIndex: message.dyeSlotIndex ?? null
});
break;
case MessageType.cancelCraft:
@@ -274,7 +285,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
characterId: session.characterId,
slotIndex: message.slotIndex | 0,
itemId: message.itemId | 0,
quantity: message.quantity | 0
quantity: message.quantity | 0,
instance: message.instance ?? null
});
break;
case MessageType.cauldronInsert:
@@ -244,6 +244,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, tileY: message.tileY | 0 tileY: message.tileY | 0 }); }); break; break; case MessageType.pick: requirePlaying(session); simulation.enqueue(session.id, { type: "pick", characterId: session.characterId, tileX: message.tileX | 0, tileY: message.tileY | 0 }); break; case MessageType.cancelGather: case MessageType.cancelGather: requirePlaying(session); requirePlaying(session); simulation.enqueue(session.id, { simulation.enqueue(session.id, {@@ -257,7 +266,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, type: "start-craft", type: "start-craft", characterId: session.characterId, characterId: session.characterId, stationId: message.stationId, stationId: message.stationId, recipeId: message.recipeId recipeId: message.recipeId, clothTier: message.clothTier ?? null, dyeSlotIndex: message.dyeSlotIndex ?? null }); }); break; break; case MessageType.cancelCraft: case MessageType.cancelCraft:@@ -274,7 +285,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, characterId: session.characterId, characterId: session.characterId, slotIndex: message.slotIndex | 0, slotIndex: message.slotIndex | 0, itemId: message.itemId | 0, itemId: message.itemId | 0, quantity: message.quantity | 0 quantity: message.quantity | 0, instance: message.instance ?? null }); }); break; break; case MessageType.cauldronInsert: case MessageType.cauldronInsert:@@ -1,6 +1,6 @@
import { Component } from "../ecs/components.js";
import { BlockType, woodTierForTreeBlock, isChopableTreeBlock } from "../../../shared/definitions/tiles.js";
import { itemDefinition } from "../../../shared/definitions/items.js";
import { BlockType, woodTierForTreeBlock, isChopableTreeBlock, plantGatherForBlock } from "../../../shared/definitions/tiles.js";
import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
import { SkillId } from "../../../shared/definitions/skills.js";
import {
materialFromOreBoulderState,
@@ -12,11 +12,21 @@ import {
EXHAUSTED_ORE_BOULDER_STATE,
resolveMiningPickaxe,
resolveWoodcuttingAxe,
resolvePlantClippers,
woodcuttingDurationMs,
woodcuttingXpForWood,
treeExhaustDurationMs,
logItemIdForWoodTier
logItemIdForWoodTier,
herbalismDurationMs,
herbalismXpForPick,
PLANT_EXHAUST_MS
} from "../../../shared/definitions/gathering.js";
import { rawClothItemId } from "../../../shared/definitions/clothItems.js";
import { ClothTier } from "../../../shared/definitions/materialTiers.js";
import {
flowerItemInstance,
randomFlowerColorId
} from "../../../shared/definitions/dyes.js";
import { insertStack } from "../../../shared/items/inventory.js";
import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
@@ -56,6 +66,13 @@ function ensureTreeRespawns (world)
return world.treeRespawns;
}
function ensurePlantRespawns (world)
{
if (!world.plantRespawns)
{ world.plantRespawns = new Map(); }
return world.plantRespawns;
}
function blockAt (world, tileX, tileY)
{
const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
@@ -97,6 +114,52 @@ function setTreeState (world, tileX, tileY, typeId, state)
return setBlockState(world, tileX, tileY, typeId, state);
}
function clearBlock (world, tileX, tileY, typeId)
{
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 prev = data?.blocks?.[index];
if (!prev || prev.typeId !== typeId)
{ return null; }
data.blocks[index] = null;
return {
type: "chunk-delta",
chunkX,
chunkY,
tileX,
tileY,
localX,
localY,
block: null
};
}
function placeBlock (world, tileX, tileY, typeId, 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 block = { typeId, state, config: null };
data.blocks[index] = block;
return {
type: "chunk-delta",
chunkX,
chunkY,
tileX,
tileY,
localX,
localY,
block
};
}
function pickaxeForOre (world, handle, materialId)
{
const inventory = world.ecs.get(handle, Component.inventory);
@@ -162,6 +225,19 @@ export function clearTreeRespawnsForChunk (world, chunkX, chunkY)
}
}
export function clearPlantRespawnsForChunk (world, chunkX, chunkY)
{
const respawns = world.plantRespawns;
if (!respawns?.size)
{ return; }
for (const key of [...respawns.keys()])
{
const [tileX, tileY] = key.split(",").map(Number);
if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
{ respawns.delete(key); }
}
}
/**
* Restore exhausted ore boulders whose timers have elapsed.
*/
@@ -210,6 +286,27 @@ export function stepTreeRespawns (world, now)
return { events };
}
export function stepPlantRespawns (world, now)
{
const respawns = world.plantRespawns;
if (!respawns?.size)
{ return { events: [] }; }
const events = [];
for (const [key, entry] of [...respawns.entries()])
{
if (now < entry.respawnsAt)
{ continue; }
respawns.delete(key);
const existing = blockAt(world, entry.tileX, entry.tileY);
if (existing)
{ continue; }
const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, entry.state);
if (delta)
{ events.push(delta); }
}
return { events };
}
function beginGatherSwing (world, handle, entityId, position, gatherFields, now)
{
clearEngage(world.ecs, entityId);
@@ -328,6 +425,57 @@ export function startChop (world, sessionId, characterId, tileX, tileY, now)
}, now);
}
/**
* Pick a plant node (flower with clippers, cotton without tools).
*/
export function startPick (world, sessionId, characterId, tileX, tileY, 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 plant."); }
const block = blockAt(world, tileX, tileY);
const plant = plantGatherForBlock(block);
if (!plant)
{ throw userError("There is nothing to pick there."); }
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 clippers = resolvePlantClippers({
inventorySlots: inventory?.slots,
equipmentSlots: equipment?.slots,
skills,
requireTool: !!plant.requiresClippers
});
if (!clippers.ok)
{ throw userError(clippers.reason); }
const toolTier = clippers.tool?.tier ?? null;
const durationMs = herbalismDurationMs(toolTier);
const toolItemId = clippers.tool?.stack?.itemId ?? null;
return beginGatherSwing(world, handle, entityId, position, {
kind: "plant",
plantKind: plant.kind,
tileX,
tileY,
typeId: block.typeId,
toolTier,
toolItemId,
durationMs
}, now);
}
function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])
{
privates.push({
@@ -488,12 +636,100 @@ function completeWoodcutting (world, handle, entityId, character, gather, events
});
}
function completePlant (world, handle, entityId, character, gather, events, privates, now)
{
const inventory = world.ecs.get(handle, Component.inventory);
if (!inventory)
{
clearGather(world.ecs, handle);
return;
}
let itemId = null;
let instance = null;
if (gather.plantKind === "flower")
{
itemId = ItemId.flower;
instance = flowerItemInstance(randomFlowerColorId());
}
else if (gather.plantKind === "cotton")
{
itemId = rawClothItemId(ClothTier.cotton);
}
else
{
clearGather(world.ecs, handle);
return;
}
const def = itemDefinition(itemId);
if (!def)
{
clearGather(world.ecs, handle);
return;
}
const origin = gatherOrigin(GatherOriginVerb.picked, characterDisplayName(world, handle));
const stack = attachOrigins({
itemId,
quantity: 1,
instance,
origins: [{ origin, quantity: 1 }]
});
const inserted = insertStack(inventory.slots, stack, def);
if (!inserted.ok || inserted.remainder > 0)
{
clearGather(world.ecs, handle);
events.push({
type: "command-error",
sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
message: "Your inventory is full."
});
return;
}
inventory.slots = inserted.slots;
const skills = world.ecs.get(handle, Component.skills);
let skillsChanged = false;
const levelUps = [];
if (skills?.xp)
{
const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind));
if (result.changed)
{ skillsChanged = true; }
if (result.levelUp)
{ levelUps.push(result.levelUp); }
}
const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId);
if (delta)
{ events.push(delta); }
ensurePlantRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
tileX: gather.tileX,
tileY: gather.tileY,
typeId: gather.typeId,
state: gather.plantKind === "flower" ? "flower" : "cotton-plant",
respawnsAt: now + PLANT_EXHAUST_MS
});
clearGather(world.ecs, handle);
pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
events.push({
type: "gather-complete",
characterId: character.characterId,
kind: "plant",
plantKind: gather.plantKind,
itemId
});
}
export function stepGather (world, now)
{
const events = [];
const privates = [];
events.push(...stepOreRespawns(world, now).events);
events.push(...stepTreeRespawns(world, now).events);
events.push(...stepPlantRespawns(world, now).events);
for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
{
@@ -527,6 +763,14 @@ export function stepGather (world, now)
continue;
}
}
else if (gather.kind === "plant")
{
if (!block || block.typeId !== gather.typeId || !plantGatherForBlock(block))
{
clearGather(world.ecs, handle);
continue;
}
}
else
{
clearGather(world.ecs, handle);
@@ -553,8 +797,10 @@ export function stepGather (world, now)
if (gather.kind === "mining")
{ completeMining(world, handle, entityId, character, gather, events, privates, now); }
else
else if (gather.kind === "woodcutting")
{ completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }
else
{ completePlant(world, handle, entityId, character, gather, events, privates, now); }
}
return { events, privates };
}
@@ -567,6 +813,8 @@ export function handleGatherCommand (world, sessionId, command, now)
return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
case "chop":
return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
case "pick":
return startPick(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
case "cancel-gather":
{
const entityId = world.characterEntities.get(command.characterId);
@@ -1,6 +1,6 @@import { Component } from "../ecs/components.js";import { Component } from "../ecs/components.js";import { BlockType, woodTierForTreeBlock, isChopableTreeBlock } from "../../../shared/definitions/tiles.js";import { BlockType, woodTierForTreeBlock, isChopableTreeBlock, plantGatherForBlock } from "../../../shared/definitions/tiles.js";import { itemDefinition } from "../../../shared/definitions/items.js";import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";import { SkillId } from "../../../shared/definitions/skills.js";import { SkillId } from "../../../shared/definitions/skills.js";import {import { materialFromOreBoulderState, materialFromOreBoulderState,@@ -12,11 +12,21 @@ import { EXHAUSTED_ORE_BOULDER_STATE, EXHAUSTED_ORE_BOULDER_STATE, resolveMiningPickaxe, resolveMiningPickaxe, resolveWoodcuttingAxe, resolveWoodcuttingAxe, resolvePlantClippers, woodcuttingDurationMs, woodcuttingDurationMs, woodcuttingXpForWood, woodcuttingXpForWood, treeExhaustDurationMs, treeExhaustDurationMs, logItemIdForWoodTier logItemIdForWoodTier, herbalismDurationMs, herbalismXpForPick, PLANT_EXHAUST_MS} from "../../../shared/definitions/gathering.js";} from "../../../shared/definitions/gathering.js";import { rawClothItemId } from "../../../shared/definitions/clothItems.js";import { ClothTier } from "../../../shared/definitions/materialTiers.js";import { flowerItemInstance, randomFlowerColorId} from "../../../shared/definitions/dyes.js";import { insertStack } from "../../../shared/items/inventory.js";import { insertStack } from "../../../shared/items/inventory.js";import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";@@ -56,6 +66,13 @@ function ensureTreeRespawns (world) return world.treeRespawns; return world.treeRespawns;}}function ensurePlantRespawns (world){ if (!world.plantRespawns) { world.plantRespawns = new Map(); } return world.plantRespawns;}function blockAt (world, tileX, tileY)function blockAt (world, tileX, tileY){{ const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY)); const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));@@ -97,6 +114,52 @@ function setTreeState (world, tileX, tileY, typeId, state) return setBlockState(world, tileX, tileY, typeId, state); return setBlockState(world, tileX, tileY, typeId, state);}}function clearBlock (world, tileX, tileY, typeId){ 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 prev = data?.blocks?.[index]; if (!prev || prev.typeId !== typeId) { return null; } data.blocks[index] = null; return { type: "chunk-delta", chunkX, chunkY, tileX, tileY, localX, localY, block: null };}function placeBlock (world, tileX, tileY, typeId, 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 block = { typeId, state, config: null }; data.blocks[index] = block; return { type: "chunk-delta", chunkX, chunkY, tileX, tileY, localX, localY, block };}function pickaxeForOre (world, handle, materialId)function pickaxeForOre (world, handle, materialId){{ const inventory = world.ecs.get(handle, Component.inventory); const inventory = world.ecs.get(handle, Component.inventory);@@ -162,6 +225,19 @@ export function clearTreeRespawnsForChunk (world, chunkX, chunkY) } }}}export function clearPlantRespawnsForChunk (world, chunkX, chunkY){ const respawns = world.plantRespawns; if (!respawns?.size) { return; } for (const key of [...respawns.keys()]) { const [tileX, tileY] = key.split(",").map(Number); if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY) { respawns.delete(key); } }}/**/** * Restore exhausted ore boulders whose timers have elapsed. * Restore exhausted ore boulders whose timers have elapsed. */ */@@ -210,6 +286,27 @@ export function stepTreeRespawns (world, now) return { events }; return { events };}}export function stepPlantRespawns (world, now){ const respawns = world.plantRespawns; if (!respawns?.size) { return { events: [] }; } const events = []; for (const [key, entry] of [...respawns.entries()]) { if (now < entry.respawnsAt) { continue; } respawns.delete(key); const existing = blockAt(world, entry.tileX, entry.tileY); if (existing) { continue; } const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, entry.state); if (delta) { events.push(delta); } } return { events };}function beginGatherSwing (world, handle, entityId, position, gatherFields, now)function beginGatherSwing (world, handle, entityId, position, gatherFields, now){{ clearEngage(world.ecs, entityId); clearEngage(world.ecs, entityId);@@ -328,6 +425,57 @@ export function startChop (world, sessionId, characterId, tileX, tileY, now) }, now); }, now);}}/** * Pick a plant node (flower with clippers, cotton without tools). */export function startPick (world, sessionId, characterId, tileX, tileY, 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 plant."); } const block = blockAt(world, tileX, tileY); const plant = plantGatherForBlock(block); if (!plant) { throw userError("There is nothing to pick there."); } 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 clippers = resolvePlantClippers({ inventorySlots: inventory?.slots, equipmentSlots: equipment?.slots, skills, requireTool: !!plant.requiresClippers }); if (!clippers.ok) { throw userError(clippers.reason); } const toolTier = clippers.tool?.tier ?? null; const durationMs = herbalismDurationMs(toolTier); const toolItemId = clippers.tool?.stack?.itemId ?? null; return beginGatherSwing(world, handle, entityId, position, { kind: "plant", plantKind: plant.kind, tileX, tileY, typeId: block.typeId, toolTier, toolItemId, durationMs }, now);}function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = []){{ privates.push({ privates.push({@@ -488,12 +636,100 @@ function completeWoodcutting (world, handle, entityId, character, gather, events }); });}}function completePlant (world, handle, entityId, character, gather, events, privates, now){ const inventory = world.ecs.get(handle, Component.inventory); if (!inventory) { clearGather(world.ecs, handle); return; } let itemId = null; let instance = null; if (gather.plantKind === "flower") { itemId = ItemId.flower; instance = flowerItemInstance(randomFlowerColorId()); } else if (gather.plantKind === "cotton") { itemId = rawClothItemId(ClothTier.cotton); } else { clearGather(world.ecs, handle); return; } const def = itemDefinition(itemId); if (!def) { clearGather(world.ecs, handle); return; } const origin = gatherOrigin(GatherOriginVerb.picked, characterDisplayName(world, handle)); const stack = attachOrigins({ itemId, quantity: 1, instance, origins: [{ origin, quantity: 1 }] }); const inserted = insertStack(inventory.slots, stack, def); if (!inserted.ok || inserted.remainder > 0) { clearGather(world.ecs, handle); events.push({ type: "command-error", sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId, message: "Your inventory is full." }); return; } inventory.slots = inserted.slots; const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp) { const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind)); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId); if (delta) { events.push(delta); } ensurePlantRespawns(world).set(tileKey(gather.tileX, gather.tileY), { tileX: gather.tileX, tileY: gather.tileY, typeId: gather.typeId, state: gather.plantKind === "flower" ? "flower" : "cotton-plant", respawnsAt: now + PLANT_EXHAUST_MS }); clearGather(world.ecs, handle); pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps); events.push({ type: "gather-complete", characterId: character.characterId, kind: "plant", plantKind: gather.plantKind, itemId });}export function stepGather (world, now)export function stepGather (world, now){{ const events = []; const events = []; const privates = []; const privates = []; events.push(...stepOreRespawns(world, now).events); events.push(...stepOreRespawns(world, now).events); events.push(...stepTreeRespawns(world, now).events); events.push(...stepTreeRespawns(world, now).events); events.push(...stepPlantRespawns(world, now).events); for (const entity of world.ecs.query(Component.gather, Component.position, Component.character)) for (const entity of world.ecs.query(Component.gather, Component.position, Component.character)) { {@@ -527,6 +763,14 @@ export function stepGather (world, now) continue; continue; } } } } else if (gather.kind === "plant") { if (!block || block.typeId !== gather.typeId || !plantGatherForBlock(block)) { clearGather(world.ecs, handle); continue; } } else else { { clearGather(world.ecs, handle); clearGather(world.ecs, handle);@@ -553,8 +797,10 @@ export function stepGather (world, now) if (gather.kind === "mining") if (gather.kind === "mining") { completeMining(world, handle, entityId, character, gather, events, privates, now); } { completeMining(world, handle, entityId, character, gather, events, privates, now); } else else if (gather.kind === "woodcutting") { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); } { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); } else { completePlant(world, handle, entityId, character, gather, events, privates, now); } } } return { events, privates }; return { events, privates };}}@@ -567,6 +813,8 @@ export function handleGatherCommand (world, sessionId, command, now) return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now); return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now); case "chop": case "chop": return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now); return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now); case "pick": return startPick(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now); case "cancel-gather": case "cancel-gather": { { const entityId = world.characterEntities.get(command.characterId); const entityId = world.characterEntities.get(command.characterId);@@ -36,7 +36,8 @@ import {
stepGather,
cancelGather,
clearOreRespawnsForChunk,
clearTreeRespawnsForChunk
clearTreeRespawnsForChunk,
clearPlantRespawnsForChunk
} from "../gathering/service.js";
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
@@ -216,6 +217,7 @@ export class WorkerWorld
{
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
data: cloneChunkData(chunk.data),
simulating: false,
@@ -233,6 +235,7 @@ export class WorkerWorld
const existing = this.chunks.get(key);
clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
this.chunks.set(key, {
data: cloneChunkData(chunk.data),
simulating: existing?.simulating ?? false,
@@ -265,6 +268,7 @@ export class WorkerWorld
{
clearOreRespawnsForChunk(this, chunkX, chunkY);
clearTreeRespawnsForChunk(this, chunkX, chunkY);
clearPlantRespawnsForChunk(this, chunkX, chunkY);
this.chunks.delete(key);
}
}
@@ -36,7 +36,8 @@ import { stepGather, stepGather, cancelGather, cancelGather, clearOreRespawnsForChunk, clearOreRespawnsForChunk, clearTreeRespawnsForChunk clearTreeRespawnsForChunk, clearPlantRespawnsForChunk} from "../gathering/service.js";} from "../gathering/service.js";import { handleCraftCommand, stepCrafting } from "../crafting/service.js";import { handleCraftCommand, stepCrafting } from "../crafting/service.js";import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";@@ -216,6 +217,7 @@ export class WorkerWorld { { clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), { this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), { data: cloneChunkData(chunk.data), data: cloneChunkData(chunk.data), simulating: false, simulating: false,@@ -233,6 +235,7 @@ export class WorkerWorld const existing = this.chunks.get(key); const existing = this.chunks.get(key); clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY); this.chunks.set(key, { this.chunks.set(key, { data: cloneChunkData(chunk.data), data: cloneChunkData(chunk.data), simulating: existing?.simulating ?? false, simulating: existing?.simulating ?? false,@@ -265,6 +268,7 @@ export class WorkerWorld { { clearOreRespawnsForChunk(this, chunkX, chunkY); clearOreRespawnsForChunk(this, chunkX, chunkY); clearTreeRespawnsForChunk(this, chunkX, chunkY); clearTreeRespawnsForChunk(this, chunkX, chunkY); clearPlantRespawnsForChunk(this, chunkX, chunkY); this.chunks.delete(key); this.chunks.delete(key); } } } }