Add water grounds, alchemy/herbalism scaffolding, and bounty office spec.
Server-authoritative cauldron brewing with potion recolor (darkness-aware), animated water/wade, and FEATURES notes for bounty offices still to build.
@@ -0,0 +1,35 @@
---
description: All world/item shaders must respect night darkness unless unlit or bloom.
alwaysApply: true
---
# Shaders respect darkness
Lit world and item shaders **must** apply the scene darkness value (e.g. `u_darkness` / ambient night darkening) unless explicitly exempt.
## Must darken
- Entity sprites, equipment overlays, ground items
- Ground/block tiles (atlas or individual), water, wade foam, coastline foam
- Potion liquid recolor / tint passes drawn in the lit world
Compose effects **before** darkness when possible: tint/foam/recolor first, then `mix(rgb, vec3(0.0), darkness)`.
## Exempt (unlit)
- Bloom-layer sprites (`RENDER_LAYER_BLOOM` / bloom companions)
- Explicitly unlit utilities (chunk edges, editor overlays, UI chrome)
- Pure UI elements not drawn through the world lit pipeline (DOM inventory panels may tint without world darkness; world-dropped potions still must darken)
```text
# ❌ BAD — fancy tint ignores night
rgb = mix(rgb, potionColor, 1.0);
gl_FragColor = vec4(rgb, a);
# ✅ GOOD — tint then darkness
rgb = mix(rgb, potionColor, fill);
rgb = mix(rgb, vec3(0.0), u_darkness);
gl_FragColor = vec4(rgb, a);
```
When adding a new fragment shader for the game world, default to respecting darkness; document any unlit exception in code comments.
@@ -0,0 +1,35 @@---description: All world/item shaders must respect night darkness unless unlit or bloom.alwaysApply: true---# Shaders respect darknessLit world and item shaders **must** apply the scene darkness value (e.g. `u_darkness` / ambient night darkening) unless explicitly exempt.## Must darken- Entity sprites, equipment overlays, ground items- Ground/block tiles (atlas or individual), water, wade foam, coastline foam- Potion liquid recolor / tint passes drawn in the lit worldCompose effects **before** darkness when possible: tint/foam/recolor first, then `mix(rgb, vec3(0.0), darkness)`.## Exempt (unlit)- Bloom-layer sprites (`RENDER_LAYER_BLOOM` / bloom companions)- Explicitly unlit utilities (chunk edges, editor overlays, UI chrome)- Pure UI elements not drawn through the world lit pipeline (DOM inventory panels may tint without world darkness; world-dropped potions still must darken)```text# ❌ BAD — fancy tint ignores nightrgb = mix(rgb, potionColor, 1.0);gl_FragColor = vec4(rgb, a);# ✅ GOOD — tint then darknessrgb = mix(rgb, potionColor, fill);rgb = mix(rgb, vec3(0.0), u_darkness);gl_FragColor = vec4(rgb, a);```When adding a new fragment shader for the game world, default to respecting darkness; document any unlit exception in code comments.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.
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#6a40a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">AL</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#6a40a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">AL</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#3a8a48"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">HB</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#3a8a48"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">HB</text></svg>@@ -172,6 +172,40 @@
</div>
</aside>
<div id="cauldron-backdrop" class="modal-backdrop" hidden></div>
<aside id="cauldron-panel" hidden>
<header>
<h2>Cauldron</h2>
<button id="cauldron-close" type="button">Close</button>
</header>
<div id="cauldron-slots" class="cauldron-slots"></div>
<div id="cauldron-inserts" class="cauldron-inserts"></div>
<div class="cauldron-vessel" aria-hidden="true">⚗</div>
<div class="cauldron-actions">
<button id="cauldron-stir" type="button">Stir</button>
<button id="cauldron-heat" type="button">Heat</button>
<button id="cauldron-cool" type="button">Cool</button>
</div>
<div class="cauldron-finish">
<button id="cauldron-bottle" type="button">Bottle</button>
<button id="cauldron-clear" type="button">Clear</button>
<button id="cauldron-save-recipe" type="button" hidden>Save Recipe</button>
</div>
<ol id="cauldron-steps" class="cauldron-steps"></ol>
<p id="cauldron-status" class="hint"></p>
</aside>
<div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div>
<aside id="cauldron-pick-panel" hidden>
<header>
<h2>Choose ingredient</h2>
<button id="cauldron-pick-cancel" type="button">Cancel</button>
</header>
<div id="cauldron-pick-list" class="cauldron-pick-list"></div>
<label class="cauldron-pick-qty">Quantity <input id="cauldron-pick-qty" type="number" min="1" value="1"></label>
<button id="cauldron-pick-confirm" type="button">Place in slot</button>
</aside>
<div id="nametag" hidden></div>
<div id="damage-numbers"></div>
<div id="chat-bubbles"></div>
@@ -172,6 +172,40 @@ </div> </div> </aside> </aside> <div id="cauldron-backdrop" class="modal-backdrop" hidden></div> <aside id="cauldron-panel" hidden> <header> <h2>Cauldron</h2> <button id="cauldron-close" type="button">Close</button> </header> <div id="cauldron-slots" class="cauldron-slots"></div> <div id="cauldron-inserts" class="cauldron-inserts"></div> <div class="cauldron-vessel" aria-hidden="true">⚗</div> <div class="cauldron-actions"> <button id="cauldron-stir" type="button">Stir</button> <button id="cauldron-heat" type="button">Heat</button> <button id="cauldron-cool" type="button">Cool</button> </div> <div class="cauldron-finish"> <button id="cauldron-bottle" type="button">Bottle</button> <button id="cauldron-clear" type="button">Clear</button> <button id="cauldron-save-recipe" type="button" hidden>Save Recipe</button> </div> <ol id="cauldron-steps" class="cauldron-steps"></ol> <p id="cauldron-status" class="hint"></p> </aside> <div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div> <aside id="cauldron-pick-panel" hidden> <header> <h2>Choose ingredient</h2> <button id="cauldron-pick-cancel" type="button">Cancel</button> </header> <div id="cauldron-pick-list" class="cauldron-pick-list"></div> <label class="cauldron-pick-qty">Quantity <input id="cauldron-pick-qty" type="number" min="1" value="1"></label> <button id="cauldron-pick-confirm" type="button">Place in slot</button> </aside> <div id="nametag" hidden></div> <div id="nametag" hidden></div> <div id="damage-numbers"></div> <div id="damage-numbers"></div> <div id="chat-bubbles"></div> <div id="chat-bubbles"></div>@@ -21,7 +21,9 @@ const labels = {
crafting: "CR",
leatherworking: "LW",
tailoring: "TL",
cooking: "CK"
cooking: "CK",
herbalism: "HB",
alchemy: "AL"
};
const colors = {
@@ -44,7 +46,9 @@ const colors = {
crafting: "#806080",
leatherworking: "#8a6040",
tailoring: "#7070a0",
cooking: "#a06030"
cooking: "#a06030",
herbalism: "#3a8a48",
alchemy: "#6a40a0"
};
mkdirSync(new URL("../assets/skills/", import.meta.url), { recursive: true });
@@ -21,7 +21,9 @@ const labels = { crafting: "CR", crafting: "CR", leatherworking: "LW", leatherworking: "LW", tailoring: "TL", tailoring: "TL", cooking: "CK" cooking: "CK", herbalism: "HB", alchemy: "AL"};};const colors = {const colors = {@@ -44,7 +46,9 @@ const colors = { crafting: "#806080", crafting: "#806080", leatherworking: "#8a6040", leatherworking: "#8a6040", tailoring: "#7070a0", tailoring: "#7070a0", cooking: "#a06030" cooking: "#a06030", herbalism: "#3a8a48", alchemy: "#6a40a0"};};mkdirSync(new URL("../assets/skills/", import.meta.url), { recursive: true });mkdirSync(new URL("../assets/skills/", import.meta.url), { recursive: true });@@ -53,6 +53,39 @@ overlay(join(root, "items", "lantern", "lantern-equip.png"), [200, 130, 48, 230]
torchBloom(join(root, "items", "lantern", "lantern-equip-bloom.png"));
torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
function writeWaterSheet (file, base, wave, foam)
{
const frames = 4;
const width = 16 * frames;
const height = 16;
const image = makeRgba(width, height, base);
for (let f = 0; f < frames; f++)
{
const ox = f * 16;
for (let y = 0; y < 16; y++)
{
const t = y / 15;
fillRect(image, ox, y, 16, 1, [
Math.round(base[0] * (1 - t * 0.15)),
Math.round(base[1] * (1 - t * 0.08)),
Math.round(base[2] * (1 + t * 0.05)),
255
]);
}
for (let i = 0; i < 3; i++)
{
const y = 3 + ((i * 4 + f) % 10);
const x0 = ox + ((f * 3 + i * 5) % 12);
fillRect(image, x0, y, 5, 1, wave);
fillRect(image, x0 + 1, y - 1, 3, 1, foam);
}
}
writeRgbaPng(file, width, height, image.pixels);
}
writeWaterSheet(join(root, "grounds", "water", "water.png"), [48, 118, 168, 255], [90, 170, 210, 255], [170, 220, 240, 220]);
writeWaterSheet(join(root, "grounds", "deep-water", "deep-water.png"), [28, 72, 118, 255], [55, 120, 170, 255], [110, 170, 210, 200]);
{
const image = makeRgba(24, 8, [0, 0, 0, 0]);
fillRect(image, 1, 2, 22, 4, [240, 220, 160, 220]);
@@ -53,6 +53,39 @@ overlay(join(root, "items", "lantern", "lantern-equip.png"), [200, 130, 48, 230]torchBloom(join(root, "items", "lantern", "lantern-equip-bloom.png"));torchBloom(join(root, "items", "lantern", "lantern-equip-bloom.png"));torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));function writeWaterSheet (file, base, wave, foam){ const frames = 4; const width = 16 * frames; const height = 16; const image = makeRgba(width, height, base); for (let f = 0; f < frames; f++) { const ox = f * 16; for (let y = 0; y < 16; y++) { const t = y / 15; fillRect(image, ox, y, 16, 1, [ Math.round(base[0] * (1 - t * 0.15)), Math.round(base[1] * (1 - t * 0.08)), Math.round(base[2] * (1 + t * 0.05)), 255 ]); } for (let i = 0; i < 3; i++) { const y = 3 + ((i * 4 + f) % 10); const x0 = ox + ((f * 3 + i * 5) % 12); fillRect(image, x0, y, 5, 1, wave); fillRect(image, x0 + 1, y - 1, 3, 1, foam); } } writeRgbaPng(file, width, height, image.pixels);}writeWaterSheet(join(root, "grounds", "water", "water.png"), [48, 118, 168, 255], [90, 170, 210, 255], [170, 220, 240, 220]);writeWaterSheet(join(root, "grounds", "deep-water", "deep-water.png"), [28, 72, 118, 255], [55, 120, 170, 255], [110, 170, 210, 200]);{{ const image = makeRgba(24, 8, [0, 0, 0, 0]); const image = makeRgba(24, 8, [0, 0, 0, 0]); fillRect(image, 1, 2, 22, 4, [240, 220, 160, 220]); fillRect(image, 1, 2, 22, 4, [240, 220, 160, 220]);@@ -0,0 +1,248 @@
import {
itemDefinition,
itemDisplayName,
itemAssetPathForStack,
formatQuantity,
ItemId
} from "/shared/definitions/items.js";
import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "/shared/definitions/alchemy.js";
import { applyItemIcon } from "../render/potionIcon.js";
export function initAlchemy ({
socket,
MessageType,
getInventorySlots
})
{
const backdrop = document.getElementById("cauldron-backdrop");
const panel = document.getElementById("cauldron-panel");
const slotsEl = document.getElementById("cauldron-slots");
const insertsEl = document.getElementById("cauldron-inserts");
const stepsEl = document.getElementById("cauldron-steps");
const statusEl = document.getElementById("cauldron-status");
const saveBtn = document.getElementById("cauldron-save-recipe");
const pickBackdrop = document.getElementById("cauldron-pick-backdrop");
const pickPanel = document.getElementById("cauldron-pick-panel");
const pickList = document.getElementById("cauldron-pick-list");
const pickQty = document.getElementById("cauldron-pick-qty");
let open = false;
let state = null;
let pickSlotIndex = null;
let pickItemId = null;
document.getElementById("cauldron-close")?.addEventListener("click", () => close());
backdrop?.addEventListener("click", () => close());
document.getElementById("cauldron-stir")?.addEventListener("click", () =>
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.stir }); });
document.getElementById("cauldron-heat")?.addEventListener("click", () =>
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.heat }); });
document.getElementById("cauldron-cool")?.addEventListener("click", () =>
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.cool }); });
document.getElementById("cauldron-bottle")?.addEventListener("click", () =>
{ socket.send({ type: MessageType.cauldronBottle }); });
document.getElementById("cauldron-clear")?.addEventListener("click", () =>
{ socket.send({ type: MessageType.cauldronClear }); });
saveBtn?.addEventListener("click", () =>
{ socket.send({ type: MessageType.cauldronSaveRecipe }); });
document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick());
document.getElementById("cauldron-pick-confirm")?.addEventListener("click", () => confirmPick());
pickBackdrop?.addEventListener("click", () => closePick());
function render ()
{
if (!open || !panel)
{ return; }
renderSlots();
renderSteps();
if (saveBtn)
{ saveBtn.hidden = !state?.canSaveRecipe; }
}
function renderSlots ()
{
slotsEl.replaceChildren();
insertsEl.replaceChildren();
for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
{
const reserved = state?.slots?.[i] ?? null;
const slotBtn = document.createElement("button");
slotBtn.type = "button";
slotBtn.className = "cauldron-slot";
if (reserved)
{
const img = document.createElement("img");
const stack = { itemId: reserved.itemId, quantity: reserved.quantity };
applyItemIcon(img, stack, itemAssetPathForStack(stack));
img.alt = itemDisplayName(stack);
const qty = document.createElement("span");
qty.className = "qty";
qty.textContent = formatQuantity(reserved.quantity);
slotBtn.append(img, qty);
slotBtn.title = `${itemDisplayName(stack)} ×${reserved.quantity}`;
}
else
{ slotBtn.textContent = "+"; }
slotBtn.addEventListener("click", () => openPick(i));
slotsEl.append(slotBtn);
const insertBtn = document.createElement("button");
insertBtn.type = "button";
insertBtn.className = "cauldron-insert";
insertBtn.textContent = "↓";
insertBtn.disabled = !reserved;
insertBtn.title = "Insert into cauldron";
insertBtn.addEventListener("click", () =>
{ socket.send({ type: MessageType.cauldronInsert, slotIndex: i }); });
insertsEl.append(insertBtn);
}
}
function renderSteps ()
{
stepsEl.replaceChildren();
for (const step of state?.steps ?? [])
{
const li = document.createElement("li");
if (step.kind === AlchemyStepKind.insert)
{
const def = itemDefinition(step.itemId);
li.textContent = `insert ${def?.displayName ?? step.itemId}`;
}
else
{ li.textContent = step.kind; }
stepsEl.append(li);
}
}
function openPick (slotIndex)
{
pickSlotIndex = slotIndex;
pickItemId = null;
pickList.replaceChildren();
const counts = new Map();
for (const slot of getInventorySlots?.() ?? [])
{
if (!slot)
{ continue; }
const def = itemDefinition(slot.itemId);
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));
}
for (const [itemId, quantity] of counts)
{
const stack = { itemId, quantity };
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)})`;
btn.append(img, label);
btn.addEventListener("click", () =>
{
pickItemId = itemId;
pickQty.max = String(quantity);
pickQty.value = String(Math.min(quantity, Number(pickQty.value) || 1));
for (const child of pickList.children)
{ child.classList.toggle("selected", child === btn); }
});
pickList.append(btn);
}
pickQty.value = "1";
pickBackdrop.hidden = false;
pickPanel.hidden = false;
}
function closePick ()
{
pickBackdrop.hidden = true;
pickPanel.hidden = true;
pickSlotIndex = null;
pickItemId = null;
}
function confirmPick ()
{
if (pickSlotIndex == null || pickItemId == null)
{ return; }
const quantity = Math.max(1, pickQty.value | 0);
socket.send({
type: MessageType.cauldronSetSlot,
slotIndex: pickSlotIndex,
itemId: pickItemId,
quantity
});
closePick();
}
function openFromServer (nextState)
{
open = true;
state = nextState;
backdrop.hidden = false;
panel.hidden = false;
statusEl.textContent = "";
render();
}
function close ()
{
if (!open)
{ return; }
open = false;
backdrop.hidden = true;
panel.hidden = true;
closePick();
socket.send({ type: MessageType.cauldronClose });
}
return {
isBlocking ()
{ return open || !pickPanel?.hidden; },
reset ()
{
open = false;
state = null;
if (backdrop)
{ backdrop.hidden = true; }
if (panel)
{ panel.hidden = true; }
closePick();
},
handleSnapshot (message)
{
if (!message.open)
{
open = false;
if (backdrop)
{ backdrop.hidden = true; }
if (panel)
{ panel.hidden = true; }
state = null;
return;
}
if (!open)
{ openFromServer(message.state); }
else
{
state = message.state;
render();
}
if (message.alchemyResult)
{
const result = message.alchemyResult;
const name = result.potion?.displayName ?? "Potion";
const lost = result.lost > 0 ? ` (${result.lost} lost — not enough bottles)` : "";
statusEl.textContent = result.success
? `Bottled ${result.produced}× ${name}${lost}.`
: `Unstable brew: ${result.produced}× ${name}${lost}.`;
}
},
refresh ()
{ render(); }
};
}
@@ -0,0 +1,248 @@import { itemDefinition, itemDisplayName, itemAssetPathForStack, formatQuantity, ItemId} from "/shared/definitions/items.js";import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "/shared/definitions/alchemy.js";import { applyItemIcon } from "../render/potionIcon.js";export function initAlchemy ({ socket, MessageType, getInventorySlots}){ const backdrop = document.getElementById("cauldron-backdrop"); const panel = document.getElementById("cauldron-panel"); const slotsEl = document.getElementById("cauldron-slots"); const insertsEl = document.getElementById("cauldron-inserts"); const stepsEl = document.getElementById("cauldron-steps"); const statusEl = document.getElementById("cauldron-status"); const saveBtn = document.getElementById("cauldron-save-recipe"); const pickBackdrop = document.getElementById("cauldron-pick-backdrop"); const pickPanel = document.getElementById("cauldron-pick-panel"); const pickList = document.getElementById("cauldron-pick-list"); const pickQty = document.getElementById("cauldron-pick-qty"); let open = false; let state = null; let pickSlotIndex = null; let pickItemId = null; document.getElementById("cauldron-close")?.addEventListener("click", () => close()); backdrop?.addEventListener("click", () => close()); document.getElementById("cauldron-stir")?.addEventListener("click", () => { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.stir }); }); document.getElementById("cauldron-heat")?.addEventListener("click", () => { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.heat }); }); document.getElementById("cauldron-cool")?.addEventListener("click", () => { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.cool }); }); document.getElementById("cauldron-bottle")?.addEventListener("click", () => { socket.send({ type: MessageType.cauldronBottle }); }); document.getElementById("cauldron-clear")?.addEventListener("click", () => { socket.send({ type: MessageType.cauldronClear }); }); saveBtn?.addEventListener("click", () => { socket.send({ type: MessageType.cauldronSaveRecipe }); }); document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick()); document.getElementById("cauldron-pick-confirm")?.addEventListener("click", () => confirmPick()); pickBackdrop?.addEventListener("click", () => closePick()); function render () { if (!open || !panel) { return; } renderSlots(); renderSteps(); if (saveBtn) { saveBtn.hidden = !state?.canSaveRecipe; } } function renderSlots () { slotsEl.replaceChildren(); insertsEl.replaceChildren(); for (let i = 0; i < CAULDRON_SLOT_COUNT; i++) { const reserved = state?.slots?.[i] ?? null; const slotBtn = document.createElement("button"); slotBtn.type = "button"; slotBtn.className = "cauldron-slot"; if (reserved) { const img = document.createElement("img"); const stack = { itemId: reserved.itemId, quantity: reserved.quantity }; applyItemIcon(img, stack, itemAssetPathForStack(stack)); img.alt = itemDisplayName(stack); const qty = document.createElement("span"); qty.className = "qty"; qty.textContent = formatQuantity(reserved.quantity); slotBtn.append(img, qty); slotBtn.title = `${itemDisplayName(stack)} ×${reserved.quantity}`; } else { slotBtn.textContent = "+"; } slotBtn.addEventListener("click", () => openPick(i)); slotsEl.append(slotBtn); const insertBtn = document.createElement("button"); insertBtn.type = "button"; insertBtn.className = "cauldron-insert"; insertBtn.textContent = "↓"; insertBtn.disabled = !reserved; insertBtn.title = "Insert into cauldron"; insertBtn.addEventListener("click", () => { socket.send({ type: MessageType.cauldronInsert, slotIndex: i }); }); insertsEl.append(insertBtn); } } function renderSteps () { stepsEl.replaceChildren(); for (const step of state?.steps ?? []) { const li = document.createElement("li"); if (step.kind === AlchemyStepKind.insert) { const def = itemDefinition(step.itemId); li.textContent = `insert ${def?.displayName ?? step.itemId}`; } else { li.textContent = step.kind; } stepsEl.append(li); } } function openPick (slotIndex) { pickSlotIndex = slotIndex; pickItemId = null; pickList.replaceChildren(); const counts = new Map(); for (const slot of getInventorySlots?.() ?? []) { if (!slot) { continue; } const def = itemDefinition(slot.itemId); 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)); } for (const [itemId, quantity] of counts) { const stack = { itemId, quantity }; 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)})`; btn.append(img, label); btn.addEventListener("click", () => { pickItemId = itemId; pickQty.max = String(quantity); pickQty.value = String(Math.min(quantity, Number(pickQty.value) || 1)); for (const child of pickList.children) { child.classList.toggle("selected", child === btn); } }); pickList.append(btn); } pickQty.value = "1"; pickBackdrop.hidden = false; pickPanel.hidden = false; } function closePick () { pickBackdrop.hidden = true; pickPanel.hidden = true; pickSlotIndex = null; pickItemId = null; } function confirmPick () { if (pickSlotIndex == null || pickItemId == null) { return; } const quantity = Math.max(1, pickQty.value | 0); socket.send({ type: MessageType.cauldronSetSlot, slotIndex: pickSlotIndex, itemId: pickItemId, quantity }); closePick(); } function openFromServer (nextState) { open = true; state = nextState; backdrop.hidden = false; panel.hidden = false; statusEl.textContent = ""; render(); } function close () { if (!open) { return; } open = false; backdrop.hidden = true; panel.hidden = true; closePick(); socket.send({ type: MessageType.cauldronClose }); } return { isBlocking () { return open || !pickPanel?.hidden; }, reset () { open = false; state = null; if (backdrop) { backdrop.hidden = true; } if (panel) { panel.hidden = true; } closePick(); }, handleSnapshot (message) { if (!message.open) { open = false; if (backdrop) { backdrop.hidden = true; } if (panel) { panel.hidden = true; } state = null; return; } if (!open) { openFromServer(message.state); } else { state = message.state; render(); } if (message.alchemyResult) { const result = message.alchemyResult; const name = result.potion?.displayName ?? "Potion"; const lost = result.lost > 0 ? ` (${result.lost} lost — not enough bottles)` : ""; statusEl.textContent = result.success ? `Bottled ${result.produced}× ${name}${lost}.` : `Unstable brew: ${result.produced}× ${name}${lost}.`; } }, refresh () { render(); } };}@@ -9,6 +9,7 @@ import {
EQUIPMENT_SLOT,
LETTER_MAX_BODY_CHARS
} from "/shared/definitions/items.js";
import { applyItemIcon } from "../render/potionIcon.js";
const EQUIP_LABELS = {
[EQUIPMENT_SLOT.head]: "Head",
@@ -156,7 +157,7 @@ export function initInventory ({
{
const def = itemDefinition(slot.itemId);
const img = document.createElement("img");
img.src = itemAssetPathForStack(slot);
applyItemIcon(img, slot, itemAssetPathForStack(slot));
img.alt = itemDisplayName(slot);
button.append(img);
if (slot.quantity > 1)
@@ -206,7 +207,7 @@ export function initInventory ({
{
const def = itemDefinition(worn.itemId);
const img = document.createElement("img");
img.src = itemAssetPathForStack(worn);
applyItemIcon(img, worn, itemAssetPathForStack(worn));
img.alt = itemDisplayName(worn);
button.append(img);
}
@@ -264,6 +265,20 @@ export function initInventory ({
});
}
}
if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper")
{
items.push({
label: "Read",
onSelect: () => openLetter({
mode: "read",
slotIndex,
instance: {
body: slot.instance.body ?? "",
authorDisplayName: slot.instance.displayName ?? "Alchemy recipe"
}
})
});
}
if (slot.itemId === ItemId.blankCheque)
{
items.push({
@@ -459,7 +474,7 @@ export function initInventory ({
button.title = tooltip(slot);
const def = itemDefinition(slot.itemId);
const img = document.createElement("img");
img.src = itemAssetPathForStack(slot);
applyItemIcon(img, slot, itemAssetPathForStack(slot));
img.alt = itemDisplayName(slot);
button.append(img);
if (slot.quantity > 1)
@@ -531,7 +546,11 @@ export function initInventory ({
maxQty: slot.quantity | 0,
destination: null
};
document.getElementById("send-item-img").src = itemAssetPathForStack(slot);
applyItemIcon(
document.getElementById("send-item-img"),
slot,
itemAssetPathForStack(slot)
);
document.getElementById("send-item-name").textContent = itemDisplayName(slot);
const qtyInput = document.getElementById("send-qty");
qtyInput.value = "1";
@@ -717,7 +736,7 @@ export function initInventory ({
button.title = tooltip(slot);
const def = itemDefinition(slot.itemId);
const img = document.createElement("img");
img.src = itemAssetPathForStack(slot);
applyItemIcon(img, slot, itemAssetPathForStack(slot));
img.alt = itemDisplayName(slot);
button.append(img);
if (slot.quantity > 1)
@@ -9,6 +9,7 @@ import { EQUIPMENT_SLOT, EQUIPMENT_SLOT, LETTER_MAX_BODY_CHARS LETTER_MAX_BODY_CHARS} from "/shared/definitions/items.js";} from "/shared/definitions/items.js";import { applyItemIcon } from "../render/potionIcon.js";const EQUIP_LABELS = {const EQUIP_LABELS = { [EQUIPMENT_SLOT.head]: "Head", [EQUIPMENT_SLOT.head]: "Head",@@ -156,7 +157,7 @@ export function initInventory ({ { { const def = itemDefinition(slot.itemId); const def = itemDefinition(slot.itemId); const img = document.createElement("img"); const img = document.createElement("img"); img.src = itemAssetPathForStack(slot); applyItemIcon(img, slot, itemAssetPathForStack(slot)); img.alt = itemDisplayName(slot); img.alt = itemDisplayName(slot); button.append(img); button.append(img); if (slot.quantity > 1) if (slot.quantity > 1)@@ -206,7 +207,7 @@ export function initInventory ({ { { const def = itemDefinition(worn.itemId); const def = itemDefinition(worn.itemId); const img = document.createElement("img"); const img = document.createElement("img"); img.src = itemAssetPathForStack(worn); applyItemIcon(img, worn, itemAssetPathForStack(worn)); img.alt = itemDisplayName(worn); img.alt = itemDisplayName(worn); button.append(img); button.append(img); } }@@ -264,6 +265,20 @@ export function initInventory ({ }); }); } } } } if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper") { items.push({ label: "Read", onSelect: () => openLetter({ mode: "read", slotIndex, instance: { body: slot.instance.body ?? "", authorDisplayName: slot.instance.displayName ?? "Alchemy recipe" } }) }); } if (slot.itemId === ItemId.blankCheque) if (slot.itemId === ItemId.blankCheque) { { items.push({ items.push({@@ -459,7 +474,7 @@ export function initInventory ({ button.title = tooltip(slot); button.title = tooltip(slot); const def = itemDefinition(slot.itemId); const def = itemDefinition(slot.itemId); const img = document.createElement("img"); const img = document.createElement("img"); img.src = itemAssetPathForStack(slot); applyItemIcon(img, slot, itemAssetPathForStack(slot)); img.alt = itemDisplayName(slot); img.alt = itemDisplayName(slot); button.append(img); button.append(img); if (slot.quantity > 1) if (slot.quantity > 1)@@ -531,7 +546,11 @@ export function initInventory ({ maxQty: slot.quantity | 0, maxQty: slot.quantity | 0, destination: null destination: null }; }; document.getElementById("send-item-img").src = itemAssetPathForStack(slot); applyItemIcon( document.getElementById("send-item-img"), slot, itemAssetPathForStack(slot) ); document.getElementById("send-item-name").textContent = itemDisplayName(slot); document.getElementById("send-item-name").textContent = itemDisplayName(slot); const qtyInput = document.getElementById("send-qty"); const qtyInput = document.getElementById("send-qty"); qtyInput.value = "1"; qtyInput.value = "1";@@ -717,7 +736,7 @@ export function initInventory ({ button.title = tooltip(slot); button.title = tooltip(slot); const def = itemDefinition(slot.itemId); const def = itemDefinition(slot.itemId); const img = document.createElement("img"); const img = document.createElement("img"); img.src = itemAssetPathForStack(slot); applyItemIcon(img, slot, itemAssetPathForStack(slot)); img.alt = itemDisplayName(slot); img.alt = itemDisplayName(slot); button.append(img); button.append(img); if (slot.quantity > 1) if (slot.quantity > 1)@@ -8,6 +8,7 @@ import { initChat } from "./chat.js";
import { initInventory } from "./inventory.js";
import { initSkills } from "./skills.js";
import { initCrafting } from "./crafting.js";
import { initAlchemy } from "./alchemy.js";
import { initContextMenu } from "./contextMenu.js";
import { initDeath } from "./death.js";
import { CraftingStationId } from "/shared/definitions/craftingStations.js";
@@ -32,10 +33,11 @@ let chat;
let inventory;
let skills;
let crafting;
let alchemy;
let contextMenu;
let death;
let pendingPickup = null;
/** @type {{ kind: "bank", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
/** @type {{ kind: "bank" | "cauldron", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
let pendingInteract = null;
/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
let leftClickConsumed = false;
@@ -77,7 +79,7 @@ function renderCharacters (characters)
function uiBlocked ()
{
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
|| crafting?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
|| crafting?.isBlocking() || alchemy?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
}
function clearPendingPickup ()
@@ -128,10 +130,24 @@ function approachAdjacentTile (tileX, tileY)
function requestOpenBank (tileX, tileY, { getCheques = false } = {})
{
clearPendingPickup();
clearAllPendingActions();
pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
if (approachAdjacentTile(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 requestOpenCauldron (tileX, tileY)
{
clearAllPendingActions();
pendingInteract = { kind: "cauldron", 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)
@@ -168,6 +184,15 @@ function flushPendingInteract ()
return;
}
if (pendingInteract.kind === "cauldron")
{
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
{ return; }
socket.send({ type: MessageType.openCauldron });
clearPendingInteract();
return;
}
if (pendingInteract.kind === "talk")
{
const target = view.entities.get(pendingInteract.targetEntityId);
@@ -273,6 +298,8 @@ function handleLeftClick (mouseX, mouseY)
{ requestPickup(ground); }
else if (isBankTile(view, tile.tileX, tile.tileY))
{ requestOpenBank(tile.tileX, tile.tileY); }
else if (isCauldronTile(view, tile.tileX, tile.tileY))
{ requestOpenCauldron(tile.tileX, tile.tileY); }
else
{
clearAllPendingActions();
@@ -357,6 +384,14 @@ function handleRightClick (event, mouseX, mouseY)
});
}
if (isCauldronTile(view, tile.tileX, tile.tileY))
{
items.push({
label: "Alchemy",
onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
});
}
contextMenu.show(event.clientX, event.clientY, items);
}
@@ -503,6 +538,14 @@ async function main ()
return skills?.skillLevel?.(skillId) ?? 1;
}
});
alchemy = initAlchemy({
socket: { send (payload) { socket.send(payload); } },
MessageType,
getInventorySlots ()
{
return inventory?.getInventorySlots?.() ?? [];
}
});
chat = initChat({
socket: { send (payload) { socket.send(payload); } },
MessageType,
@@ -564,6 +607,7 @@ async function main ()
case MessageType.inventory:
inventory?.handleInventory(message);
crafting?.refresh();
alchemy?.refresh();
break;
case MessageType.skills:
skills?.render(message.skills);
@@ -572,6 +616,9 @@ async function main ()
case MessageType.bankSnapshot:
inventory?.handleBank(message);
break;
case MessageType.cauldronSnapshot:
alchemy?.handleSnapshot(message);
break;
case MessageType.pigeonDispatched:
inventory?.handlePigeonDispatched(message);
break;
@@ -648,6 +695,7 @@ function returnToMenu (reason = "")
chat?.reset();
inventory?.reset();
crafting?.reset();
alchemy?.reset();
skills?.hide();
contextMenu?.hide();
death?.reset();
@@ -690,15 +738,25 @@ main().catch((error) =>
});
function isBankTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.bank;
}
function isCauldronTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
}
function blockTypeAt (view, tileX, tileY)
{
const chunkX = Math.floor(tileX / CHUNK_SIZE);
const chunkY = Math.floor(tileY / CHUNK_SIZE);
const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
if (!snapshot)
{ return false; }
{ return null; }
const localX = tileX - chunkX * CHUNK_SIZE;
const localY = tileY - chunkY * CHUNK_SIZE;
return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId === BlockType.bank;
return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId ?? null;
}
function chebyshev (ax, ay, bx, by)
@@ -8,6 +8,7 @@ import { initChat } from "./chat.js";import { initInventory } from "./inventory.js";import { initInventory } from "./inventory.js";import { initSkills } from "./skills.js";import { initSkills } from "./skills.js";import { initCrafting } from "./crafting.js";import { initCrafting } from "./crafting.js";import { initAlchemy } from "./alchemy.js";import { initContextMenu } from "./contextMenu.js";import { initContextMenu } from "./contextMenu.js";import { initDeath } from "./death.js";import { initDeath } from "./death.js";import { CraftingStationId } from "/shared/definitions/craftingStations.js";import { CraftingStationId } from "/shared/definitions/craftingStations.js";@@ -32,10 +33,11 @@ let chat;let inventory;let inventory;let skills;let skills;let crafting;let crafting;let alchemy;let contextMenu;let contextMenu;let death;let death;let pendingPickup = null;let pendingPickup = null;/** @type {{ kind: "bank", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } *//** @type {{ kind: "bank" | "cauldron", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */let pendingInteract = null;let pendingInteract = null;/** Framework can report mousePressed for two frames; latch so one physical click is one command. *//** Framework can report mousePressed for two frames; latch so one physical click is one command. */let leftClickConsumed = false;let leftClickConsumed = false;@@ -77,7 +79,7 @@ function renderCharacters (characters)function uiBlocked ()function uiBlocked (){{ return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() || crafting?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking()); || crafting?.isBlocking() || alchemy?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());}}function clearPendingPickup ()function clearPendingPickup ()@@ -128,10 +130,24 @@ function approachAdjacentTile (tileX, tileY)function requestOpenBank (tileX, tileY, { getCheques = false } = {})function requestOpenBank (tileX, tileY, { getCheques = false } = {}){{ clearPendingPickup(); clearAllPendingActions(); pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques }; pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques }; if (approachAdjacentTile(tileX, tileY)) const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); }}function requestOpenCauldron (tileX, tileY){ clearAllPendingActions(); pendingInteract = { kind: "cauldron", 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)@@ -168,6 +184,15 @@ function flushPendingInteract () return; return; } } if (pendingInteract.kind === "cauldron") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.openCauldron }); clearPendingInteract(); return; } if (pendingInteract.kind === "talk") if (pendingInteract.kind === "talk") { { const target = view.entities.get(pendingInteract.targetEntityId); const target = view.entities.get(pendingInteract.targetEntityId);@@ -273,6 +298,8 @@ function handleLeftClick (mouseX, mouseY) { requestPickup(ground); } { requestPickup(ground); } else if (isBankTile(view, tile.tileX, tile.tileY)) else if (isBankTile(view, tile.tileX, tile.tileY)) { requestOpenBank(tile.tileX, tile.tileY); } { requestOpenBank(tile.tileX, tile.tileY); } else if (isCauldronTile(view, tile.tileX, tile.tileY)) { requestOpenCauldron(tile.tileX, tile.tileY); } else else { { clearAllPendingActions(); clearAllPendingActions();@@ -357,6 +384,14 @@ function handleRightClick (event, mouseX, mouseY) }); }); } } if (isCauldronTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Alchemy", onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY) }); } contextMenu.show(event.clientX, event.clientY, items); contextMenu.show(event.clientX, event.clientY, items);}}@@ -503,6 +538,14 @@ async function main () return skills?.skillLevel?.(skillId) ?? 1; return skills?.skillLevel?.(skillId) ?? 1; } } }); }); alchemy = initAlchemy({ socket: { send (payload) { socket.send(payload); } }, MessageType, getInventorySlots () { return inventory?.getInventorySlots?.() ?? []; } }); chat = initChat({ chat = initChat({ socket: { send (payload) { socket.send(payload); } }, socket: { send (payload) { socket.send(payload); } }, MessageType, MessageType,@@ -564,6 +607,7 @@ async function main () case MessageType.inventory: case MessageType.inventory: inventory?.handleInventory(message); inventory?.handleInventory(message); crafting?.refresh(); crafting?.refresh(); alchemy?.refresh(); break; break; case MessageType.skills: case MessageType.skills: skills?.render(message.skills); skills?.render(message.skills);@@ -572,6 +616,9 @@ async function main () case MessageType.bankSnapshot: case MessageType.bankSnapshot: inventory?.handleBank(message); inventory?.handleBank(message); break; break; case MessageType.cauldronSnapshot: alchemy?.handleSnapshot(message); break; case MessageType.pigeonDispatched: case MessageType.pigeonDispatched: inventory?.handlePigeonDispatched(message); inventory?.handlePigeonDispatched(message); break; break;@@ -648,6 +695,7 @@ function returnToMenu (reason = "") chat?.reset(); chat?.reset(); inventory?.reset(); inventory?.reset(); crafting?.reset(); crafting?.reset(); alchemy?.reset(); skills?.hide(); skills?.hide(); contextMenu?.hide(); contextMenu?.hide(); death?.reset(); death?.reset();@@ -690,15 +738,25 @@ main().catch((error) =>});});function isBankTile (view, tileX, tileY)function isBankTile (view, tileX, tileY){ return blockTypeAt(view, tileX, tileY) === BlockType.bank;}function isCauldronTile (view, tileX, tileY){ return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;}function blockTypeAt (view, tileX, tileY){{ const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = view.chunks.get(`${chunkX},${chunkY}`); const snapshot = view.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) if (!snapshot) { return false; } { return null; } const localX = tileX - chunkX * CHUNK_SIZE; const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId === BlockType.bank; return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId ?? null;}}function chebyshev (ax, ay, bx, by)function chebyshev (ax, ay, bx, by)@@ -4,7 +4,7 @@ import { bloomImageName, resolveState, spriteImageName } from "/shared/definitio
/**
* Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
* Oversized or animated blocks are returned in `tallBlocks` for individual Y-sorted sprites.
* Oversized or animated blocks/grounds are returned for individual sprites.
*/
export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
{
@@ -26,6 +26,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
}
const tallBlocks = [];
const animatedGrounds = [];
const baseTileX = snapshot.chunkX * CHUNK_SIZE;
const baseTileY = snapshot.chunkY * CHUNK_SIZE;
@@ -49,11 +50,24 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
const dx = localX * SPRITE_SIZE_PX;
const dy = localY * SPRITE_SIZE_PX;
const groundName = groundSpriteName(catalog, groundEntry);
blit(groundCtx, images[groundName], dx, dy);
const groundBloom = groundBloomName(catalog, groundEntry);
if (groundBloom)
{ blit(bloomCtx, images[groundBloom], dx, dy); }
const groundMeta = groundCatalogMeta(catalog, groundEntry);
if (isBakeable(images[groundName], groundMeta))
{
blit(groundCtx, images[groundName], dx, dy);
const groundBloom = groundBloomName(catalog, groundEntry);
if (groundBloom)
{ blit(bloomCtx, images[groundBloom], dx, dy); }
}
else if (groundName)
{
animatedGrounds.push({
tileX,
tileY,
sprite: groundName,
typeId: normalizeGround(groundEntry).typeId,
bloom: groundBloomName(catalog, groundEntry)
});
}
const blockName = blockSpriteName(catalog, blockEntry);
if (!blockName)
@@ -78,7 +92,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
}
}
return { ground, blockRows, bloom, tallBlocks };
return { ground, blockRows, bloom, tallBlocks, animatedGrounds };
}
export function isBakeable (sprite, meta = null)
@@ -178,3 +192,13 @@ function blockCatalogMeta (catalog, block)
{ return null; }
return catalog.blocks?.[def.key] ?? null;
}
function groundCatalogMeta (catalog, ground)
{
const entry = normalizeGround(ground);
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
return catalog.grounds?.[def.key] ?? {
frames: def.frames,
animationSpeed: def.animationSpeed
};
}
@@ -4,7 +4,7 @@ import { bloomImageName, resolveState, spriteImageName } from "/shared/definitio/**/** * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases. * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases. * Oversized or animated blocks are returned in `tallBlocks` for individual Y-sorted sprites. * Oversized or animated blocks/grounds are returned for individual sprites. */ */export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null }){{@@ -26,6 +26,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null }) } } const tallBlocks = []; const tallBlocks = []; const animatedGrounds = []; const baseTileX = snapshot.chunkX * CHUNK_SIZE; const baseTileX = snapshot.chunkX * CHUNK_SIZE; const baseTileY = snapshot.chunkY * CHUNK_SIZE; const baseTileY = snapshot.chunkY * CHUNK_SIZE;@@ -49,11 +50,24 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null }) const dx = localX * SPRITE_SIZE_PX; const dx = localX * SPRITE_SIZE_PX; const dy = localY * SPRITE_SIZE_PX; const dy = localY * SPRITE_SIZE_PX; const groundName = groundSpriteName(catalog, groundEntry); const groundName = groundSpriteName(catalog, groundEntry); blit(groundCtx, images[groundName], dx, dy); const groundMeta = groundCatalogMeta(catalog, groundEntry); if (isBakeable(images[groundName], groundMeta)) const groundBloom = groundBloomName(catalog, groundEntry); { if (groundBloom) blit(groundCtx, images[groundName], dx, dy); { blit(bloomCtx, images[groundBloom], dx, dy); } const groundBloom = groundBloomName(catalog, groundEntry); if (groundBloom) { blit(bloomCtx, images[groundBloom], dx, dy); } } else if (groundName) { animatedGrounds.push({ tileX, tileY, sprite: groundName, typeId: normalizeGround(groundEntry).typeId, bloom: groundBloomName(catalog, groundEntry) }); } const blockName = blockSpriteName(catalog, blockEntry); const blockName = blockSpriteName(catalog, blockEntry); if (!blockName) if (!blockName)@@ -78,7 +92,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null }) } } } } return { ground, blockRows, bloom, tallBlocks }; return { ground, blockRows, bloom, tallBlocks, animatedGrounds };}}export function isBakeable (sprite, meta = null)export function isBakeable (sprite, meta = null)@@ -178,3 +192,13 @@ function blockCatalogMeta (catalog, block) { return null; } { return null; } return catalog.blocks?.[def.key] ?? null; return catalog.blocks?.[def.key] ?? null;}}function groundCatalogMeta (catalog, ground){ const entry = normalizeGround(ground); const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass]; return catalog.grounds?.[def.key] ?? { frames: def.frames, animationSpeed: def.animationSpeed };}@@ -0,0 +1,109 @@
import { ItemId } from "/shared/definitions/items.js";
import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
const bottleCache = new Map();
const fillCache = new Map();
const urlCache = new Map();
function loadImage (src)
{
return new Promise((resolve, reject) =>
{
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error(`Failed to load ${src}`));
img.src = src;
});
}
async function getBottle ()
{
if (!bottleCache.has("bottle"))
{ bottleCache.set("bottle", loadImage("/assets/items/glass-bottle/glass-bottle.png")); }
return bottleCache.get("bottle");
}
async function getFill (level)
{
const key = Math.max(1, Math.min(5, level | 0 || 4));
if (!fillCache.has(key))
{ fillCache.set(key, loadImage(`/assets/items/potion/fill-${key}.png`)); }
return fillCache.get(key);
}
function colorKey (color)
{
if (!color)
{ return "0,0,0"; }
const r = Math.round((color.r ?? 0) * 255);
const g = Math.round((color.g ?? 0) * 255);
const b = Math.round((color.b ?? 0) * 255);
return `${r},${g},${b}`;
}
/**
* Build a data-URL icon: clear bottle + fill mask tinted to potion color.
* UI-only; world ground items use the same bake then lit darkness shader.
*/
export async function potionIconDataUrl (instance)
{
const fillLevel = Math.max(1, Math.min(5, instance?.fillLevel | 0 || 4));
const key = `${fillLevel}|${colorKey(instance?.color)}`;
if (urlCache.has(key))
{ return urlCache.get(key); }
const [bottle, fill] = await Promise.all([getBottle(), getFill(fillLevel)]);
const canvas = document.createElement("canvas");
canvas.width = SPRITE_SIZE_PX;
canvas.height = SPRITE_SIZE_PX;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(fill, 0, 0);
const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = image.data;
const r = Math.round((instance?.color?.r ?? 0.4) * 255);
const g = Math.round((instance?.color?.g ?? 0.4) * 255);
const b = Math.round((instance?.color?.b ?? 0.7) * 255);
for (let i = 0; i < data.length; i += 4)
{
if (data[i + 3] < 8)
{ continue; }
const a = data[i + 3] / 255;
data[i] = r;
data[i + 1] = g;
data[i + 2] = b;
data[i + 3] = Math.round(220 * a);
}
ctx.putImageData(image, 0, 0);
ctx.drawImage(bottle, 0, 0);
const url = canvas.toDataURL("image/png");
urlCache.set(key, url);
return url;
}
export function isPotionStack (stack)
{
return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion";
}
/** Sync helper: set img.src to recolored potion or fall back to asset path. */
export function applyItemIcon (img, stack, fallbackPath)
{
if (!img)
{ return; }
if (!isPotionStack(stack))
{
img.src = fallbackPath;
return;
}
img.src = fallbackPath;
potionIconDataUrl(stack.instance).then((url) =>
{
img.src = url;
}).catch(() =>
{
img.src = fallbackPath;
});
}
@@ -0,0 +1,109 @@import { ItemId } from "/shared/definitions/items.js";import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";const bottleCache = new Map();const fillCache = new Map();const urlCache = new Map();function loadImage (src){ return new Promise((resolve, reject) => { const img = new Image(); img.onload = () => resolve(img); img.onerror = () => reject(new Error(`Failed to load ${src}`)); img.src = src; });}async function getBottle (){ if (!bottleCache.has("bottle")) { bottleCache.set("bottle", loadImage("/assets/items/glass-bottle/glass-bottle.png")); } return bottleCache.get("bottle");}async function getFill (level){ const key = Math.max(1, Math.min(5, level | 0 || 4)); if (!fillCache.has(key)) { fillCache.set(key, loadImage(`/assets/items/potion/fill-${key}.png`)); } return fillCache.get(key);}function colorKey (color){ if (!color) { return "0,0,0"; } const r = Math.round((color.r ?? 0) * 255); const g = Math.round((color.g ?? 0) * 255); const b = Math.round((color.b ?? 0) * 255); return `${r},${g},${b}`;}/** * Build a data-URL icon: clear bottle + fill mask tinted to potion color. * UI-only; world ground items use the same bake then lit darkness shader. */export async function potionIconDataUrl (instance){ const fillLevel = Math.max(1, Math.min(5, instance?.fillLevel | 0 || 4)); const key = `${fillLevel}|${colorKey(instance?.color)}`; if (urlCache.has(key)) { return urlCache.get(key); } const [bottle, fill] = await Promise.all([getBottle(), getFill(fillLevel)]); const canvas = document.createElement("canvas"); canvas.width = SPRITE_SIZE_PX; canvas.height = SPRITE_SIZE_PX; const ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(fill, 0, 0); const image = ctx.getImageData(0, 0, canvas.width, canvas.height); const data = image.data; const r = Math.round((instance?.color?.r ?? 0.4) * 255); const g = Math.round((instance?.color?.g ?? 0.4) * 255); const b = Math.round((instance?.color?.b ?? 0.7) * 255); for (let i = 0; i < data.length; i += 4) { if (data[i + 3] < 8) { continue; } const a = data[i + 3] / 255; data[i] = r; data[i + 1] = g; data[i + 2] = b; data[i + 3] = Math.round(220 * a); } ctx.putImageData(image, 0, 0); ctx.drawImage(bottle, 0, 0); const url = canvas.toDataURL("image/png"); urlCache.set(key, url); return url;}export function isPotionStack (stack){ return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion";}/** Sync helper: set img.src to recolored potion or fall back to asset path. */export function applyItemIcon (img, stack, fallbackPath){ if (!img) { return; } if (!isPotionStack(stack)) { img.src = fallbackPath; return; } img.src = fallbackPath; potionIconDataUrl(stack.instance).then((url) => { img.src = url; }).catch(() => { img.src = fallbackPath; });}@@ -3,6 +3,7 @@ import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js"
import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
import { itemSpriteName } from "/shared/definitions/items.js";
import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
import { bakeChunkAtlases } from "./chunkBake.js";
import {
@@ -34,15 +35,75 @@ const SPRITE_LIGHTING_FRAG = [
"uniform sampler2D u_texture;",
"uniform float u_darkness;",
"uniform float u_strength;",
"uniform float u_wade;",
"uniform float u_spriteHeight;",
"void main() {",
" vec4 color = texture2D(u_texture, v_texCoord);",
" if (color.a <= 0.0) { discard; }",
" vec3 rgb = mix(color.rgb, vec3(0.0), u_darkness);",
" float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
" if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
" vec3 rgb = color.rgb;",
" if (u_wade > 0.5 && fromBottom < 5.0) {",
" rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
" }",
" rgb = mix(rgb, vec3(0.0), u_darkness);",
" rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
" gl_FragColor = vec4(rgb, color.a);",
"}"
].join("\n");
const WATER_GROUND_FRAG = [
"precision mediump float;",
"varying vec2 v_texCoord;",
"uniform sampler2D u_texture;",
"uniform float u_darkness;",
"uniform float u_time;",
"uniform float u_edgeN;",
"uniform float u_edgeE;",
"uniform float u_edgeS;",
"uniform float u_edgeW;",
"void main() {",
" vec4 color = texture2D(u_texture, v_texCoord);",
" if (color.a <= 0.0) { discard; }",
" vec3 rgb = color.rgb;",
" float foam = 0.0;",
" float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);",
" if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {",
" foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);",
" }",
" if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {",
" foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);",
" }",
" if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {",
" foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);",
" }",
" if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {",
" foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
" }",
" rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
" rgb = mix(rgb, vec3(0.0), u_darkness);",
" gl_FragColor = vec4(rgb, color.a);",
"}"
].join("\n");
/** Potion bottle: recolor near-white liquid, then apply night darkness. */
const POTION_SPRITE_FRAG = [
"precision mediump float;",
"varying vec2 v_texCoord;",
"uniform sampler2D u_texture;",
"uniform float u_darkness;",
"uniform vec3 u_potionColor;",
"void main() {",
" vec4 color = texture2D(u_texture, v_texCoord);",
" if (color.a <= 0.0) { discard; }",
" vec3 rgb = color.rgb;",
" float liquid = step(0.95, min(min(color.r, color.g), color.b));",
" rgb = mix(rgb, u_potionColor, liquid);",
" rgb = mix(rgb, vec3(0.0), u_darkness);",
" gl_FragColor = vec4(rgb, color.a);",
"}"
].join("\n");
const ATLAS_LIGHTING_FRAG = [
"precision mediump float;",
"varying vec2 v_texCoord;",
@@ -66,6 +127,8 @@ const ATLAS_LIGHTING_FRAG = [
let spriteLightingShader = null;
let atlasLightingShader = null;
let waterGroundShader = null;
let potionSpriteShader = null;
function getSpriteLightingShader ()
{
@@ -81,6 +144,20 @@ function getAtlasLightingShader ()
return atlasLightingShader;
}
function getWaterGroundShader ()
{
if (!waterGroundShader)
{ waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); }
return waterGroundShader;
}
function getPotionSpriteShader ()
{
if (!potionSpriteShader)
{ potionSpriteShader = Shader.fragment(POTION_SPRITE_FRAG); }
return potionSpriteShader;
}
export class WorldView
{
constructor (game, scene, catalog = { grounds: {}, blocks: {} })
@@ -140,6 +217,7 @@ export class WorldView
this.chunks.set(key, snapshot);
this.#rebuildChunk(snapshot);
this.#redrawPreview();
this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
for (const entity of snapshot.entities ?? [])
{ this.#upsertEntity(entity); }
const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
@@ -292,23 +370,31 @@ export class WorldView
{
const size = this.tileSize();
const pivot = tilePivot(payload.tileX, payload.tileY, size);
const potion = payload.instance?.kind === "potion" ? payload.instance : null;
const spriteName = potion
? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`)
: (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance));
let item = this.groundItems.get(payload.groundItemId);
if (!item)
{
const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
this.scene.addObject(object);
item = { object };
this.groundItems.set(payload.groundItemId, item);
}
else if (item.object && this.game.images[spriteName])
{ item.object.image = this.game.images[spriteName]; }
item.groundItemId = payload.groundItemId;
item.tileX = payload.tileX;
item.tileY = payload.tileY;
item.itemId = payload.itemId;
item.quantity = payload.quantity;
item.displayName = payload.displayName;
item.sprite = payload.sprite;
item.sprite = spriteName;
item.instance = payload.instance ?? null;
item.potionColor = potion?.color ?? null;
this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
this.#syncLitSprite(item.object, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
}
despawnGroundItem (groundItemId)
@@ -884,21 +970,23 @@ export class WorldView
? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
: 0;
const tileShade = this.#entityShadeAlpha(entity, now);
const wade = isWadeGround(this.#groundTypeAt(entity.tileX, entity.tileY));
entity.object.transform.rotation = walkTilt;
this.#syncLitSprite(entity.object, tileShade, flashStrength);
this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
for (let index = 0; index < (entity.overlays ?? []).length; index++)
{
const overlay = entity.overlays[index];
const overlaySortY = entity.visualY + 0.5 * (index + 1);
overlay.transform.rotation = walkTilt;
this.#syncLitSprite(overlay, tileShade, flashStrength);
this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
}
for (const overlay of entity.bloomOverlays ?? [])
{
overlay.transform.rotation = walkTilt;
this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
}
this.#placeHpBar(entity, pivotX, pivotY);
@@ -914,18 +1002,89 @@ export class WorldView
object.renderer.secondaryMap = null;
}
#syncLitSprite (object, darkness, flashStrength = 0)
#syncLitSprite (object, darkness, flashStrength = 0, wade = false)
{
if (!object?.renderer || object._lit === false)
{ return; }
object._lit = true;
const dark = Math.min(1, Math.max(0, darkness ?? 0));
const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
object.renderer.shader = getSpriteLightingShader();
object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash };
object.renderer.shaderUniforms = {
u_darkness: dark,
u_strength: flash,
u_wade: wade ? 1 : 0,
u_spriteHeight: height
};
object.renderer.secondaryMap = null;
}
#syncGroundItemSprite (item, darkness)
{
if (item?.potionColor)
{ this.#syncPotionSprite(item.object, darkness, item.potionColor); }
else
{ this.#syncLitSprite(item?.object, darkness); }
}
#syncPotionSprite (object, darkness, color)
{
if (!object?.renderer || object._lit === false)
{ return; }
object._lit = true;
object.renderer.shader = getPotionSpriteShader();
object.renderer.shaderUniforms = {
u_darkness: Math.min(1, Math.max(0, darkness ?? 0)),
u_potionColor: [
Math.min(1, Math.max(0, color?.r ?? 0.4)),
Math.min(1, Math.max(0, color?.g ?? 0.4)),
Math.min(1, Math.max(0, color?.b ?? 0.7))
]
};
object.renderer.secondaryMap = null;
}
#groundTypeAt (tileX, tileY)
{
const chunkX = Math.floor(tileX / CHUNK_SIZE);
const chunkY = Math.floor(tileY / CHUNK_SIZE);
const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
if (!snapshot)
{ return null; }
const localX = tileX - chunkX * CHUNK_SIZE;
const localY = tileY - chunkY * CHUNK_SIZE;
const index = localY * CHUNK_SIZE + localX;
return normalizeGround(snapshot.grounds?.[index]).typeId;
}
#waterCoastEdges (tileX, tileY)
{
return {
n: !isWaterGround(this.#groundTypeAt(tileX, tileY - 1)) ? 1 : 0,
e: !isWaterGround(this.#groundTypeAt(tileX + 1, tileY)) ? 1 : 0,
s: !isWaterGround(this.#groundTypeAt(tileX, tileY + 1)) ? 1 : 0,
w: !isWaterGround(this.#groundTypeAt(tileX - 1, tileY)) ? 1 : 0
};
}
#syncWaterGroundSprite (object, darkness, edges, timeSec)
{
if (!object?.renderer)
{ return; }
object._lit = true;
object.renderer.shader = getWaterGroundShader();
object.renderer.secondaryMap = null;
object.renderer.shaderUniforms = {
u_darkness: Math.min(1, Math.max(0, darkness ?? 0)),
u_time: timeSec,
u_edgeN: edges?.n ?? 0,
u_edgeE: edges?.e ?? 0,
u_edgeS: edges?.s ?? 0,
u_edgeW: edges?.w ?? 0
};
}
#applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
{
const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
@@ -1028,6 +1187,7 @@ export class WorldView
blockObjects: [],
bloomObject: null,
tallBlocks: atlases.tallBlocks,
animatedGrounds: atlases.animatedGrounds,
lightmapPixels: null
};
baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
@@ -1057,6 +1217,7 @@ export class WorldView
{ invalidateCanvasTexture(this.scene, canvas); }
invalidateCanvasTexture(this.scene, baked.bloomCanvas);
baked.tallBlocks = atlases.tallBlocks;
baked.animatedGrounds = atlases.animatedGrounds;
}
baked.chunkX = snapshot.chunkX;
baked.chunkY = snapshot.chunkY;
@@ -1140,6 +1301,20 @@ export class WorldView
{ this.#rebuildChunk(snapshot); }
}
#refreshWaterCoastsNear (chunkX, chunkY)
{
const timeSec = performance.now() / 1000;
for (const objects of this.tiles.values())
{
if (!objects.ground || !isWaterGround(objects.groundTypeId))
{ continue; }
if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
{ continue; }
objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, objects.waterEdges, timeSec);
}
}
#drawTile (tileX, tileY, forceTall = null)
{
const chunkX = Math.floor(tileX / CHUNK_SIZE);
@@ -1163,18 +1338,44 @@ export class WorldView
objects.chunkY = chunkY;
objects.light = snapshot.light[index] ?? 0;
if (objects.ground)
const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
if (animatedGround)
{
objects.ground.destroy();
objects.ground = null;
objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
if (objects.ground)
{
const size = this.tileSize();
objects.ground.transform.position.x = tileX * size + size / 2;
objects.ground.transform.position.y = tileY * size + size / 2;
objects.ground.transform.size = new vector(size, size);
objects.ground.layer = LAYER_GROUND;
objects.groundTypeId = animatedGround.typeId;
const edges = isWaterGround(animatedGround.typeId)
? this.#waterCoastEdges(tileX, tileY)
: { n: 0, e: 0, s: 0, w: 0 };
objects.waterEdges = edges;
this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, edges, performance.now() / 1000);
this.#markSortDirty();
}
if (animatedGround.bloom)
{ objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
else
{
objects.groundBloom?.destroy();
objects.groundBloom = null;
}
}
if (objects.groundBloom)
else
{
objects.groundBloom.destroy();
objects.ground?.destroy();
objects.ground = null;
objects.groundBloom?.destroy();
objects.groundBloom = null;
objects.groundTypeId = null;
objects.waterEdges = null;
}
const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
const isTall = forceTall === true || !!tallEntry;
if (isTall && tallEntry)
@@ -1386,6 +1587,17 @@ export class WorldView
objects.shadeAlpha = ambientDark * (1 - intensity);
if (objects.block)
{ this.#syncLitSprite(objects.block, objects.shadeAlpha); }
if (objects.ground && isWaterGround(objects.groundTypeId))
{
this.#syncWaterGroundSprite(
objects.ground,
objects.shadeAlpha,
objects.waterEdges ?? this.#waterCoastEdges(objects.tileX, objects.tileY),
now / 1000
);
}
else if (objects.ground)
{ this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
}
for (const baked of this.bakedChunks.values())
@@ -1403,7 +1615,7 @@ export class WorldView
for (const item of this.groundItems.values())
{
const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
this.#syncLitSprite(item.object, alpha);
this.#syncGroundItemSprite(item, alpha);
}
}
@@ -3,6 +3,7 @@ import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js"import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";import { itemSpriteName } from "/shared/definitions/items.js";import { itemSpriteName } from "/shared/definitions/items.js";import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";import { bakeChunkAtlases } from "./chunkBake.js";import { bakeChunkAtlases } from "./chunkBake.js";import {import {@@ -34,15 +35,75 @@ const SPRITE_LIGHTING_FRAG = [ "uniform sampler2D u_texture;", "uniform sampler2D u_texture;", "uniform float u_darkness;", "uniform float u_darkness;", "uniform float u_strength;", "uniform float u_strength;", "uniform float u_wade;", "uniform float u_spriteHeight;", "void main() {", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " if (color.a <= 0.0) { discard; }", " vec3 rgb = mix(color.rgb, vec3(0.0), u_darkness);", " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", " vec3 rgb = color.rgb;", " if (u_wade > 0.5 && fromBottom < 5.0) {", " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", " }", " rgb = mix(rgb, vec3(0.0), u_darkness);", " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", " gl_FragColor = vec4(rgb, color.a);", " gl_FragColor = vec4(rgb, color.a);", "}" "}"].join("\n");].join("\n");const WATER_GROUND_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_darkness;", "uniform float u_time;", "uniform float u_edgeN;", "uniform float u_edgeE;", "uniform float u_edgeS;", "uniform float u_edgeW;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " vec3 rgb = color.rgb;", " float foam = 0.0;", " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);", " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {", " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);", " }", " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {", " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);", " }", " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {", " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);", " }", " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {", " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);", " }", " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));", " rgb = mix(rgb, vec3(0.0), u_darkness);", " gl_FragColor = vec4(rgb, color.a);", "}"].join("\n");/** Potion bottle: recolor near-white liquid, then apply night darkness. */const POTION_SPRITE_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_darkness;", "uniform vec3 u_potionColor;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " vec3 rgb = color.rgb;", " float liquid = step(0.95, min(min(color.r, color.g), color.b));", " rgb = mix(rgb, u_potionColor, liquid);", " rgb = mix(rgb, vec3(0.0), u_darkness);", " gl_FragColor = vec4(rgb, color.a);", "}"].join("\n");const ATLAS_LIGHTING_FRAG = [const ATLAS_LIGHTING_FRAG = [ "precision mediump float;", "precision mediump float;", "varying vec2 v_texCoord;", "varying vec2 v_texCoord;",@@ -66,6 +127,8 @@ const ATLAS_LIGHTING_FRAG = [let spriteLightingShader = null;let spriteLightingShader = null;let atlasLightingShader = null;let atlasLightingShader = null;let waterGroundShader = null;let potionSpriteShader = null;function getSpriteLightingShader ()function getSpriteLightingShader (){{@@ -81,6 +144,20 @@ function getAtlasLightingShader () return atlasLightingShader; return atlasLightingShader;}}function getWaterGroundShader (){ if (!waterGroundShader) { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); } return waterGroundShader;}function getPotionSpriteShader (){ if (!potionSpriteShader) { potionSpriteShader = Shader.fragment(POTION_SPRITE_FRAG); } return potionSpriteShader;}export class WorldViewexport class WorldView{{ constructor (game, scene, catalog = { grounds: {}, blocks: {} }) constructor (game, scene, catalog = { grounds: {}, blocks: {} })@@ -140,6 +217,7 @@ export class WorldView this.chunks.set(key, snapshot); this.chunks.set(key, snapshot); this.#rebuildChunk(snapshot); this.#rebuildChunk(snapshot); this.#redrawPreview(); this.#redrawPreview(); this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY); for (const entity of snapshot.entities ?? []) for (const entity of snapshot.entities ?? []) { this.#upsertEntity(entity); } { this.#upsertEntity(entity); } const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`; const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;@@ -292,23 +370,31 @@ export class WorldView { { const size = this.tileSize(); const size = this.tileSize(); const pivot = tilePivot(payload.tileX, payload.tileY, size); const pivot = tilePivot(payload.tileX, payload.tileY, size); const potion = payload.instance?.kind === "potion" ? payload.instance : null; const spriteName = potion ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`) : (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance)); let item = this.groundItems.get(payload.groundItemId); let item = this.groundItems.get(payload.groundItemId); if (!item) if (!item) { { const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); this.scene.addObject(object); this.scene.addObject(object); item = { object }; item = { object }; this.groundItems.set(payload.groundItemId, item); this.groundItems.set(payload.groundItemId, item); } } else if (item.object && this.game.images[spriteName]) { item.object.image = this.game.images[spriteName]; } item.groundItemId = payload.groundItemId; item.groundItemId = payload.groundItemId; item.tileX = payload.tileX; item.tileX = payload.tileX; item.tileY = payload.tileY; item.tileY = payload.tileY; item.itemId = payload.itemId; item.itemId = payload.itemId; item.quantity = payload.quantity; item.quantity = payload.quantity; item.displayName = payload.displayName; item.displayName = payload.displayName; item.sprite = payload.sprite; item.sprite = spriteName; item.instance = payload.instance ?? null; item.potionColor = potion?.color ?? null; this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); this.#syncLitSprite(item.object, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0); this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0); } } despawnGroundItem (groundItemId) despawnGroundItem (groundItemId)@@ -884,21 +970,23 @@ export class WorldView ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS : 0; : 0; const tileShade = this.#entityShadeAlpha(entity, now); const tileShade = this.#entityShadeAlpha(entity, now); const wade = isWadeGround(this.#groundTypeAt(entity.tileX, entity.tileY)); entity.object.transform.rotation = walkTilt; entity.object.transform.rotation = walkTilt; this.#syncLitSprite(entity.object, tileShade, flashStrength); this.#syncLitSprite(entity.object, tileShade, flashStrength, wade); this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY); this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY); for (let index = 0; index < (entity.overlays ?? []).length; index++) for (let index = 0; index < (entity.overlays ?? []).length; index++) { { const overlay = entity.overlays[index]; const overlay = entity.overlays[index]; const overlaySortY = entity.visualY + 0.5 * (index + 1); const overlaySortY = entity.visualY + 0.5 * (index + 1); overlay.transform.rotation = walkTilt; overlay.transform.rotation = walkTilt; this.#syncLitSprite(overlay, tileShade, flashStrength); this.#syncLitSprite(overlay, tileShade, flashStrength, wade); this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY); this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY); } } for (const overlay of entity.bloomOverlays ?? []) for (const overlay of entity.bloomOverlays ?? []) { { overlay.transform.rotation = walkTilt; overlay.transform.rotation = walkTilt; this.#syncLitSprite(overlay, tileShade, flashStrength, wade); this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY); this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY); } } this.#placeHpBar(entity, pivotX, pivotY); this.#placeHpBar(entity, pivotX, pivotY);@@ -914,18 +1002,89 @@ export class WorldView object.renderer.secondaryMap = null; object.renderer.secondaryMap = null; } } #syncLitSprite (object, darkness, flashStrength = 0) #syncLitSprite (object, darkness, flashStrength = 0, wade = false) { { if (!object?.renderer || object._lit === false) if (!object?.renderer || object._lit === false) { return; } { return; } object._lit = true; object._lit = true; const dark = Math.min(1, Math.max(0, darkness ?? 0)); const dark = Math.min(1, Math.max(0, darkness ?? 0)); const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; object.renderer.shader = getSpriteLightingShader(); object.renderer.shader = getSpriteLightingShader(); object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash }; object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash, u_wade: wade ? 1 : 0, u_spriteHeight: height }; object.renderer.secondaryMap = null; } #syncGroundItemSprite (item, darkness) { if (item?.potionColor) { this.#syncPotionSprite(item.object, darkness, item.potionColor); } else { this.#syncLitSprite(item?.object, darkness); } } #syncPotionSprite (object, darkness, color) { if (!object?.renderer || object._lit === false) { return; } object._lit = true; object.renderer.shader = getPotionSpriteShader(); object.renderer.shaderUniforms = { u_darkness: Math.min(1, Math.max(0, darkness ?? 0)), u_potionColor: [ Math.min(1, Math.max(0, color?.r ?? 0.4)), Math.min(1, Math.max(0, color?.g ?? 0.4)), Math.min(1, Math.max(0, color?.b ?? 0.7)) ] }; object.renderer.secondaryMap = null; object.renderer.secondaryMap = null; } } #groundTypeAt (tileX, tileY) { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return null; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; const index = localY * CHUNK_SIZE + localX; return normalizeGround(snapshot.grounds?.[index]).typeId; } #waterCoastEdges (tileX, tileY) { return { n: !isWaterGround(this.#groundTypeAt(tileX, tileY - 1)) ? 1 : 0, e: !isWaterGround(this.#groundTypeAt(tileX + 1, tileY)) ? 1 : 0, s: !isWaterGround(this.#groundTypeAt(tileX, tileY + 1)) ? 1 : 0, w: !isWaterGround(this.#groundTypeAt(tileX - 1, tileY)) ? 1 : 0 }; } #syncWaterGroundSprite (object, darkness, edges, timeSec) { if (!object?.renderer) { return; } object._lit = true; object.renderer.shader = getWaterGroundShader(); object.renderer.secondaryMap = null; object.renderer.shaderUniforms = { u_darkness: Math.min(1, Math.max(0, darkness ?? 0)), u_time: timeSec, u_edgeN: edges?.n ?? 0, u_edgeE: edges?.e ?? 0, u_edgeS: edges?.s ?? 0, u_edgeW: edges?.w ?? 0 }; } #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY) #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY) { { const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0; const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;@@ -1028,6 +1187,7 @@ export class WorldView blockObjects: [], blockObjects: [], bloomObject: null, bloomObject: null, tallBlocks: atlases.tallBlocks, tallBlocks: atlases.tallBlocks, animatedGrounds: atlases.animatedGrounds, lightmapPixels: null lightmapPixels: null }; }; baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND); baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);@@ -1057,6 +1217,7 @@ export class WorldView { invalidateCanvasTexture(this.scene, canvas); } { invalidateCanvasTexture(this.scene, canvas); } invalidateCanvasTexture(this.scene, baked.bloomCanvas); invalidateCanvasTexture(this.scene, baked.bloomCanvas); baked.tallBlocks = atlases.tallBlocks; baked.tallBlocks = atlases.tallBlocks; baked.animatedGrounds = atlases.animatedGrounds; } } baked.chunkX = snapshot.chunkX; baked.chunkX = snapshot.chunkX; baked.chunkY = snapshot.chunkY; baked.chunkY = snapshot.chunkY;@@ -1140,6 +1301,20 @@ export class WorldView { this.#rebuildChunk(snapshot); } { this.#rebuildChunk(snapshot); } } } #refreshWaterCoastsNear (chunkX, chunkY) { const timeSec = performance.now() / 1000; for (const objects of this.tiles.values()) { if (!objects.ground || !isWaterGround(objects.groundTypeId)) { continue; } if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1) { continue; } objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY); this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, objects.waterEdges, timeSec); } } #drawTile (tileX, tileY, forceTall = null) #drawTile (tileX, tileY, forceTall = null) { { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkX = Math.floor(tileX / CHUNK_SIZE);@@ -1163,18 +1338,44 @@ export class WorldView objects.chunkY = chunkY; objects.chunkY = chunkY; objects.light = snapshot.light[index] ?? 0; objects.light = snapshot.light[index] ?? 0; if (objects.ground) const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); if (animatedGround) { { objects.ground.destroy(); objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND); objects.ground = null; if (objects.ground) { const size = this.tileSize(); objects.ground.transform.position.x = tileX * size + size / 2; objects.ground.transform.position.y = tileY * size + size / 2; objects.ground.transform.size = new vector(size, size); objects.ground.layer = LAYER_GROUND; objects.groundTypeId = animatedGround.typeId; const edges = isWaterGround(animatedGround.typeId) ? this.#waterCoastEdges(tileX, tileY) : { n: 0, e: 0, s: 0, w: 0 }; objects.waterEdges = edges; this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, edges, performance.now() / 1000); this.#markSortDirty(); } if (animatedGround.bloom) { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); } else { objects.groundBloom?.destroy(); objects.groundBloom = null; } } } if (objects.groundBloom) else { { objects.groundBloom.destroy(); objects.ground?.destroy(); objects.ground = null; objects.groundBloom?.destroy(); objects.groundBloom = null; objects.groundBloom = null; objects.groundTypeId = null; objects.waterEdges = null; } } const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); const isTall = forceTall === true || !!tallEntry; const isTall = forceTall === true || !!tallEntry; if (isTall && tallEntry) if (isTall && tallEntry)@@ -1386,6 +1587,17 @@ export class WorldView objects.shadeAlpha = ambientDark * (1 - intensity); objects.shadeAlpha = ambientDark * (1 - intensity); if (objects.block) if (objects.block) { this.#syncLitSprite(objects.block, objects.shadeAlpha); } { this.#syncLitSprite(objects.block, objects.shadeAlpha); } if (objects.ground && isWaterGround(objects.groundTypeId)) { this.#syncWaterGroundSprite( objects.ground, objects.shadeAlpha, objects.waterEdges ?? this.#waterCoastEdges(objects.tileX, objects.tileY), now / 1000 ); } else if (objects.ground) { this.#syncLitSprite(objects.ground, objects.shadeAlpha); } } } for (const baked of this.bakedChunks.values()) for (const baked of this.bakedChunks.values())@@ -1403,7 +1615,7 @@ export class WorldView for (const item of this.groundItems.values()) for (const item of this.groundItems.values()) { { const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0; const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0; this.#syncLitSprite(item.object, alpha); this.#syncGroundItemSprite(item, alpha); } } } }@@ -378,6 +378,114 @@ a { color: #d4c48a; }
margin-bottom: 0.5rem;
}
#cauldron-panel,
#cauldron-pick-panel {
position: fixed;
z-index: 6;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: min(360px, 92vw);
max-height: min(85vh, 720px);
overflow: auto;
background: #1a1e26;
border: 1px solid #2c3340;
padding: 0.85rem 1rem 1rem;
}
#cauldron-pick-panel {
z-index: 7;
width: min(420px, 94vw);
}
#cauldron-panel header,
#cauldron-pick-panel header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
}
.cauldron-slots,
.cauldron-inserts {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 0.35rem;
margin-bottom: 0.35rem;
}
.cauldron-slot,
.cauldron-insert,
.cauldron-pick-item {
min-height: 3rem;
display: grid;
place-items: center;
position: relative;
background: #12151c;
}
.cauldron-slot img,
.cauldron-pick-item img {
width: 32px;
height: 32px;
image-rendering: pixelated;
}
.cauldron-slot .qty {
position: absolute;
right: 0.2rem;
bottom: 0.1rem;
font-size: 0.75rem;
}
.cauldron-vessel {
text-align: center;
font-size: 2rem;
margin: 0.35rem 0;
opacity: 0.85;
}
.cauldron-actions,
.cauldron-finish {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
margin: 0.35rem 0;
}
.cauldron-steps {
margin: 0.5rem 0 0;
padding-left: 1.2rem;
color: #9aa3b2;
font-size: 0.9rem;
}
.cauldron-pick-list {
display: grid;
gap: 0.35rem;
max-height: 40vh;
overflow: auto;
margin-bottom: 0.5rem;
}
.cauldron-pick-item {
grid-template-columns: 36px 1fr;
justify-items: start;
padding: 0.35rem 0.5rem;
gap: 0.5rem;
}
.cauldron-pick-item.selected {
border-color: #d4c48a;
}
.cauldron-pick-qty {
display: flex;
gap: 0.5rem;
align-items: center;
margin-bottom: 0.5rem;
}
.craft-layout {
display: grid;
grid-template-columns: 1fr 1fr;
@@ -667,6 +775,10 @@ a { color: #d4c48a; }
#bank-panel[hidden],
#craft-panel[hidden],
#craft-backdrop[hidden],
#cauldron-panel[hidden],
#cauldron-backdrop[hidden],
#cauldron-pick-panel[hidden],
#cauldron-pick-backdrop[hidden],
#nametag[hidden],
#chat-bar[hidden] {
display: none !important;
@@ -378,6 +378,114 @@ a { color: #d4c48a; } margin-bottom: 0.5rem; margin-bottom: 0.5rem;}}#cauldron-panel,#cauldron-pick-panel { position: fixed; z-index: 6; top: 50%; left: 50%; transform: translate(-50%, -50%); width: min(360px, 92vw); max-height: min(85vh, 720px); overflow: auto; background: #1a1e26; border: 1px solid #2c3340; padding: 0.85rem 1rem 1rem;}#cauldron-pick-panel { z-index: 7; width: min(420px, 94vw);}#cauldron-panel header,#cauldron-pick-panel header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;}.cauldron-slots,.cauldron-inserts { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.35rem; margin-bottom: 0.35rem;}.cauldron-slot,.cauldron-insert,.cauldron-pick-item { min-height: 3rem; display: grid; place-items: center; position: relative; background: #12151c;}.cauldron-slot img,.cauldron-pick-item img { width: 32px; height: 32px; image-rendering: pixelated;}.cauldron-slot .qty { position: absolute; right: 0.2rem; bottom: 0.1rem; font-size: 0.75rem;}.cauldron-vessel { text-align: center; font-size: 2rem; margin: 0.35rem 0; opacity: 0.85;}.cauldron-actions,.cauldron-finish { display: flex; flex-wrap: wrap; gap: 0.35rem; margin: 0.35rem 0;}.cauldron-steps { margin: 0.5rem 0 0; padding-left: 1.2rem; color: #9aa3b2; font-size: 0.9rem;}.cauldron-pick-list { display: grid; gap: 0.35rem; max-height: 40vh; overflow: auto; margin-bottom: 0.5rem;}.cauldron-pick-item { grid-template-columns: 36px 1fr; justify-items: start; padding: 0.35rem 0.5rem; gap: 0.5rem;}.cauldron-pick-item.selected { border-color: #d4c48a;}.cauldron-pick-qty { display: flex; gap: 0.5rem; align-items: center; margin-bottom: 0.5rem;}.craft-layout {.craft-layout { display: grid; display: grid; grid-template-columns: 1fr 1fr; grid-template-columns: 1fr 1fr;@@ -667,6 +775,10 @@ a { color: #d4c48a; }#bank-panel[hidden],#bank-panel[hidden],#craft-panel[hidden],#craft-panel[hidden],#craft-backdrop[hidden],#craft-backdrop[hidden],#cauldron-panel[hidden],#cauldron-backdrop[hidden],#cauldron-pick-panel[hidden],#cauldron-pick-backdrop[hidden],#nametag[hidden],#nametag[hidden],#chat-bar[hidden] {#chat-bar[hidden] { display: none !important; display: none !important;@@ -16,7 +16,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Ground and block tile layers
**Status:** full
**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live block types include grass grounds, wood, stone wall, torch, bank, and **church altar** (respawn destination — see **Player death and respawn**). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks stay individual sprites so mobiles can Y-sort behind them.
**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). Live block types include stone wall, torch, bank, and **church altar** (respawn destination — see **Player death and respawn**). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Water tiles use a coast-foam shader on edges against non-water; entity sprites use a wade clip+foam tint that respects night darkness.
**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
## Open and closed chunks
@@ -234,8 +234,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Gathering, crafting, and production skills
**Status:** not implemented
**Spec:** Skill IDs exist for **Woodcutting**, **Mining**, **Fishing**, **Smithing**, **Crafting**, **Leatherworking**, **Tailoring**, and **Cooking**. **Axes** (Woodcutting) and **pickaxes** (Mining) are tools, not melee weapons — tier sets min Woodcutting/Mining to equip; better tools gather faster. **Fishing rods** and **nets** use Fishing. **Smithing** crafts metal items (min Smithing per recipe). **Crafting** makes misc items (e.g. arrows from smithed tips). **Leatherworking** makes leather armour (Dexterity bonus, not Defence). **Tailoring** makes cloth armour; separate **wizard cloth** tiers grant Magic bonus. **Cooking** prepares raw food at ovens and campfires (see **Crafting stations**). Gathering attempts always succeed when in range; non-cooking crafts always succeed when skill ≥ recipe min. Resources have a **minimum tier** (tool tier must meet or exceed). **Leather** needs no tool — drops from certain mobs. **TODO:** resource nodes (trees, ores, fish spots), gather commands, recipe data files, tool/item sprites, gather speed formula, mob leather drops, sheep shearing. Craft UI is specified under **Crafting stations**.
**Code:** `shared/definitions/skills.js` (skill IDs + panel entries only)
**Spec:** Skill IDs exist for **Woodcutting**, **Mining**, **Fishing**, **Smithing**, **Crafting**, **Leatherworking**, **Tailoring**, **Cooking**, **Herbalism**, and **Alchemy**. **Axes** (Woodcutting) and **pickaxes** (Mining) are tools, not melee weapons — tier sets min Woodcutting/Mining to equip; better tools gather faster. **Plant clippers** (Herbalism) mirror that pattern for herb nodes (gather mechanics later). **Fishing rods** and **nets** use Fishing. **Smithing** crafts metal items (min Smithing per recipe). **Crafting** makes misc items (e.g. arrows from smithed tips). **Leatherworking** makes leather armour (Dexterity bonus, not Defence). **Tailoring** makes cloth armour; separate **wizard cloth** tiers grant Magic bonus. **Cooking** prepares raw food at ovens and campfires (see **Crafting stations**). **Alchemy** brews potions at a **Cauldron** (see **Alchemy / cauldron**). Gathering attempts always succeed when in range; non-cooking crafts always succeed when skill ≥ recipe min. Resources have a **minimum tier** (tool tier must meet or exceed). **Leather** needs no tool — drops from certain mobs. **TODO:** resource nodes (trees, ores, fish spots, herb nodes), gather commands, recipe data files, tool/item sprites, gather speed formula, mob leather drops, sheep shearing. Craft UI is specified under **Crafting stations**.
**Code:** `shared/definitions/skills.js` (skill IDs + panel entries), `shared/definitions/equipmentKinds.js` (`plantClippers`), `shared/definitions/alchemy.js`
## Crafting stations
@@ -266,6 +266,18 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
**TODO:** station block/entity types and sprites, real recipe tables per station, open/close from world interaction, server craft command + timer + adjacency checks, Cooking burn formula, log/tinderbox behaviour, campfire ground entity lifecycle & replication, spinning wheel wool input once sheep exist.
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/craftingItems.js`, `shared/definitions/itemCategories.js`, `shared/crafting/recipes.js`, `shared/crafting/stationRecipes.js`, `client/src/play/crafting.js`, `client/ui/play.css` (#craft-panel)
## 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 (and other ingredients) at a **Cauldron** block (`BlockType.cauldron`, editor placeable). Nonstandard UI: four reserve slots above the vessel, ↓ insert arrows under each slot, **Stir / Heat / Cool** actions, **Bottle**, **Clear** (also auto-clears after bottle), and **Save Recipe** after a successful brew when the player has blank **paper**.
Slots register item+quantity without consuming until insert; insert consumes the reserved amount into the brew and records an `insert` step. Recipes list ≤4 unique ingredients as **ratios** (double inputs → double output if bottles allow; excess brew is lost without enough **glass bottles**). Steps must match; wrong order/ratios or Alchemy level below the recipe minimum yields an **Unstable Potion** chosen by hashing the step transcript (same mistakes → same failure potion). Unstable effects are stubs (slow, damage, blind, queasy). Success + paper → Save Recipe writes a unique **recipe paper** (read like a letter: ratios, steps, Alchemy level). Potions of the same type/effect stack to **16**. Shared potion art: clear bottle (= empty bottle) + fill levels 1–5; liquid is recolored per potion `color` (inventory canvas tint; world ground items use a lit shader that tints then applies darkness).
Example scaffold recipe: **Green draught** — heat → insert green herb → stir → insert apple → cool → Bottle (ratios 2 green herb : 1 apple).
**TODO:** more recipes, drink/effect application, herb nodes + Herbalism XP, more clipper tiers, polish cauldron art.
**Code:** `shared/definitions/alchemy.js`, `shared/alchemy/recipes.js`, `shared/definitions/items.js`, `shared/definitions/tiles.js` (`cauldron`), `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, `client/src/render/potionIcon.js`, `client/src/render/worldView.js` (potion shader), tests in `server/tests/alchemy.test.js`
## Stamina and running
**Status:** not implemented
@@ -290,6 +302,21 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
**Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
## Bounty offices
**Status:** not implemented
**Spec:** Placeable **Bounty Office** blocks (sprite/form TBD). Interacting opens a modal with two tabs:
1. **Place / raise bounty** — Search a character by name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success).
2. **My bounty** — Shows how much coin is currently on **your** head.
**Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.
**Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
**TODO:** block type + art, modal UI, character search reuse, persistent bounty ledger per character, coin add intent, nearest-office pigeon on PvP kill, vault deposit + letter body, inspect bounty line, tests.
**Code:** —
## Banking, cheques, shops, player-driven marketplace
**Status:** partial
@@ -16,7 +16,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Ground and block tile layers## Ground and block tile layers**Status:** full **Status:** full **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live block types include grass grounds, wood, stone wall, torch, bank, and **church altar** (respawn destination — see **Player death and respawn**). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks stay individual sprites so mobiles can Y-sort behind them. **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). Live block types include stone wall, torch, bank, and **church altar** (respawn destination — see **Player death and respawn**). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Water tiles use a coast-foam shader on edges against non-water; entity sprites use a wade clip+foam tint that respects night darkness. **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`## Open and closed chunks## Open and closed chunks@@ -234,8 +234,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Gathering, crafting, and production skills## Gathering, crafting, and production skills**Status:** not implemented **Status:** not implemented **Spec:** Skill IDs exist for **Woodcutting**, **Mining**, **Fishing**, **Smithing**, **Crafting**, **Leatherworking**, **Tailoring**, and **Cooking**. **Axes** (Woodcutting) and **pickaxes** (Mining) are tools, not melee weapons — tier sets min Woodcutting/Mining to equip; better tools gather faster. **Fishing rods** and **nets** use Fishing. **Smithing** crafts metal items (min Smithing per recipe). **Crafting** makes misc items (e.g. arrows from smithed tips). **Leatherworking** makes leather armour (Dexterity bonus, not Defence). **Tailoring** makes cloth armour; separate **wizard cloth** tiers grant Magic bonus. **Cooking** prepares raw food at ovens and campfires (see **Crafting stations**). Gathering attempts always succeed when in range; non-cooking crafts always succeed when skill ≥ recipe min. Resources have a **minimum tier** (tool tier must meet or exceed). **Leather** needs no tool — drops from certain mobs. **TODO:** resource nodes (trees, ores, fish spots), gather commands, recipe data files, tool/item sprites, gather speed formula, mob leather drops, sheep shearing. Craft UI is specified under **Crafting stations**. **Spec:** Skill IDs exist for **Woodcutting**, **Mining**, **Fishing**, **Smithing**, **Crafting**, **Leatherworking**, **Tailoring**, **Cooking**, **Herbalism**, and **Alchemy**. **Axes** (Woodcutting) and **pickaxes** (Mining) are tools, not melee weapons — tier sets min Woodcutting/Mining to equip; better tools gather faster. **Plant clippers** (Herbalism) mirror that pattern for herb nodes (gather mechanics later). **Fishing rods** and **nets** use Fishing. **Smithing** crafts metal items (min Smithing per recipe). **Crafting** makes misc items (e.g. arrows from smithed tips). **Leatherworking** makes leather armour (Dexterity bonus, not Defence). **Tailoring** makes cloth armour; separate **wizard cloth** tiers grant Magic bonus. **Cooking** prepares raw food at ovens and campfires (see **Crafting stations**). **Alchemy** brews potions at a **Cauldron** (see **Alchemy / cauldron**). Gathering attempts always succeed when in range; non-cooking crafts always succeed when skill ≥ recipe min. Resources have a **minimum tier** (tool tier must meet or exceed). **Leather** needs no tool — drops from certain mobs. **TODO:** resource nodes (trees, ores, fish spots, herb nodes), gather commands, recipe data files, tool/item sprites, gather speed formula, mob leather drops, sheep shearing. Craft UI is specified under **Crafting stations**. **Code:** `shared/definitions/skills.js` (skill IDs + panel entries only)**Code:** `shared/definitions/skills.js` (skill IDs + panel entries), `shared/definitions/equipmentKinds.js` (`plantClippers`), `shared/definitions/alchemy.js`## Crafting stations## Crafting stations@@ -266,6 +266,18 @@ Each entry is a short note on behaviour and where the code lives. Update this fi**TODO:** station block/entity types and sprites, real recipe tables per station, open/close from world interaction, server craft command + timer + adjacency checks, Cooking burn formula, log/tinderbox behaviour, campfire ground entity lifecycle & replication, spinning wheel wool input once sheep exist. **TODO:** station block/entity types and sprites, real recipe tables per station, open/close from world interaction, server craft command + timer + adjacency checks, Cooking burn formula, log/tinderbox behaviour, campfire ground entity lifecycle & replication, spinning wheel wool input once sheep exist. **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/craftingItems.js`, `shared/definitions/itemCategories.js`, `shared/crafting/recipes.js`, `shared/crafting/stationRecipes.js`, `client/src/play/crafting.js`, `client/ui/play.css` (#craft-panel)**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/craftingItems.js`, `shared/definitions/itemCategories.js`, `shared/crafting/recipes.js`, `shared/crafting/stationRecipes.js`, `client/src/play/crafting.js`, `client/ui/play.css` (#craft-panel)## 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 (and other ingredients) at a **Cauldron** block (`BlockType.cauldron`, editor placeable). Nonstandard UI: four reserve slots above the vessel, ↓ insert arrows under each slot, **Stir / Heat / Cool** actions, **Bottle**, **Clear** (also auto-clears after bottle), and **Save Recipe** after a successful brew when the player has blank **paper**.Slots register item+quantity without consuming until insert; insert consumes the reserved amount into the brew and records an `insert` step. Recipes list ≤4 unique ingredients as **ratios** (double inputs → double output if bottles allow; excess brew is lost without enough **glass bottles**). Steps must match; wrong order/ratios or Alchemy level below the recipe minimum yields an **Unstable Potion** chosen by hashing the step transcript (same mistakes → same failure potion). Unstable effects are stubs (slow, damage, blind, queasy). Success + paper → Save Recipe writes a unique **recipe paper** (read like a letter: ratios, steps, Alchemy level). Potions of the same type/effect stack to **16**. Shared potion art: clear bottle (= empty bottle) + fill levels 1–5; liquid is recolored per potion `color` (inventory canvas tint; world ground items use a lit shader that tints then applies darkness).Example scaffold recipe: **Green draught** — heat → insert green herb → stir → insert apple → cool → Bottle (ratios 2 green herb : 1 apple).**TODO:** more recipes, drink/effect application, herb nodes + Herbalism XP, more clipper tiers, polish cauldron art. **Code:** `shared/definitions/alchemy.js`, `shared/alchemy/recipes.js`, `shared/definitions/items.js`, `shared/definitions/tiles.js` (`cauldron`), `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, `client/src/render/potionIcon.js`, `client/src/render/worldView.js` (potion shader), tests in `server/tests/alchemy.test.js`## Stamina and running## Stamina and running**Status:** not implemented **Status:** not implemented @@ -290,6 +302,21 @@ Each entry is a short note on behaviour and where the code lives. Update this fi**Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel. **Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel. **Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`## Bounty offices**Status:** not implemented **Spec:** Placeable **Bounty Office** blocks (sprite/form TBD). Interacting opens a modal with two tabs:1. **Place / raise bounty** — Search a character by name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success).2. **My bounty** — Shows how much coin is currently on **your** head.**Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.**Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.**TODO:** block type + art, modal UI, character search reuse, persistent bounty ledger per character, coin add intent, nearest-office pigeon on PvP kill, vault deposit + letter body, inspect bounty line, tests. **Code:** —## Banking, cheques, shops, player-driven marketplace## Banking, cheques, shops, player-driven marketplace**Status:** partial **Status:** partial @@ -0,0 +1,399 @@
import { Component } from "../ecs/components.js";
import { BlockType } from "../../../shared/definitions/tiles.js";
import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "../../../shared/definitions/alchemy.js";
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
import {
evaluateAlchemyBottle,
potionItemInstance,
recipePaperBody,
resolvedAlchemyPotions
} from "../../../shared/alchemy/recipes.js";
import { bagView } from "../items/bags.js";
import {
countItemInSlots,
emptySlots,
insertStack,
normalizeInventorySlots,
takeMatchingFromSlots,
stackQuantity
} from "../../../shared/items/inventory.js";
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
import { randomUUID } from "node:crypto";
/**
* Cauldron sessions live on the worker world (per character while the UI is open).
* Clients send intents only; all brew outcomes are evaluated here.
*/
function userError (message)
{
const error = new Error(message);
error.userFacing = true;
return error;
}
function ensureSessions (world)
{
if (!world.cauldronSessions)
{ world.cauldronSessions = new Map(); }
return world.cauldronSessions;
}
function emptySession ()
{
return {
slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
brew: [],
steps: [],
lastSuccessRecipe: null
};
}
function sessionView (session)
{
return {
slots: (session.slots ?? []).map((slot) => (slot
? { itemId: slot.itemId, quantity: slot.quantity | 0 }
: null)),
brew: (session.brew ?? []).map((row) => ({ itemId: row.itemId, quantity: row.quantity | 0 })),
steps: (session.steps ?? []).map((step) => ({ ...step })),
canSaveRecipe: !!session.lastSuccessRecipe,
lastSuccess: session.lastSuccessRecipe
? {
potionKey: session.lastSuccessRecipe.potionKey,
displayName: session.lastSuccessRecipe.displayName,
minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1
}
: null
};
}
function nearCauldron (world, tileX, tileY)
{
for (let dy = -1; dy <= 1; dy++)
{
for (let dx = -1; dx <= 1; dx++)
{
const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
if (data.blocks[index]?.typeId === BlockType.cauldron)
{ return true; }
}
}
return false;
}
function requireNearCauldron (world, handle)
{
const position = world.ecs.get(handle, Component.position);
if (!nearCauldron(world, position.tileX, position.tileY))
{ throw userError("Stand next to a cauldron."); }
}
function requireSession (world, characterId)
{
const session = ensureSessions(world).get(characterId);
if (!session)
{ throw userError("Open a cauldron first."); }
return session;
}
function clearBrew (session)
{
session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);
session.brew = [];
session.steps = [];
}
function ensureInventory (world, handle)
{
let inventory = world.ecs.get(handle, Component.inventory);
if (!inventory)
{ inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
return inventory;
}
export function handleAlchemyCommand (world, sessionId, command)
{
switch (command.type)
{
case "open-cauldron":
return openCauldron(world, sessionId, command);
case "cauldron-set-slot":
return setSlot(world, sessionId, command);
case "cauldron-insert":
return insertFromSlot(world, sessionId, command);
case "cauldron-action":
return action(world, sessionId, command);
case "cauldron-bottle":
return bottle(world, sessionId, command);
case "cauldron-clear":
return clear(world, sessionId, command);
case "cauldron-save-recipe":
return saveRecipe(world, sessionId, command);
case "cauldron-close":
return closeCauldron(world, sessionId, command);
default:
return null;
}
}
function openCauldron (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
requireNearCauldron(world, handle);
const sessions = ensureSessions(world);
const existing = sessions.get(command.characterId) ?? emptySession();
sessions.set(command.characterId, existing);
return {
events: [],
private: bagView(world.ecs, handle),
cauldron: true,
cauldronState: sessionView(existing)
};
}
function closeCauldron (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
ensureSessions(world).delete(command.characterId);
return { events: [], private: bagView(world.ecs, handle), cauldron: false };
}
function setSlot (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
requireNearCauldron(world, handle);
const session = requireSession(world, command.characterId);
const slotIndex = command.slotIndex | 0;
if (slotIndex < 0 || slotIndex >= CAULDRON_SLOT_COUNT)
{ throw userError("Invalid cauldron slot."); }
const itemId = command.itemId | 0;
const quantity = Math.max(0, command.quantity | 0);
if (!itemId || quantity <= 0)
{
session.slots[slotIndex] = null;
return {
events: [],
private: bagView(world.ecs, handle),
cauldron: true,
cauldronState: sessionView(session)
};
}
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."); }
const inventory = ensureInventory(world, handle);
const have = countItemInSlots(inventory.slots, itemId);
if (have < quantity)
{ throw userError("Not enough of that item in your inventory."); }
session.slots[slotIndex] = { itemId, quantity };
return {
events: [],
private: bagView(world.ecs, handle),
cauldron: true,
cauldronState: sessionView(session)
};
}
function insertFromSlot (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
requireNearCauldron(world, handle);
const session = requireSession(world, command.characterId);
const slotIndex = command.slotIndex | 0;
const reserved = session.slots[slotIndex];
if (!reserved)
{ throw userError("That cauldron slot is empty."); }
const inventory = ensureInventory(world, handle);
const pulled = takeMatchingFromSlots(inventory.slots, {
itemId: reserved.itemId,
quantity: reserved.quantity,
compact: false
});
if (!pulled.ok)
{ throw userError("Not enough of that item in your inventory."); }
inventory.slots = pulled.slots;
session.slots[slotIndex] = null;
const existing = session.brew.find((row) => row.itemId === reserved.itemId);
if (existing)
{ existing.quantity += reserved.quantity; }
else
{ session.brew.push({ itemId: reserved.itemId, quantity: reserved.quantity }); }
session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId });
session.lastSuccessRecipe = null;
return {
events: [],
private: bagView(world.ecs, handle),
cauldron: true,
cauldronState: sessionView(session)
};
}
function action (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
requireNearCauldron(world, handle);
const session = requireSession(world, command.characterId);
const kind = command.action;
if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool)
{ throw userError("Unknown cauldron action."); }
session.steps.push({ kind });
session.lastSuccessRecipe = null;
return {
events: [],
private: bagView(world.ecs, handle),
cauldron: true,
cauldronState: sessionView(session)
};
}
function bottle (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
requireNearCauldron(world, handle);
const session = requireSession(world, command.characterId);
if (!(session.brew?.length > 0) && !(session.steps?.length > 0))
{ throw userError("The cauldron is empty."); }
const inventory = ensureInventory(world, handle);
const skills = world.ecs.get(handle, Component.skills) ?? {};
const evaluation = evaluateAlchemyBottle({
skills,
brewStacks: session.brew,
takenSteps: session.steps,
potions: resolvedAlchemyPotions()
});
const wanted = Math.max(1, evaluation.batch | 0);
const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
const produced = Math.min(wanted, bottles);
if (produced <= 0)
{ throw userError("You need glass bottles to bottle the brew."); }
const takeBottles = takeMatchingFromSlots(inventory.slots, {
itemId: ItemId.glassBottle,
quantity: produced,
compact: false
});
if (!takeBottles.ok)
{ throw userError("You need glass bottles to bottle the brew."); }
inventory.slots = takeBottles.slots;
const instance = potionItemInstance(evaluation.result);
const potionDef = itemDefinition(ItemId.potion);
const inserted = insertStack(inventory.slots, {
itemId: ItemId.potion,
quantity: produced,
instance
}, potionDef);
if (!inserted.ok)
{
const refund = insertStack(inventory.slots, {
itemId: ItemId.glassBottle,
quantity: produced
}, itemDefinition(ItemId.glassBottle));
inventory.slots = refund.ok ? refund.slots : inventory.slots;
throw userError("Not enough inventory space for potions.");
}
inventory.slots = inserted.slots;
session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
clearBrew(session);
return {
events: [],
private: bagView(world.ecs, handle),
cauldron: true,
cauldronState: sessionView(session),
alchemyResult: {
success: !!evaluation.success,
reason: evaluation.reason ?? null,
produced,
wanted,
lost: Math.max(0, wanted - produced),
potion: {
potionKey: instance.potionKey,
displayName: instance.displayName,
unstable: instance.unstable,
color: instance.color,
fillLevel: instance.fillLevel
}
}
};
}
function clear (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
requireNearCauldron(world, handle);
const session = requireSession(world, command.characterId);
clearBrew(session);
session.lastSuccessRecipe = null;
return {
events: [],
private: bagView(world.ecs, handle),
cauldron: true,
cauldronState: sessionView(session)
};
}
function saveRecipe (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
requireNearCauldron(world, handle);
const session = requireSession(world, command.characterId);
const recipe = session.lastSuccessRecipe;
if (!recipe)
{ throw userError("No successful recipe to save."); }
const inventory = ensureInventory(world, handle);
const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper);
if (paperIndex < 0)
{ throw userError("You need a sheet of paper."); }
const paperSlot = inventory.slots[paperIndex];
const recipeStack = {
itemId: ItemId.recipePaper,
quantity: 1,
instance: {
kind: "recipe-paper",
recipeId: randomUUID(),
potionKey: recipe.potionKey,
displayName: `${recipe.displayName} recipe`,
minAlchemyLevel: recipe.minAlchemyLevel ?? 1,
body: recipePaperBody(recipe),
writtenAt: Date.now()
}
};
if (stackQuantity(paperSlot.quantity) <= 1)
{ inventory.slots[paperIndex] = recipeStack; }
else
{
const free = inventory.slots.findIndex((entry) => !entry);
if (free < 0)
{ throw userError("Need a free inventory slot for the recipe paper."); }
paperSlot.quantity -= 1;
inventory.slots[free] = recipeStack;
}
session.lastSuccessRecipe = null;
return {
events: [],
private: bagView(world.ecs, handle),
cauldron: true,
cauldronState: sessionView(session)
};
}
@@ -0,0 +1,399 @@import { Component } from "../ecs/components.js";import { BlockType } from "../../../shared/definitions/tiles.js";import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "../../../shared/definitions/alchemy.js";import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";import { evaluateAlchemyBottle, potionItemInstance, recipePaperBody, resolvedAlchemyPotions} from "../../../shared/alchemy/recipes.js";import { bagView } from "../items/bags.js";import { countItemInSlots, emptySlots, insertStack, normalizeInventorySlots, takeMatchingFromSlots, stackQuantity} from "../../../shared/items/inventory.js";import { tileToChunk, tileToLocal } from "../world/coordinates.js";import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";import { randomUUID } from "node:crypto";/** * Cauldron sessions live on the worker world (per character while the UI is open). * Clients send intents only; all brew outcomes are evaluated here. */function userError (message){ const error = new Error(message); error.userFacing = true; return error;}function ensureSessions (world){ if (!world.cauldronSessions) { world.cauldronSessions = new Map(); } return world.cauldronSessions;}function emptySession (){ return { slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null), brew: [], steps: [], lastSuccessRecipe: null };}function sessionView (session){ return { slots: (session.slots ?? []).map((slot) => (slot ? { itemId: slot.itemId, quantity: slot.quantity | 0 } : null)), brew: (session.brew ?? []).map((row) => ({ itemId: row.itemId, quantity: row.quantity | 0 })), steps: (session.steps ?? []).map((step) => ({ ...step })), canSaveRecipe: !!session.lastSuccessRecipe, lastSuccess: session.lastSuccessRecipe ? { potionKey: session.lastSuccessRecipe.potionKey, displayName: session.lastSuccessRecipe.displayName, minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1 } : null };}function nearCauldron (world, tileX, tileY){ for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy)); const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx); if (data.blocks[index]?.typeId === BlockType.cauldron) { return true; } } } return false;}function requireNearCauldron (world, handle){ const position = world.ecs.get(handle, Component.position); if (!nearCauldron(world, position.tileX, position.tileY)) { throw userError("Stand next to a cauldron."); }}function requireSession (world, characterId){ const session = ensureSessions(world).get(characterId); if (!session) { throw userError("Open a cauldron first."); } return session;}function clearBrew (session){ session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null); session.brew = []; session.steps = [];}function ensureInventory (world, handle){ let inventory = world.ecs.get(handle, Component.inventory); if (!inventory) { inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); } inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots()); return inventory;}export function handleAlchemyCommand (world, sessionId, command){ switch (command.type) { case "open-cauldron": return openCauldron(world, sessionId, command); case "cauldron-set-slot": return setSlot(world, sessionId, command); case "cauldron-insert": return insertFromSlot(world, sessionId, command); case "cauldron-action": return action(world, sessionId, command); case "cauldron-bottle": return bottle(world, sessionId, command); case "cauldron-clear": return clear(world, sessionId, command); case "cauldron-save-recipe": return saveRecipe(world, sessionId, command); case "cauldron-close": return closeCauldron(world, sessionId, command); default: return null; }}function openCauldron (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const sessions = ensureSessions(world); const existing = sessions.get(command.characterId) ?? emptySession(); sessions.set(command.characterId, existing); return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(existing) };}function closeCauldron (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); ensureSessions(world).delete(command.characterId); return { events: [], private: bagView(world.ecs, handle), cauldron: false };}function setSlot (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); const slotIndex = command.slotIndex | 0; if (slotIndex < 0 || slotIndex >= CAULDRON_SLOT_COUNT) { throw userError("Invalid cauldron slot."); } const itemId = command.itemId | 0; const quantity = Math.max(0, command.quantity | 0); if (!itemId || quantity <= 0) { session.slots[slotIndex] = null; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) }; } 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."); } const inventory = ensureInventory(world, handle); const have = countItemInSlots(inventory.slots, itemId); if (have < quantity) { throw userError("Not enough of that item in your inventory."); } session.slots[slotIndex] = { itemId, quantity }; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) };}function insertFromSlot (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); const slotIndex = command.slotIndex | 0; const reserved = session.slots[slotIndex]; if (!reserved) { throw userError("That cauldron slot is empty."); } const inventory = ensureInventory(world, handle); const pulled = takeMatchingFromSlots(inventory.slots, { itemId: reserved.itemId, quantity: reserved.quantity, compact: false }); if (!pulled.ok) { throw userError("Not enough of that item in your inventory."); } inventory.slots = pulled.slots; session.slots[slotIndex] = null; const existing = session.brew.find((row) => row.itemId === reserved.itemId); if (existing) { existing.quantity += reserved.quantity; } else { session.brew.push({ itemId: reserved.itemId, quantity: reserved.quantity }); } session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId }); session.lastSuccessRecipe = null; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) };}function action (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); const kind = command.action; if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool) { throw userError("Unknown cauldron action."); } session.steps.push({ kind }); session.lastSuccessRecipe = null; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) };}function bottle (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); if (!(session.brew?.length > 0) && !(session.steps?.length > 0)) { throw userError("The cauldron is empty."); } const inventory = ensureInventory(world, handle); const skills = world.ecs.get(handle, Component.skills) ?? {}; const evaluation = evaluateAlchemyBottle({ skills, brewStacks: session.brew, takenSteps: session.steps, potions: resolvedAlchemyPotions() }); const wanted = Math.max(1, evaluation.batch | 0); const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle); const produced = Math.min(wanted, bottles); if (produced <= 0) { throw userError("You need glass bottles to bottle the brew."); } const takeBottles = takeMatchingFromSlots(inventory.slots, { itemId: ItemId.glassBottle, quantity: produced, compact: false }); if (!takeBottles.ok) { throw userError("You need glass bottles to bottle the brew."); } inventory.slots = takeBottles.slots; const instance = potionItemInstance(evaluation.result); const potionDef = itemDefinition(ItemId.potion); const inserted = insertStack(inventory.slots, { itemId: ItemId.potion, quantity: produced, instance }, potionDef); if (!inserted.ok) { const refund = insertStack(inventory.slots, { itemId: ItemId.glassBottle, quantity: produced }, itemDefinition(ItemId.glassBottle)); inventory.slots = refund.ok ? refund.slots : inventory.slots; throw userError("Not enough inventory space for potions."); } inventory.slots = inserted.slots; session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null; clearBrew(session); return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session), alchemyResult: { success: !!evaluation.success, reason: evaluation.reason ?? null, produced, wanted, lost: Math.max(0, wanted - produced), potion: { potionKey: instance.potionKey, displayName: instance.displayName, unstable: instance.unstable, color: instance.color, fillLevel: instance.fillLevel } } };}function clear (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); clearBrew(session); session.lastSuccessRecipe = null; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) };}function saveRecipe (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireNearCauldron(world, handle); const session = requireSession(world, command.characterId); const recipe = session.lastSuccessRecipe; if (!recipe) { throw userError("No successful recipe to save."); } const inventory = ensureInventory(world, handle); const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper); if (paperIndex < 0) { throw userError("You need a sheet of paper."); } const paperSlot = inventory.slots[paperIndex]; const recipeStack = { itemId: ItemId.recipePaper, quantity: 1, instance: { kind: "recipe-paper", recipeId: randomUUID(), potionKey: recipe.potionKey, displayName: `${recipe.displayName} recipe`, minAlchemyLevel: recipe.minAlchemyLevel ?? 1, body: recipePaperBody(recipe), writtenAt: Date.now() } }; if (stackQuantity(paperSlot.quantity) <= 1) { inventory.slots[paperIndex] = recipeStack; } else { const free = inventory.slots.findIndex((entry) => !entry); if (free < 0) { throw userError("Need a free inventory slot for the recipe paper."); } paperSlot.quantity -= 1; inventory.slots[free] = recipeStack; } session.lastSuccessRecipe = null; return { events: [], private: bagView(world.ecs, handle), cauldron: true, cauldronState: sessionView(session) };}@@ -192,6 +192,67 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
characterId: session.characterId
});
break;
case MessageType.openCauldron:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "open-cauldron",
characterId: session.characterId
});
break;
case MessageType.cauldronSetSlot:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "cauldron-set-slot",
characterId: session.characterId,
slotIndex: message.slotIndex | 0,
itemId: message.itemId | 0,
quantity: message.quantity | 0
});
break;
case MessageType.cauldronInsert:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "cauldron-insert",
characterId: session.characterId,
slotIndex: message.slotIndex | 0
});
break;
case MessageType.cauldronAction:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "cauldron-action",
characterId: session.characterId,
action: message.action
});
break;
case MessageType.cauldronBottle:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "cauldron-bottle",
characterId: session.characterId
});
break;
case MessageType.cauldronClear:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "cauldron-clear",
characterId: session.characterId
});
break;
case MessageType.cauldronSaveRecipe:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "cauldron-save-recipe",
characterId: session.characterId
});
break;
case MessageType.cauldronClose:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "cauldron-close",
characterId: session.characterId
});
break;
case MessageType.bankDeposit:
requirePlaying(session);
simulation.enqueue(session.id, {
@@ -592,6 +653,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
inheritance: stateDb.getInheritance(session.account.account_id)
});
}
if (event.cauldron != null)
{
send(session, {
type: MessageType.cauldronSnapshot,
open: !!event.cauldron,
state: event.cauldronState ?? null,
alchemyResult: event.alchemyResult ?? null
});
}
continue;
}
if (event.type === "skills")
@@ -192,6 +192,67 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, characterId: session.characterId characterId: session.characterId }); }); break; break; case MessageType.openCauldron: requirePlaying(session); simulation.enqueue(session.id, { type: "open-cauldron", characterId: session.characterId }); break; case MessageType.cauldronSetSlot: requirePlaying(session); simulation.enqueue(session.id, { type: "cauldron-set-slot", characterId: session.characterId, slotIndex: message.slotIndex | 0, itemId: message.itemId | 0, quantity: message.quantity | 0 }); break; case MessageType.cauldronInsert: requirePlaying(session); simulation.enqueue(session.id, { type: "cauldron-insert", characterId: session.characterId, slotIndex: message.slotIndex | 0 }); break; case MessageType.cauldronAction: requirePlaying(session); simulation.enqueue(session.id, { type: "cauldron-action", characterId: session.characterId, action: message.action }); break; case MessageType.cauldronBottle: requirePlaying(session); simulation.enqueue(session.id, { type: "cauldron-bottle", characterId: session.characterId }); break; case MessageType.cauldronClear: requirePlaying(session); simulation.enqueue(session.id, { type: "cauldron-clear", characterId: session.characterId }); break; case MessageType.cauldronSaveRecipe: requirePlaying(session); simulation.enqueue(session.id, { type: "cauldron-save-recipe", characterId: session.characterId }); break; case MessageType.cauldronClose: requirePlaying(session); simulation.enqueue(session.id, { type: "cauldron-close", characterId: session.characterId }); break; case MessageType.bankDeposit: case MessageType.bankDeposit: requirePlaying(session); requirePlaying(session); simulation.enqueue(session.id, { simulation.enqueue(session.id, {@@ -592,6 +653,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, inheritance: stateDb.getInheritance(session.account.account_id) inheritance: stateDb.getInheritance(session.account.account_id) }); }); } } if (event.cauldron != null) { send(session, { type: MessageType.cauldronSnapshot, open: !!event.cauldron, state: event.cauldronState ?? null, alchemyResult: event.alchemyResult ?? null }); } continue; continue; } } if (event.type === "skills") if (event.type === "skills")@@ -25,7 +25,7 @@ import { randomUUID } from "node:crypto";
export function publicGroundItem (item)
{
const def = itemDefinition(item.stack?.itemId);
const instance = item.stack?.instance ?? null;
return {
groundItemId: item.groundItemId,
tileX: item.tileX,
@@ -33,7 +33,10 @@ export function publicGroundItem (item)
itemId: item.stack.itemId,
quantity: item.stack.quantity,
displayName: stackDisplayLabel(item.stack),
sprite: itemSpriteName(item.stack.itemId, item.stack.instance),
sprite: itemSpriteName(item.stack.itemId, instance),
instance: instance && (instance.kind === "potion" || instance.kind === "letter" || instance.kind === "recipe-paper")
? instance
: null,
expiresAt: item.expiresAt
};
}
@@ -25,7 +25,7 @@ import { randomUUID } from "node:crypto";export function publicGroundItem (item)export function publicGroundItem (item){{ const def = itemDefinition(item.stack?.itemId); const instance = item.stack?.instance ?? null; return { return { groundItemId: item.groundItemId, groundItemId: item.groundItemId, tileX: item.tileX, tileX: item.tileX,@@ -33,7 +33,10 @@ export function publicGroundItem (item) itemId: item.stack.itemId, itemId: item.stack.itemId, quantity: item.stack.quantity, quantity: item.stack.quantity, displayName: stackDisplayLabel(item.stack), displayName: stackDisplayLabel(item.stack), sprite: itemSpriteName(item.stack.itemId, item.stack.instance), sprite: itemSpriteName(item.stack.itemId, instance), instance: instance && (instance.kind === "potion" || instance.kind === "letter" || instance.kind === "recipe-paper") ? instance : null, expiresAt: item.expiresAt expiresAt: item.expiresAt }; };}}@@ -766,6 +766,9 @@ export class Simulation
type: "inventory",
sessionId: item.sessionId,
bank: !!result.bank,
cauldron: result.cauldron,
cauldronState: result.cauldronState ?? null,
alchemyResult: result.alchemyResult ?? null,
...result.private
});
}
@@ -766,6 +766,9 @@ export class Simulation type: "inventory", type: "inventory", sessionId: item.sessionId, sessionId: item.sessionId, bank: !!result.bank, bank: !!result.bank, cauldron: result.cauldron, cauldronState: result.cauldronState ?? null, alchemyResult: result.alchemyResult ?? null, ...result.private ...result.private }); }); } }@@ -30,6 +30,7 @@ import {
publicGroundItem,
setGroundItemsForRegion
} from "../items/bags.js";
import { handleAlchemyCommand } from "../alchemy/service.js";
import {
applyRemoteMeleeSwing,
clearEngage,
@@ -367,6 +368,9 @@ export class WorkerWorld
return this.#cancelFollow(sessionId, command.characterId);
default:
{
const alchemy = handleAlchemyCommand(this, sessionId, command);
if (alchemy)
{ return alchemy; }
const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
return result ?? { events: [] };
}
@@ -30,6 +30,7 @@ import { publicGroundItem, publicGroundItem, setGroundItemsForRegion setGroundItemsForRegion} from "../items/bags.js";} from "../items/bags.js";import { handleAlchemyCommand } from "../alchemy/service.js";import {import { applyRemoteMeleeSwing, applyRemoteMeleeSwing, clearEngage, clearEngage,@@ -367,6 +368,9 @@ export class WorkerWorld return this.#cancelFollow(sessionId, command.characterId); return this.#cancelFollow(sessionId, command.characterId); default: default: { { const alchemy = handleAlchemyCommand(this, sessionId, command); if (alchemy) { return alchemy; } const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now()); const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now()); return result ?? { events: [] }; return result ?? { events: [] }; } }@@ -3,6 +3,7 @@ import {
GroundType,
BlockType,
isBlockPassable,
isGroundPassable,
blockLightRange,
normalizeGround,
normalizeBlock
@@ -147,7 +148,11 @@ export function setBlock (data, localX, localY, block)
export function isChunkTilePassable (data, localX, localY)
{
const block = data.blocks[tileIndex(localX, localY)];
const index = tileIndex(localX, localY);
const ground = normalizeGround(data.grounds[index]);
if (!isGroundPassable(ground.typeId))
{ return false; }
const block = data.blocks[index];
return isBlockPassable(block?.typeId ?? null);
}
@@ -3,6 +3,7 @@ import { GroundType, GroundType, BlockType, BlockType, isBlockPassable, isBlockPassable, isGroundPassable, blockLightRange, blockLightRange, normalizeGround, normalizeGround, normalizeBlock normalizeBlock@@ -147,7 +148,11 @@ export function setBlock (data, localX, localY, block)export function isChunkTilePassable (data, localX, localY)export function isChunkTilePassable (data, localX, localY){{ const block = data.blocks[tileIndex(localX, localY)]; const index = tileIndex(localX, localY); const ground = normalizeGround(data.grounds[index]); if (!isGroundPassable(ground.typeId)) { return false; } const block = data.blocks[index]; return isBlockPassable(block?.typeId ?? null); return isBlockPassable(block?.typeId ?? null);}}@@ -0,0 +1,161 @@
import test from "node:test";
import assert from "node:assert/strict";
import { BlockType } from "../../shared/definitions/tiles.js";
import { ItemId } from "../../shared/definitions/items.js";
import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";
import {
evaluateAlchemyBottle,
hashAlchemySteps,
resolvedAlchemyPotions,
unstablePotionFromSteps
} from "../../shared/alchemy/recipes.js";
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
import {
makeCharacter,
makeSimulation
} from "./helpers/simulationHarness.js";
function placeCauldron (worldDb, tileX, tileY)
{
const chunkX = Math.floor(tileX / 16);
const chunkY = Math.floor(tileY / 16);
const data = createEmptyChunkData();
data.open = true;
const localX = tileX - chunkX * 16;
const localY = tileY - chunkY * 16;
data.blocks[localY * 16 + localX] = { typeId: BlockType.cauldron, state: 0 };
worldDb.saveChunkVersion(
chunkX,
chunkY,
worldDb.getActiveRevisionId(),
true,
encodeChunkBlob(data)
);
}
function countItem (slots, itemId)
{
return (slots ?? [])
.filter((slot) => slot?.itemId === itemId)
.reduce((sum, slot) => sum + (slot.quantity | 0), 0);
}
test("green draught ratios and steps evaluate to a success batch", () =>
{
const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "greenDraught");
assert.ok(potion);
const evaluation = evaluateAlchemyBottle({
skills: { levels: { alchemy: 1 } },
brewStacks: [
{ itemId: ItemId.greenHerb, quantity: 4 },
{ itemId: ItemId.apple, quantity: 2 }
],
takenSteps: [
{ kind: AlchemyStepKind.heat },
{ kind: AlchemyStepKind.insert, itemId: ItemId.greenHerb },
{ kind: AlchemyStepKind.stir },
{ kind: AlchemyStepKind.insert, itemId: ItemId.apple },
{ kind: AlchemyStepKind.cool }
]
});
assert.equal(evaluation.success, true);
assert.equal(evaluation.batch, 2);
assert.equal(evaluation.result.potionKey, "greenDraught");
});
test("same wrong steps hash to the same unstable potion", () =>
{
const steps = [
{ kind: AlchemyStepKind.heat },
{ kind: AlchemyStepKind.stir },
{ kind: AlchemyStepKind.cool }
];
const a = unstablePotionFromSteps(steps);
const b = unstablePotionFromSteps(steps);
assert.equal(a.potionKey, b.potionKey);
assert.equal(a.stepsHash, hashAlchemySteps(steps));
});
test("cauldron bottles green draught when steps and ratios match", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
placeCauldron(harness.worldDb, 8, 8);
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
const inventory = emptySlots();
inventory[0] = { itemId: ItemId.greenHerb, quantity: 4 };
inventory[1] = { itemId: ItemId.apple, quantity: 2 };
inventory[2] = { itemId: ItemId.glassBottle, quantity: 2 };
inventory[3] = { itemId: ItemId.paper, quantity: 1 };
harness.stateDb.saveBag(character.character_id, {
inventory,
equipment: emptyEquipment(),
vault: [],
vaultReserved: []
});
const entityId = harness.simulation.spawnCharacter(1, character);
const cid = character.character_id;
harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
harness.simulation.step();
harness.simulation.enqueue(1, {
type: "cauldron-set-slot",
characterId: cid,
slotIndex: 0,
itemId: ItemId.greenHerb,
quantity: 4
});
harness.simulation.enqueue(1, {
type: "cauldron-set-slot",
characterId: cid,
slotIndex: 1,
itemId: ItemId.apple,
quantity: 2
});
harness.simulation.step();
harness.simulation.enqueue(1, {
type: "cauldron-action",
characterId: cid,
action: AlchemyStepKind.heat
});
harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 0 });
harness.simulation.enqueue(1, {
type: "cauldron-action",
characterId: cid,
action: AlchemyStepKind.stir
});
harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 });
harness.simulation.enqueue(1, {
type: "cauldron-action",
characterId: cid,
action: AlchemyStepKind.cool
});
harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid });
harness.simulation.step();
const bag = harness.simulation.bagOf(entityId);
assert.equal(countItem(bag.inventory, ItemId.greenHerb), 0);
assert.equal(countItem(bag.inventory, ItemId.apple), 0);
assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0);
assert.equal(countItem(bag.inventory, ItemId.potion), 2);
const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion);
assert.equal(potion.instance?.potionKey, "greenDraught");
assert.equal(potion.instance?.unstable, false);
harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid });
harness.simulation.step();
const after = harness.simulation.bagOf(entityId);
assert.equal(countItem(after.inventory, ItemId.paper), 0);
assert.equal(countItem(after.inventory, ItemId.recipePaper), 1);
const recipe = after.inventory.find((slot) => slot?.itemId === ItemId.recipePaper);
assert.match(recipe.instance?.body ?? "", /Green draught/);
assert.match(recipe.instance?.body ?? "", /Alchemy level required/);
}
finally
{ harness.close(); }
});
@@ -0,0 +1,161 @@import test from "node:test";import assert from "node:assert/strict";import { BlockType } from "../../shared/definitions/tiles.js";import { ItemId } from "../../shared/definitions/items.js";import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";import { evaluateAlchemyBottle, hashAlchemySteps, resolvedAlchemyPotions, unstablePotionFromSteps} from "../../shared/alchemy/recipes.js";import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";import { makeCharacter, makeSimulation} from "./helpers/simulationHarness.js";function placeCauldron (worldDb, tileX, tileY){ const chunkX = Math.floor(tileX / 16); const chunkY = Math.floor(tileY / 16); const data = createEmptyChunkData(); data.open = true; const localX = tileX - chunkX * 16; const localY = tileY - chunkY * 16; data.blocks[localY * 16 + localX] = { typeId: BlockType.cauldron, state: 0 }; worldDb.saveChunkVersion( chunkX, chunkY, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data) );}function countItem (slots, itemId){ return (slots ?? []) .filter((slot) => slot?.itemId === itemId) .reduce((sum, slot) => sum + (slot.quantity | 0), 0);}test("green draught ratios and steps evaluate to a success batch", () =>{ const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "greenDraught"); assert.ok(potion); const evaluation = evaluateAlchemyBottle({ skills: { levels: { alchemy: 1 } }, brewStacks: [ { itemId: ItemId.greenHerb, quantity: 4 }, { itemId: ItemId.apple, quantity: 2 } ], takenSteps: [ { kind: AlchemyStepKind.heat }, { kind: AlchemyStepKind.insert, itemId: ItemId.greenHerb }, { kind: AlchemyStepKind.stir }, { kind: AlchemyStepKind.insert, itemId: ItemId.apple }, { kind: AlchemyStepKind.cool } ] }); assert.equal(evaluation.success, true); assert.equal(evaluation.batch, 2); assert.equal(evaluation.result.potionKey, "greenDraught");});test("same wrong steps hash to the same unstable potion", () =>{ const steps = [ { kind: AlchemyStepKind.heat }, { kind: AlchemyStepKind.stir }, { kind: AlchemyStepKind.cool } ]; const a = unstablePotionFromSteps(steps); const b = unstablePotionFromSteps(steps); assert.equal(a.potionKey, b.potionKey); assert.equal(a.stepsHash, hashAlchemySteps(steps));});test("cauldron bottles green draught when steps and ratios match", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { placeCauldron(harness.worldDb, 8, 8); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 }); const inventory = emptySlots(); inventory[0] = { itemId: ItemId.greenHerb, quantity: 4 }; inventory[1] = { itemId: ItemId.apple, quantity: 2 }; inventory[2] = { itemId: ItemId.glassBottle, quantity: 2 }; inventory[3] = { itemId: ItemId.paper, quantity: 1 }; harness.stateDb.saveBag(character.character_id, { inventory, equipment: emptyEquipment(), vault: [], vaultReserved: [] }); const entityId = harness.simulation.spawnCharacter(1, character); const cid = character.character_id; harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid }); harness.simulation.step(); harness.simulation.enqueue(1, { type: "cauldron-set-slot", characterId: cid, slotIndex: 0, itemId: ItemId.greenHerb, quantity: 4 }); harness.simulation.enqueue(1, { type: "cauldron-set-slot", characterId: cid, slotIndex: 1, itemId: ItemId.apple, quantity: 2 }); harness.simulation.step(); harness.simulation.enqueue(1, { type: "cauldron-action", characterId: cid, action: AlchemyStepKind.heat }); harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 0 }); harness.simulation.enqueue(1, { type: "cauldron-action", characterId: cid, action: AlchemyStepKind.stir }); harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 }); harness.simulation.enqueue(1, { type: "cauldron-action", characterId: cid, action: AlchemyStepKind.cool }); harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid }); harness.simulation.step(); const bag = harness.simulation.bagOf(entityId); assert.equal(countItem(bag.inventory, ItemId.greenHerb), 0); assert.equal(countItem(bag.inventory, ItemId.apple), 0); assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0); assert.equal(countItem(bag.inventory, ItemId.potion), 2); const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion); assert.equal(potion.instance?.potionKey, "greenDraught"); assert.equal(potion.instance?.unstable, false); harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid }); harness.simulation.step(); const after = harness.simulation.bagOf(entityId); assert.equal(countItem(after.inventory, ItemId.paper), 0); assert.equal(countItem(after.inventory, ItemId.recipePaper), 1); const recipe = after.inventory.find((slot) => slot?.itemId === ItemId.recipePaper); assert.match(recipe.instance?.body ?? "", /Green draught/); assert.match(recipe.instance?.body ?? "", /Alchemy level required/); } finally { harness.close(); }});@@ -0,0 +1,20 @@
import test from "node:test";
import assert from "node:assert/strict";
import { GroundType, isGroundPassable, isWadeGround, isWaterGround } from "../../shared/definitions/tiles.js";
import { createEmptyChunkData, isChunkTilePassable, setGround } from "../src/world/chunkData.js";
test("deep water ground is impassable; shallow water is passable and wadeable", () =>
{
assert.equal(isGroundPassable(GroundType.water), true);
assert.equal(isGroundPassable(GroundType.deepWater), false);
assert.equal(isWadeGround(GroundType.water), true);
assert.equal(isWadeGround(GroundType.deepWater), false);
assert.equal(isWaterGround(GroundType.water), true);
assert.equal(isWaterGround(GroundType.deepWater), true);
const data = createEmptyChunkData();
setGround(data, 1, 1, GroundType.water);
setGround(data, 2, 2, GroundType.deepWater);
assert.equal(isChunkTilePassable(data, 1, 1), true);
assert.equal(isChunkTilePassable(data, 2, 2), false);
});
@@ -0,0 +1,20 @@import test from "node:test";import assert from "node:assert/strict";import { GroundType, isGroundPassable, isWadeGround, isWaterGround } from "../../shared/definitions/tiles.js";import { createEmptyChunkData, isChunkTilePassable, setGround } from "../src/world/chunkData.js";test("deep water ground is impassable; shallow water is passable and wadeable", () =>{ assert.equal(isGroundPassable(GroundType.water), true); assert.equal(isGroundPassable(GroundType.deepWater), false); assert.equal(isWadeGround(GroundType.water), true); assert.equal(isWadeGround(GroundType.deepWater), false); assert.equal(isWaterGround(GroundType.water), true); assert.equal(isWaterGround(GroundType.deepWater), true); const data = createEmptyChunkData(); setGround(data, 1, 1, GroundType.water); setGround(data, 2, 2, GroundType.deepWater); assert.equal(isChunkTilePassable(data, 1, 1), true); assert.equal(isChunkTilePassable(data, 2, 2), false);});