BlueGit

timfa questward

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.

timfa Tim Falken · pushed by timfa

Authored 2026-08-25 · 2 months ago

Hash
973474066b942029cef7e526a1b8938e1e2ed646
Parent
661b81e5
52 files changed +2142 −58
.cursor/rules/shader-darkness.mdc added +35 −0
@@ -0,0 +1,35 @@
1 ---
2 description: All world/item shaders must respect night darkness unless unlit or bloom.
3 alwaysApply: true
4 ---
5
6 # Shaders respect darkness
7
8 Lit world and item shaders **must** apply the scene darkness value (e.g. `u_darkness` / ambient night darkening) unless explicitly exempt.
9
10 ## Must darken
11
12 - Entity sprites, equipment overlays, ground items
13 - Ground/block tiles (atlas or individual), water, wade foam, coastline foam
14 - Potion liquid recolor / tint passes drawn in the lit world
15
16 Compose effects **before** darkness when possible: tint/foam/recolor first, then `mix(rgb, vec3(0.0), darkness)`.
17
18 ## Exempt (unlit)
19
20 - Bloom-layer sprites (`RENDER_LAYER_BLOOM` / bloom companions)
21 - Explicitly unlit utilities (chunk edges, editor overlays, UI chrome)
22 - Pure UI elements not drawn through the world lit pipeline (DOM inventory panels may tint without world darkness; world-dropped potions still must darken)
23
24 ```text
25 # ❌ BAD — fancy tint ignores night
26 rgb = mix(rgb, potionColor, 1.0);
27 gl_FragColor = vec4(rgb, a);
28
29 # ✅ GOOD — tint then darkness
30 rgb = mix(rgb, potionColor, fill);
31 rgb = mix(rgb, vec3(0.0), u_darkness);
32 gl_FragColor = vec4(rgb, a);
33 ```
34
35 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 @@
1---
2description: All world/item shaders must respect night darkness unless unlit or bloom.
3alwaysApply: true
4---
5
6# Shaders respect darkness
7
8Lit world and item shaders **must** apply the scene darkness value (e.g. `u_darkness` / ambient night darkening) unless explicitly exempt.
9
10## Must darken
11
12- Entity sprites, equipment overlays, ground items
13- Ground/block tiles (atlas or individual), water, wade foam, coastline foam
14- Potion liquid recolor / tint passes drawn in the lit world
15
16Compose effects **before** darkness when possible: tint/foam/recolor first, then `mix(rgb, vec3(0.0), darkness)`.
17
18## Exempt (unlit)
19
20- Bloom-layer sprites (`RENDER_LAYER_BLOOM` / bloom companions)
21- Explicitly unlit utilities (chunk edges, editor overlays, UI chrome)
22- Pure UI elements not drawn through the world lit pipeline (DOM inventory panels may tint without world darkness; world-dropped potions still must darken)
23
24```text
25# ❌ BAD — fancy tint ignores night
26rgb = mix(rgb, potionColor, 1.0);
27gl_FragColor = vec4(rgb, a);
28
29# ✅ GOOD — tint then darkness
30rgb = mix(rgb, potionColor, fill);
31rgb = mix(rgb, vec3(0.0), u_darkness);
32gl_FragColor = vec4(rgb, a);
33```
34
35When adding a new fragment shader for the game world, default to respecting darkness; document any unlit exception in code comments.
client/assets/blocks/cauldron/cauldron.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/grounds/deep-water/deep-water.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/grounds/water/water.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bronze-plant-clippers/bronze-plant-clippers-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bronze-plant-clippers/bronze-plant-clippers.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/glass-bottle/glass-bottle.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/green-herb/green-herb.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/fill-1.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/fill-2.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/fill-3.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/fill-4.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/fill-5.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion-1.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion-2.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion-3.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion-4.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion-5.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/red-beet/red-beet.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/skills/alchemy.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/herbalism.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/index.html +34 −0
@@ -172,6 +172,40 @@
172 172 </div>
173 173 </aside>
174 174
175 <div id="cauldron-backdrop" class="modal-backdrop" hidden></div>
176 <aside id="cauldron-panel" hidden>
177 <header>
178 <h2>Cauldron</h2>
179 <button id="cauldron-close" type="button">Close</button>
180 </header>
181 <div id="cauldron-slots" class="cauldron-slots"></div>
182 <div id="cauldron-inserts" class="cauldron-inserts"></div>
183 <div class="cauldron-vessel" aria-hidden="true">⚗</div>
184 <div class="cauldron-actions">
185 <button id="cauldron-stir" type="button">Stir</button>
186 <button id="cauldron-heat" type="button">Heat</button>
187 <button id="cauldron-cool" type="button">Cool</button>
188 </div>
189 <div class="cauldron-finish">
190 <button id="cauldron-bottle" type="button">Bottle</button>
191 <button id="cauldron-clear" type="button">Clear</button>
192 <button id="cauldron-save-recipe" type="button" hidden>Save Recipe</button>
193 </div>
194 <ol id="cauldron-steps" class="cauldron-steps"></ol>
195 <p id="cauldron-status" class="hint"></p>
196 </aside>
197
198 <div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div>
199 <aside id="cauldron-pick-panel" hidden>
200 <header>
201 <h2>Choose ingredient</h2>
202 <button id="cauldron-pick-cancel" type="button">Cancel</button>
203 </header>
204 <div id="cauldron-pick-list" class="cauldron-pick-list"></div>
205 <label class="cauldron-pick-qty">Quantity <input id="cauldron-pick-qty" type="number" min="1" value="1"></label>
206 <button id="cauldron-pick-confirm" type="button">Place in slot</button>
207 </aside>
208
175 209 <div id="nametag" hidden></div>
176 210 <div id="damage-numbers"></div>
177 211 <div id="chat-bubbles"></div>
@@ -172,6 +172,40 @@
172 </div>
172 </div>
173 </aside>
173 </aside>
174
174
175 <div id="cauldron-backdrop" class="modal-backdrop" hidden></div>
176 <aside id="cauldron-panel" hidden>
177 <header>
178 <h2>Cauldron</h2>
179 <button id="cauldron-close" type="button">Close</button>
180 </header>
181 <div id="cauldron-slots" class="cauldron-slots"></div>
182 <div id="cauldron-inserts" class="cauldron-inserts"></div>
183 <div class="cauldron-vessel" aria-hidden="true">⚗</div>
184 <div class="cauldron-actions">
185 <button id="cauldron-stir" type="button">Stir</button>
186 <button id="cauldron-heat" type="button">Heat</button>
187 <button id="cauldron-cool" type="button">Cool</button>
188 </div>
189 <div class="cauldron-finish">
190 <button id="cauldron-bottle" type="button">Bottle</button>
191 <button id="cauldron-clear" type="button">Clear</button>
192 <button id="cauldron-save-recipe" type="button" hidden>Save Recipe</button>
193 </div>
194 <ol id="cauldron-steps" class="cauldron-steps"></ol>
195 <p id="cauldron-status" class="hint"></p>
196 </aside>
197
198 <div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div>
199 <aside id="cauldron-pick-panel" hidden>
200 <header>
201 <h2>Choose ingredient</h2>
202 <button id="cauldron-pick-cancel" type="button">Cancel</button>
203 </header>
204 <div id="cauldron-pick-list" class="cauldron-pick-list"></div>
205 <label class="cauldron-pick-qty">Quantity <input id="cauldron-pick-qty" type="number" min="1" value="1"></label>
206 <button id="cauldron-pick-confirm" type="button">Place in slot</button>
207 </aside>
208
175 <div id="nametag" hidden></div>
209 <div id="nametag" hidden></div>
176 <div id="damage-numbers"></div>
210 <div id="damage-numbers"></div>
177 <div id="chat-bubbles"></div>
211 <div id="chat-bubbles"></div>
client/scripts/generate-skill-icons.mjs +6 −2
@@ -21,7 +21,9 @@ const labels = {
21 21 crafting: "CR",
22 22 leatherworking: "LW",
23 23 tailoring: "TL",
24 cooking: "CK"
24 cooking: "CK",
25 herbalism: "HB",
26 alchemy: "AL"
25 27 };
26 28
27 29 const colors = {
@@ -44,7 +46,9 @@ const colors = {
44 46 crafting: "#806080",
45 47 leatherworking: "#8a6040",
46 48 tailoring: "#7070a0",
47 cooking: "#a06030"
49 cooking: "#a06030",
50 herbalism: "#3a8a48",
51 alchemy: "#6a40a0"
48 52 };
49 53
50 54 mkdirSync(new URL("../assets/skills/", import.meta.url), { recursive: true });
@@ -21,7 +21,9 @@ const labels = {
21 crafting: "CR",
21 crafting: "CR",
22 leatherworking: "LW",
22 leatherworking: "LW",
23 tailoring: "TL",
23 tailoring: "TL",
24 cooking: "CK"
24 cooking: "CK",
25 herbalism: "HB",
26 alchemy: "AL"
25};
27};
26
28
27const colors = {
29const colors = {
@@ -44,7 +46,9 @@ const colors = {
44 crafting: "#806080",
46 crafting: "#806080",
45 leatherworking: "#8a6040",
47 leatherworking: "#8a6040",
46 tailoring: "#7070a0",
48 tailoring: "#7070a0",
47 cooking: "#a06030"
49 cooking: "#a06030",
50 herbalism: "#3a8a48",
51 alchemy: "#6a40a0"
48};
52};
49
53
50mkdirSync(new URL("../assets/skills/", import.meta.url), { recursive: true });
54mkdirSync(new URL("../assets/skills/", import.meta.url), { recursive: true });
client/scripts/write-placeholder-assets.mjs +33 −0
@@ -53,6 +53,39 @@ overlay(join(root, "items", "lantern", "lantern-equip.png"), [200, 130, 48, 230]
53 53 torchBloom(join(root, "items", "lantern", "lantern-equip-bloom.png"));
54 54 torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
55 55
56 function writeWaterSheet (file, base, wave, foam)
57 {
58 const frames = 4;
59 const width = 16 * frames;
60 const height = 16;
61 const image = makeRgba(width, height, base);
62 for (let f = 0; f < frames; f++)
63 {
64 const ox = f * 16;
65 for (let y = 0; y < 16; y++)
66 {
67 const t = y / 15;
68 fillRect(image, ox, y, 16, 1, [
69 Math.round(base[0] * (1 - t * 0.15)),
70 Math.round(base[1] * (1 - t * 0.08)),
71 Math.round(base[2] * (1 + t * 0.05)),
72 255
73 ]);
74 }
75 for (let i = 0; i < 3; i++)
76 {
77 const y = 3 + ((i * 4 + f) % 10);
78 const x0 = ox + ((f * 3 + i * 5) % 12);
79 fillRect(image, x0, y, 5, 1, wave);
80 fillRect(image, x0 + 1, y - 1, 3, 1, foam);
81 }
82 }
83 writeRgbaPng(file, width, height, image.pixels);
84 }
85
86 writeWaterSheet(join(root, "grounds", "water", "water.png"), [48, 118, 168, 255], [90, 170, 210, 255], [170, 220, 240, 220]);
87 writeWaterSheet(join(root, "grounds", "deep-water", "deep-water.png"), [28, 72, 118, 255], [55, 120, 170, 255], [110, 170, 210, 200]);
88
56 89 {
57 90 const image = makeRgba(24, 8, [0, 0, 0, 0]);
58 91 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]
53torchBloom(join(root, "items", "lantern", "lantern-equip-bloom.png"));
53torchBloom(join(root, "items", "lantern", "lantern-equip-bloom.png"));
54torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
54torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
55
55
56function writeWaterSheet (file, base, wave, foam)
57{
58 const frames = 4;
59 const width = 16 * frames;
60 const height = 16;
61 const image = makeRgba(width, height, base);
62 for (let f = 0; f < frames; f++)
63 {
64 const ox = f * 16;
65 for (let y = 0; y < 16; y++)
66 {
67 const t = y / 15;
68 fillRect(image, ox, y, 16, 1, [
69 Math.round(base[0] * (1 - t * 0.15)),
70 Math.round(base[1] * (1 - t * 0.08)),
71 Math.round(base[2] * (1 + t * 0.05)),
72 255
73 ]);
74 }
75 for (let i = 0; i < 3; i++)
76 {
77 const y = 3 + ((i * 4 + f) % 10);
78 const x0 = ox + ((f * 3 + i * 5) % 12);
79 fillRect(image, x0, y, 5, 1, wave);
80 fillRect(image, x0 + 1, y - 1, 3, 1, foam);
81 }
82 }
83 writeRgbaPng(file, width, height, image.pixels);
84}
85
86writeWaterSheet(join(root, "grounds", "water", "water.png"), [48, 118, 168, 255], [90, 170, 210, 255], [170, 220, 240, 220]);
87writeWaterSheet(join(root, "grounds", "deep-water", "deep-water.png"), [28, 72, 118, 255], [55, 120, 170, 255], [110, 170, 210, 200]);
88
56{
89{
57 const image = makeRgba(24, 8, [0, 0, 0, 0]);
90 const image = makeRgba(24, 8, [0, 0, 0, 0]);
58 fillRect(image, 1, 2, 22, 4, [240, 220, 160, 220]);
91 fillRect(image, 1, 2, 22, 4, [240, 220, 160, 220]);
client/src/play/alchemy.js added +248 −0
@@ -0,0 +1,248 @@
1 import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity,
6 ItemId
7 } from "/shared/definitions/items.js";
8 import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "/shared/definitions/alchemy.js";
9 import { applyItemIcon } from "../render/potionIcon.js";
10
11 export function initAlchemy ({
12 socket,
13 MessageType,
14 getInventorySlots
15 })
16 {
17 const backdrop = document.getElementById("cauldron-backdrop");
18 const panel = document.getElementById("cauldron-panel");
19 const slotsEl = document.getElementById("cauldron-slots");
20 const insertsEl = document.getElementById("cauldron-inserts");
21 const stepsEl = document.getElementById("cauldron-steps");
22 const statusEl = document.getElementById("cauldron-status");
23 const saveBtn = document.getElementById("cauldron-save-recipe");
24 const pickBackdrop = document.getElementById("cauldron-pick-backdrop");
25 const pickPanel = document.getElementById("cauldron-pick-panel");
26 const pickList = document.getElementById("cauldron-pick-list");
27 const pickQty = document.getElementById("cauldron-pick-qty");
28
29 let open = false;
30 let state = null;
31 let pickSlotIndex = null;
32 let pickItemId = null;
33
34 document.getElementById("cauldron-close")?.addEventListener("click", () => close());
35 backdrop?.addEventListener("click", () => close());
36 document.getElementById("cauldron-stir")?.addEventListener("click", () =>
37 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.stir }); });
38 document.getElementById("cauldron-heat")?.addEventListener("click", () =>
39 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.heat }); });
40 document.getElementById("cauldron-cool")?.addEventListener("click", () =>
41 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.cool }); });
42 document.getElementById("cauldron-bottle")?.addEventListener("click", () =>
43 { socket.send({ type: MessageType.cauldronBottle }); });
44 document.getElementById("cauldron-clear")?.addEventListener("click", () =>
45 { socket.send({ type: MessageType.cauldronClear }); });
46 saveBtn?.addEventListener("click", () =>
47 { socket.send({ type: MessageType.cauldronSaveRecipe }); });
48 document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick());
49 document.getElementById("cauldron-pick-confirm")?.addEventListener("click", () => confirmPick());
50 pickBackdrop?.addEventListener("click", () => closePick());
51
52 function render ()
53 {
54 if (!open || !panel)
55 { return; }
56 renderSlots();
57 renderSteps();
58 if (saveBtn)
59 { saveBtn.hidden = !state?.canSaveRecipe; }
60 }
61
62 function renderSlots ()
63 {
64 slotsEl.replaceChildren();
65 insertsEl.replaceChildren();
66 for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
67 {
68 const reserved = state?.slots?.[i] ?? null;
69 const slotBtn = document.createElement("button");
70 slotBtn.type = "button";
71 slotBtn.className = "cauldron-slot";
72 if (reserved)
73 {
74 const img = document.createElement("img");
75 const stack = { itemId: reserved.itemId, quantity: reserved.quantity };
76 applyItemIcon(img, stack, itemAssetPathForStack(stack));
77 img.alt = itemDisplayName(stack);
78 const qty = document.createElement("span");
79 qty.className = "qty";
80 qty.textContent = formatQuantity(reserved.quantity);
81 slotBtn.append(img, qty);
82 slotBtn.title = `${itemDisplayName(stack)} ×${reserved.quantity}`;
83 }
84 else
85 { slotBtn.textContent = "+"; }
86 slotBtn.addEventListener("click", () => openPick(i));
87 slotsEl.append(slotBtn);
88
89 const insertBtn = document.createElement("button");
90 insertBtn.type = "button";
91 insertBtn.className = "cauldron-insert";
92 insertBtn.textContent = "↓";
93 insertBtn.disabled = !reserved;
94 insertBtn.title = "Insert into cauldron";
95 insertBtn.addEventListener("click", () =>
96 { socket.send({ type: MessageType.cauldronInsert, slotIndex: i }); });
97 insertsEl.append(insertBtn);
98 }
99 }
100
101 function renderSteps ()
102 {
103 stepsEl.replaceChildren();
104 for (const step of state?.steps ?? [])
105 {
106 const li = document.createElement("li");
107 if (step.kind === AlchemyStepKind.insert)
108 {
109 const def = itemDefinition(step.itemId);
110 li.textContent = `insert ${def?.displayName ?? step.itemId}`;
111 }
112 else
113 { li.textContent = step.kind; }
114 stepsEl.append(li);
115 }
116 }
117
118 function openPick (slotIndex)
119 {
120 pickSlotIndex = slotIndex;
121 pickItemId = null;
122 pickList.replaceChildren();
123 const counts = new Map();
124 for (const slot of getInventorySlots?.() ?? [])
125 {
126 if (!slot)
127 { continue; }
128 const def = itemDefinition(slot.itemId);
129 if (!def || def.uniqueInstance || def.equipment
130 || slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle)
131 { continue; }
132 counts.set(slot.itemId, (counts.get(slot.itemId) ?? 0) + (slot.quantity | 0));
133 }
134 for (const [itemId, quantity] of counts)
135 {
136 const stack = { itemId, quantity };
137 const btn = document.createElement("button");
138 btn.type = "button";
139 btn.className = "cauldron-pick-item";
140 const img = document.createElement("img");
141 applyItemIcon(img, stack, itemAssetPathForStack(stack));
142 const label = document.createElement("span");
143 label.textContent = `${itemDisplayName(stack)} (${formatQuantity(quantity)})`;
144 btn.append(img, label);
145 btn.addEventListener("click", () =>
146 {
147 pickItemId = itemId;
148 pickQty.max = String(quantity);
149 pickQty.value = String(Math.min(quantity, Number(pickQty.value) || 1));
150 for (const child of pickList.children)
151 { child.classList.toggle("selected", child === btn); }
152 });
153 pickList.append(btn);
154 }
155 pickQty.value = "1";
156 pickBackdrop.hidden = false;
157 pickPanel.hidden = false;
158 }
159
160 function closePick ()
161 {
162 pickBackdrop.hidden = true;
163 pickPanel.hidden = true;
164 pickSlotIndex = null;
165 pickItemId = null;
166 }
167
168 function confirmPick ()
169 {
170 if (pickSlotIndex == null || pickItemId == null)
171 { return; }
172 const quantity = Math.max(1, pickQty.value | 0);
173 socket.send({
174 type: MessageType.cauldronSetSlot,
175 slotIndex: pickSlotIndex,
176 itemId: pickItemId,
177 quantity
178 });
179 closePick();
180 }
181
182 function openFromServer (nextState)
183 {
184 open = true;
185 state = nextState;
186 backdrop.hidden = false;
187 panel.hidden = false;
188 statusEl.textContent = "";
189 render();
190 }
191
192 function close ()
193 {
194 if (!open)
195 { return; }
196 open = false;
197 backdrop.hidden = true;
198 panel.hidden = true;
199 closePick();
200 socket.send({ type: MessageType.cauldronClose });
201 }
202
203 return {
204 isBlocking ()
205 { return open || !pickPanel?.hidden; },
206 reset ()
207 {
208 open = false;
209 state = null;
210 if (backdrop)
211 { backdrop.hidden = true; }
212 if (panel)
213 { panel.hidden = true; }
214 closePick();
215 },
216 handleSnapshot (message)
217 {
218 if (!message.open)
219 {
220 open = false;
221 if (backdrop)
222 { backdrop.hidden = true; }
223 if (panel)
224 { panel.hidden = true; }
225 state = null;
226 return;
227 }
228 if (!open)
229 { openFromServer(message.state); }
230 else
231 {
232 state = message.state;
233 render();
234 }
235 if (message.alchemyResult)
236 {
237 const result = message.alchemyResult;
238 const name = result.potion?.displayName ?? "Potion";
239 const lost = result.lost > 0 ? ` (${result.lost} lost — not enough bottles)` : "";
240 statusEl.textContent = result.success
241 ? `Bottled ${result.produced}× ${name}${lost}.`
242 : `Unstable brew: ${result.produced}× ${name}${lost}.`;
243 }
244 },
245 refresh ()
246 { render(); }
247 };
248 }
@@ -0,0 +1,248 @@
1import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity,
6 ItemId
7} from "/shared/definitions/items.js";
8import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "/shared/definitions/alchemy.js";
9import { applyItemIcon } from "../render/potionIcon.js";
10
11export function initAlchemy ({
12 socket,
13 MessageType,
14 getInventorySlots
15})
16{
17 const backdrop = document.getElementById("cauldron-backdrop");
18 const panel = document.getElementById("cauldron-panel");
19 const slotsEl = document.getElementById("cauldron-slots");
20 const insertsEl = document.getElementById("cauldron-inserts");
21 const stepsEl = document.getElementById("cauldron-steps");
22 const statusEl = document.getElementById("cauldron-status");
23 const saveBtn = document.getElementById("cauldron-save-recipe");
24 const pickBackdrop = document.getElementById("cauldron-pick-backdrop");
25 const pickPanel = document.getElementById("cauldron-pick-panel");
26 const pickList = document.getElementById("cauldron-pick-list");
27 const pickQty = document.getElementById("cauldron-pick-qty");
28
29 let open = false;
30 let state = null;
31 let pickSlotIndex = null;
32 let pickItemId = null;
33
34 document.getElementById("cauldron-close")?.addEventListener("click", () => close());
35 backdrop?.addEventListener("click", () => close());
36 document.getElementById("cauldron-stir")?.addEventListener("click", () =>
37 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.stir }); });
38 document.getElementById("cauldron-heat")?.addEventListener("click", () =>
39 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.heat }); });
40 document.getElementById("cauldron-cool")?.addEventListener("click", () =>
41 { socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.cool }); });
42 document.getElementById("cauldron-bottle")?.addEventListener("click", () =>
43 { socket.send({ type: MessageType.cauldronBottle }); });
44 document.getElementById("cauldron-clear")?.addEventListener("click", () =>
45 { socket.send({ type: MessageType.cauldronClear }); });
46 saveBtn?.addEventListener("click", () =>
47 { socket.send({ type: MessageType.cauldronSaveRecipe }); });
48 document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick());
49 document.getElementById("cauldron-pick-confirm")?.addEventListener("click", () => confirmPick());
50 pickBackdrop?.addEventListener("click", () => closePick());
51
52 function render ()
53 {
54 if (!open || !panel)
55 { return; }
56 renderSlots();
57 renderSteps();
58 if (saveBtn)
59 { saveBtn.hidden = !state?.canSaveRecipe; }
60 }
61
62 function renderSlots ()
63 {
64 slotsEl.replaceChildren();
65 insertsEl.replaceChildren();
66 for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
67 {
68 const reserved = state?.slots?.[i] ?? null;
69 const slotBtn = document.createElement("button");
70 slotBtn.type = "button";
71 slotBtn.className = "cauldron-slot";
72 if (reserved)
73 {
74 const img = document.createElement("img");
75 const stack = { itemId: reserved.itemId, quantity: reserved.quantity };
76 applyItemIcon(img, stack, itemAssetPathForStack(stack));
77 img.alt = itemDisplayName(stack);
78 const qty = document.createElement("span");
79 qty.className = "qty";
80 qty.textContent = formatQuantity(reserved.quantity);
81 slotBtn.append(img, qty);
82 slotBtn.title = `${itemDisplayName(stack)} ×${reserved.quantity}`;
83 }
84 else
85 { slotBtn.textContent = "+"; }
86 slotBtn.addEventListener("click", () => openPick(i));
87 slotsEl.append(slotBtn);
88
89 const insertBtn = document.createElement("button");
90 insertBtn.type = "button";
91 insertBtn.className = "cauldron-insert";
92 insertBtn.textContent = "↓";
93 insertBtn.disabled = !reserved;
94 insertBtn.title = "Insert into cauldron";
95 insertBtn.addEventListener("click", () =>
96 { socket.send({ type: MessageType.cauldronInsert, slotIndex: i }); });
97 insertsEl.append(insertBtn);
98 }
99 }
100
101 function renderSteps ()
102 {
103 stepsEl.replaceChildren();
104 for (const step of state?.steps ?? [])
105 {
106 const li = document.createElement("li");
107 if (step.kind === AlchemyStepKind.insert)
108 {
109 const def = itemDefinition(step.itemId);
110 li.textContent = `insert ${def?.displayName ?? step.itemId}`;
111 }
112 else
113 { li.textContent = step.kind; }
114 stepsEl.append(li);
115 }
116 }
117
118 function openPick (slotIndex)
119 {
120 pickSlotIndex = slotIndex;
121 pickItemId = null;
122 pickList.replaceChildren();
123 const counts = new Map();
124 for (const slot of getInventorySlots?.() ?? [])
125 {
126 if (!slot)
127 { continue; }
128 const def = itemDefinition(slot.itemId);
129 if (!def || def.uniqueInstance || def.equipment
130 || slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle)
131 { continue; }
132 counts.set(slot.itemId, (counts.get(slot.itemId) ?? 0) + (slot.quantity | 0));
133 }
134 for (const [itemId, quantity] of counts)
135 {
136 const stack = { itemId, quantity };
137 const btn = document.createElement("button");
138 btn.type = "button";
139 btn.className = "cauldron-pick-item";
140 const img = document.createElement("img");
141 applyItemIcon(img, stack, itemAssetPathForStack(stack));
142 const label = document.createElement("span");
143 label.textContent = `${itemDisplayName(stack)} (${formatQuantity(quantity)})`;
144 btn.append(img, label);
145 btn.addEventListener("click", () =>
146 {
147 pickItemId = itemId;
148 pickQty.max = String(quantity);
149 pickQty.value = String(Math.min(quantity, Number(pickQty.value) || 1));
150 for (const child of pickList.children)
151 { child.classList.toggle("selected", child === btn); }
152 });
153 pickList.append(btn);
154 }
155 pickQty.value = "1";
156 pickBackdrop.hidden = false;
157 pickPanel.hidden = false;
158 }
159
160 function closePick ()
161 {
162 pickBackdrop.hidden = true;
163 pickPanel.hidden = true;
164 pickSlotIndex = null;
165 pickItemId = null;
166 }
167
168 function confirmPick ()
169 {
170 if (pickSlotIndex == null || pickItemId == null)
171 { return; }
172 const quantity = Math.max(1, pickQty.value | 0);
173 socket.send({
174 type: MessageType.cauldronSetSlot,
175 slotIndex: pickSlotIndex,
176 itemId: pickItemId,
177 quantity
178 });
179 closePick();
180 }
181
182 function openFromServer (nextState)
183 {
184 open = true;
185 state = nextState;
186 backdrop.hidden = false;
187 panel.hidden = false;
188 statusEl.textContent = "";
189 render();
190 }
191
192 function close ()
193 {
194 if (!open)
195 { return; }
196 open = false;
197 backdrop.hidden = true;
198 panel.hidden = true;
199 closePick();
200 socket.send({ type: MessageType.cauldronClose });
201 }
202
203 return {
204 isBlocking ()
205 { return open || !pickPanel?.hidden; },
206 reset ()
207 {
208 open = false;
209 state = null;
210 if (backdrop)
211 { backdrop.hidden = true; }
212 if (panel)
213 { panel.hidden = true; }
214 closePick();
215 },
216 handleSnapshot (message)
217 {
218 if (!message.open)
219 {
220 open = false;
221 if (backdrop)
222 { backdrop.hidden = true; }
223 if (panel)
224 { panel.hidden = true; }
225 state = null;
226 return;
227 }
228 if (!open)
229 { openFromServer(message.state); }
230 else
231 {
232 state = message.state;
233 render();
234 }
235 if (message.alchemyResult)
236 {
237 const result = message.alchemyResult;
238 const name = result.potion?.displayName ?? "Potion";
239 const lost = result.lost > 0 ? ` (${result.lost} lost — not enough bottles)` : "";
240 statusEl.textContent = result.success
241 ? `Bottled ${result.produced}× ${name}${lost}.`
242 : `Unstable brew: ${result.produced}× ${name}${lost}.`;
243 }
244 },
245 refresh ()
246 { render(); }
247 };
248}
client/src/play/inventory.js +24 −5
@@ -9,6 +9,7 @@ import {
9 9 EQUIPMENT_SLOT,
10 10 LETTER_MAX_BODY_CHARS
11 11 } from "/shared/definitions/items.js";
12 import { applyItemIcon } from "../render/potionIcon.js";
12 13
13 14 const EQUIP_LABELS = {
14 15 [EQUIPMENT_SLOT.head]: "Head",
@@ -156,7 +157,7 @@ export function initInventory ({
156 157 {
157 158 const def = itemDefinition(slot.itemId);
158 159 const img = document.createElement("img");
159 img.src = itemAssetPathForStack(slot);
160 applyItemIcon(img, slot, itemAssetPathForStack(slot));
160 161 img.alt = itemDisplayName(slot);
161 162 button.append(img);
162 163 if (slot.quantity > 1)
@@ -206,7 +207,7 @@ export function initInventory ({
206 207 {
207 208 const def = itemDefinition(worn.itemId);
208 209 const img = document.createElement("img");
209 img.src = itemAssetPathForStack(worn);
210 applyItemIcon(img, worn, itemAssetPathForStack(worn));
210 211 img.alt = itemDisplayName(worn);
211 212 button.append(img);
212 213 }
@@ -264,6 +265,20 @@ export function initInventory ({
264 265 });
265 266 }
266 267 }
268 if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper")
269 {
270 items.push({
271 label: "Read",
272 onSelect: () => openLetter({
273 mode: "read",
274 slotIndex,
275 instance: {
276 body: slot.instance.body ?? "",
277 authorDisplayName: slot.instance.displayName ?? "Alchemy recipe"
278 }
279 })
280 });
281 }
267 282 if (slot.itemId === ItemId.blankCheque)
268 283 {
269 284 items.push({
@@ -459,7 +474,7 @@ export function initInventory ({
459 474 button.title = tooltip(slot);
460 475 const def = itemDefinition(slot.itemId);
461 476 const img = document.createElement("img");
462 img.src = itemAssetPathForStack(slot);
477 applyItemIcon(img, slot, itemAssetPathForStack(slot));
463 478 img.alt = itemDisplayName(slot);
464 479 button.append(img);
465 480 if (slot.quantity > 1)
@@ -531,7 +546,11 @@ export function initInventory ({
531 546 maxQty: slot.quantity | 0,
532 547 destination: null
533 548 };
534 document.getElementById("send-item-img").src = itemAssetPathForStack(slot);
549 applyItemIcon(
550 document.getElementById("send-item-img"),
551 slot,
552 itemAssetPathForStack(slot)
553 );
535 554 document.getElementById("send-item-name").textContent = itemDisplayName(slot);
536 555 const qtyInput = document.getElementById("send-qty");
537 556 qtyInput.value = "1";
@@ -717,7 +736,7 @@ export function initInventory ({
717 736 button.title = tooltip(slot);
718 737 const def = itemDefinition(slot.itemId);
719 738 const img = document.createElement("img");
720 img.src = itemAssetPathForStack(slot);
739 applyItemIcon(img, slot, itemAssetPathForStack(slot));
721 740 img.alt = itemDisplayName(slot);
722 741 button.append(img);
723 742 if (slot.quantity > 1)
@@ -9,6 +9,7 @@ import {
9 EQUIPMENT_SLOT,
9 EQUIPMENT_SLOT,
10 LETTER_MAX_BODY_CHARS
10 LETTER_MAX_BODY_CHARS
11} from "/shared/definitions/items.js";
11} from "/shared/definitions/items.js";
12import { applyItemIcon } from "../render/potionIcon.js";
12
13
13const EQUIP_LABELS = {
14const EQUIP_LABELS = {
14 [EQUIPMENT_SLOT.head]: "Head",
15 [EQUIPMENT_SLOT.head]: "Head",
@@ -156,7 +157,7 @@ export function initInventory ({
156 {
157 {
157 const def = itemDefinition(slot.itemId);
158 const def = itemDefinition(slot.itemId);
158 const img = document.createElement("img");
159 const img = document.createElement("img");
159 img.src = itemAssetPathForStack(slot);
160 applyItemIcon(img, slot, itemAssetPathForStack(slot));
160 img.alt = itemDisplayName(slot);
161 img.alt = itemDisplayName(slot);
161 button.append(img);
162 button.append(img);
162 if (slot.quantity > 1)
163 if (slot.quantity > 1)
@@ -206,7 +207,7 @@ export function initInventory ({
206 {
207 {
207 const def = itemDefinition(worn.itemId);
208 const def = itemDefinition(worn.itemId);
208 const img = document.createElement("img");
209 const img = document.createElement("img");
209 img.src = itemAssetPathForStack(worn);
210 applyItemIcon(img, worn, itemAssetPathForStack(worn));
210 img.alt = itemDisplayName(worn);
211 img.alt = itemDisplayName(worn);
211 button.append(img);
212 button.append(img);
212 }
213 }
@@ -264,6 +265,20 @@ export function initInventory ({
264 });
265 });
265 }
266 }
266 }
267 }
268 if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper")
269 {
270 items.push({
271 label: "Read",
272 onSelect: () => openLetter({
273 mode: "read",
274 slotIndex,
275 instance: {
276 body: slot.instance.body ?? "",
277 authorDisplayName: slot.instance.displayName ?? "Alchemy recipe"
278 }
279 })
280 });
281 }
267 if (slot.itemId === ItemId.blankCheque)
282 if (slot.itemId === ItemId.blankCheque)
268 {
283 {
269 items.push({
284 items.push({
@@ -459,7 +474,7 @@ export function initInventory ({
459 button.title = tooltip(slot);
474 button.title = tooltip(slot);
460 const def = itemDefinition(slot.itemId);
475 const def = itemDefinition(slot.itemId);
461 const img = document.createElement("img");
476 const img = document.createElement("img");
462 img.src = itemAssetPathForStack(slot);
477 applyItemIcon(img, slot, itemAssetPathForStack(slot));
463 img.alt = itemDisplayName(slot);
478 img.alt = itemDisplayName(slot);
464 button.append(img);
479 button.append(img);
465 if (slot.quantity > 1)
480 if (slot.quantity > 1)
@@ -531,7 +546,11 @@ export function initInventory ({
531 maxQty: slot.quantity | 0,
546 maxQty: slot.quantity | 0,
532 destination: null
547 destination: null
533 };
548 };
534 document.getElementById("send-item-img").src = itemAssetPathForStack(slot);
549 applyItemIcon(
550 document.getElementById("send-item-img"),
551 slot,
552 itemAssetPathForStack(slot)
553 );
535 document.getElementById("send-item-name").textContent = itemDisplayName(slot);
554 document.getElementById("send-item-name").textContent = itemDisplayName(slot);
536 const qtyInput = document.getElementById("send-qty");
555 const qtyInput = document.getElementById("send-qty");
537 qtyInput.value = "1";
556 qtyInput.value = "1";
@@ -717,7 +736,7 @@ export function initInventory ({
717 button.title = tooltip(slot);
736 button.title = tooltip(slot);
718 const def = itemDefinition(slot.itemId);
737 const def = itemDefinition(slot.itemId);
719 const img = document.createElement("img");
738 const img = document.createElement("img");
720 img.src = itemAssetPathForStack(slot);
739 applyItemIcon(img, slot, itemAssetPathForStack(slot));
721 img.alt = itemDisplayName(slot);
740 img.alt = itemDisplayName(slot);
722 button.append(img);
741 button.append(img);
723 if (slot.quantity > 1)
742 if (slot.quantity > 1)
client/src/play/main.js +64 −6
@@ -8,6 +8,7 @@ import { initChat } from "./chat.js";
8 8 import { initInventory } from "./inventory.js";
9 9 import { initSkills } from "./skills.js";
10 10 import { initCrafting } from "./crafting.js";
11 import { initAlchemy } from "./alchemy.js";
11 12 import { initContextMenu } from "./contextMenu.js";
12 13 import { initDeath } from "./death.js";
13 14 import { CraftingStationId } from "/shared/definitions/craftingStations.js";
@@ -32,10 +33,11 @@ let chat;
32 33 let inventory;
33 34 let skills;
34 35 let crafting;
36 let alchemy;
35 37 let contextMenu;
36 38 let death;
37 39 let pendingPickup = null;
38 /** @type {{ kind: "bank", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
40 /** @type {{ kind: "bank" | "cauldron", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
39 41 let pendingInteract = null;
40 42 /** Framework can report mousePressed for two frames; latch so one physical click is one command. */
41 43 let leftClickConsumed = false;
@@ -77,7 +79,7 @@ function renderCharacters (characters)
77 79 function uiBlocked ()
78 80 {
79 81 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
80 || crafting?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
82 || crafting?.isBlocking() || alchemy?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
81 83 }
82 84
83 85 function clearPendingPickup ()
@@ -128,10 +130,24 @@ function approachAdjacentTile (tileX, tileY)
128 130
129 131 function requestOpenBank (tileX, tileY, { getCheques = false } = {})
130 132 {
131 clearPendingPickup();
133 clearAllPendingActions();
132 134 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
133 if (approachAdjacentTile(tileX, tileY))
135 const local = view?.entities.get(view.localEntityId);
136 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
134 137 { flushPendingInteract(); }
138 else
139 { approachAdjacentTile(tileX, tileY); }
140 }
141
142 function requestOpenCauldron (tileX, tileY)
143 {
144 clearAllPendingActions();
145 pendingInteract = { kind: "cauldron", tileX, tileY };
146 const local = view?.entities.get(view.localEntityId);
147 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
148 { flushPendingInteract(); }
149 else
150 { approachAdjacentTile(tileX, tileY); }
135 151 }
136 152
137 153 function requestTalk (targetEntityId)
@@ -168,6 +184,15 @@ function flushPendingInteract ()
168 184 return;
169 185 }
170 186
187 if (pendingInteract.kind === "cauldron")
188 {
189 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
190 { return; }
191 socket.send({ type: MessageType.openCauldron });
192 clearPendingInteract();
193 return;
194 }
195
171 196 if (pendingInteract.kind === "talk")
172 197 {
173 198 const target = view.entities.get(pendingInteract.targetEntityId);
@@ -273,6 +298,8 @@ function handleLeftClick (mouseX, mouseY)
273 298 { requestPickup(ground); }
274 299 else if (isBankTile(view, tile.tileX, tile.tileY))
275 300 { requestOpenBank(tile.tileX, tile.tileY); }
301 else if (isCauldronTile(view, tile.tileX, tile.tileY))
302 { requestOpenCauldron(tile.tileX, tile.tileY); }
276 303 else
277 304 {
278 305 clearAllPendingActions();
@@ -357,6 +384,14 @@ function handleRightClick (event, mouseX, mouseY)
357 384 });
358 385 }
359 386
387 if (isCauldronTile(view, tile.tileX, tile.tileY))
388 {
389 items.push({
390 label: "Alchemy",
391 onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
392 });
393 }
394
360 395 contextMenu.show(event.clientX, event.clientY, items);
361 396 }
362 397
@@ -503,6 +538,14 @@ async function main ()
503 538 return skills?.skillLevel?.(skillId) ?? 1;
504 539 }
505 540 });
541 alchemy = initAlchemy({
542 socket: { send (payload) { socket.send(payload); } },
543 MessageType,
544 getInventorySlots ()
545 {
546 return inventory?.getInventorySlots?.() ?? [];
547 }
548 });
506 549 chat = initChat({
507 550 socket: { send (payload) { socket.send(payload); } },
508 551 MessageType,
@@ -564,6 +607,7 @@ async function main ()
564 607 case MessageType.inventory:
565 608 inventory?.handleInventory(message);
566 609 crafting?.refresh();
610 alchemy?.refresh();
567 611 break;
568 612 case MessageType.skills:
569 613 skills?.render(message.skills);
@@ -572,6 +616,9 @@ async function main ()
572 616 case MessageType.bankSnapshot:
573 617 inventory?.handleBank(message);
574 618 break;
619 case MessageType.cauldronSnapshot:
620 alchemy?.handleSnapshot(message);
621 break;
575 622 case MessageType.pigeonDispatched:
576 623 inventory?.handlePigeonDispatched(message);
577 624 break;
@@ -648,6 +695,7 @@ function returnToMenu (reason = "")
648 695 chat?.reset();
649 696 inventory?.reset();
650 697 crafting?.reset();
698 alchemy?.reset();
651 699 skills?.hide();
652 700 contextMenu?.hide();
653 701 death?.reset();
@@ -690,15 +738,25 @@ main().catch((error) =>
690 738 });
691 739
692 740 function isBankTile (view, tileX, tileY)
741 {
742 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
743 }
744
745 function isCauldronTile (view, tileX, tileY)
746 {
747 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
748 }
749
750 function blockTypeAt (view, tileX, tileY)
693 751 {
694 752 const chunkX = Math.floor(tileX / CHUNK_SIZE);
695 753 const chunkY = Math.floor(tileY / CHUNK_SIZE);
696 754 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
697 755 if (!snapshot)
698 { return false; }
756 { return null; }
699 757 const localX = tileX - chunkX * CHUNK_SIZE;
700 758 const localY = tileY - chunkY * CHUNK_SIZE;
701 return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId === BlockType.bank;
759 return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId ?? null;
702 760 }
703 761
704 762 function chebyshev (ax, ay, bx, by)
@@ -8,6 +8,7 @@ import { initChat } from "./chat.js";
8import { initInventory } from "./inventory.js";
8import { initInventory } from "./inventory.js";
9import { initSkills } from "./skills.js";
9import { initSkills } from "./skills.js";
10import { initCrafting } from "./crafting.js";
10import { initCrafting } from "./crafting.js";
11import { initAlchemy } from "./alchemy.js";
11import { initContextMenu } from "./contextMenu.js";
12import { initContextMenu } from "./contextMenu.js";
12import { initDeath } from "./death.js";
13import { initDeath } from "./death.js";
13import { CraftingStationId } from "/shared/definitions/craftingStations.js";
14import { CraftingStationId } from "/shared/definitions/craftingStations.js";
@@ -32,10 +33,11 @@ let chat;
32let inventory;
33let inventory;
33let skills;
34let skills;
34let crafting;
35let crafting;
36let alchemy;
35let contextMenu;
37let contextMenu;
36let death;
38let death;
37let pendingPickup = null;
39let pendingPickup = null;
38/** @type {{ kind: "bank", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
40/** @type {{ kind: "bank" | "cauldron", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
39let pendingInteract = null;
41let pendingInteract = null;
40/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
42/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
41let leftClickConsumed = false;
43let leftClickConsumed = false;
@@ -77,7 +79,7 @@ function renderCharacters (characters)
77function uiBlocked ()
79function uiBlocked ()
78{
80{
79 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
81 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
80 || crafting?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
82 || crafting?.isBlocking() || alchemy?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
81}
83}
82
84
83function clearPendingPickup ()
85function clearPendingPickup ()
@@ -128,10 +130,24 @@ function approachAdjacentTile (tileX, tileY)
128
130
129function requestOpenBank (tileX, tileY, { getCheques = false } = {})
131function requestOpenBank (tileX, tileY, { getCheques = false } = {})
130{
132{
131 clearPendingPickup();
133 clearAllPendingActions();
132 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
134 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
133 if (approachAdjacentTile(tileX, tileY))
135 const local = view?.entities.get(view.localEntityId);
136 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
134 { flushPendingInteract(); }
137 { flushPendingInteract(); }
138 else
139 { approachAdjacentTile(tileX, tileY); }
140}
141
142function requestOpenCauldron (tileX, tileY)
143{
144 clearAllPendingActions();
145 pendingInteract = { kind: "cauldron", tileX, tileY };
146 const local = view?.entities.get(view.localEntityId);
147 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
148 { flushPendingInteract(); }
149 else
150 { approachAdjacentTile(tileX, tileY); }
135}
151}
136
152
137function requestTalk (targetEntityId)
153function requestTalk (targetEntityId)
@@ -168,6 +184,15 @@ function flushPendingInteract ()
168 return;
184 return;
169 }
185 }
170
186
187 if (pendingInteract.kind === "cauldron")
188 {
189 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
190 { return; }
191 socket.send({ type: MessageType.openCauldron });
192 clearPendingInteract();
193 return;
194 }
195
171 if (pendingInteract.kind === "talk")
196 if (pendingInteract.kind === "talk")
172 {
197 {
173 const target = view.entities.get(pendingInteract.targetEntityId);
198 const target = view.entities.get(pendingInteract.targetEntityId);
@@ -273,6 +298,8 @@ function handleLeftClick (mouseX, mouseY)
273 { requestPickup(ground); }
298 { requestPickup(ground); }
274 else if (isBankTile(view, tile.tileX, tile.tileY))
299 else if (isBankTile(view, tile.tileX, tile.tileY))
275 { requestOpenBank(tile.tileX, tile.tileY); }
300 { requestOpenBank(tile.tileX, tile.tileY); }
301 else if (isCauldronTile(view, tile.tileX, tile.tileY))
302 { requestOpenCauldron(tile.tileX, tile.tileY); }
276 else
303 else
277 {
304 {
278 clearAllPendingActions();
305 clearAllPendingActions();
@@ -357,6 +384,14 @@ function handleRightClick (event, mouseX, mouseY)
357 });
384 });
358 }
385 }
359
386
387 if (isCauldronTile(view, tile.tileX, tile.tileY))
388 {
389 items.push({
390 label: "Alchemy",
391 onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
392 });
393 }
394
360 contextMenu.show(event.clientX, event.clientY, items);
395 contextMenu.show(event.clientX, event.clientY, items);
361}
396}
362
397
@@ -503,6 +538,14 @@ async function main ()
503 return skills?.skillLevel?.(skillId) ?? 1;
538 return skills?.skillLevel?.(skillId) ?? 1;
504 }
539 }
505 });
540 });
541 alchemy = initAlchemy({
542 socket: { send (payload) { socket.send(payload); } },
543 MessageType,
544 getInventorySlots ()
545 {
546 return inventory?.getInventorySlots?.() ?? [];
547 }
548 });
506 chat = initChat({
549 chat = initChat({
507 socket: { send (payload) { socket.send(payload); } },
550 socket: { send (payload) { socket.send(payload); } },
508 MessageType,
551 MessageType,
@@ -564,6 +607,7 @@ async function main ()
564 case MessageType.inventory:
607 case MessageType.inventory:
565 inventory?.handleInventory(message);
608 inventory?.handleInventory(message);
566 crafting?.refresh();
609 crafting?.refresh();
610 alchemy?.refresh();
567 break;
611 break;
568 case MessageType.skills:
612 case MessageType.skills:
569 skills?.render(message.skills);
613 skills?.render(message.skills);
@@ -572,6 +616,9 @@ async function main ()
572 case MessageType.bankSnapshot:
616 case MessageType.bankSnapshot:
573 inventory?.handleBank(message);
617 inventory?.handleBank(message);
574 break;
618 break;
619 case MessageType.cauldronSnapshot:
620 alchemy?.handleSnapshot(message);
621 break;
575 case MessageType.pigeonDispatched:
622 case MessageType.pigeonDispatched:
576 inventory?.handlePigeonDispatched(message);
623 inventory?.handlePigeonDispatched(message);
577 break;
624 break;
@@ -648,6 +695,7 @@ function returnToMenu (reason = "")
648 chat?.reset();
695 chat?.reset();
649 inventory?.reset();
696 inventory?.reset();
650 crafting?.reset();
697 crafting?.reset();
698 alchemy?.reset();
651 skills?.hide();
699 skills?.hide();
652 contextMenu?.hide();
700 contextMenu?.hide();
653 death?.reset();
701 death?.reset();
@@ -690,15 +738,25 @@ main().catch((error) =>
690});
738});
691
739
692function isBankTile (view, tileX, tileY)
740function isBankTile (view, tileX, tileY)
741{
742 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
743}
744
745function isCauldronTile (view, tileX, tileY)
746{
747 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
748}
749
750function blockTypeAt (view, tileX, tileY)
693{
751{
694 const chunkX = Math.floor(tileX / CHUNK_SIZE);
752 const chunkX = Math.floor(tileX / CHUNK_SIZE);
695 const chunkY = Math.floor(tileY / CHUNK_SIZE);
753 const chunkY = Math.floor(tileY / CHUNK_SIZE);
696 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
754 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
697 if (!snapshot)
755 if (!snapshot)
698 { return false; }
756 { return null; }
699 const localX = tileX - chunkX * CHUNK_SIZE;
757 const localX = tileX - chunkX * CHUNK_SIZE;
700 const localY = tileY - chunkY * CHUNK_SIZE;
758 const localY = tileY - chunkY * CHUNK_SIZE;
701 return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId === BlockType.bank;
759 return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId ?? null;
702}
760}
703
761
704function chebyshev (ax, ay, bx, by)
762function chebyshev (ax, ay, bx, by)
client/src/render/chunkBake.js +31 −7
@@ -4,7 +4,7 @@ import { bloomImageName, resolveState, spriteImageName } from "/shared/definitio
4 4
5 5 /**
6 6 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
7 * Oversized or animated blocks are returned in `tallBlocks` for individual Y-sorted sprites.
7 * Oversized or animated blocks/grounds are returned for individual sprites.
8 8 */
9 9 export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
10 10 {
@@ -26,6 +26,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
26 26 }
27 27
28 28 const tallBlocks = [];
29 const animatedGrounds = [];
29 30 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
30 31 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
31 32
@@ -49,11 +50,24 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
49 50 const dx = localX * SPRITE_SIZE_PX;
50 51 const dy = localY * SPRITE_SIZE_PX;
51 52 const groundName = groundSpriteName(catalog, groundEntry);
52 blit(groundCtx, images[groundName], dx, dy);
53
54 const groundBloom = groundBloomName(catalog, groundEntry);
55 if (groundBloom)
56 { blit(bloomCtx, images[groundBloom], dx, dy); }
53 const groundMeta = groundCatalogMeta(catalog, groundEntry);
54 if (isBakeable(images[groundName], groundMeta))
55 {
56 blit(groundCtx, images[groundName], dx, dy);
57 const groundBloom = groundBloomName(catalog, groundEntry);
58 if (groundBloom)
59 { blit(bloomCtx, images[groundBloom], dx, dy); }
60 }
61 else if (groundName)
62 {
63 animatedGrounds.push({
64 tileX,
65 tileY,
66 sprite: groundName,
67 typeId: normalizeGround(groundEntry).typeId,
68 bloom: groundBloomName(catalog, groundEntry)
69 });
70 }
57 71
58 72 const blockName = blockSpriteName(catalog, blockEntry);
59 73 if (!blockName)
@@ -78,7 +92,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
78 92 }
79 93 }
80 94
81 return { ground, blockRows, bloom, tallBlocks };
95 return { ground, blockRows, bloom, tallBlocks, animatedGrounds };
82 96 }
83 97
84 98 export function isBakeable (sprite, meta = null)
@@ -178,3 +192,13 @@ function blockCatalogMeta (catalog, block)
178 192 { return null; }
179 193 return catalog.blocks?.[def.key] ?? null;
180 194 }
195
196 function groundCatalogMeta (catalog, ground)
197 {
198 const entry = normalizeGround(ground);
199 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
200 return catalog.grounds?.[def.key] ?? {
201 frames: def.frames,
202 animationSpeed: def.animationSpeed
203 };
204 }
@@ -4,7 +4,7 @@ import { bloomImageName, resolveState, spriteImageName } from "/shared/definitio
4
4
5/**
5/**
6 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
6 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
7 * Oversized or animated blocks are returned in `tallBlocks` for individual Y-sorted sprites.
7 * Oversized or animated blocks/grounds are returned for individual sprites.
8 */
8 */
9export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
9export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
10{
10{
@@ -26,6 +26,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
26 }
26 }
27
27
28 const tallBlocks = [];
28 const tallBlocks = [];
29 const animatedGrounds = [];
29 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
30 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
30 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
31 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
31
32
@@ -49,11 +50,24 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
49 const dx = localX * SPRITE_SIZE_PX;
50 const dx = localX * SPRITE_SIZE_PX;
50 const dy = localY * SPRITE_SIZE_PX;
51 const dy = localY * SPRITE_SIZE_PX;
51 const groundName = groundSpriteName(catalog, groundEntry);
52 const groundName = groundSpriteName(catalog, groundEntry);
52 blit(groundCtx, images[groundName], dx, dy);
53 const groundMeta = groundCatalogMeta(catalog, groundEntry);
53
54 if (isBakeable(images[groundName], groundMeta))
54 const groundBloom = groundBloomName(catalog, groundEntry);
55 {
55 if (groundBloom)
56 blit(groundCtx, images[groundName], dx, dy);
56 { blit(bloomCtx, images[groundBloom], dx, dy); }
57 const groundBloom = groundBloomName(catalog, groundEntry);
58 if (groundBloom)
59 { blit(bloomCtx, images[groundBloom], dx, dy); }
60 }
61 else if (groundName)
62 {
63 animatedGrounds.push({
64 tileX,
65 tileY,
66 sprite: groundName,
67 typeId: normalizeGround(groundEntry).typeId,
68 bloom: groundBloomName(catalog, groundEntry)
69 });
70 }
57
71
58 const blockName = blockSpriteName(catalog, blockEntry);
72 const blockName = blockSpriteName(catalog, blockEntry);
59 if (!blockName)
73 if (!blockName)
@@ -78,7 +92,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
78 }
92 }
79 }
93 }
80
94
81 return { ground, blockRows, bloom, tallBlocks };
95 return { ground, blockRows, bloom, tallBlocks, animatedGrounds };
82}
96}
83
97
84export function isBakeable (sprite, meta = null)
98export function isBakeable (sprite, meta = null)
@@ -178,3 +192,13 @@ function blockCatalogMeta (catalog, block)
178 { return null; }
192 { return null; }
179 return catalog.blocks?.[def.key] ?? null;
193 return catalog.blocks?.[def.key] ?? null;
180}
194}
195
196function groundCatalogMeta (catalog, ground)
197{
198 const entry = normalizeGround(ground);
199 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
200 return catalog.grounds?.[def.key] ?? {
201 frames: def.frames,
202 animationSpeed: def.animationSpeed
203 };
204}
client/src/render/potionIcon.js added +109 −0
@@ -0,0 +1,109 @@
1 import { ItemId } from "/shared/definitions/items.js";
2 import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
3
4 const bottleCache = new Map();
5 const fillCache = new Map();
6 const urlCache = new Map();
7
8 function loadImage (src)
9 {
10 return new Promise((resolve, reject) =>
11 {
12 const img = new Image();
13 img.onload = () => resolve(img);
14 img.onerror = () => reject(new Error(`Failed to load ${src}`));
15 img.src = src;
16 });
17 }
18
19 async function getBottle ()
20 {
21 if (!bottleCache.has("bottle"))
22 { bottleCache.set("bottle", loadImage("/assets/items/glass-bottle/glass-bottle.png")); }
23 return bottleCache.get("bottle");
24 }
25
26 async function getFill (level)
27 {
28 const key = Math.max(1, Math.min(5, level | 0 || 4));
29 if (!fillCache.has(key))
30 { fillCache.set(key, loadImage(`/assets/items/potion/fill-${key}.png`)); }
31 return fillCache.get(key);
32 }
33
34 function colorKey (color)
35 {
36 if (!color)
37 { return "0,0,0"; }
38 const r = Math.round((color.r ?? 0) * 255);
39 const g = Math.round((color.g ?? 0) * 255);
40 const b = Math.round((color.b ?? 0) * 255);
41 return `${r},${g},${b}`;
42 }
43
44 /**
45 * Build a data-URL icon: clear bottle + fill mask tinted to potion color.
46 * UI-only; world ground items use the same bake then lit darkness shader.
47 */
48 export async function potionIconDataUrl (instance)
49 {
50 const fillLevel = Math.max(1, Math.min(5, instance?.fillLevel | 0 || 4));
51 const key = `${fillLevel}|${colorKey(instance?.color)}`;
52 if (urlCache.has(key))
53 { return urlCache.get(key); }
54
55 const [bottle, fill] = await Promise.all([getBottle(), getFill(fillLevel)]);
56 const canvas = document.createElement("canvas");
57 canvas.width = SPRITE_SIZE_PX;
58 canvas.height = SPRITE_SIZE_PX;
59 const ctx = canvas.getContext("2d");
60 ctx.clearRect(0, 0, canvas.width, canvas.height);
61
62 ctx.drawImage(fill, 0, 0);
63 const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
64 const data = image.data;
65 const r = Math.round((instance?.color?.r ?? 0.4) * 255);
66 const g = Math.round((instance?.color?.g ?? 0.4) * 255);
67 const b = Math.round((instance?.color?.b ?? 0.7) * 255);
68 for (let i = 0; i < data.length; i += 4)
69 {
70 if (data[i + 3] < 8)
71 { continue; }
72 const a = data[i + 3] / 255;
73 data[i] = r;
74 data[i + 1] = g;
75 data[i + 2] = b;
76 data[i + 3] = Math.round(220 * a);
77 }
78 ctx.putImageData(image, 0, 0);
79 ctx.drawImage(bottle, 0, 0);
80
81 const url = canvas.toDataURL("image/png");
82 urlCache.set(key, url);
83 return url;
84 }
85
86 export function isPotionStack (stack)
87 {
88 return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion";
89 }
90
91 /** Sync helper: set img.src to recolored potion or fall back to asset path. */
92 export function applyItemIcon (img, stack, fallbackPath)
93 {
94 if (!img)
95 { return; }
96 if (!isPotionStack(stack))
97 {
98 img.src = fallbackPath;
99 return;
100 }
101 img.src = fallbackPath;
102 potionIconDataUrl(stack.instance).then((url) =>
103 {
104 img.src = url;
105 }).catch(() =>
106 {
107 img.src = fallbackPath;
108 });
109 }
@@ -0,0 +1,109 @@
1import { ItemId } from "/shared/definitions/items.js";
2import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
3
4const bottleCache = new Map();
5const fillCache = new Map();
6const urlCache = new Map();
7
8function loadImage (src)
9{
10 return new Promise((resolve, reject) =>
11 {
12 const img = new Image();
13 img.onload = () => resolve(img);
14 img.onerror = () => reject(new Error(`Failed to load ${src}`));
15 img.src = src;
16 });
17}
18
19async function getBottle ()
20{
21 if (!bottleCache.has("bottle"))
22 { bottleCache.set("bottle", loadImage("/assets/items/glass-bottle/glass-bottle.png")); }
23 return bottleCache.get("bottle");
24}
25
26async function getFill (level)
27{
28 const key = Math.max(1, Math.min(5, level | 0 || 4));
29 if (!fillCache.has(key))
30 { fillCache.set(key, loadImage(`/assets/items/potion/fill-${key}.png`)); }
31 return fillCache.get(key);
32}
33
34function colorKey (color)
35{
36 if (!color)
37 { return "0,0,0"; }
38 const r = Math.round((color.r ?? 0) * 255);
39 const g = Math.round((color.g ?? 0) * 255);
40 const b = Math.round((color.b ?? 0) * 255);
41 return `${r},${g},${b}`;
42}
43
44/**
45 * Build a data-URL icon: clear bottle + fill mask tinted to potion color.
46 * UI-only; world ground items use the same bake then lit darkness shader.
47 */
48export async function potionIconDataUrl (instance)
49{
50 const fillLevel = Math.max(1, Math.min(5, instance?.fillLevel | 0 || 4));
51 const key = `${fillLevel}|${colorKey(instance?.color)}`;
52 if (urlCache.has(key))
53 { return urlCache.get(key); }
54
55 const [bottle, fill] = await Promise.all([getBottle(), getFill(fillLevel)]);
56 const canvas = document.createElement("canvas");
57 canvas.width = SPRITE_SIZE_PX;
58 canvas.height = SPRITE_SIZE_PX;
59 const ctx = canvas.getContext("2d");
60 ctx.clearRect(0, 0, canvas.width, canvas.height);
61
62 ctx.drawImage(fill, 0, 0);
63 const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
64 const data = image.data;
65 const r = Math.round((instance?.color?.r ?? 0.4) * 255);
66 const g = Math.round((instance?.color?.g ?? 0.4) * 255);
67 const b = Math.round((instance?.color?.b ?? 0.7) * 255);
68 for (let i = 0; i < data.length; i += 4)
69 {
70 if (data[i + 3] < 8)
71 { continue; }
72 const a = data[i + 3] / 255;
73 data[i] = r;
74 data[i + 1] = g;
75 data[i + 2] = b;
76 data[i + 3] = Math.round(220 * a);
77 }
78 ctx.putImageData(image, 0, 0);
79 ctx.drawImage(bottle, 0, 0);
80
81 const url = canvas.toDataURL("image/png");
82 urlCache.set(key, url);
83 return url;
84}
85
86export function isPotionStack (stack)
87{
88 return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion";
89}
90
91/** Sync helper: set img.src to recolored potion or fall back to asset path. */
92export function applyItemIcon (img, stack, fallbackPath)
93{
94 if (!img)
95 { return; }
96 if (!isPotionStack(stack))
97 {
98 img.src = fallbackPath;
99 return;
100 }
101 img.src = fallbackPath;
102 potionIconDataUrl(stack.instance).then((url) =>
103 {
104 img.src = url;
105 }).catch(() =>
106 {
107 img.src = fallbackPath;
108 });
109}
client/src/render/worldView.js +227 −15
@@ -3,6 +3,7 @@ import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js"
3 3 import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
4 4 import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5 5 import { itemSpriteName } from "/shared/definitions/items.js";
6 import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";
6 7 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
7 8 import { bakeChunkAtlases } from "./chunkBake.js";
8 9 import {
@@ -34,15 +35,75 @@ const SPRITE_LIGHTING_FRAG = [
34 35 "uniform sampler2D u_texture;",
35 36 "uniform float u_darkness;",
36 37 "uniform float u_strength;",
38 "uniform float u_wade;",
39 "uniform float u_spriteHeight;",
37 40 "void main() {",
38 41 " vec4 color = texture2D(u_texture, v_texCoord);",
39 42 " if (color.a <= 0.0) { discard; }",
40 " vec3 rgb = mix(color.rgb, vec3(0.0), u_darkness);",
43 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
44 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
45 " vec3 rgb = color.rgb;",
46 " if (u_wade > 0.5 && fromBottom < 5.0) {",
47 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
48 " }",
49 " rgb = mix(rgb, vec3(0.0), u_darkness);",
41 50 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
42 51 " gl_FragColor = vec4(rgb, color.a);",
43 52 "}"
44 53 ].join("\n");
45 54
55 const WATER_GROUND_FRAG = [
56 "precision mediump float;",
57 "varying vec2 v_texCoord;",
58 "uniform sampler2D u_texture;",
59 "uniform float u_darkness;",
60 "uniform float u_time;",
61 "uniform float u_edgeN;",
62 "uniform float u_edgeE;",
63 "uniform float u_edgeS;",
64 "uniform float u_edgeW;",
65 "void main() {",
66 " vec4 color = texture2D(u_texture, v_texCoord);",
67 " if (color.a <= 0.0) { discard; }",
68 " vec3 rgb = color.rgb;",
69 " float foam = 0.0;",
70 " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);",
71 " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {",
72 " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);",
73 " }",
74 " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {",
75 " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);",
76 " }",
77 " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {",
78 " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);",
79 " }",
80 " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {",
81 " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
82 " }",
83 " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
84 " rgb = mix(rgb, vec3(0.0), u_darkness);",
85 " gl_FragColor = vec4(rgb, color.a);",
86 "}"
87 ].join("\n");
88
89 /** Potion bottle: recolor near-white liquid, then apply night darkness. */
90 const POTION_SPRITE_FRAG = [
91 "precision mediump float;",
92 "varying vec2 v_texCoord;",
93 "uniform sampler2D u_texture;",
94 "uniform float u_darkness;",
95 "uniform vec3 u_potionColor;",
96 "void main() {",
97 " vec4 color = texture2D(u_texture, v_texCoord);",
98 " if (color.a <= 0.0) { discard; }",
99 " vec3 rgb = color.rgb;",
100 " float liquid = step(0.95, min(min(color.r, color.g), color.b));",
101 " rgb = mix(rgb, u_potionColor, liquid);",
102 " rgb = mix(rgb, vec3(0.0), u_darkness);",
103 " gl_FragColor = vec4(rgb, color.a);",
104 "}"
105 ].join("\n");
106
46 107 const ATLAS_LIGHTING_FRAG = [
47 108 "precision mediump float;",
48 109 "varying vec2 v_texCoord;",
@@ -66,6 +127,8 @@ const ATLAS_LIGHTING_FRAG = [
66 127
67 128 let spriteLightingShader = null;
68 129 let atlasLightingShader = null;
130 let waterGroundShader = null;
131 let potionSpriteShader = null;
69 132
70 133 function getSpriteLightingShader ()
71 134 {
@@ -81,6 +144,20 @@ function getAtlasLightingShader ()
81 144 return atlasLightingShader;
82 145 }
83 146
147 function getWaterGroundShader ()
148 {
149 if (!waterGroundShader)
150 { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); }
151 return waterGroundShader;
152 }
153
154 function getPotionSpriteShader ()
155 {
156 if (!potionSpriteShader)
157 { potionSpriteShader = Shader.fragment(POTION_SPRITE_FRAG); }
158 return potionSpriteShader;
159 }
160
84 161 export class WorldView
85 162 {
86 163 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
@@ -140,6 +217,7 @@ export class WorldView
140 217 this.chunks.set(key, snapshot);
141 218 this.#rebuildChunk(snapshot);
142 219 this.#redrawPreview();
220 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
143 221 for (const entity of snapshot.entities ?? [])
144 222 { this.#upsertEntity(entity); }
145 223 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
@@ -292,23 +370,31 @@ export class WorldView
292 370 {
293 371 const size = this.tileSize();
294 372 const pivot = tilePivot(payload.tileX, payload.tileY, size);
373 const potion = payload.instance?.kind === "potion" ? payload.instance : null;
374 const spriteName = potion
375 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`)
376 : (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance));
295 377 let item = this.groundItems.get(payload.groundItemId);
296 378 if (!item)
297 379 {
298 const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
380 const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
299 381 this.scene.addObject(object);
300 382 item = { object };
301 383 this.groundItems.set(payload.groundItemId, item);
302 384 }
385 else if (item.object && this.game.images[spriteName])
386 { item.object.image = this.game.images[spriteName]; }
303 387 item.groundItemId = payload.groundItemId;
304 388 item.tileX = payload.tileX;
305 389 item.tileY = payload.tileY;
306 390 item.itemId = payload.itemId;
307 391 item.quantity = payload.quantity;
308 392 item.displayName = payload.displayName;
309 item.sprite = payload.sprite;
393 item.sprite = spriteName;
394 item.instance = payload.instance ?? null;
395 item.potionColor = potion?.color ?? null;
310 396 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
311 this.#syncLitSprite(item.object, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
397 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
312 398 }
313 399
314 400 despawnGroundItem (groundItemId)
@@ -884,21 +970,23 @@ export class WorldView
884 970 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
885 971 : 0;
886 972 const tileShade = this.#entityShadeAlpha(entity, now);
973 const wade = isWadeGround(this.#groundTypeAt(entity.tileX, entity.tileY));
887 974
888 975 entity.object.transform.rotation = walkTilt;
889 this.#syncLitSprite(entity.object, tileShade, flashStrength);
976 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
890 977 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
891 978 for (let index = 0; index < (entity.overlays ?? []).length; index++)
892 979 {
893 980 const overlay = entity.overlays[index];
894 981 const overlaySortY = entity.visualY + 0.5 * (index + 1);
895 982 overlay.transform.rotation = walkTilt;
896 this.#syncLitSprite(overlay, tileShade, flashStrength);
983 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
897 984 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
898 985 }
899 986 for (const overlay of entity.bloomOverlays ?? [])
900 987 {
901 988 overlay.transform.rotation = walkTilt;
989 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
902 990 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
903 991 }
904 992 this.#placeHpBar(entity, pivotX, pivotY);
@@ -914,18 +1002,89 @@ export class WorldView
914 1002 object.renderer.secondaryMap = null;
915 1003 }
916 1004
917 #syncLitSprite (object, darkness, flashStrength = 0)
1005 #syncLitSprite (object, darkness, flashStrength = 0, wade = false)
918 1006 {
919 1007 if (!object?.renderer || object._lit === false)
920 1008 { return; }
921 1009 object._lit = true;
922 1010 const dark = Math.min(1, Math.max(0, darkness ?? 0));
923 1011 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1012 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
924 1013 object.renderer.shader = getSpriteLightingShader();
925 object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash };
1014 object.renderer.shaderUniforms = {
1015 u_darkness: dark,
1016 u_strength: flash,
1017 u_wade: wade ? 1 : 0,
1018 u_spriteHeight: height
1019 };
1020 object.renderer.secondaryMap = null;
1021 }
1022
1023 #syncGroundItemSprite (item, darkness)
1024 {
1025 if (item?.potionColor)
1026 { this.#syncPotionSprite(item.object, darkness, item.potionColor); }
1027 else
1028 { this.#syncLitSprite(item?.object, darkness); }
1029 }
1030
1031 #syncPotionSprite (object, darkness, color)
1032 {
1033 if (!object?.renderer || object._lit === false)
1034 { return; }
1035 object._lit = true;
1036 object.renderer.shader = getPotionSpriteShader();
1037 object.renderer.shaderUniforms = {
1038 u_darkness: Math.min(1, Math.max(0, darkness ?? 0)),
1039 u_potionColor: [
1040 Math.min(1, Math.max(0, color?.r ?? 0.4)),
1041 Math.min(1, Math.max(0, color?.g ?? 0.4)),
1042 Math.min(1, Math.max(0, color?.b ?? 0.7))
1043 ]
1044 };
926 1045 object.renderer.secondaryMap = null;
927 1046 }
928 1047
1048 #groundTypeAt (tileX, tileY)
1049 {
1050 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1051 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1052 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1053 if (!snapshot)
1054 { return null; }
1055 const localX = tileX - chunkX * CHUNK_SIZE;
1056 const localY = tileY - chunkY * CHUNK_SIZE;
1057 const index = localY * CHUNK_SIZE + localX;
1058 return normalizeGround(snapshot.grounds?.[index]).typeId;
1059 }
1060
1061 #waterCoastEdges (tileX, tileY)
1062 {
1063 return {
1064 n: !isWaterGround(this.#groundTypeAt(tileX, tileY - 1)) ? 1 : 0,
1065 e: !isWaterGround(this.#groundTypeAt(tileX + 1, tileY)) ? 1 : 0,
1066 s: !isWaterGround(this.#groundTypeAt(tileX, tileY + 1)) ? 1 : 0,
1067 w: !isWaterGround(this.#groundTypeAt(tileX - 1, tileY)) ? 1 : 0
1068 };
1069 }
1070
1071 #syncWaterGroundSprite (object, darkness, edges, timeSec)
1072 {
1073 if (!object?.renderer)
1074 { return; }
1075 object._lit = true;
1076 object.renderer.shader = getWaterGroundShader();
1077 object.renderer.secondaryMap = null;
1078 object.renderer.shaderUniforms = {
1079 u_darkness: Math.min(1, Math.max(0, darkness ?? 0)),
1080 u_time: timeSec,
1081 u_edgeN: edges?.n ?? 0,
1082 u_edgeE: edges?.e ?? 0,
1083 u_edgeS: edges?.s ?? 0,
1084 u_edgeW: edges?.w ?? 0
1085 };
1086 }
1087
929 1088 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
930 1089 {
931 1090 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
@@ -1028,6 +1187,7 @@ export class WorldView
1028 1187 blockObjects: [],
1029 1188 bloomObject: null,
1030 1189 tallBlocks: atlases.tallBlocks,
1190 animatedGrounds: atlases.animatedGrounds,
1031 1191 lightmapPixels: null
1032 1192 };
1033 1193 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
@@ -1057,6 +1217,7 @@ export class WorldView
1057 1217 { invalidateCanvasTexture(this.scene, canvas); }
1058 1218 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
1059 1219 baked.tallBlocks = atlases.tallBlocks;
1220 baked.animatedGrounds = atlases.animatedGrounds;
1060 1221 }
1061 1222 baked.chunkX = snapshot.chunkX;
1062 1223 baked.chunkY = snapshot.chunkY;
@@ -1140,6 +1301,20 @@ export class WorldView
1140 1301 { this.#rebuildChunk(snapshot); }
1141 1302 }
1142 1303
1304 #refreshWaterCoastsNear (chunkX, chunkY)
1305 {
1306 const timeSec = performance.now() / 1000;
1307 for (const objects of this.tiles.values())
1308 {
1309 if (!objects.ground || !isWaterGround(objects.groundTypeId))
1310 { continue; }
1311 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
1312 { continue; }
1313 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1314 this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, objects.waterEdges, timeSec);
1315 }
1316 }
1317
1143 1318 #drawTile (tileX, tileY, forceTall = null)
1144 1319 {
1145 1320 const chunkX = Math.floor(tileX / CHUNK_SIZE);
@@ -1163,18 +1338,44 @@ export class WorldView
1163 1338 objects.chunkY = chunkY;
1164 1339 objects.light = snapshot.light[index] ?? 0;
1165 1340
1166 if (objects.ground)
1341 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
1342 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1343 if (animatedGround)
1167 1344 {
1168 objects.ground.destroy();
1169 objects.ground = null;
1345 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
1346 if (objects.ground)
1347 {
1348 const size = this.tileSize();
1349 objects.ground.transform.position.x = tileX * size + size / 2;
1350 objects.ground.transform.position.y = tileY * size + size / 2;
1351 objects.ground.transform.size = new vector(size, size);
1352 objects.ground.layer = LAYER_GROUND;
1353 objects.groundTypeId = animatedGround.typeId;
1354 const edges = isWaterGround(animatedGround.typeId)
1355 ? this.#waterCoastEdges(tileX, tileY)
1356 : { n: 0, e: 0, s: 0, w: 0 };
1357 objects.waterEdges = edges;
1358 this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, edges, performance.now() / 1000);
1359 this.#markSortDirty();
1360 }
1361 if (animatedGround.bloom)
1362 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
1363 else
1364 {
1365 objects.groundBloom?.destroy();
1366 objects.groundBloom = null;
1367 }
1170 1368 }
1171 if (objects.groundBloom)
1369 else
1172 1370 {
1173 objects.groundBloom.destroy();
1371 objects.ground?.destroy();
1372 objects.ground = null;
1373 objects.groundBloom?.destroy();
1174 1374 objects.groundBloom = null;
1375 objects.groundTypeId = null;
1376 objects.waterEdges = null;
1175 1377 }
1176 1378
1177 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
1178 1379 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1179 1380 const isTall = forceTall === true || !!tallEntry;
1180 1381 if (isTall && tallEntry)
@@ -1386,6 +1587,17 @@ export class WorldView
1386 1587 objects.shadeAlpha = ambientDark * (1 - intensity);
1387 1588 if (objects.block)
1388 1589 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1590 if (objects.ground && isWaterGround(objects.groundTypeId))
1591 {
1592 this.#syncWaterGroundSprite(
1593 objects.ground,
1594 objects.shadeAlpha,
1595 objects.waterEdges ?? this.#waterCoastEdges(objects.tileX, objects.tileY),
1596 now / 1000
1597 );
1598 }
1599 else if (objects.ground)
1600 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
1389 1601 }
1390 1602
1391 1603 for (const baked of this.bakedChunks.values())
@@ -1403,7 +1615,7 @@ export class WorldView
1403 1615 for (const item of this.groundItems.values())
1404 1616 {
1405 1617 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
1406 this.#syncLitSprite(item.object, alpha);
1618 this.#syncGroundItemSprite(item, alpha);
1407 1619 }
1408 1620 }
1409 1621
@@ -3,6 +3,7 @@ import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js"
3import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
3import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5import { itemSpriteName } from "/shared/definitions/items.js";
5import { itemSpriteName } from "/shared/definitions/items.js";
6import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";
6import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
7import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
7import { bakeChunkAtlases } from "./chunkBake.js";
8import { bakeChunkAtlases } from "./chunkBake.js";
8import {
9import {
@@ -34,15 +35,75 @@ const SPRITE_LIGHTING_FRAG = [
34 "uniform sampler2D u_texture;",
35 "uniform sampler2D u_texture;",
35 "uniform float u_darkness;",
36 "uniform float u_darkness;",
36 "uniform float u_strength;",
37 "uniform float u_strength;",
38 "uniform float u_wade;",
39 "uniform float u_spriteHeight;",
37 "void main() {",
40 "void main() {",
38 " vec4 color = texture2D(u_texture, v_texCoord);",
41 " vec4 color = texture2D(u_texture, v_texCoord);",
39 " if (color.a <= 0.0) { discard; }",
42 " if (color.a <= 0.0) { discard; }",
40 " vec3 rgb = mix(color.rgb, vec3(0.0), u_darkness);",
43 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
44 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
45 " vec3 rgb = color.rgb;",
46 " if (u_wade > 0.5 && fromBottom < 5.0) {",
47 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
48 " }",
49 " rgb = mix(rgb, vec3(0.0), u_darkness);",
41 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
50 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
42 " gl_FragColor = vec4(rgb, color.a);",
51 " gl_FragColor = vec4(rgb, color.a);",
43 "}"
52 "}"
44].join("\n");
53].join("\n");
45
54
55const WATER_GROUND_FRAG = [
56 "precision mediump float;",
57 "varying vec2 v_texCoord;",
58 "uniform sampler2D u_texture;",
59 "uniform float u_darkness;",
60 "uniform float u_time;",
61 "uniform float u_edgeN;",
62 "uniform float u_edgeE;",
63 "uniform float u_edgeS;",
64 "uniform float u_edgeW;",
65 "void main() {",
66 " vec4 color = texture2D(u_texture, v_texCoord);",
67 " if (color.a <= 0.0) { discard; }",
68 " vec3 rgb = color.rgb;",
69 " float foam = 0.0;",
70 " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);",
71 " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {",
72 " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);",
73 " }",
74 " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {",
75 " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);",
76 " }",
77 " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {",
78 " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);",
79 " }",
80 " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {",
81 " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
82 " }",
83 " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
84 " rgb = mix(rgb, vec3(0.0), u_darkness);",
85 " gl_FragColor = vec4(rgb, color.a);",
86 "}"
87].join("\n");
88
89/** Potion bottle: recolor near-white liquid, then apply night darkness. */
90const POTION_SPRITE_FRAG = [
91 "precision mediump float;",
92 "varying vec2 v_texCoord;",
93 "uniform sampler2D u_texture;",
94 "uniform float u_darkness;",
95 "uniform vec3 u_potionColor;",
96 "void main() {",
97 " vec4 color = texture2D(u_texture, v_texCoord);",
98 " if (color.a <= 0.0) { discard; }",
99 " vec3 rgb = color.rgb;",
100 " float liquid = step(0.95, min(min(color.r, color.g), color.b));",
101 " rgb = mix(rgb, u_potionColor, liquid);",
102 " rgb = mix(rgb, vec3(0.0), u_darkness);",
103 " gl_FragColor = vec4(rgb, color.a);",
104 "}"
105].join("\n");
106
46const ATLAS_LIGHTING_FRAG = [
107const ATLAS_LIGHTING_FRAG = [
47 "precision mediump float;",
108 "precision mediump float;",
48 "varying vec2 v_texCoord;",
109 "varying vec2 v_texCoord;",
@@ -66,6 +127,8 @@ const ATLAS_LIGHTING_FRAG = [
66
127
67let spriteLightingShader = null;
128let spriteLightingShader = null;
68let atlasLightingShader = null;
129let atlasLightingShader = null;
130let waterGroundShader = null;
131let potionSpriteShader = null;
69
132
70function getSpriteLightingShader ()
133function getSpriteLightingShader ()
71{
134{
@@ -81,6 +144,20 @@ function getAtlasLightingShader ()
81 return atlasLightingShader;
144 return atlasLightingShader;
82}
145}
83
146
147function getWaterGroundShader ()
148{
149 if (!waterGroundShader)
150 { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); }
151 return waterGroundShader;
152}
153
154function getPotionSpriteShader ()
155{
156 if (!potionSpriteShader)
157 { potionSpriteShader = Shader.fragment(POTION_SPRITE_FRAG); }
158 return potionSpriteShader;
159}
160
84export class WorldView
161export class WorldView
85{
162{
86 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
163 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
@@ -140,6 +217,7 @@ export class WorldView
140 this.chunks.set(key, snapshot);
217 this.chunks.set(key, snapshot);
141 this.#rebuildChunk(snapshot);
218 this.#rebuildChunk(snapshot);
142 this.#redrawPreview();
219 this.#redrawPreview();
220 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
143 for (const entity of snapshot.entities ?? [])
221 for (const entity of snapshot.entities ?? [])
144 { this.#upsertEntity(entity); }
222 { this.#upsertEntity(entity); }
145 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
223 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
@@ -292,23 +370,31 @@ export class WorldView
292 {
370 {
293 const size = this.tileSize();
371 const size = this.tileSize();
294 const pivot = tilePivot(payload.tileX, payload.tileY, size);
372 const pivot = tilePivot(payload.tileX, payload.tileY, size);
373 const potion = payload.instance?.kind === "potion" ? payload.instance : null;
374 const spriteName = potion
375 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`)
376 : (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance));
295 let item = this.groundItems.get(payload.groundItemId);
377 let item = this.groundItems.get(payload.groundItemId);
296 if (!item)
378 if (!item)
297 {
379 {
298 const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
380 const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
299 this.scene.addObject(object);
381 this.scene.addObject(object);
300 item = { object };
382 item = { object };
301 this.groundItems.set(payload.groundItemId, item);
383 this.groundItems.set(payload.groundItemId, item);
302 }
384 }
385 else if (item.object && this.game.images[spriteName])
386 { item.object.image = this.game.images[spriteName]; }
303 item.groundItemId = payload.groundItemId;
387 item.groundItemId = payload.groundItemId;
304 item.tileX = payload.tileX;
388 item.tileX = payload.tileX;
305 item.tileY = payload.tileY;
389 item.tileY = payload.tileY;
306 item.itemId = payload.itemId;
390 item.itemId = payload.itemId;
307 item.quantity = payload.quantity;
391 item.quantity = payload.quantity;
308 item.displayName = payload.displayName;
392 item.displayName = payload.displayName;
309 item.sprite = payload.sprite;
393 item.sprite = spriteName;
394 item.instance = payload.instance ?? null;
395 item.potionColor = potion?.color ?? null;
310 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
396 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
311 this.#syncLitSprite(item.object, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
397 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
312 }
398 }
313
399
314 despawnGroundItem (groundItemId)
400 despawnGroundItem (groundItemId)
@@ -884,21 +970,23 @@ export class WorldView
884 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
970 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
885 : 0;
971 : 0;
886 const tileShade = this.#entityShadeAlpha(entity, now);
972 const tileShade = this.#entityShadeAlpha(entity, now);
973 const wade = isWadeGround(this.#groundTypeAt(entity.tileX, entity.tileY));
887
974
888 entity.object.transform.rotation = walkTilt;
975 entity.object.transform.rotation = walkTilt;
889 this.#syncLitSprite(entity.object, tileShade, flashStrength);
976 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
890 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
977 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
891 for (let index = 0; index < (entity.overlays ?? []).length; index++)
978 for (let index = 0; index < (entity.overlays ?? []).length; index++)
892 {
979 {
893 const overlay = entity.overlays[index];
980 const overlay = entity.overlays[index];
894 const overlaySortY = entity.visualY + 0.5 * (index + 1);
981 const overlaySortY = entity.visualY + 0.5 * (index + 1);
895 overlay.transform.rotation = walkTilt;
982 overlay.transform.rotation = walkTilt;
896 this.#syncLitSprite(overlay, tileShade, flashStrength);
983 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
897 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
984 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
898 }
985 }
899 for (const overlay of entity.bloomOverlays ?? [])
986 for (const overlay of entity.bloomOverlays ?? [])
900 {
987 {
901 overlay.transform.rotation = walkTilt;
988 overlay.transform.rotation = walkTilt;
989 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
902 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
990 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
903 }
991 }
904 this.#placeHpBar(entity, pivotX, pivotY);
992 this.#placeHpBar(entity, pivotX, pivotY);
@@ -914,18 +1002,89 @@ export class WorldView
914 object.renderer.secondaryMap = null;
1002 object.renderer.secondaryMap = null;
915 }
1003 }
916
1004
917 #syncLitSprite (object, darkness, flashStrength = 0)
1005 #syncLitSprite (object, darkness, flashStrength = 0, wade = false)
918 {
1006 {
919 if (!object?.renderer || object._lit === false)
1007 if (!object?.renderer || object._lit === false)
920 { return; }
1008 { return; }
921 object._lit = true;
1009 object._lit = true;
922 const dark = Math.min(1, Math.max(0, darkness ?? 0));
1010 const dark = Math.min(1, Math.max(0, darkness ?? 0));
923 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1011 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1012 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
924 object.renderer.shader = getSpriteLightingShader();
1013 object.renderer.shader = getSpriteLightingShader();
925 object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash };
1014 object.renderer.shaderUniforms = {
1015 u_darkness: dark,
1016 u_strength: flash,
1017 u_wade: wade ? 1 : 0,
1018 u_spriteHeight: height
1019 };
1020 object.renderer.secondaryMap = null;
1021 }
1022
1023 #syncGroundItemSprite (item, darkness)
1024 {
1025 if (item?.potionColor)
1026 { this.#syncPotionSprite(item.object, darkness, item.potionColor); }
1027 else
1028 { this.#syncLitSprite(item?.object, darkness); }
1029 }
1030
1031 #syncPotionSprite (object, darkness, color)
1032 {
1033 if (!object?.renderer || object._lit === false)
1034 { return; }
1035 object._lit = true;
1036 object.renderer.shader = getPotionSpriteShader();
1037 object.renderer.shaderUniforms = {
1038 u_darkness: Math.min(1, Math.max(0, darkness ?? 0)),
1039 u_potionColor: [
1040 Math.min(1, Math.max(0, color?.r ?? 0.4)),
1041 Math.min(1, Math.max(0, color?.g ?? 0.4)),
1042 Math.min(1, Math.max(0, color?.b ?? 0.7))
1043 ]
1044 };
926 object.renderer.secondaryMap = null;
1045 object.renderer.secondaryMap = null;
927 }
1046 }
928
1047
1048 #groundTypeAt (tileX, tileY)
1049 {
1050 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1051 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1052 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1053 if (!snapshot)
1054 { return null; }
1055 const localX = tileX - chunkX * CHUNK_SIZE;
1056 const localY = tileY - chunkY * CHUNK_SIZE;
1057 const index = localY * CHUNK_SIZE + localX;
1058 return normalizeGround(snapshot.grounds?.[index]).typeId;
1059 }
1060
1061 #waterCoastEdges (tileX, tileY)
1062 {
1063 return {
1064 n: !isWaterGround(this.#groundTypeAt(tileX, tileY - 1)) ? 1 : 0,
1065 e: !isWaterGround(this.#groundTypeAt(tileX + 1, tileY)) ? 1 : 0,
1066 s: !isWaterGround(this.#groundTypeAt(tileX, tileY + 1)) ? 1 : 0,
1067 w: !isWaterGround(this.#groundTypeAt(tileX - 1, tileY)) ? 1 : 0
1068 };
1069 }
1070
1071 #syncWaterGroundSprite (object, darkness, edges, timeSec)
1072 {
1073 if (!object?.renderer)
1074 { return; }
1075 object._lit = true;
1076 object.renderer.shader = getWaterGroundShader();
1077 object.renderer.secondaryMap = null;
1078 object.renderer.shaderUniforms = {
1079 u_darkness: Math.min(1, Math.max(0, darkness ?? 0)),
1080 u_time: timeSec,
1081 u_edgeN: edges?.n ?? 0,
1082 u_edgeE: edges?.e ?? 0,
1083 u_edgeS: edges?.s ?? 0,
1084 u_edgeW: edges?.w ?? 0
1085 };
1086 }
1087
929 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
1088 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
930 {
1089 {
931 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
1090 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
@@ -1028,6 +1187,7 @@ export class WorldView
1028 blockObjects: [],
1187 blockObjects: [],
1029 bloomObject: null,
1188 bloomObject: null,
1030 tallBlocks: atlases.tallBlocks,
1189 tallBlocks: atlases.tallBlocks,
1190 animatedGrounds: atlases.animatedGrounds,
1031 lightmapPixels: null
1191 lightmapPixels: null
1032 };
1192 };
1033 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
1193 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
@@ -1057,6 +1217,7 @@ export class WorldView
1057 { invalidateCanvasTexture(this.scene, canvas); }
1217 { invalidateCanvasTexture(this.scene, canvas); }
1058 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
1218 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
1059 baked.tallBlocks = atlases.tallBlocks;
1219 baked.tallBlocks = atlases.tallBlocks;
1220 baked.animatedGrounds = atlases.animatedGrounds;
1060 }
1221 }
1061 baked.chunkX = snapshot.chunkX;
1222 baked.chunkX = snapshot.chunkX;
1062 baked.chunkY = snapshot.chunkY;
1223 baked.chunkY = snapshot.chunkY;
@@ -1140,6 +1301,20 @@ export class WorldView
1140 { this.#rebuildChunk(snapshot); }
1301 { this.#rebuildChunk(snapshot); }
1141 }
1302 }
1142
1303
1304 #refreshWaterCoastsNear (chunkX, chunkY)
1305 {
1306 const timeSec = performance.now() / 1000;
1307 for (const objects of this.tiles.values())
1308 {
1309 if (!objects.ground || !isWaterGround(objects.groundTypeId))
1310 { continue; }
1311 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
1312 { continue; }
1313 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1314 this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, objects.waterEdges, timeSec);
1315 }
1316 }
1317
1143 #drawTile (tileX, tileY, forceTall = null)
1318 #drawTile (tileX, tileY, forceTall = null)
1144 {
1319 {
1145 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1320 const chunkX = Math.floor(tileX / CHUNK_SIZE);
@@ -1163,18 +1338,44 @@ export class WorldView
1163 objects.chunkY = chunkY;
1338 objects.chunkY = chunkY;
1164 objects.light = snapshot.light[index] ?? 0;
1339 objects.light = snapshot.light[index] ?? 0;
1165
1340
1166 if (objects.ground)
1341 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
1342 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1343 if (animatedGround)
1167 {
1344 {
1168 objects.ground.destroy();
1345 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
1169 objects.ground = null;
1346 if (objects.ground)
1347 {
1348 const size = this.tileSize();
1349 objects.ground.transform.position.x = tileX * size + size / 2;
1350 objects.ground.transform.position.y = tileY * size + size / 2;
1351 objects.ground.transform.size = new vector(size, size);
1352 objects.ground.layer = LAYER_GROUND;
1353 objects.groundTypeId = animatedGround.typeId;
1354 const edges = isWaterGround(animatedGround.typeId)
1355 ? this.#waterCoastEdges(tileX, tileY)
1356 : { n: 0, e: 0, s: 0, w: 0 };
1357 objects.waterEdges = edges;
1358 this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, edges, performance.now() / 1000);
1359 this.#markSortDirty();
1360 }
1361 if (animatedGround.bloom)
1362 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
1363 else
1364 {
1365 objects.groundBloom?.destroy();
1366 objects.groundBloom = null;
1367 }
1170 }
1368 }
1171 if (objects.groundBloom)
1369 else
1172 {
1370 {
1173 objects.groundBloom.destroy();
1371 objects.ground?.destroy();
1372 objects.ground = null;
1373 objects.groundBloom?.destroy();
1174 objects.groundBloom = null;
1374 objects.groundBloom = null;
1375 objects.groundTypeId = null;
1376 objects.waterEdges = null;
1175 }
1377 }
1176
1378
1177 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
1178 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1379 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1179 const isTall = forceTall === true || !!tallEntry;
1380 const isTall = forceTall === true || !!tallEntry;
1180 if (isTall && tallEntry)
1381 if (isTall && tallEntry)
@@ -1386,6 +1587,17 @@ export class WorldView
1386 objects.shadeAlpha = ambientDark * (1 - intensity);
1587 objects.shadeAlpha = ambientDark * (1 - intensity);
1387 if (objects.block)
1588 if (objects.block)
1388 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1589 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1590 if (objects.ground && isWaterGround(objects.groundTypeId))
1591 {
1592 this.#syncWaterGroundSprite(
1593 objects.ground,
1594 objects.shadeAlpha,
1595 objects.waterEdges ?? this.#waterCoastEdges(objects.tileX, objects.tileY),
1596 now / 1000
1597 );
1598 }
1599 else if (objects.ground)
1600 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
1389 }
1601 }
1390
1602
1391 for (const baked of this.bakedChunks.values())
1603 for (const baked of this.bakedChunks.values())
@@ -1403,7 +1615,7 @@ export class WorldView
1403 for (const item of this.groundItems.values())
1615 for (const item of this.groundItems.values())
1404 {
1616 {
1405 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
1617 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
1406 this.#syncLitSprite(item.object, alpha);
1618 this.#syncGroundItemSprite(item, alpha);
1407 }
1619 }
1408 }
1620 }
1409
1621
client/ui/play.css +112 −0
@@ -378,6 +378,114 @@ a { color: #d4c48a; }
378 378 margin-bottom: 0.5rem;
379 379 }
380 380
381 #cauldron-panel,
382 #cauldron-pick-panel {
383 position: fixed;
384 z-index: 6;
385 top: 50%;
386 left: 50%;
387 transform: translate(-50%, -50%);
388 width: min(360px, 92vw);
389 max-height: min(85vh, 720px);
390 overflow: auto;
391 background: #1a1e26;
392 border: 1px solid #2c3340;
393 padding: 0.85rem 1rem 1rem;
394 }
395
396 #cauldron-pick-panel {
397 z-index: 7;
398 width: min(420px, 94vw);
399 }
400
401 #cauldron-panel header,
402 #cauldron-pick-panel header {
403 display: flex;
404 justify-content: space-between;
405 align-items: center;
406 margin-bottom: 0.5rem;
407 }
408
409 .cauldron-slots,
410 .cauldron-inserts {
411 display: grid;
412 grid-template-columns: repeat(4, 1fr);
413 gap: 0.35rem;
414 margin-bottom: 0.35rem;
415 }
416
417 .cauldron-slot,
418 .cauldron-insert,
419 .cauldron-pick-item {
420 min-height: 3rem;
421 display: grid;
422 place-items: center;
423 position: relative;
424 background: #12151c;
425 }
426
427 .cauldron-slot img,
428 .cauldron-pick-item img {
429 width: 32px;
430 height: 32px;
431 image-rendering: pixelated;
432 }
433
434 .cauldron-slot .qty {
435 position: absolute;
436 right: 0.2rem;
437 bottom: 0.1rem;
438 font-size: 0.75rem;
439 }
440
441 .cauldron-vessel {
442 text-align: center;
443 font-size: 2rem;
444 margin: 0.35rem 0;
445 opacity: 0.85;
446 }
447
448 .cauldron-actions,
449 .cauldron-finish {
450 display: flex;
451 flex-wrap: wrap;
452 gap: 0.35rem;
453 margin: 0.35rem 0;
454 }
455
456 .cauldron-steps {
457 margin: 0.5rem 0 0;
458 padding-left: 1.2rem;
459 color: #9aa3b2;
460 font-size: 0.9rem;
461 }
462
463 .cauldron-pick-list {
464 display: grid;
465 gap: 0.35rem;
466 max-height: 40vh;
467 overflow: auto;
468 margin-bottom: 0.5rem;
469 }
470
471 .cauldron-pick-item {
472 grid-template-columns: 36px 1fr;
473 justify-items: start;
474 padding: 0.35rem 0.5rem;
475 gap: 0.5rem;
476 }
477
478 .cauldron-pick-item.selected {
479 border-color: #d4c48a;
480 }
481
482 .cauldron-pick-qty {
483 display: flex;
484 gap: 0.5rem;
485 align-items: center;
486 margin-bottom: 0.5rem;
487 }
488
381 489 .craft-layout {
382 490 display: grid;
383 491 grid-template-columns: 1fr 1fr;
@@ -667,6 +775,10 @@ a { color: #d4c48a; }
667 775 #bank-panel[hidden],
668 776 #craft-panel[hidden],
669 777 #craft-backdrop[hidden],
778 #cauldron-panel[hidden],
779 #cauldron-backdrop[hidden],
780 #cauldron-pick-panel[hidden],
781 #cauldron-pick-backdrop[hidden],
670 782 #nametag[hidden],
671 783 #chat-bar[hidden] {
672 784 display: none !important;
@@ -378,6 +378,114 @@ a { color: #d4c48a; }
378 margin-bottom: 0.5rem;
378 margin-bottom: 0.5rem;
379}
379}
380
380
381#cauldron-panel,
382#cauldron-pick-panel {
383 position: fixed;
384 z-index: 6;
385 top: 50%;
386 left: 50%;
387 transform: translate(-50%, -50%);
388 width: min(360px, 92vw);
389 max-height: min(85vh, 720px);
390 overflow: auto;
391 background: #1a1e26;
392 border: 1px solid #2c3340;
393 padding: 0.85rem 1rem 1rem;
394}
395
396#cauldron-pick-panel {
397 z-index: 7;
398 width: min(420px, 94vw);
399}
400
401#cauldron-panel header,
402#cauldron-pick-panel header {
403 display: flex;
404 justify-content: space-between;
405 align-items: center;
406 margin-bottom: 0.5rem;
407}
408
409.cauldron-slots,
410.cauldron-inserts {
411 display: grid;
412 grid-template-columns: repeat(4, 1fr);
413 gap: 0.35rem;
414 margin-bottom: 0.35rem;
415}
416
417.cauldron-slot,
418.cauldron-insert,
419.cauldron-pick-item {
420 min-height: 3rem;
421 display: grid;
422 place-items: center;
423 position: relative;
424 background: #12151c;
425}
426
427.cauldron-slot img,
428.cauldron-pick-item img {
429 width: 32px;
430 height: 32px;
431 image-rendering: pixelated;
432}
433
434.cauldron-slot .qty {
435 position: absolute;
436 right: 0.2rem;
437 bottom: 0.1rem;
438 font-size: 0.75rem;
439}
440
441.cauldron-vessel {
442 text-align: center;
443 font-size: 2rem;
444 margin: 0.35rem 0;
445 opacity: 0.85;
446}
447
448.cauldron-actions,
449.cauldron-finish {
450 display: flex;
451 flex-wrap: wrap;
452 gap: 0.35rem;
453 margin: 0.35rem 0;
454}
455
456.cauldron-steps {
457 margin: 0.5rem 0 0;
458 padding-left: 1.2rem;
459 color: #9aa3b2;
460 font-size: 0.9rem;
461}
462
463.cauldron-pick-list {
464 display: grid;
465 gap: 0.35rem;
466 max-height: 40vh;
467 overflow: auto;
468 margin-bottom: 0.5rem;
469}
470
471.cauldron-pick-item {
472 grid-template-columns: 36px 1fr;
473 justify-items: start;
474 padding: 0.35rem 0.5rem;
475 gap: 0.5rem;
476}
477
478.cauldron-pick-item.selected {
479 border-color: #d4c48a;
480}
481
482.cauldron-pick-qty {
483 display: flex;
484 gap: 0.5rem;
485 align-items: center;
486 margin-bottom: 0.5rem;
487}
488
381.craft-layout {
489.craft-layout {
382 display: grid;
490 display: grid;
383 grid-template-columns: 1fr 1fr;
491 grid-template-columns: 1fr 1fr;
@@ -667,6 +775,10 @@ a { color: #d4c48a; }
667#bank-panel[hidden],
775#bank-panel[hidden],
668#craft-panel[hidden],
776#craft-panel[hidden],
669#craft-backdrop[hidden],
777#craft-backdrop[hidden],
778#cauldron-panel[hidden],
779#cauldron-backdrop[hidden],
780#cauldron-pick-panel[hidden],
781#cauldron-pick-backdrop[hidden],
670#nametag[hidden],
782#nametag[hidden],
671#chat-bar[hidden] {
783#chat-bar[hidden] {
672 display: none !important;
784 display: none !important;
docs/FEATURES.md +30 −3
@@ -16,7 +16,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16 16 ## Ground and block tile layers
17 17
18 18 **Status:** full
19 **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.
19 **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.
20 20 **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`
21 21
22 22 ## Open and closed chunks
@@ -234,8 +234,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
234 234 ## Gathering, crafting, and production skills
235 235
236 236 **Status:** not implemented
237 **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**.
238 **Code:** `shared/definitions/skills.js` (skill IDs + panel entries only)
237 **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**.
238 **Code:** `shared/definitions/skills.js` (skill IDs + panel entries), `shared/definitions/equipmentKinds.js` (`plantClippers`), `shared/definitions/alchemy.js`
239 239
240 240 ## Crafting stations
241 241
@@ -266,6 +266,18 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
266 266 **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.
267 267 **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)
268 268
269 ## Alchemy / cauldron
270
271 **Status:** partial (scaffolding)
272 **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**.
273
274 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).
275
276 Example scaffold recipe: **Green draught** — heat → insert green herb → stir → insert apple → cool → Bottle (ratios 2 green herb : 1 apple).
277
278 **TODO:** more recipes, drink/effect application, herb nodes + Herbalism XP, more clipper tiers, polish cauldron art.
279 **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`
280
269 281 ## Stamina and running
270 282
271 283 **Status:** not implemented
@@ -290,6 +302,21 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
290 302 **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.
291 303 **Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
292 304
305 ## Bounty offices
306
307 **Status:** not implemented
308 **Spec:** Placeable **Bounty Office** blocks (sprite/form TBD). Interacting opens a modal with two tabs:
309
310 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).
311 2. **My bounty** — Shows how much coin is currently on **your** head.
312
313 **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**.
314
315 **Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
316
317 **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.
318 **Code:** —
319
293 320 ## Banking, cheques, shops, player-driven marketplace
294 321
295 322 **Status:** partial
@@ -16,7 +16,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16## Ground and block tile layers
16## Ground and block tile layers
17
17
18**Status:** full
18**Status:** full
19**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.
19**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.
20**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`
20**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`
21
21
22## Open and closed chunks
22## Open and closed chunks
@@ -234,8 +234,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
234## Gathering, crafting, and production skills
234## Gathering, crafting, and production skills
235
235
236**Status:** not implemented
236**Status:** not implemented
237**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**.
237**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**.
238**Code:** `shared/definitions/skills.js` (skill IDs + panel entries only)
238**Code:** `shared/definitions/skills.js` (skill IDs + panel entries), `shared/definitions/equipmentKinds.js` (`plantClippers`), `shared/definitions/alchemy.js`
239
239
240## Crafting stations
240## Crafting stations
241
241
@@ -266,6 +266,18 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
266**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.
266**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.
267**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)
267**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)
268
268
269## Alchemy / cauldron
270
271**Status:** partial (scaffolding)
272**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**.
273
274Slots 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).
275
276Example scaffold recipe: **Green draught** — heat → insert green herb → stir → insert apple → cool → Bottle (ratios 2 green herb : 1 apple).
277
278**TODO:** more recipes, drink/effect application, herb nodes + Herbalism XP, more clipper tiers, polish cauldron art.
279**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`
280
269## Stamina and running
281## Stamina and running
270
282
271**Status:** not implemented
283**Status:** not implemented
@@ -290,6 +302,21 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
290**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.
302**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.
291**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
303**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
292
304
305## Bounty offices
306
307**Status:** not implemented
308**Spec:** Placeable **Bounty Office** blocks (sprite/form TBD). Interacting opens a modal with two tabs:
309
3101. **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).
3112. **My bounty** — Shows how much coin is currently on **your** head.
312
313**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**.
314
315**Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
316
317**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.
318**Code:** —
319
293## Banking, cheques, shops, player-driven marketplace
320## Banking, cheques, shops, player-driven marketplace
294
321
295**Status:** partial
322**Status:** partial
server/src/alchemy/service.js added +399 −0
@@ -0,0 +1,399 @@
1 import { Component } from "../ecs/components.js";
2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "../../../shared/definitions/alchemy.js";
4 import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5 import {
6 evaluateAlchemyBottle,
7 potionItemInstance,
8 recipePaperBody,
9 resolvedAlchemyPotions
10 } from "../../../shared/alchemy/recipes.js";
11 import { bagView } from "../items/bags.js";
12 import {
13 countItemInSlots,
14 emptySlots,
15 insertStack,
16 normalizeInventorySlots,
17 takeMatchingFromSlots,
18 stackQuantity
19 } from "../../../shared/items/inventory.js";
20 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
21 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22 import { randomUUID } from "node:crypto";
23
24 /**
25 * Cauldron sessions live on the worker world (per character while the UI is open).
26 * Clients send intents only; all brew outcomes are evaluated here.
27 */
28
29 function userError (message)
30 {
31 const error = new Error(message);
32 error.userFacing = true;
33 return error;
34 }
35
36 function ensureSessions (world)
37 {
38 if (!world.cauldronSessions)
39 { world.cauldronSessions = new Map(); }
40 return world.cauldronSessions;
41 }
42
43 function emptySession ()
44 {
45 return {
46 slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
47 brew: [],
48 steps: [],
49 lastSuccessRecipe: null
50 };
51 }
52
53 function sessionView (session)
54 {
55 return {
56 slots: (session.slots ?? []).map((slot) => (slot
57 ? { itemId: slot.itemId, quantity: slot.quantity | 0 }
58 : null)),
59 brew: (session.brew ?? []).map((row) => ({ itemId: row.itemId, quantity: row.quantity | 0 })),
60 steps: (session.steps ?? []).map((step) => ({ ...step })),
61 canSaveRecipe: !!session.lastSuccessRecipe,
62 lastSuccess: session.lastSuccessRecipe
63 ? {
64 potionKey: session.lastSuccessRecipe.potionKey,
65 displayName: session.lastSuccessRecipe.displayName,
66 minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1
67 }
68 : null
69 };
70 }
71
72 function nearCauldron (world, tileX, tileY)
73 {
74 for (let dy = -1; dy <= 1; dy++)
75 {
76 for (let dx = -1; dx <= 1; dx++)
77 {
78 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
79 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
80 if (data.blocks[index]?.typeId === BlockType.cauldron)
81 { return true; }
82 }
83 }
84 return false;
85 }
86
87 function requireNearCauldron (world, handle)
88 {
89 const position = world.ecs.get(handle, Component.position);
90 if (!nearCauldron(world, position.tileX, position.tileY))
91 { throw userError("Stand next to a cauldron."); }
92 }
93
94 function requireSession (world, characterId)
95 {
96 const session = ensureSessions(world).get(characterId);
97 if (!session)
98 { throw userError("Open a cauldron first."); }
99 return session;
100 }
101
102 function clearBrew (session)
103 {
104 session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);
105 session.brew = [];
106 session.steps = [];
107 }
108
109 function ensureInventory (world, handle)
110 {
111 let inventory = world.ecs.get(handle, Component.inventory);
112 if (!inventory)
113 { inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
114 inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
115 return inventory;
116 }
117
118 export function handleAlchemyCommand (world, sessionId, command)
119 {
120 switch (command.type)
121 {
122 case "open-cauldron":
123 return openCauldron(world, sessionId, command);
124 case "cauldron-set-slot":
125 return setSlot(world, sessionId, command);
126 case "cauldron-insert":
127 return insertFromSlot(world, sessionId, command);
128 case "cauldron-action":
129 return action(world, sessionId, command);
130 case "cauldron-bottle":
131 return bottle(world, sessionId, command);
132 case "cauldron-clear":
133 return clear(world, sessionId, command);
134 case "cauldron-save-recipe":
135 return saveRecipe(world, sessionId, command);
136 case "cauldron-close":
137 return closeCauldron(world, sessionId, command);
138 default:
139 return null;
140 }
141 }
142
143 function openCauldron (world, sessionId, command)
144 {
145 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
146 requireNearCauldron(world, handle);
147 const sessions = ensureSessions(world);
148 const existing = sessions.get(command.characterId) ?? emptySession();
149 sessions.set(command.characterId, existing);
150 return {
151 events: [],
152 private: bagView(world.ecs, handle),
153 cauldron: true,
154 cauldronState: sessionView(existing)
155 };
156 }
157
158 function closeCauldron (world, sessionId, command)
159 {
160 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
161 ensureSessions(world).delete(command.characterId);
162 return { events: [], private: bagView(world.ecs, handle), cauldron: false };
163 }
164
165 function setSlot (world, sessionId, command)
166 {
167 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
168 requireNearCauldron(world, handle);
169 const session = requireSession(world, command.characterId);
170 const slotIndex = command.slotIndex | 0;
171 if (slotIndex < 0 || slotIndex >= CAULDRON_SLOT_COUNT)
172 { throw userError("Invalid cauldron slot."); }
173
174 const itemId = command.itemId | 0;
175 const quantity = Math.max(0, command.quantity | 0);
176 if (!itemId || quantity <= 0)
177 {
178 session.slots[slotIndex] = null;
179 return {
180 events: [],
181 private: bagView(world.ecs, handle),
182 cauldron: true,
183 cauldronState: sessionView(session)
184 };
185 }
186
187 const def = itemDefinition(itemId);
188 if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle)
189 { throw userError("That cannot go in a cauldron slot."); }
190
191 const inventory = ensureInventory(world, handle);
192 const have = countItemInSlots(inventory.slots, itemId);
193 if (have < quantity)
194 { throw userError("Not enough of that item in your inventory."); }
195
196 session.slots[slotIndex] = { itemId, quantity };
197 return {
198 events: [],
199 private: bagView(world.ecs, handle),
200 cauldron: true,
201 cauldronState: sessionView(session)
202 };
203 }
204
205 function insertFromSlot (world, sessionId, command)
206 {
207 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
208 requireNearCauldron(world, handle);
209 const session = requireSession(world, command.characterId);
210 const slotIndex = command.slotIndex | 0;
211 const reserved = session.slots[slotIndex];
212 if (!reserved)
213 { throw userError("That cauldron slot is empty."); }
214
215 const inventory = ensureInventory(world, handle);
216 const pulled = takeMatchingFromSlots(inventory.slots, {
217 itemId: reserved.itemId,
218 quantity: reserved.quantity,
219 compact: false
220 });
221 if (!pulled.ok)
222 { throw userError("Not enough of that item in your inventory."); }
223 inventory.slots = pulled.slots;
224 session.slots[slotIndex] = null;
225
226 const existing = session.brew.find((row) => row.itemId === reserved.itemId);
227 if (existing)
228 { existing.quantity += reserved.quantity; }
229 else
230 { session.brew.push({ itemId: reserved.itemId, quantity: reserved.quantity }); }
231
232 session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId });
233 session.lastSuccessRecipe = null;
234
235 return {
236 events: [],
237 private: bagView(world.ecs, handle),
238 cauldron: true,
239 cauldronState: sessionView(session)
240 };
241 }
242
243 function action (world, sessionId, command)
244 {
245 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
246 requireNearCauldron(world, handle);
247 const session = requireSession(world, command.characterId);
248 const kind = command.action;
249 if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool)
250 { throw userError("Unknown cauldron action."); }
251 session.steps.push({ kind });
252 session.lastSuccessRecipe = null;
253 return {
254 events: [],
255 private: bagView(world.ecs, handle),
256 cauldron: true,
257 cauldronState: sessionView(session)
258 };
259 }
260
261 function bottle (world, sessionId, command)
262 {
263 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
264 requireNearCauldron(world, handle);
265 const session = requireSession(world, command.characterId);
266 if (!(session.brew?.length > 0) && !(session.steps?.length > 0))
267 { throw userError("The cauldron is empty."); }
268
269 const inventory = ensureInventory(world, handle);
270 const skills = world.ecs.get(handle, Component.skills) ?? {};
271
272 const evaluation = evaluateAlchemyBottle({
273 skills,
274 brewStacks: session.brew,
275 takenSteps: session.steps,
276 potions: resolvedAlchemyPotions()
277 });
278
279 const wanted = Math.max(1, evaluation.batch | 0);
280 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
281 const produced = Math.min(wanted, bottles);
282 if (produced <= 0)
283 { throw userError("You need glass bottles to bottle the brew."); }
284
285 const takeBottles = takeMatchingFromSlots(inventory.slots, {
286 itemId: ItemId.glassBottle,
287 quantity: produced,
288 compact: false
289 });
290 if (!takeBottles.ok)
291 { throw userError("You need glass bottles to bottle the brew."); }
292 inventory.slots = takeBottles.slots;
293
294 const instance = potionItemInstance(evaluation.result);
295 const potionDef = itemDefinition(ItemId.potion);
296 const inserted = insertStack(inventory.slots, {
297 itemId: ItemId.potion,
298 quantity: produced,
299 instance
300 }, potionDef);
301 if (!inserted.ok)
302 {
303 const refund = insertStack(inventory.slots, {
304 itemId: ItemId.glassBottle,
305 quantity: produced
306 }, itemDefinition(ItemId.glassBottle));
307 inventory.slots = refund.ok ? refund.slots : inventory.slots;
308 throw userError("Not enough inventory space for potions.");
309 }
310 inventory.slots = inserted.slots;
311
312 session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
313 clearBrew(session);
314
315 return {
316 events: [],
317 private: bagView(world.ecs, handle),
318 cauldron: true,
319 cauldronState: sessionView(session),
320 alchemyResult: {
321 success: !!evaluation.success,
322 reason: evaluation.reason ?? null,
323 produced,
324 wanted,
325 lost: Math.max(0, wanted - produced),
326 potion: {
327 potionKey: instance.potionKey,
328 displayName: instance.displayName,
329 unstable: instance.unstable,
330 color: instance.color,
331 fillLevel: instance.fillLevel
332 }
333 }
334 };
335 }
336
337 function clear (world, sessionId, command)
338 {
339 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
340 requireNearCauldron(world, handle);
341 const session = requireSession(world, command.characterId);
342 clearBrew(session);
343 session.lastSuccessRecipe = null;
344 return {
345 events: [],
346 private: bagView(world.ecs, handle),
347 cauldron: true,
348 cauldronState: sessionView(session)
349 };
350 }
351
352 function saveRecipe (world, sessionId, command)
353 {
354 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
355 requireNearCauldron(world, handle);
356 const session = requireSession(world, command.characterId);
357 const recipe = session.lastSuccessRecipe;
358 if (!recipe)
359 { throw userError("No successful recipe to save."); }
360
361 const inventory = ensureInventory(world, handle);
362 const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper);
363 if (paperIndex < 0)
364 { throw userError("You need a sheet of paper."); }
365
366 const paperSlot = inventory.slots[paperIndex];
367 const recipeStack = {
368 itemId: ItemId.recipePaper,
369 quantity: 1,
370 instance: {
371 kind: "recipe-paper",
372 recipeId: randomUUID(),
373 potionKey: recipe.potionKey,
374 displayName: `${recipe.displayName} recipe`,
375 minAlchemyLevel: recipe.minAlchemyLevel ?? 1,
376 body: recipePaperBody(recipe),
377 writtenAt: Date.now()
378 }
379 };
380
381 if (stackQuantity(paperSlot.quantity) <= 1)
382 { inventory.slots[paperIndex] = recipeStack; }
383 else
384 {
385 const free = inventory.slots.findIndex((entry) => !entry);
386 if (free < 0)
387 { throw userError("Need a free inventory slot for the recipe paper."); }
388 paperSlot.quantity -= 1;
389 inventory.slots[free] = recipeStack;
390 }
391
392 session.lastSuccessRecipe = null;
393 return {
394 events: [],
395 private: bagView(world.ecs, handle),
396 cauldron: true,
397 cauldronState: sessionView(session)
398 };
399 }
@@ -0,0 +1,399 @@
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "../../../shared/definitions/alchemy.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import {
6 evaluateAlchemyBottle,
7 potionItemInstance,
8 recipePaperBody,
9 resolvedAlchemyPotions
10} from "../../../shared/alchemy/recipes.js";
11import { bagView } from "../items/bags.js";
12import {
13 countItemInSlots,
14 emptySlots,
15 insertStack,
16 normalizeInventorySlots,
17 takeMatchingFromSlots,
18 stackQuantity
19} from "../../../shared/items/inventory.js";
20import { tileToChunk, tileToLocal } from "../world/coordinates.js";
21import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22import { randomUUID } from "node:crypto";
23
24/**
25 * Cauldron sessions live on the worker world (per character while the UI is open).
26 * Clients send intents only; all brew outcomes are evaluated here.
27 */
28
29function userError (message)
30{
31 const error = new Error(message);
32 error.userFacing = true;
33 return error;
34}
35
36function ensureSessions (world)
37{
38 if (!world.cauldronSessions)
39 { world.cauldronSessions = new Map(); }
40 return world.cauldronSessions;
41}
42
43function emptySession ()
44{
45 return {
46 slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
47 brew: [],
48 steps: [],
49 lastSuccessRecipe: null
50 };
51}
52
53function sessionView (session)
54{
55 return {
56 slots: (session.slots ?? []).map((slot) => (slot
57 ? { itemId: slot.itemId, quantity: slot.quantity | 0 }
58 : null)),
59 brew: (session.brew ?? []).map((row) => ({ itemId: row.itemId, quantity: row.quantity | 0 })),
60 steps: (session.steps ?? []).map((step) => ({ ...step })),
61 canSaveRecipe: !!session.lastSuccessRecipe,
62 lastSuccess: session.lastSuccessRecipe
63 ? {
64 potionKey: session.lastSuccessRecipe.potionKey,
65 displayName: session.lastSuccessRecipe.displayName,
66 minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1
67 }
68 : null
69 };
70}
71
72function nearCauldron (world, tileX, tileY)
73{
74 for (let dy = -1; dy <= 1; dy++)
75 {
76 for (let dx = -1; dx <= 1; dx++)
77 {
78 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
79 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
80 if (data.blocks[index]?.typeId === BlockType.cauldron)
81 { return true; }
82 }
83 }
84 return false;
85}
86
87function requireNearCauldron (world, handle)
88{
89 const position = world.ecs.get(handle, Component.position);
90 if (!nearCauldron(world, position.tileX, position.tileY))
91 { throw userError("Stand next to a cauldron."); }
92}
93
94function requireSession (world, characterId)
95{
96 const session = ensureSessions(world).get(characterId);
97 if (!session)
98 { throw userError("Open a cauldron first."); }
99 return session;
100}
101
102function clearBrew (session)
103{
104 session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);
105 session.brew = [];
106 session.steps = [];
107}
108
109function ensureInventory (world, handle)
110{
111 let inventory = world.ecs.get(handle, Component.inventory);
112 if (!inventory)
113 { inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
114 inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
115 return inventory;
116}
117
118export function handleAlchemyCommand (world, sessionId, command)
119{
120 switch (command.type)
121 {
122 case "open-cauldron":
123 return openCauldron(world, sessionId, command);
124 case "cauldron-set-slot":
125 return setSlot(world, sessionId, command);
126 case "cauldron-insert":
127 return insertFromSlot(world, sessionId, command);
128 case "cauldron-action":
129 return action(world, sessionId, command);
130 case "cauldron-bottle":
131 return bottle(world, sessionId, command);
132 case "cauldron-clear":
133 return clear(world, sessionId, command);
134 case "cauldron-save-recipe":
135 return saveRecipe(world, sessionId, command);
136 case "cauldron-close":
137 return closeCauldron(world, sessionId, command);
138 default:
139 return null;
140 }
141}
142
143function openCauldron (world, sessionId, command)
144{
145 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
146 requireNearCauldron(world, handle);
147 const sessions = ensureSessions(world);
148 const existing = sessions.get(command.characterId) ?? emptySession();
149 sessions.set(command.characterId, existing);
150 return {
151 events: [],
152 private: bagView(world.ecs, handle),
153 cauldron: true,
154 cauldronState: sessionView(existing)
155 };
156}
157
158function closeCauldron (world, sessionId, command)
159{
160 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
161 ensureSessions(world).delete(command.characterId);
162 return { events: [], private: bagView(world.ecs, handle), cauldron: false };
163}
164
165function setSlot (world, sessionId, command)
166{
167 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
168 requireNearCauldron(world, handle);
169 const session = requireSession(world, command.characterId);
170 const slotIndex = command.slotIndex | 0;
171 if (slotIndex < 0 || slotIndex >= CAULDRON_SLOT_COUNT)
172 { throw userError("Invalid cauldron slot."); }
173
174 const itemId = command.itemId | 0;
175 const quantity = Math.max(0, command.quantity | 0);
176 if (!itemId || quantity <= 0)
177 {
178 session.slots[slotIndex] = null;
179 return {
180 events: [],
181 private: bagView(world.ecs, handle),
182 cauldron: true,
183 cauldronState: sessionView(session)
184 };
185 }
186
187 const def = itemDefinition(itemId);
188 if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle)
189 { throw userError("That cannot go in a cauldron slot."); }
190
191 const inventory = ensureInventory(world, handle);
192 const have = countItemInSlots(inventory.slots, itemId);
193 if (have < quantity)
194 { throw userError("Not enough of that item in your inventory."); }
195
196 session.slots[slotIndex] = { itemId, quantity };
197 return {
198 events: [],
199 private: bagView(world.ecs, handle),
200 cauldron: true,
201 cauldronState: sessionView(session)
202 };
203}
204
205function insertFromSlot (world, sessionId, command)
206{
207 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
208 requireNearCauldron(world, handle);
209 const session = requireSession(world, command.characterId);
210 const slotIndex = command.slotIndex | 0;
211 const reserved = session.slots[slotIndex];
212 if (!reserved)
213 { throw userError("That cauldron slot is empty."); }
214
215 const inventory = ensureInventory(world, handle);
216 const pulled = takeMatchingFromSlots(inventory.slots, {
217 itemId: reserved.itemId,
218 quantity: reserved.quantity,
219 compact: false
220 });
221 if (!pulled.ok)
222 { throw userError("Not enough of that item in your inventory."); }
223 inventory.slots = pulled.slots;
224 session.slots[slotIndex] = null;
225
226 const existing = session.brew.find((row) => row.itemId === reserved.itemId);
227 if (existing)
228 { existing.quantity += reserved.quantity; }
229 else
230 { session.brew.push({ itemId: reserved.itemId, quantity: reserved.quantity }); }
231
232 session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId });
233 session.lastSuccessRecipe = null;
234
235 return {
236 events: [],
237 private: bagView(world.ecs, handle),
238 cauldron: true,
239 cauldronState: sessionView(session)
240 };
241}
242
243function action (world, sessionId, command)
244{
245 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
246 requireNearCauldron(world, handle);
247 const session = requireSession(world, command.characterId);
248 const kind = command.action;
249 if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool)
250 { throw userError("Unknown cauldron action."); }
251 session.steps.push({ kind });
252 session.lastSuccessRecipe = null;
253 return {
254 events: [],
255 private: bagView(world.ecs, handle),
256 cauldron: true,
257 cauldronState: sessionView(session)
258 };
259}
260
261function bottle (world, sessionId, command)
262{
263 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
264 requireNearCauldron(world, handle);
265 const session = requireSession(world, command.characterId);
266 if (!(session.brew?.length > 0) && !(session.steps?.length > 0))
267 { throw userError("The cauldron is empty."); }
268
269 const inventory = ensureInventory(world, handle);
270 const skills = world.ecs.get(handle, Component.skills) ?? {};
271
272 const evaluation = evaluateAlchemyBottle({
273 skills,
274 brewStacks: session.brew,
275 takenSteps: session.steps,
276 potions: resolvedAlchemyPotions()
277 });
278
279 const wanted = Math.max(1, evaluation.batch | 0);
280 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
281 const produced = Math.min(wanted, bottles);
282 if (produced <= 0)
283 { throw userError("You need glass bottles to bottle the brew."); }
284
285 const takeBottles = takeMatchingFromSlots(inventory.slots, {
286 itemId: ItemId.glassBottle,
287 quantity: produced,
288 compact: false
289 });
290 if (!takeBottles.ok)
291 { throw userError("You need glass bottles to bottle the brew."); }
292 inventory.slots = takeBottles.slots;
293
294 const instance = potionItemInstance(evaluation.result);
295 const potionDef = itemDefinition(ItemId.potion);
296 const inserted = insertStack(inventory.slots, {
297 itemId: ItemId.potion,
298 quantity: produced,
299 instance
300 }, potionDef);
301 if (!inserted.ok)
302 {
303 const refund = insertStack(inventory.slots, {
304 itemId: ItemId.glassBottle,
305 quantity: produced
306 }, itemDefinition(ItemId.glassBottle));
307 inventory.slots = refund.ok ? refund.slots : inventory.slots;
308 throw userError("Not enough inventory space for potions.");
309 }
310 inventory.slots = inserted.slots;
311
312 session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
313 clearBrew(session);
314
315 return {
316 events: [],
317 private: bagView(world.ecs, handle),
318 cauldron: true,
319 cauldronState: sessionView(session),
320 alchemyResult: {
321 success: !!evaluation.success,
322 reason: evaluation.reason ?? null,
323 produced,
324 wanted,
325 lost: Math.max(0, wanted - produced),
326 potion: {
327 potionKey: instance.potionKey,
328 displayName: instance.displayName,
329 unstable: instance.unstable,
330 color: instance.color,
331 fillLevel: instance.fillLevel
332 }
333 }
334 };
335}
336
337function clear (world, sessionId, command)
338{
339 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
340 requireNearCauldron(world, handle);
341 const session = requireSession(world, command.characterId);
342 clearBrew(session);
343 session.lastSuccessRecipe = null;
344 return {
345 events: [],
346 private: bagView(world.ecs, handle),
347 cauldron: true,
348 cauldronState: sessionView(session)
349 };
350}
351
352function saveRecipe (world, sessionId, command)
353{
354 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
355 requireNearCauldron(world, handle);
356 const session = requireSession(world, command.characterId);
357 const recipe = session.lastSuccessRecipe;
358 if (!recipe)
359 { throw userError("No successful recipe to save."); }
360
361 const inventory = ensureInventory(world, handle);
362 const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper);
363 if (paperIndex < 0)
364 { throw userError("You need a sheet of paper."); }
365
366 const paperSlot = inventory.slots[paperIndex];
367 const recipeStack = {
368 itemId: ItemId.recipePaper,
369 quantity: 1,
370 instance: {
371 kind: "recipe-paper",
372 recipeId: randomUUID(),
373 potionKey: recipe.potionKey,
374 displayName: `${recipe.displayName} recipe`,
375 minAlchemyLevel: recipe.minAlchemyLevel ?? 1,
376 body: recipePaperBody(recipe),
377 writtenAt: Date.now()
378 }
379 };
380
381 if (stackQuantity(paperSlot.quantity) <= 1)
382 { inventory.slots[paperIndex] = recipeStack; }
383 else
384 {
385 const free = inventory.slots.findIndex((entry) => !entry);
386 if (free < 0)
387 { throw userError("Need a free inventory slot for the recipe paper."); }
388 paperSlot.quantity -= 1;
389 inventory.slots[free] = recipeStack;
390 }
391
392 session.lastSuccessRecipe = null;
393 return {
394 events: [],
395 private: bagView(world.ecs, handle),
396 cauldron: true,
397 cauldronState: sessionView(session)
398 };
399}
server/src/gateway/websocket.js +70 −0
@@ -192,6 +192,67 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
192 192 characterId: session.characterId
193 193 });
194 194 break;
195 case MessageType.openCauldron:
196 requirePlaying(session);
197 simulation.enqueue(session.id, {
198 type: "open-cauldron",
199 characterId: session.characterId
200 });
201 break;
202 case MessageType.cauldronSetSlot:
203 requirePlaying(session);
204 simulation.enqueue(session.id, {
205 type: "cauldron-set-slot",
206 characterId: session.characterId,
207 slotIndex: message.slotIndex | 0,
208 itemId: message.itemId | 0,
209 quantity: message.quantity | 0
210 });
211 break;
212 case MessageType.cauldronInsert:
213 requirePlaying(session);
214 simulation.enqueue(session.id, {
215 type: "cauldron-insert",
216 characterId: session.characterId,
217 slotIndex: message.slotIndex | 0
218 });
219 break;
220 case MessageType.cauldronAction:
221 requirePlaying(session);
222 simulation.enqueue(session.id, {
223 type: "cauldron-action",
224 characterId: session.characterId,
225 action: message.action
226 });
227 break;
228 case MessageType.cauldronBottle:
229 requirePlaying(session);
230 simulation.enqueue(session.id, {
231 type: "cauldron-bottle",
232 characterId: session.characterId
233 });
234 break;
235 case MessageType.cauldronClear:
236 requirePlaying(session);
237 simulation.enqueue(session.id, {
238 type: "cauldron-clear",
239 characterId: session.characterId
240 });
241 break;
242 case MessageType.cauldronSaveRecipe:
243 requirePlaying(session);
244 simulation.enqueue(session.id, {
245 type: "cauldron-save-recipe",
246 characterId: session.characterId
247 });
248 break;
249 case MessageType.cauldronClose:
250 requirePlaying(session);
251 simulation.enqueue(session.id, {
252 type: "cauldron-close",
253 characterId: session.characterId
254 });
255 break;
195 256 case MessageType.bankDeposit:
196 257 requirePlaying(session);
197 258 simulation.enqueue(session.id, {
@@ -592,6 +653,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
592 653 inheritance: stateDb.getInheritance(session.account.account_id)
593 654 });
594 655 }
656 if (event.cauldron != null)
657 {
658 send(session, {
659 type: MessageType.cauldronSnapshot,
660 open: !!event.cauldron,
661 state: event.cauldronState ?? null,
662 alchemyResult: event.alchemyResult ?? null
663 });
664 }
595 665 continue;
596 666 }
597 667 if (event.type === "skills")
@@ -192,6 +192,67 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
192 characterId: session.characterId
192 characterId: session.characterId
193 });
193 });
194 break;
194 break;
195 case MessageType.openCauldron:
196 requirePlaying(session);
197 simulation.enqueue(session.id, {
198 type: "open-cauldron",
199 characterId: session.characterId
200 });
201 break;
202 case MessageType.cauldronSetSlot:
203 requirePlaying(session);
204 simulation.enqueue(session.id, {
205 type: "cauldron-set-slot",
206 characterId: session.characterId,
207 slotIndex: message.slotIndex | 0,
208 itemId: message.itemId | 0,
209 quantity: message.quantity | 0
210 });
211 break;
212 case MessageType.cauldronInsert:
213 requirePlaying(session);
214 simulation.enqueue(session.id, {
215 type: "cauldron-insert",
216 characterId: session.characterId,
217 slotIndex: message.slotIndex | 0
218 });
219 break;
220 case MessageType.cauldronAction:
221 requirePlaying(session);
222 simulation.enqueue(session.id, {
223 type: "cauldron-action",
224 characterId: session.characterId,
225 action: message.action
226 });
227 break;
228 case MessageType.cauldronBottle:
229 requirePlaying(session);
230 simulation.enqueue(session.id, {
231 type: "cauldron-bottle",
232 characterId: session.characterId
233 });
234 break;
235 case MessageType.cauldronClear:
236 requirePlaying(session);
237 simulation.enqueue(session.id, {
238 type: "cauldron-clear",
239 characterId: session.characterId
240 });
241 break;
242 case MessageType.cauldronSaveRecipe:
243 requirePlaying(session);
244 simulation.enqueue(session.id, {
245 type: "cauldron-save-recipe",
246 characterId: session.characterId
247 });
248 break;
249 case MessageType.cauldronClose:
250 requirePlaying(session);
251 simulation.enqueue(session.id, {
252 type: "cauldron-close",
253 characterId: session.characterId
254 });
255 break;
195 case MessageType.bankDeposit:
256 case MessageType.bankDeposit:
196 requirePlaying(session);
257 requirePlaying(session);
197 simulation.enqueue(session.id, {
258 simulation.enqueue(session.id, {
@@ -592,6 +653,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
592 inheritance: stateDb.getInheritance(session.account.account_id)
653 inheritance: stateDb.getInheritance(session.account.account_id)
593 });
654 });
594 }
655 }
656 if (event.cauldron != null)
657 {
658 send(session, {
659 type: MessageType.cauldronSnapshot,
660 open: !!event.cauldron,
661 state: event.cauldronState ?? null,
662 alchemyResult: event.alchemyResult ?? null
663 });
664 }
595 continue;
665 continue;
596 }
666 }
597 if (event.type === "skills")
667 if (event.type === "skills")
server/src/items/bags.js +5 −2
@@ -25,7 +25,7 @@ import { randomUUID } from "node:crypto";
25 25
26 26 export function publicGroundItem (item)
27 27 {
28 const def = itemDefinition(item.stack?.itemId);
28 const instance = item.stack?.instance ?? null;
29 29 return {
30 30 groundItemId: item.groundItemId,
31 31 tileX: item.tileX,
@@ -33,7 +33,10 @@ export function publicGroundItem (item)
33 33 itemId: item.stack.itemId,
34 34 quantity: item.stack.quantity,
35 35 displayName: stackDisplayLabel(item.stack),
36 sprite: itemSpriteName(item.stack.itemId, item.stack.instance),
36 sprite: itemSpriteName(item.stack.itemId, instance),
37 instance: instance && (instance.kind === "potion" || instance.kind === "letter" || instance.kind === "recipe-paper")
38 ? instance
39 : null,
37 40 expiresAt: item.expiresAt
38 41 };
39 42 }
@@ -25,7 +25,7 @@ import { randomUUID } from "node:crypto";
25
25
26export function publicGroundItem (item)
26export function publicGroundItem (item)
27{
27{
28 const def = itemDefinition(item.stack?.itemId);
28 const instance = item.stack?.instance ?? null;
29 return {
29 return {
30 groundItemId: item.groundItemId,
30 groundItemId: item.groundItemId,
31 tileX: item.tileX,
31 tileX: item.tileX,
@@ -33,7 +33,10 @@ export function publicGroundItem (item)
33 itemId: item.stack.itemId,
33 itemId: item.stack.itemId,
34 quantity: item.stack.quantity,
34 quantity: item.stack.quantity,
35 displayName: stackDisplayLabel(item.stack),
35 displayName: stackDisplayLabel(item.stack),
36 sprite: itemSpriteName(item.stack.itemId, item.stack.instance),
36 sprite: itemSpriteName(item.stack.itemId, instance),
37 instance: instance && (instance.kind === "potion" || instance.kind === "letter" || instance.kind === "recipe-paper")
38 ? instance
39 : null,
37 expiresAt: item.expiresAt
40 expiresAt: item.expiresAt
38 };
41 };
39}
42}
server/src/simulation/simulation.js +3 −0
@@ -766,6 +766,9 @@ export class Simulation
766 766 type: "inventory",
767 767 sessionId: item.sessionId,
768 768 bank: !!result.bank,
769 cauldron: result.cauldron,
770 cauldronState: result.cauldronState ?? null,
771 alchemyResult: result.alchemyResult ?? null,
769 772 ...result.private
770 773 });
771 774 }
@@ -766,6 +766,9 @@ export class Simulation
766 type: "inventory",
766 type: "inventory",
767 sessionId: item.sessionId,
767 sessionId: item.sessionId,
768 bank: !!result.bank,
768 bank: !!result.bank,
769 cauldron: result.cauldron,
770 cauldronState: result.cauldronState ?? null,
771 alchemyResult: result.alchemyResult ?? null,
769 ...result.private
772 ...result.private
770 });
773 });
771 }
774 }
server/src/simulation/workerWorld.js +4 −0
@@ -30,6 +30,7 @@ import {
30 30 publicGroundItem,
31 31 setGroundItemsForRegion
32 32 } from "../items/bags.js";
33 import { handleAlchemyCommand } from "../alchemy/service.js";
33 34 import {
34 35 applyRemoteMeleeSwing,
35 36 clearEngage,
@@ -367,6 +368,9 @@ export class WorkerWorld
367 368 return this.#cancelFollow(sessionId, command.characterId);
368 369 default:
369 370 {
371 const alchemy = handleAlchemyCommand(this, sessionId, command);
372 if (alchemy)
373 { return alchemy; }
370 374 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
371 375 return result ?? { events: [] };
372 376 }
@@ -30,6 +30,7 @@ import {
30 publicGroundItem,
30 publicGroundItem,
31 setGroundItemsForRegion
31 setGroundItemsForRegion
32} from "../items/bags.js";
32} from "../items/bags.js";
33import { handleAlchemyCommand } from "../alchemy/service.js";
33import {
34import {
34 applyRemoteMeleeSwing,
35 applyRemoteMeleeSwing,
35 clearEngage,
36 clearEngage,
@@ -367,6 +368,9 @@ export class WorkerWorld
367 return this.#cancelFollow(sessionId, command.characterId);
368 return this.#cancelFollow(sessionId, command.characterId);
368 default:
369 default:
369 {
370 {
371 const alchemy = handleAlchemyCommand(this, sessionId, command);
372 if (alchemy)
373 { return alchemy; }
370 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
374 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
371 return result ?? { events: [] };
375 return result ?? { events: [] };
372 }
376 }
server/src/world/chunkData.js +6 −1
@@ -3,6 +3,7 @@ import {
3 3 GroundType,
4 4 BlockType,
5 5 isBlockPassable,
6 isGroundPassable,
6 7 blockLightRange,
7 8 normalizeGround,
8 9 normalizeBlock
@@ -147,7 +148,11 @@ export function setBlock (data, localX, localY, block)
147 148
148 149 export function isChunkTilePassable (data, localX, localY)
149 150 {
150 const block = data.blocks[tileIndex(localX, localY)];
151 const index = tileIndex(localX, localY);
152 const ground = normalizeGround(data.grounds[index]);
153 if (!isGroundPassable(ground.typeId))
154 { return false; }
155 const block = data.blocks[index];
151 156 return isBlockPassable(block?.typeId ?? null);
152 157 }
153 158
@@ -3,6 +3,7 @@ import {
3 GroundType,
3 GroundType,
4 BlockType,
4 BlockType,
5 isBlockPassable,
5 isBlockPassable,
6 isGroundPassable,
6 blockLightRange,
7 blockLightRange,
7 normalizeGround,
8 normalizeGround,
8 normalizeBlock
9 normalizeBlock
@@ -147,7 +148,11 @@ export function setBlock (data, localX, localY, block)
147
148
148export function isChunkTilePassable (data, localX, localY)
149export function isChunkTilePassable (data, localX, localY)
149{
150{
150 const block = data.blocks[tileIndex(localX, localY)];
151 const index = tileIndex(localX, localY);
152 const ground = normalizeGround(data.grounds[index]);
153 if (!isGroundPassable(ground.typeId))
154 { return false; }
155 const block = data.blocks[index];
151 return isBlockPassable(block?.typeId ?? null);
156 return isBlockPassable(block?.typeId ?? null);
152}
157}
153
158
server/tests/alchemy.test.js added +161 −0
@@ -0,0 +1,161 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { BlockType } from "../../shared/definitions/tiles.js";
4 import { ItemId } from "../../shared/definitions/items.js";
5 import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";
6 import {
7 evaluateAlchemyBottle,
8 hashAlchemySteps,
9 resolvedAlchemyPotions,
10 unstablePotionFromSteps
11 } from "../../shared/alchemy/recipes.js";
12 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
13 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
14 import {
15 makeCharacter,
16 makeSimulation
17 } from "./helpers/simulationHarness.js";
18
19 function placeCauldron (worldDb, tileX, tileY)
20 {
21 const chunkX = Math.floor(tileX / 16);
22 const chunkY = Math.floor(tileY / 16);
23 const data = createEmptyChunkData();
24 data.open = true;
25 const localX = tileX - chunkX * 16;
26 const localY = tileY - chunkY * 16;
27 data.blocks[localY * 16 + localX] = { typeId: BlockType.cauldron, state: 0 };
28 worldDb.saveChunkVersion(
29 chunkX,
30 chunkY,
31 worldDb.getActiveRevisionId(),
32 true,
33 encodeChunkBlob(data)
34 );
35 }
36
37 function countItem (slots, itemId)
38 {
39 return (slots ?? [])
40 .filter((slot) => slot?.itemId === itemId)
41 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
42 }
43
44 test("green draught ratios and steps evaluate to a success batch", () =>
45 {
46 const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "greenDraught");
47 assert.ok(potion);
48 const evaluation = evaluateAlchemyBottle({
49 skills: { levels: { alchemy: 1 } },
50 brewStacks: [
51 { itemId: ItemId.greenHerb, quantity: 4 },
52 { itemId: ItemId.apple, quantity: 2 }
53 ],
54 takenSteps: [
55 { kind: AlchemyStepKind.heat },
56 { kind: AlchemyStepKind.insert, itemId: ItemId.greenHerb },
57 { kind: AlchemyStepKind.stir },
58 { kind: AlchemyStepKind.insert, itemId: ItemId.apple },
59 { kind: AlchemyStepKind.cool }
60 ]
61 });
62 assert.equal(evaluation.success, true);
63 assert.equal(evaluation.batch, 2);
64 assert.equal(evaluation.result.potionKey, "greenDraught");
65 });
66
67 test("same wrong steps hash to the same unstable potion", () =>
68 {
69 const steps = [
70 { kind: AlchemyStepKind.heat },
71 { kind: AlchemyStepKind.stir },
72 { kind: AlchemyStepKind.cool }
73 ];
74 const a = unstablePotionFromSteps(steps);
75 const b = unstablePotionFromSteps(steps);
76 assert.equal(a.potionKey, b.potionKey);
77 assert.equal(a.stepsHash, hashAlchemySteps(steps));
78 });
79
80 test("cauldron bottles green draught when steps and ratios match", () =>
81 {
82 const harness = makeSimulation({ workerCount: 1 });
83 try
84 {
85 placeCauldron(harness.worldDb, 8, 8);
86 harness.simulation.reloadWorld();
87 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
88 const inventory = emptySlots();
89 inventory[0] = { itemId: ItemId.greenHerb, quantity: 4 };
90 inventory[1] = { itemId: ItemId.apple, quantity: 2 };
91 inventory[2] = { itemId: ItemId.glassBottle, quantity: 2 };
92 inventory[3] = { itemId: ItemId.paper, quantity: 1 };
93 harness.stateDb.saveBag(character.character_id, {
94 inventory,
95 equipment: emptyEquipment(),
96 vault: [],
97 vaultReserved: []
98 });
99 const entityId = harness.simulation.spawnCharacter(1, character);
100 const cid = character.character_id;
101
102 harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
103 harness.simulation.step();
104
105 harness.simulation.enqueue(1, {
106 type: "cauldron-set-slot",
107 characterId: cid,
108 slotIndex: 0,
109 itemId: ItemId.greenHerb,
110 quantity: 4
111 });
112 harness.simulation.enqueue(1, {
113 type: "cauldron-set-slot",
114 characterId: cid,
115 slotIndex: 1,
116 itemId: ItemId.apple,
117 quantity: 2
118 });
119 harness.simulation.step();
120
121 harness.simulation.enqueue(1, {
122 type: "cauldron-action",
123 characterId: cid,
124 action: AlchemyStepKind.heat
125 });
126 harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 0 });
127 harness.simulation.enqueue(1, {
128 type: "cauldron-action",
129 characterId: cid,
130 action: AlchemyStepKind.stir
131 });
132 harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 });
133 harness.simulation.enqueue(1, {
134 type: "cauldron-action",
135 characterId: cid,
136 action: AlchemyStepKind.cool
137 });
138 harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid });
139 harness.simulation.step();
140
141 const bag = harness.simulation.bagOf(entityId);
142 assert.equal(countItem(bag.inventory, ItemId.greenHerb), 0);
143 assert.equal(countItem(bag.inventory, ItemId.apple), 0);
144 assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0);
145 assert.equal(countItem(bag.inventory, ItemId.potion), 2);
146 const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion);
147 assert.equal(potion.instance?.potionKey, "greenDraught");
148 assert.equal(potion.instance?.unstable, false);
149
150 harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid });
151 harness.simulation.step();
152 const after = harness.simulation.bagOf(entityId);
153 assert.equal(countItem(after.inventory, ItemId.paper), 0);
154 assert.equal(countItem(after.inventory, ItemId.recipePaper), 1);
155 const recipe = after.inventory.find((slot) => slot?.itemId === ItemId.recipePaper);
156 assert.match(recipe.instance?.body ?? "", /Green draught/);
157 assert.match(recipe.instance?.body ?? "", /Alchemy level required/);
158 }
159 finally
160 { harness.close(); }
161 });
@@ -0,0 +1,161 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { BlockType } from "../../shared/definitions/tiles.js";
4import { ItemId } from "../../shared/definitions/items.js";
5import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";
6import {
7 evaluateAlchemyBottle,
8 hashAlchemySteps,
9 resolvedAlchemyPotions,
10 unstablePotionFromSteps
11} from "../../shared/alchemy/recipes.js";
12import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
13import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
14import {
15 makeCharacter,
16 makeSimulation
17} from "./helpers/simulationHarness.js";
18
19function placeCauldron (worldDb, tileX, tileY)
20{
21 const chunkX = Math.floor(tileX / 16);
22 const chunkY = Math.floor(tileY / 16);
23 const data = createEmptyChunkData();
24 data.open = true;
25 const localX = tileX - chunkX * 16;
26 const localY = tileY - chunkY * 16;
27 data.blocks[localY * 16 + localX] = { typeId: BlockType.cauldron, state: 0 };
28 worldDb.saveChunkVersion(
29 chunkX,
30 chunkY,
31 worldDb.getActiveRevisionId(),
32 true,
33 encodeChunkBlob(data)
34 );
35}
36
37function countItem (slots, itemId)
38{
39 return (slots ?? [])
40 .filter((slot) => slot?.itemId === itemId)
41 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
42}
43
44test("green draught ratios and steps evaluate to a success batch", () =>
45{
46 const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "greenDraught");
47 assert.ok(potion);
48 const evaluation = evaluateAlchemyBottle({
49 skills: { levels: { alchemy: 1 } },
50 brewStacks: [
51 { itemId: ItemId.greenHerb, quantity: 4 },
52 { itemId: ItemId.apple, quantity: 2 }
53 ],
54 takenSteps: [
55 { kind: AlchemyStepKind.heat },
56 { kind: AlchemyStepKind.insert, itemId: ItemId.greenHerb },
57 { kind: AlchemyStepKind.stir },
58 { kind: AlchemyStepKind.insert, itemId: ItemId.apple },
59 { kind: AlchemyStepKind.cool }
60 ]
61 });
62 assert.equal(evaluation.success, true);
63 assert.equal(evaluation.batch, 2);
64 assert.equal(evaluation.result.potionKey, "greenDraught");
65});
66
67test("same wrong steps hash to the same unstable potion", () =>
68{
69 const steps = [
70 { kind: AlchemyStepKind.heat },
71 { kind: AlchemyStepKind.stir },
72 { kind: AlchemyStepKind.cool }
73 ];
74 const a = unstablePotionFromSteps(steps);
75 const b = unstablePotionFromSteps(steps);
76 assert.equal(a.potionKey, b.potionKey);
77 assert.equal(a.stepsHash, hashAlchemySteps(steps));
78});
79
80test("cauldron bottles green draught when steps and ratios match", () =>
81{
82 const harness = makeSimulation({ workerCount: 1 });
83 try
84 {
85 placeCauldron(harness.worldDb, 8, 8);
86 harness.simulation.reloadWorld();
87 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
88 const inventory = emptySlots();
89 inventory[0] = { itemId: ItemId.greenHerb, quantity: 4 };
90 inventory[1] = { itemId: ItemId.apple, quantity: 2 };
91 inventory[2] = { itemId: ItemId.glassBottle, quantity: 2 };
92 inventory[3] = { itemId: ItemId.paper, quantity: 1 };
93 harness.stateDb.saveBag(character.character_id, {
94 inventory,
95 equipment: emptyEquipment(),
96 vault: [],
97 vaultReserved: []
98 });
99 const entityId = harness.simulation.spawnCharacter(1, character);
100 const cid = character.character_id;
101
102 harness.simulation.enqueue(1, { type: "open-cauldron", characterId: cid });
103 harness.simulation.step();
104
105 harness.simulation.enqueue(1, {
106 type: "cauldron-set-slot",
107 characterId: cid,
108 slotIndex: 0,
109 itemId: ItemId.greenHerb,
110 quantity: 4
111 });
112 harness.simulation.enqueue(1, {
113 type: "cauldron-set-slot",
114 characterId: cid,
115 slotIndex: 1,
116 itemId: ItemId.apple,
117 quantity: 2
118 });
119 harness.simulation.step();
120
121 harness.simulation.enqueue(1, {
122 type: "cauldron-action",
123 characterId: cid,
124 action: AlchemyStepKind.heat
125 });
126 harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 0 });
127 harness.simulation.enqueue(1, {
128 type: "cauldron-action",
129 characterId: cid,
130 action: AlchemyStepKind.stir
131 });
132 harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 });
133 harness.simulation.enqueue(1, {
134 type: "cauldron-action",
135 characterId: cid,
136 action: AlchemyStepKind.cool
137 });
138 harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid });
139 harness.simulation.step();
140
141 const bag = harness.simulation.bagOf(entityId);
142 assert.equal(countItem(bag.inventory, ItemId.greenHerb), 0);
143 assert.equal(countItem(bag.inventory, ItemId.apple), 0);
144 assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0);
145 assert.equal(countItem(bag.inventory, ItemId.potion), 2);
146 const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion);
147 assert.equal(potion.instance?.potionKey, "greenDraught");
148 assert.equal(potion.instance?.unstable, false);
149
150 harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid });
151 harness.simulation.step();
152 const after = harness.simulation.bagOf(entityId);
153 assert.equal(countItem(after.inventory, ItemId.paper), 0);
154 assert.equal(countItem(after.inventory, ItemId.recipePaper), 1);
155 const recipe = after.inventory.find((slot) => slot?.itemId === ItemId.recipePaper);
156 assert.match(recipe.instance?.body ?? "", /Green draught/);
157 assert.match(recipe.instance?.body ?? "", /Alchemy level required/);
158 }
159 finally
160 { harness.close(); }
161});
server/tests/water-grounds.test.js added +20 −0
@@ -0,0 +1,20 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { GroundType, isGroundPassable, isWadeGround, isWaterGround } from "../../shared/definitions/tiles.js";
4 import { createEmptyChunkData, isChunkTilePassable, setGround } from "../src/world/chunkData.js";
5
6 test("deep water ground is impassable; shallow water is passable and wadeable", () =>
7 {
8 assert.equal(isGroundPassable(GroundType.water), true);
9 assert.equal(isGroundPassable(GroundType.deepWater), false);
10 assert.equal(isWadeGround(GroundType.water), true);
11 assert.equal(isWadeGround(GroundType.deepWater), false);
12 assert.equal(isWaterGround(GroundType.water), true);
13 assert.equal(isWaterGround(GroundType.deepWater), true);
14
15 const data = createEmptyChunkData();
16 setGround(data, 1, 1, GroundType.water);
17 setGround(data, 2, 2, GroundType.deepWater);
18 assert.equal(isChunkTilePassable(data, 1, 1), true);
19 assert.equal(isChunkTilePassable(data, 2, 2), false);
20 });
@@ -0,0 +1,20 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { GroundType, isGroundPassable, isWadeGround, isWaterGround } from "../../shared/definitions/tiles.js";
4import { createEmptyChunkData, isChunkTilePassable, setGround } from "../src/world/chunkData.js";
5
6test("deep water ground is impassable; shallow water is passable and wadeable", () =>
7{
8 assert.equal(isGroundPassable(GroundType.water), true);
9 assert.equal(isGroundPassable(GroundType.deepWater), false);
10 assert.equal(isWadeGround(GroundType.water), true);
11 assert.equal(isWadeGround(GroundType.deepWater), false);
12 assert.equal(isWaterGround(GroundType.water), true);
13 assert.equal(isWaterGround(GroundType.deepWater), true);
14
15 const data = createEmptyChunkData();
16 setGround(data, 1, 1, GroundType.water);
17 setGround(data, 2, 2, GroundType.deepWater);
18 assert.equal(isChunkTilePassable(data, 1, 1), true);
19 assert.equal(isChunkTilePassable(data, 2, 2), false);
20});
shared/alchemy/recipes.js added +243 −0
@@ -0,0 +1,243 @@
1 import { AlchemyStepKind, ALCHEMY_POTION_DEFINITIONS, UNSTABLE_POTION_EFFECTS } from "../definitions/alchemy.js";
2 import { ITEM_DEFINITIONS, itemDefinition } from "../definitions/items.js";
3 import { skillLevel, SkillId } from "../definitions/skills.js";
4
5 /** Serialize a step for hashing / recipe papers. */
6 export function formatAlchemyStep (step)
7 {
8 if (step.kind === AlchemyStepKind.insert)
9 {
10 const def = itemDefinition(step.itemId);
11 return `insert ${def?.displayName ?? step.itemKey ?? step.itemId}`;
12 }
13 return step.kind;
14 }
15
16 export function hashAlchemySteps (steps)
17 {
18 const text = (steps ?? []).map((step) =>
19 {
20 if (step.kind === AlchemyStepKind.insert)
21 { return `insert:${step.itemId ?? step.itemKey}`; }
22 return step.kind;
23 }).join("|");
24 let hash = 2166136261;
25 for (let i = 0; i < text.length; i++)
26 {
27 hash ^= text.charCodeAt(i);
28 hash = Math.imul(hash, 16777619);
29 }
30 return hash >>> 0;
31 }
32
33 export function unstablePotionFromSteps (steps)
34 {
35 const hash = hashAlchemySteps(steps);
36 const index = hash % UNSTABLE_POTION_EFFECTS.length;
37 const effect = UNSTABLE_POTION_EFFECTS[index];
38 return {
39 potionKey: `unstable:${effect.effectKey}`,
40 unstable: true,
41 stepsHash: hash,
42 displayName: effect.displayName,
43 color: effect.color,
44 fillLevel: effect.fillLevel,
45 effect: effect.effect,
46 effectKey: effect.effectKey
47 };
48 }
49
50 export function itemIdByKeyMap ()
51 {
52 const map = new Map();
53 for (const def of Object.values(ITEM_DEFINITIONS))
54 {
55 if (def?.key != null)
56 { map.set(def.key, def.itemId); }
57 }
58 return map;
59 }
60
61 /**
62 * Resolve ingredient itemIds on potion defs that use item keys (after items are loaded).
63 */
64 export function resolvePotionIngredientIds (potion, byKey = itemIdByKeyMap())
65 {
66 const ingredients = (potion.ingredients ?? []).map((row) =>
67 {
68 const itemId = row.itemId ?? byKey.get(row.key) ?? null;
69 return { itemId, key: row.key, quantity: row.quantity };
70 });
71 const steps = (potion.steps ?? []).map((step) =>
72 {
73 if (step.kind !== AlchemyStepKind.insert)
74 { return { ...step }; }
75 const itemId = step.itemId ?? byKey.get(step.itemKey) ?? null;
76 return { kind: AlchemyStepKind.insert, itemId, itemKey: step.itemKey };
77 });
78 return { ...potion, ingredients, steps };
79 }
80
81 let cachedResolvedPotions = null;
82
83 export function resolvedAlchemyPotions ()
84 {
85 if (!cachedResolvedPotions)
86 {
87 const byKey = itemIdByKeyMap();
88 cachedResolvedPotions = Object.values(ALCHEMY_POTION_DEFINITIONS)
89 .map((potion) => resolvePotionIngredientIds(potion, byKey));
90 }
91 return cachedResolvedPotions;
92 }
93
94 /**
95 * Greatest integer batch size for reserved slot quantities vs recipe ingredient ratios.
96 * Returns 0 if ratios do not match (wrong items or non-integer multiple).
97 */
98 export function alchemyBatchCount (recipeIngredients, reservedStacks)
99 {
100 const need = new Map();
101 for (const row of recipeIngredients ?? [])
102 {
103 if (row.itemId == null || row.quantity <= 0)
104 { return 0; }
105 need.set(row.itemId, (need.get(row.itemId) ?? 0) + row.quantity);
106 }
107 if (need.size === 0 || need.size > 4)
108 { return 0; }
109
110 const have = new Map();
111 for (const stack of reservedStacks ?? [])
112 {
113 if (!stack?.itemId || !(stack.quantity > 0))
114 { continue; }
115 have.set(stack.itemId, (have.get(stack.itemId) ?? 0) + stack.quantity);
116 }
117 if (have.size !== need.size)
118 { return 0; }
119
120 let batch = Infinity;
121 for (const [itemId, qty] of need)
122 {
123 const got = have.get(itemId);
124 if (got == null || got % qty !== 0)
125 { return 0; }
126 batch = Math.min(batch, got / qty);
127 }
128 for (const itemId of have.keys())
129 {
130 if (!need.has(itemId))
131 { return 0; }
132 }
133 return Number.isFinite(batch) && batch > 0 ? batch | 0 : 0;
134 }
135
136 export function stepsMatchRecipe (takenSteps, recipeSteps)
137 {
138 if (!Array.isArray(takenSteps) || !Array.isArray(recipeSteps))
139 { return false; }
140 if (takenSteps.length !== recipeSteps.length)
141 { return false; }
142 for (let i = 0; i < recipeSteps.length; i++)
143 {
144 const want = recipeSteps[i];
145 const got = takenSteps[i];
146 if (want.kind !== got.kind)
147 { return false; }
148 if (want.kind === AlchemyStepKind.insert && want.itemId !== got.itemId)
149 { return false; }
150 }
151 return true;
152 }
153
154 /**
155 * Evaluate bottling: success potion + batch, or unstable failure.
156 * Underleveled Alchemy on a correct recipe also yields unstable.
157 */
158 export function evaluateAlchemyBottle ({
159 skills,
160 brewStacks,
161 takenSteps,
162 potions = resolvedAlchemyPotions()
163 })
164 {
165 const level = skillLevel(skills, SkillId.alchemy);
166 for (const potion of potions)
167 {
168 const batch = alchemyBatchCount(potion.ingredients, brewStacks);
169 if (batch <= 0)
170 { continue; }
171 if (!stepsMatchRecipe(takenSteps, potion.steps))
172 { continue; }
173 if (level < (potion.minAlchemyLevel ?? 1))
174 {
175 return {
176 ok: true,
177 success: false,
178 batch: 1,
179 result: unstablePotionFromSteps(takenSteps),
180 reason: "alchemy-level"
181 };
182 }
183 return {
184 ok: true,
185 success: true,
186 batch,
187 result: {
188 potionKey: potion.potionKey,
189 unstable: false,
190 displayName: potion.displayName,
191 color: potion.color,
192 fillLevel: potion.fillLevel ?? 4,
193 effect: potion.effect,
194 effectKey: potion.effect?.type ?? potion.potionKey,
195 minAlchemyLevel: potion.minAlchemyLevel ?? 1
196 },
197 recipe: potion
198 };
199 }
200 return {
201 ok: true,
202 success: false,
203 batch: 1,
204 result: unstablePotionFromSteps(takenSteps),
205 reason: "no-match"
206 };
207 }
208
209 export function recipePaperBody (potion)
210 {
211 const lines = [
212 `${potion.displayName}`,
213 `Alchemy level required: ${potion.minAlchemyLevel ?? 1}`,
214 "",
215 "Ingredients (ratios):"
216 ];
217 for (const row of potion.ingredients ?? [])
218 {
219 const def = itemDefinition(row.itemId);
220 lines.push(`- ${row.quantity}× ${def?.displayName ?? row.key ?? row.itemId}`);
221 }
222 lines.push("", "Steps:");
223 for (const step of potion.steps ?? [])
224 { lines.push(`- ${formatAlchemyStep(step)}`); }
225 lines.push("", "Finish by bottling at the cauldron.");
226 return lines.join("\n");
227 }
228
229 export function potionItemInstance (result)
230 {
231 return {
232 kind: "potion",
233 potionKey: result.potionKey,
234 unstable: !!result.unstable,
235 displayName: result.displayName,
236 color: result.color,
237 fillLevel: Math.max(1, Math.min(5, result.fillLevel | 0 || 4)),
238 effect: result.effect ?? null,
239 effectKey: result.effectKey ?? result.effect?.type ?? result.potionKey,
240 stepsHash: result.stepsHash ?? null,
241 minAlchemyLevel: result.minAlchemyLevel ?? null
242 };
243 }
@@ -0,0 +1,243 @@
1import { AlchemyStepKind, ALCHEMY_POTION_DEFINITIONS, UNSTABLE_POTION_EFFECTS } from "../definitions/alchemy.js";
2import { ITEM_DEFINITIONS, itemDefinition } from "../definitions/items.js";
3import { skillLevel, SkillId } from "../definitions/skills.js";
4
5/** Serialize a step for hashing / recipe papers. */
6export function formatAlchemyStep (step)
7{
8 if (step.kind === AlchemyStepKind.insert)
9 {
10 const def = itemDefinition(step.itemId);
11 return `insert ${def?.displayName ?? step.itemKey ?? step.itemId}`;
12 }
13 return step.kind;
14}
15
16export function hashAlchemySteps (steps)
17{
18 const text = (steps ?? []).map((step) =>
19 {
20 if (step.kind === AlchemyStepKind.insert)
21 { return `insert:${step.itemId ?? step.itemKey}`; }
22 return step.kind;
23 }).join("|");
24 let hash = 2166136261;
25 for (let i = 0; i < text.length; i++)
26 {
27 hash ^= text.charCodeAt(i);
28 hash = Math.imul(hash, 16777619);
29 }
30 return hash >>> 0;
31}
32
33export function unstablePotionFromSteps (steps)
34{
35 const hash = hashAlchemySteps(steps);
36 const index = hash % UNSTABLE_POTION_EFFECTS.length;
37 const effect = UNSTABLE_POTION_EFFECTS[index];
38 return {
39 potionKey: `unstable:${effect.effectKey}`,
40 unstable: true,
41 stepsHash: hash,
42 displayName: effect.displayName,
43 color: effect.color,
44 fillLevel: effect.fillLevel,
45 effect: effect.effect,
46 effectKey: effect.effectKey
47 };
48}
49
50export function itemIdByKeyMap ()
51{
52 const map = new Map();
53 for (const def of Object.values(ITEM_DEFINITIONS))
54 {
55 if (def?.key != null)
56 { map.set(def.key, def.itemId); }
57 }
58 return map;
59}
60
61/**
62 * Resolve ingredient itemIds on potion defs that use item keys (after items are loaded).
63 */
64export function resolvePotionIngredientIds (potion, byKey = itemIdByKeyMap())
65{
66 const ingredients = (potion.ingredients ?? []).map((row) =>
67 {
68 const itemId = row.itemId ?? byKey.get(row.key) ?? null;
69 return { itemId, key: row.key, quantity: row.quantity };
70 });
71 const steps = (potion.steps ?? []).map((step) =>
72 {
73 if (step.kind !== AlchemyStepKind.insert)
74 { return { ...step }; }
75 const itemId = step.itemId ?? byKey.get(step.itemKey) ?? null;
76 return { kind: AlchemyStepKind.insert, itemId, itemKey: step.itemKey };
77 });
78 return { ...potion, ingredients, steps };
79}
80
81let cachedResolvedPotions = null;
82
83export function resolvedAlchemyPotions ()
84{
85 if (!cachedResolvedPotions)
86 {
87 const byKey = itemIdByKeyMap();
88 cachedResolvedPotions = Object.values(ALCHEMY_POTION_DEFINITIONS)
89 .map((potion) => resolvePotionIngredientIds(potion, byKey));
90 }
91 return cachedResolvedPotions;
92}
93
94/**
95 * Greatest integer batch size for reserved slot quantities vs recipe ingredient ratios.
96 * Returns 0 if ratios do not match (wrong items or non-integer multiple).
97 */
98export function alchemyBatchCount (recipeIngredients, reservedStacks)
99{
100 const need = new Map();
101 for (const row of recipeIngredients ?? [])
102 {
103 if (row.itemId == null || row.quantity <= 0)
104 { return 0; }
105 need.set(row.itemId, (need.get(row.itemId) ?? 0) + row.quantity);
106 }
107 if (need.size === 0 || need.size > 4)
108 { return 0; }
109
110 const have = new Map();
111 for (const stack of reservedStacks ?? [])
112 {
113 if (!stack?.itemId || !(stack.quantity > 0))
114 { continue; }
115 have.set(stack.itemId, (have.get(stack.itemId) ?? 0) + stack.quantity);
116 }
117 if (have.size !== need.size)
118 { return 0; }
119
120 let batch = Infinity;
121 for (const [itemId, qty] of need)
122 {
123 const got = have.get(itemId);
124 if (got == null || got % qty !== 0)
125 { return 0; }
126 batch = Math.min(batch, got / qty);
127 }
128 for (const itemId of have.keys())
129 {
130 if (!need.has(itemId))
131 { return 0; }
132 }
133 return Number.isFinite(batch) && batch > 0 ? batch | 0 : 0;
134}
135
136export function stepsMatchRecipe (takenSteps, recipeSteps)
137{
138 if (!Array.isArray(takenSteps) || !Array.isArray(recipeSteps))
139 { return false; }
140 if (takenSteps.length !== recipeSteps.length)
141 { return false; }
142 for (let i = 0; i < recipeSteps.length; i++)
143 {
144 const want = recipeSteps[i];
145 const got = takenSteps[i];
146 if (want.kind !== got.kind)
147 { return false; }
148 if (want.kind === AlchemyStepKind.insert && want.itemId !== got.itemId)
149 { return false; }
150 }
151 return true;
152}
153
154/**
155 * Evaluate bottling: success potion + batch, or unstable failure.
156 * Underleveled Alchemy on a correct recipe also yields unstable.
157 */
158export function evaluateAlchemyBottle ({
159 skills,
160 brewStacks,
161 takenSteps,
162 potions = resolvedAlchemyPotions()
163})
164{
165 const level = skillLevel(skills, SkillId.alchemy);
166 for (const potion of potions)
167 {
168 const batch = alchemyBatchCount(potion.ingredients, brewStacks);
169 if (batch <= 0)
170 { continue; }
171 if (!stepsMatchRecipe(takenSteps, potion.steps))
172 { continue; }
173 if (level < (potion.minAlchemyLevel ?? 1))
174 {
175 return {
176 ok: true,
177 success: false,
178 batch: 1,
179 result: unstablePotionFromSteps(takenSteps),
180 reason: "alchemy-level"
181 };
182 }
183 return {
184 ok: true,
185 success: true,
186 batch,
187 result: {
188 potionKey: potion.potionKey,
189 unstable: false,
190 displayName: potion.displayName,
191 color: potion.color,
192 fillLevel: potion.fillLevel ?? 4,
193 effect: potion.effect,
194 effectKey: potion.effect?.type ?? potion.potionKey,
195 minAlchemyLevel: potion.minAlchemyLevel ?? 1
196 },
197 recipe: potion
198 };
199 }
200 return {
201 ok: true,
202 success: false,
203 batch: 1,
204 result: unstablePotionFromSteps(takenSteps),
205 reason: "no-match"
206 };
207}
208
209export function recipePaperBody (potion)
210{
211 const lines = [
212 `${potion.displayName}`,
213 `Alchemy level required: ${potion.minAlchemyLevel ?? 1}`,
214 "",
215 "Ingredients (ratios):"
216 ];
217 for (const row of potion.ingredients ?? [])
218 {
219 const def = itemDefinition(row.itemId);
220 lines.push(`- ${row.quantity}× ${def?.displayName ?? row.key ?? row.itemId}`);
221 }
222 lines.push("", "Steps:");
223 for (const step of potion.steps ?? [])
224 { lines.push(`- ${formatAlchemyStep(step)}`); }
225 lines.push("", "Finish by bottling at the cauldron.");
226 return lines.join("\n");
227}
228
229export function potionItemInstance (result)
230{
231 return {
232 kind: "potion",
233 potionKey: result.potionKey,
234 unstable: !!result.unstable,
235 displayName: result.displayName,
236 color: result.color,
237 fillLevel: Math.max(1, Math.min(5, result.fillLevel | 0 || 4)),
238 effect: result.effect ?? null,
239 effectKey: result.effectKey ?? result.effect?.type ?? result.potionKey,
240 stepsHash: result.stepsHash ?? null,
241 minAlchemyLevel: result.minAlchemyLevel ?? null
242 };
243}
shared/definitions/alchemy.js added +58 −0
@@ -0,0 +1,58 @@
1 /** Cauldron action / step kinds (authoritative recipe language). */
2 export const AlchemyStepKind = Object.freeze({
3 heat: "heat",
4 cool: "cool",
5 stir: "stir",
6 insert: "insert"
7 });
8
9 export const POTION_MAX_STACK = 16;
10 export const POTION_FILL_LEVELS = Object.freeze([1, 2, 3, 4, 5]);
11 export const CAULDRON_SLOT_COUNT = 4;
12
13 /**
14 * Known successful potions. Ingredient `key` matches item def keys (resolved to itemId at runtime).
15 * A potion may never use more than 4 unique ingredients (ratio units).
16 */
17 export const ALCHEMY_POTION_DEFINITIONS = Object.freeze({
18 greenDraught: Object.freeze({
19 potionKey: "greenDraught",
20 displayName: "Green draught",
21 minAlchemyLevel: 1,
22 color: Object.freeze({ r: 0.25, g: 0.72, b: 0.35 }),
23 fillLevel: 4,
24 ingredients: Object.freeze([
25 Object.freeze({ key: "green-herb", quantity: 2 }),
26 Object.freeze({ key: "apple", quantity: 1 })
27 ]),
28 steps: Object.freeze([
29 Object.freeze({ kind: AlchemyStepKind.heat }),
30 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "green-herb" }),
31 Object.freeze({ kind: AlchemyStepKind.stir }),
32 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "apple" }),
33 Object.freeze({ kind: AlchemyStepKind.cool })
34 ]),
35 effect: Object.freeze({ type: "heal", amount: 5 })
36 })
37 });
38
39 /**
40 * Failure (unstable) potions chosen by hashing the step transcript.
41 * Effects are stubs for later systems.
42 */
43 export const UNSTABLE_POTION_EFFECTS = Object.freeze([
44 Object.freeze({ effectKey: "slow", displayName: "Unstable draught (sluggish)", color: { r: 0.45, g: 0.35, b: 0.55 }, fillLevel: 3, effect: { type: "slow", durationMs: 60_000 } }),
45 Object.freeze({ effectKey: "harm", displayName: "Unstable draught (bitter)", color: { r: 0.7, g: 0.2, b: 0.15 }, fillLevel: 2, effect: { type: "damage", amount: 4 } }),
46 Object.freeze({ effectKey: "blind", displayName: "Unstable draught (murky)", color: { r: 0.15, g: 0.15, b: 0.2 }, fillLevel: 3, effect: { type: "blind", durationMs: 30_000 } }),
47 Object.freeze({ effectKey: "queasy", displayName: "Unstable draught (queasy)", color: { r: 0.55, g: 0.65, b: 0.2 }, fillLevel: 2, effect: { type: "queasy", durationMs: 45_000 } })
48 ]);
49
50 export function alchemyPotionDefinition (potionKey)
51 {
52 return ALCHEMY_POTION_DEFINITIONS[potionKey] ?? null;
53 }
54
55 export function listAlchemyPotions ()
56 {
57 return Object.values(ALCHEMY_POTION_DEFINITIONS);
58 }
@@ -0,0 +1,58 @@
1/** Cauldron action / step kinds (authoritative recipe language). */
2export const AlchemyStepKind = Object.freeze({
3 heat: "heat",
4 cool: "cool",
5 stir: "stir",
6 insert: "insert"
7});
8
9export const POTION_MAX_STACK = 16;
10export const POTION_FILL_LEVELS = Object.freeze([1, 2, 3, 4, 5]);
11export const CAULDRON_SLOT_COUNT = 4;
12
13/**
14 * Known successful potions. Ingredient `key` matches item def keys (resolved to itemId at runtime).
15 * A potion may never use more than 4 unique ingredients (ratio units).
16 */
17export const ALCHEMY_POTION_DEFINITIONS = Object.freeze({
18 greenDraught: Object.freeze({
19 potionKey: "greenDraught",
20 displayName: "Green draught",
21 minAlchemyLevel: 1,
22 color: Object.freeze({ r: 0.25, g: 0.72, b: 0.35 }),
23 fillLevel: 4,
24 ingredients: Object.freeze([
25 Object.freeze({ key: "green-herb", quantity: 2 }),
26 Object.freeze({ key: "apple", quantity: 1 })
27 ]),
28 steps: Object.freeze([
29 Object.freeze({ kind: AlchemyStepKind.heat }),
30 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "green-herb" }),
31 Object.freeze({ kind: AlchemyStepKind.stir }),
32 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "apple" }),
33 Object.freeze({ kind: AlchemyStepKind.cool })
34 ]),
35 effect: Object.freeze({ type: "heal", amount: 5 })
36 })
37});
38
39/**
40 * Failure (unstable) potions chosen by hashing the step transcript.
41 * Effects are stubs for later systems.
42 */
43export const UNSTABLE_POTION_EFFECTS = Object.freeze([
44 Object.freeze({ effectKey: "slow", displayName: "Unstable draught (sluggish)", color: { r: 0.45, g: 0.35, b: 0.55 }, fillLevel: 3, effect: { type: "slow", durationMs: 60_000 } }),
45 Object.freeze({ effectKey: "harm", displayName: "Unstable draught (bitter)", color: { r: 0.7, g: 0.2, b: 0.15 }, fillLevel: 2, effect: { type: "damage", amount: 4 } }),
46 Object.freeze({ effectKey: "blind", displayName: "Unstable draught (murky)", color: { r: 0.15, g: 0.15, b: 0.2 }, fillLevel: 3, effect: { type: "blind", durationMs: 30_000 } }),
47 Object.freeze({ effectKey: "queasy", displayName: "Unstable draught (queasy)", color: { r: 0.55, g: 0.65, b: 0.2 }, fillLevel: 2, effect: { type: "queasy", durationMs: 45_000 } })
48]);
49
50export function alchemyPotionDefinition (potionKey)
51{
52 return ALCHEMY_POTION_DEFINITIONS[potionKey] ?? null;
53}
54
55export function listAlchemyPotions ()
56{
57 return Object.values(ALCHEMY_POTION_DEFINITIONS);
58}
shared/definitions/equipmentKinds.js +2 −1
@@ -12,5 +12,6 @@ export const EquipmentKind = Object.freeze({
12 12 axeTool: "axeTool",
13 13 pickaxeTool: "pickaxeTool",
14 14 fishingRod: "fishingRod",
15 fishingNet: "fishingNet"
15 fishingNet: "fishingNet",
16 plantClippers: "plantClippers"
16 17 });
@@ -12,5 +12,6 @@ export const EquipmentKind = Object.freeze({
12 axeTool: "axeTool",
12 axeTool: "axeTool",
13 pickaxeTool: "pickaxeTool",
13 pickaxeTool: "pickaxeTool",
14 fishingRod: "fishingRod",
14 fishingRod: "fishingRod",
15 fishingNet: "fishingNet"
15 fishingNet: "fishingNet",
16 plantClippers: "plantClippers"
16});
17});
shared/definitions/itemCategories.js +1 −0
@@ -5,6 +5,7 @@ export const ItemCategory = Object.freeze({
5 5 finished: "finished",
6 6 tool: "tool",
7 7 food: "food",
8 potion: "potion",
8 9 document: "document",
9 10 currency: "currency",
10 11 other: "other"
@@ -5,6 +5,7 @@ export const ItemCategory = Object.freeze({
5 finished: "finished",
5 finished: "finished",
6 tool: "tool",
6 tool: "tool",
7 food: "food",
7 food: "food",
8 potion: "potion",
8 document: "document",
9 document: "document",
9 currency: "currency",
10 currency: "currency",
10 other: "other"
11 other: "other"
shared/definitions/items.js +103 −1
@@ -6,6 +6,7 @@ import { EquipmentKind } from "./equipmentKinds.js";
6 6 import { formatQuantity } from "../items/formatQuantity.js";
7 7 import { formatOriginBreakdown } from "../items/origin.js";
8 8 import { CraftingItemId, CRAFTING_ITEM_STUBS } from "./craftingItems.js";
9 import { POTION_MAX_STACK } from "./alchemy.js";
9 10
10 11 export const ItemId = Object.freeze({
11 12 paper: 1,
@@ -19,7 +20,13 @@ export const ItemId = Object.freeze({
19 20 ...CraftingItemId,
20 21 lantern: 26,
21 22 bones: 27,
22 skull: 28
23 skull: 28,
24 glassBottle: 29,
25 greenHerb: 30,
26 redBeet: 31,
27 potion: 32,
28 recipePaper: 33,
29 bronzePlantClippers: 34
23 30 });
24 31
25 32 export const EQUIPMENT_SLOT = Object.freeze({
@@ -205,6 +212,81 @@ export const ITEM_DEFINITIONS = Object.freeze({
205 212 uniqueInstance: false,
206 213 category: "misc"
207 214 }),
215 [ItemId.glassBottle]: Object.freeze({
216 itemId: ItemId.glassBottle,
217 key: "glass-bottle",
218 displayName: "Glass bottle",
219 description: "An empty bottle for alchemy. Used when bottling a cauldron brew.",
220 seedValue: 2,
221 stackable: true,
222 maxStackSize: DEFAULT_MAX_STACK,
223 uniqueInstance: false,
224 category: "tool"
225 }),
226 [ItemId.greenHerb]: Object.freeze({
227 itemId: ItemId.greenHerb,
228 key: "green-herb",
229 displayName: "Green herb",
230 description: "A common herb. Gathered with plant clippers (Herbalism). Used in alchemy.",
231 seedValue: 2,
232 stackable: true,
233 maxStackSize: DEFAULT_MAX_STACK,
234 uniqueInstance: false,
235 category: "ingredient"
236 }),
237 [ItemId.redBeet]: Object.freeze({
238 itemId: ItemId.redBeet,
239 key: "red-beet",
240 displayName: "Red beet",
241 description: "A root vegetable used in some alchemy recipes.",
242 seedValue: 1,
243 stackable: true,
244 maxStackSize: DEFAULT_MAX_STACK,
245 uniqueInstance: false,
246 category: "ingredient"
247 }),
248 [ItemId.potion]: Object.freeze({
249 itemId: ItemId.potion,
250 key: "potion",
251 displayName: "Potion",
252 description: "A bottled brew. Drink to apply its effect (effects TBD).",
253 seedValue: 8,
254 stackable: true,
255 maxStackSize: POTION_MAX_STACK,
256 uniqueInstance: false,
257 category: "potion",
258 potion: true,
259 iconKey: "potion"
260 }),
261 [ItemId.recipePaper]: Object.freeze({
262 itemId: ItemId.recipePaper,
263 key: "recipe-paper",
264 displayName: "Recipe paper",
265 description: "An alchemy recipe you wrote down. Read like a letter.",
266 seedValue: 2,
267 stackable: false,
268 maxStackSize: 1,
269 uniqueInstance: true,
270 category: "document",
271 defaultState: "recipe-paper",
272 iconKey: "paper"
273 }),
274 [ItemId.bronzePlantClippers]: Object.freeze({
275 itemId: ItemId.bronzePlantClippers,
276 key: "bronze-plant-clippers",
277 displayName: "Bronze plant clippers",
278 description: "Herbalism tool. Tier sets minimum Herbalism to equip; better tiers gather faster (later).",
279 seedValue: 10,
280 stackable: false,
281 maxStackSize: 1,
282 uniqueInstance: false,
283 category: "tool",
284 equipment: Object.freeze({
285 slot: EQUIPMENT_SLOT.weapon,
286 tier: MaterialTier.bronze,
287 kind: EquipmentKind.plantClippers
288 })
289 }),
208 290 ...CRAFTING_ITEM_STUBS
209 291 });
210 292
@@ -222,6 +304,10 @@ export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
222 304 const qty = stack?.quantity ?? 1;
223 305 if (stack?.itemId === ItemId.coins)
224 306 { return qty === 1 ? (def.displayName ?? "Coin") : (def.displayNamePlural ?? "Coins"); }
307 if (stack?.itemId === ItemId.potion && stack.instance?.displayName)
308 { return stack.instance.displayName; }
309 if (stack?.itemId === ItemId.recipePaper && stack.instance?.displayName)
310 { return stack.instance.displayName; }
225 311 return def.displayName ?? "Item";
226 312 }
227 313
@@ -271,6 +357,15 @@ export function itemDescription (stack, { localCharacterId } = {})
271 357 const name = reserved?.displayName ?? "goods";
272 358 return `Bearer cheque for ${qty}× ${name}.`;
273 359 }
360 if (stack.itemId === ItemId.potion && stack.instance?.kind === "potion")
361 {
362 const name = stack.instance.displayName ?? "Potion";
363 return stack.instance.unstable
364 ? `${name}. An unstable brew — effects are unpredictable.`
365 : `${name}. Drink to apply its effect (effects TBD).`;
366 }
367 if (stack.itemId === ItemId.recipePaper && stack.instance?.kind === "recipe-paper")
368 { return "An alchemy recipe you wrote down. Read like a letter."; }
274 369 return def.description ?? "";
275 370 }
276 371
@@ -345,6 +440,13 @@ export function itemAssetPathForStack (stack)
345 440 const tier = coinSpriteTierForQuantity(stack.quantity);
346 441 return `/assets/items/coins/coins-${tier}.png`;
347 442 }
443 if (stack.itemId === ItemId.potion)
444 {
445 const fill = Math.max(1, Math.min(5, stack.instance?.fillLevel | 0 || 4));
446 return `/assets/items/potion/potion-${fill}.png`;
447 }
448 if (stack.itemId === ItemId.glassBottle)
449 { return `/assets/items/glass-bottle/glass-bottle.png`; }
348 450 return itemAssetPath(stack.itemId, null, stack.instance);
349 451 }
350 452
@@ -6,6 +6,7 @@ import { EquipmentKind } from "./equipmentKinds.js";
6import { formatQuantity } from "../items/formatQuantity.js";
6import { formatQuantity } from "../items/formatQuantity.js";
7import { formatOriginBreakdown } from "../items/origin.js";
7import { formatOriginBreakdown } from "../items/origin.js";
8import { CraftingItemId, CRAFTING_ITEM_STUBS } from "./craftingItems.js";
8import { CraftingItemId, CRAFTING_ITEM_STUBS } from "./craftingItems.js";
9import { POTION_MAX_STACK } from "./alchemy.js";
9
10
10export const ItemId = Object.freeze({
11export const ItemId = Object.freeze({
11 paper: 1,
12 paper: 1,
@@ -19,7 +20,13 @@ export const ItemId = Object.freeze({
19 ...CraftingItemId,
20 ...CraftingItemId,
20 lantern: 26,
21 lantern: 26,
21 bones: 27,
22 bones: 27,
22 skull: 28
23 skull: 28,
24 glassBottle: 29,
25 greenHerb: 30,
26 redBeet: 31,
27 potion: 32,
28 recipePaper: 33,
29 bronzePlantClippers: 34
23});
30});
24
31
25export const EQUIPMENT_SLOT = Object.freeze({
32export const EQUIPMENT_SLOT = Object.freeze({
@@ -205,6 +212,81 @@ export const ITEM_DEFINITIONS = Object.freeze({
205 uniqueInstance: false,
212 uniqueInstance: false,
206 category: "misc"
213 category: "misc"
207 }),
214 }),
215 [ItemId.glassBottle]: Object.freeze({
216 itemId: ItemId.glassBottle,
217 key: "glass-bottle",
218 displayName: "Glass bottle",
219 description: "An empty bottle for alchemy. Used when bottling a cauldron brew.",
220 seedValue: 2,
221 stackable: true,
222 maxStackSize: DEFAULT_MAX_STACK,
223 uniqueInstance: false,
224 category: "tool"
225 }),
226 [ItemId.greenHerb]: Object.freeze({
227 itemId: ItemId.greenHerb,
228 key: "green-herb",
229 displayName: "Green herb",
230 description: "A common herb. Gathered with plant clippers (Herbalism). Used in alchemy.",
231 seedValue: 2,
232 stackable: true,
233 maxStackSize: DEFAULT_MAX_STACK,
234 uniqueInstance: false,
235 category: "ingredient"
236 }),
237 [ItemId.redBeet]: Object.freeze({
238 itemId: ItemId.redBeet,
239 key: "red-beet",
240 displayName: "Red beet",
241 description: "A root vegetable used in some alchemy recipes.",
242 seedValue: 1,
243 stackable: true,
244 maxStackSize: DEFAULT_MAX_STACK,
245 uniqueInstance: false,
246 category: "ingredient"
247 }),
248 [ItemId.potion]: Object.freeze({
249 itemId: ItemId.potion,
250 key: "potion",
251 displayName: "Potion",
252 description: "A bottled brew. Drink to apply its effect (effects TBD).",
253 seedValue: 8,
254 stackable: true,
255 maxStackSize: POTION_MAX_STACK,
256 uniqueInstance: false,
257 category: "potion",
258 potion: true,
259 iconKey: "potion"
260 }),
261 [ItemId.recipePaper]: Object.freeze({
262 itemId: ItemId.recipePaper,
263 key: "recipe-paper",
264 displayName: "Recipe paper",
265 description: "An alchemy recipe you wrote down. Read like a letter.",
266 seedValue: 2,
267 stackable: false,
268 maxStackSize: 1,
269 uniqueInstance: true,
270 category: "document",
271 defaultState: "recipe-paper",
272 iconKey: "paper"
273 }),
274 [ItemId.bronzePlantClippers]: Object.freeze({
275 itemId: ItemId.bronzePlantClippers,
276 key: "bronze-plant-clippers",
277 displayName: "Bronze plant clippers",
278 description: "Herbalism tool. Tier sets minimum Herbalism to equip; better tiers gather faster (later).",
279 seedValue: 10,
280 stackable: false,
281 maxStackSize: 1,
282 uniqueInstance: false,
283 category: "tool",
284 equipment: Object.freeze({
285 slot: EQUIPMENT_SLOT.weapon,
286 tier: MaterialTier.bronze,
287 kind: EquipmentKind.plantClippers
288 })
289 }),
208 ...CRAFTING_ITEM_STUBS
290 ...CRAFTING_ITEM_STUBS
209});
291});
210
292
@@ -222,6 +304,10 @@ export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
222 const qty = stack?.quantity ?? 1;
304 const qty = stack?.quantity ?? 1;
223 if (stack?.itemId === ItemId.coins)
305 if (stack?.itemId === ItemId.coins)
224 { return qty === 1 ? (def.displayName ?? "Coin") : (def.displayNamePlural ?? "Coins"); }
306 { return qty === 1 ? (def.displayName ?? "Coin") : (def.displayNamePlural ?? "Coins"); }
307 if (stack?.itemId === ItemId.potion && stack.instance?.displayName)
308 { return stack.instance.displayName; }
309 if (stack?.itemId === ItemId.recipePaper && stack.instance?.displayName)
310 { return stack.instance.displayName; }
225 return def.displayName ?? "Item";
311 return def.displayName ?? "Item";
226}
312}
227
313
@@ -271,6 +357,15 @@ export function itemDescription (stack, { localCharacterId } = {})
271 const name = reserved?.displayName ?? "goods";
357 const name = reserved?.displayName ?? "goods";
272 return `Bearer cheque for ${qty}× ${name}.`;
358 return `Bearer cheque for ${qty}× ${name}.`;
273 }
359 }
360 if (stack.itemId === ItemId.potion && stack.instance?.kind === "potion")
361 {
362 const name = stack.instance.displayName ?? "Potion";
363 return stack.instance.unstable
364 ? `${name}. An unstable brew — effects are unpredictable.`
365 : `${name}. Drink to apply its effect (effects TBD).`;
366 }
367 if (stack.itemId === ItemId.recipePaper && stack.instance?.kind === "recipe-paper")
368 { return "An alchemy recipe you wrote down. Read like a letter."; }
274 return def.description ?? "";
369 return def.description ?? "";
275}
370}
276
371
@@ -345,6 +440,13 @@ export function itemAssetPathForStack (stack)
345 const tier = coinSpriteTierForQuantity(stack.quantity);
440 const tier = coinSpriteTierForQuantity(stack.quantity);
346 return `/assets/items/coins/coins-${tier}.png`;
441 return `/assets/items/coins/coins-${tier}.png`;
347 }
442 }
443 if (stack.itemId === ItemId.potion)
444 {
445 const fill = Math.max(1, Math.min(5, stack.instance?.fillLevel | 0 || 4));
446 return `/assets/items/potion/potion-${fill}.png`;
447 }
448 if (stack.itemId === ItemId.glassBottle)
449 { return `/assets/items/glass-bottle/glass-bottle.png`; }
348 return itemAssetPath(stack.itemId, null, stack.instance);
450 return itemAssetPath(stack.itemId, null, stack.instance);
349}
451}
350
452
shared/definitions/skills.js +9 −3
@@ -18,7 +18,9 @@ export const SkillId = Object.freeze({
18 18 crafting: "crafting",
19 19 leatherworking: "leatherworking",
20 20 tailoring: "tailoring",
21 cooking: "cooking"
21 cooking: "cooking",
22 herbalism: "herbalism",
23 alchemy: "alchemy"
22 24 });
23 25
24 26 /** Display order for the skills panel (two columns, top to bottom). */
@@ -42,7 +44,9 @@ export const ALL_SKILL_IDS = Object.freeze([
42 44 SkillId.crafting,
43 45 SkillId.leatherworking,
44 46 SkillId.tailoring,
45 SkillId.cooking
47 SkillId.cooking,
48 SkillId.herbalism,
49 SkillId.alchemy
46 50 ]);
47 51
48 52 export const SKILL_DEFINITIONS = Object.freeze({
@@ -65,7 +69,9 @@ export const SKILL_DEFINITIONS = Object.freeze({
65 69 [SkillId.crafting]: Object.freeze({ skillId: SkillId.crafting, displayName: "Crafting" }),
66 70 [SkillId.leatherworking]: Object.freeze({ skillId: SkillId.leatherworking, displayName: "Leatherworking" }),
67 71 [SkillId.tailoring]: Object.freeze({ skillId: SkillId.tailoring, displayName: "Tailoring" }),
68 [SkillId.cooking]: Object.freeze({ skillId: SkillId.cooking, displayName: "Cooking" })
72 [SkillId.cooking]: Object.freeze({ skillId: SkillId.cooking, displayName: "Cooking" }),
73 [SkillId.herbalism]: Object.freeze({ skillId: SkillId.herbalism, displayName: "Herbalism" }),
74 [SkillId.alchemy]: Object.freeze({ skillId: SkillId.alchemy, displayName: "Alchemy" })
69 75 });
70 76
71 77 export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze(Object.fromEntries(
@@ -18,7 +18,9 @@ export const SkillId = Object.freeze({
18 crafting: "crafting",
18 crafting: "crafting",
19 leatherworking: "leatherworking",
19 leatherworking: "leatherworking",
20 tailoring: "tailoring",
20 tailoring: "tailoring",
21 cooking: "cooking"
21 cooking: "cooking",
22 herbalism: "herbalism",
23 alchemy: "alchemy"
22});
24});
23
25
24/** Display order for the skills panel (two columns, top to bottom). */
26/** Display order for the skills panel (two columns, top to bottom). */
@@ -42,7 +44,9 @@ export const ALL_SKILL_IDS = Object.freeze([
42 SkillId.crafting,
44 SkillId.crafting,
43 SkillId.leatherworking,
45 SkillId.leatherworking,
44 SkillId.tailoring,
46 SkillId.tailoring,
45 SkillId.cooking
47 SkillId.cooking,
48 SkillId.herbalism,
49 SkillId.alchemy
46]);
50]);
47
51
48export const SKILL_DEFINITIONS = Object.freeze({
52export const SKILL_DEFINITIONS = Object.freeze({
@@ -65,7 +69,9 @@ export const SKILL_DEFINITIONS = Object.freeze({
65 [SkillId.crafting]: Object.freeze({ skillId: SkillId.crafting, displayName: "Crafting" }),
69 [SkillId.crafting]: Object.freeze({ skillId: SkillId.crafting, displayName: "Crafting" }),
66 [SkillId.leatherworking]: Object.freeze({ skillId: SkillId.leatherworking, displayName: "Leatherworking" }),
70 [SkillId.leatherworking]: Object.freeze({ skillId: SkillId.leatherworking, displayName: "Leatherworking" }),
67 [SkillId.tailoring]: Object.freeze({ skillId: SkillId.tailoring, displayName: "Tailoring" }),
71 [SkillId.tailoring]: Object.freeze({ skillId: SkillId.tailoring, displayName: "Tailoring" }),
68 [SkillId.cooking]: Object.freeze({ skillId: SkillId.cooking, displayName: "Cooking" })
72 [SkillId.cooking]: Object.freeze({ skillId: SkillId.cooking, displayName: "Cooking" }),
73 [SkillId.herbalism]: Object.freeze({ skillId: SkillId.herbalism, displayName: "Herbalism" }),
74 [SkillId.alchemy]: Object.freeze({ skillId: SkillId.alchemy, displayName: "Alchemy" })
69});
75});
70
76
71export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze(Object.fromEntries(
77export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze(Object.fromEntries(
shared/definitions/tiles.js +61 −2
@@ -1,6 +1,8 @@
1 1 export const GroundType = Object.freeze({
2 2 grass: 1,
3 wood: 2
3 wood: 2,
4 water: 3,
5 deepWater: 4
4 6 });
5 7
6 8 export const BlockType = Object.freeze({
@@ -9,7 +11,8 @@ export const BlockType = Object.freeze({
9 11 /** @deprecated Legacy authored block; migrated into chunk `spawners[]` on load. */
10 12 spawner: 3,
11 13 bank: 4,
12 churchAltar: 5
14 churchAltar: 5,
15 cauldron: 6
13 16 });
14 17
15 18 export const GROUND_DEFINITIONS = Object.freeze({
@@ -17,6 +20,9 @@ export const GROUND_DEFINITIONS = Object.freeze({
17 20 id: GroundType.grass,
18 21 key: "grass",
19 22 displayName: "Grass",
23 passable: true,
24 wades: false,
25 water: false,
20 26 frames: 1,
21 27 framesPerRow: 1,
22 28 animationSpeed: 0
@@ -25,9 +31,34 @@ export const GROUND_DEFINITIONS = Object.freeze({
25 31 id: GroundType.wood,
26 32 key: "wood",
27 33 displayName: "Wood",
34 passable: true,
35 wades: false,
36 water: false,
28 37 frames: 1,
29 38 framesPerRow: 1,
30 39 animationSpeed: 0
40 }),
41 [GroundType.water]: Object.freeze({
42 id: GroundType.water,
43 key: "water",
44 displayName: "Water",
45 passable: true,
46 wades: true,
47 water: true,
48 frames: 4,
49 framesPerRow: 4,
50 animationSpeed: 0.12
51 }),
52 [GroundType.deepWater]: Object.freeze({
53 id: GroundType.deepWater,
54 key: "deep-water",
55 displayName: "Deep water",
56 passable: false,
57 wades: false,
58 water: true,
59 frames: 4,
60 framesPerRow: 4,
61 animationSpeed: 0.12
31 62 })
32 63 });
33 64
@@ -83,6 +114,16 @@ export const BLOCK_DEFINITIONS = Object.freeze({
83 114 frames: 1,
84 115 framesPerRow: 1,
85 116 animationSpeed: 0
117 }),
118 [BlockType.cauldron]: Object.freeze({
119 id: BlockType.cauldron,
120 key: "cauldron",
121 displayName: "Cauldron",
122 passable: false,
123 lightRangeTiles: 0,
124 frames: 1,
125 framesPerRow: 1,
126 animationSpeed: 0
86 127 })
87 128 });
88 129
@@ -107,6 +148,24 @@ export function blockDefinition (typeId)
107 148 return BLOCK_DEFINITIONS[typeId] ?? null;
108 149 }
109 150
151 export function isGroundPassable (typeId)
152 {
153 const def = groundDefinition(typeId);
154 if (!def)
155 { return true; }
156 return def.passable !== false;
157 }
158
159 export function isWaterGround (typeId)
160 {
161 return !!groundDefinition(typeId)?.water;
162 }
163
164 export function isWadeGround (typeId)
165 {
166 return !!groundDefinition(typeId)?.wades;
167 }
168
110 169 export function isBlockPassable (typeId)
111 170 {
112 171 if (typeId == null)
@@ -1,6 +1,8 @@
1export const GroundType = Object.freeze({
1export const GroundType = Object.freeze({
2 grass: 1,
2 grass: 1,
3 wood: 2
3 wood: 2,
4 water: 3,
5 deepWater: 4
4});
6});
5
7
6export const BlockType = Object.freeze({
8export const BlockType = Object.freeze({
@@ -9,7 +11,8 @@ export const BlockType = Object.freeze({
9 /** @deprecated Legacy authored block; migrated into chunk `spawners[]` on load. */
11 /** @deprecated Legacy authored block; migrated into chunk `spawners[]` on load. */
10 spawner: 3,
12 spawner: 3,
11 bank: 4,
13 bank: 4,
12 churchAltar: 5
14 churchAltar: 5,
15 cauldron: 6
13});
16});
14
17
15export const GROUND_DEFINITIONS = Object.freeze({
18export const GROUND_DEFINITIONS = Object.freeze({
@@ -17,6 +20,9 @@ export const GROUND_DEFINITIONS = Object.freeze({
17 id: GroundType.grass,
20 id: GroundType.grass,
18 key: "grass",
21 key: "grass",
19 displayName: "Grass",
22 displayName: "Grass",
23 passable: true,
24 wades: false,
25 water: false,
20 frames: 1,
26 frames: 1,
21 framesPerRow: 1,
27 framesPerRow: 1,
22 animationSpeed: 0
28 animationSpeed: 0
@@ -25,9 +31,34 @@ export const GROUND_DEFINITIONS = Object.freeze({
25 id: GroundType.wood,
31 id: GroundType.wood,
26 key: "wood",
32 key: "wood",
27 displayName: "Wood",
33 displayName: "Wood",
34 passable: true,
35 wades: false,
36 water: false,
28 frames: 1,
37 frames: 1,
29 framesPerRow: 1,
38 framesPerRow: 1,
30 animationSpeed: 0
39 animationSpeed: 0
40 }),
41 [GroundType.water]: Object.freeze({
42 id: GroundType.water,
43 key: "water",
44 displayName: "Water",
45 passable: true,
46 wades: true,
47 water: true,
48 frames: 4,
49 framesPerRow: 4,
50 animationSpeed: 0.12
51 }),
52 [GroundType.deepWater]: Object.freeze({
53 id: GroundType.deepWater,
54 key: "deep-water",
55 displayName: "Deep water",
56 passable: false,
57 wades: false,
58 water: true,
59 frames: 4,
60 framesPerRow: 4,
61 animationSpeed: 0.12
31 })
62 })
32});
63});
33
64
@@ -83,6 +114,16 @@ export const BLOCK_DEFINITIONS = Object.freeze({
83 frames: 1,
114 frames: 1,
84 framesPerRow: 1,
115 framesPerRow: 1,
85 animationSpeed: 0
116 animationSpeed: 0
117 }),
118 [BlockType.cauldron]: Object.freeze({
119 id: BlockType.cauldron,
120 key: "cauldron",
121 displayName: "Cauldron",
122 passable: false,
123 lightRangeTiles: 0,
124 frames: 1,
125 framesPerRow: 1,
126 animationSpeed: 0
86 })
127 })
87});
128});
88
129
@@ -107,6 +148,24 @@ export function blockDefinition (typeId)
107 return BLOCK_DEFINITIONS[typeId] ?? null;
148 return BLOCK_DEFINITIONS[typeId] ?? null;
108}
149}
109
150
151export function isGroundPassable (typeId)
152{
153 const def = groundDefinition(typeId);
154 if (!def)
155 { return true; }
156 return def.passable !== false;
157}
158
159export function isWaterGround (typeId)
160{
161 return !!groundDefinition(typeId)?.water;
162}
163
164export function isWadeGround (typeId)
165{
166 return !!groundDefinition(typeId)?.wades;
167}
168
110export function isBlockPassable (typeId)
169export function isBlockPassable (typeId)
111{
170{
112 if (typeId == null)
171 if (typeId == null)
shared/equipment/stats.js +2 −0
@@ -44,6 +44,8 @@ export function equipMinSkillId (equipmentDef)
44 44 case EquipmentKind.fishingRod:
45 45 case EquipmentKind.fishingNet:
46 46 return SkillId.fishing;
47 case EquipmentKind.plantClippers:
48 return SkillId.herbalism;
47 49 default:
48 50 return null;
49 51 }
@@ -44,6 +44,8 @@ export function equipMinSkillId (equipmentDef)
44 case EquipmentKind.fishingRod:
44 case EquipmentKind.fishingRod:
45 case EquipmentKind.fishingNet:
45 case EquipmentKind.fishingNet:
46 return SkillId.fishing;
46 return SkillId.fishing;
47 case EquipmentKind.plantClippers:
48 return SkillId.herbalism;
47 default:
49 default:
48 return null;
50 return null;
49 }
51 }
shared/items/inventory.js +26 −8
@@ -47,6 +47,15 @@ export function singleItemFromStack (stack)
47 47 };
48 48 }
49 49
50 export function potionStackIdentity (instance)
51 {
52 if (!instance || instance.kind !== "potion")
53 { return null; }
54 const effectKey = instance.effectKey
55 ?? (instance.effect ? JSON.stringify(instance.effect) : "");
56 return `${instance.potionKey ?? ""}|${effectKey}`;
57 }
58
50 59 export function stacksMatch (left, right, definition, { inVault = false } = {})
51 60 {
52 61 if (!left || !right || left.itemId !== right.itemId)
@@ -56,6 +65,14 @@ export function stacksMatch (left, right, definition, { inVault = false } = {})
56 65 {
57 66 return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
58 67 }
68 if (definition?.potion)
69 {
70 const a = potionStackIdentity(left.instance);
71 const b = potionStackIdentity(right.instance);
72 return a != null && a === b;
73 }
74 if (left.instance != null || right.instance != null)
75 { return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null); }
59 76 return rules.stackable;
60 77 }
61 78
@@ -85,9 +102,7 @@ export function insertStack (slots, stack, definition, options = {})
85 102 {
86 103 for (const slot of next)
87 104 {
88 if (!slot || slot.itemId !== stack.itemId)
89 { continue; }
90 if (slot.instance != null || stack.instance != null)
105 if (!slot || !stacksMatch(slot, stack, definition, options))
91 106 { continue; }
92 107 const space = rules.maxStackSize - stackQuantity(slot.quantity);
93 108 if (space <= 0)
@@ -96,6 +111,8 @@ export function insertStack (slots, stack, definition, options = {})
96 111 const split = splitOrigins(pendingOrigins, add);
97 112 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
98 113 slot.quantity = stackQuantity(slot.quantity) + add;
114 if (stack.instance != null && slot.instance == null)
115 { slot.instance = cloneStack(stack.instance); }
99 116 delete slot.origin;
100 117 pendingOrigins = split.remain;
101 118 remaining -= add;
@@ -163,7 +180,7 @@ export function insertStackGrowable (slots, stack, definition)
163 180 {
164 181 for (const slot of next)
165 182 {
166 if (!slot || slot.itemId !== stack.itemId || slot.instance != null || stack.instance != null)
183 if (!slot || !stacksMatch(slot, stack, definition, { inVault: true }))
167 184 { continue; }
168 185 const space = rules.maxStackSize - stackQuantity(slot.quantity);
169 186 if (space <= 0)
@@ -172,6 +189,8 @@ export function insertStackGrowable (slots, stack, definition)
172 189 const split = splitOrigins(pendingOrigins, add);
173 190 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
174 191 slot.quantity = stackQuantity(slot.quantity) + add;
192 if (stack.instance != null && slot.instance == null)
193 { slot.instance = cloneStack(stack.instance); }
175 194 delete slot.origin;
176 195 pendingOrigins = split.remain;
177 196 remaining -= add;
@@ -196,8 +215,8 @@ export function insertStackGrowable (slots, stack, definition)
196 215 return { ok: remaining === 0, slots: next, remainder: remaining };
197 216 }
198 217
199 /** Take `quantity` of matching goods from vault slots (any slots). */
200 export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null })
218 /** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
219 export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
201 220 {
202 221 let remaining = Math.max(0, stackQuantity(quantity));
203 222 if (!remaining)
@@ -227,12 +246,11 @@ export function takeMatchingFromSlots (slots, { itemId, quantity, instance = nul
227 246 }
228 247 remaining -= amount;
229 248 }
230 const compact = next.filter((slot) => slot);
231 249 if (remaining > 0)
232 250 { return { ok: false, slots, taken: null }; }
233 251 return {
234 252 ok: true,
235 slots: compact,
253 slots: compact ? next.filter((slot) => slot) : next,
236 254 taken: attachOrigins({
237 255 itemId,
238 256 quantity: stackQuantity(quantity),
@@ -47,6 +47,15 @@ export function singleItemFromStack (stack)
47 };
47 };
48}
48}
49
49
50export function potionStackIdentity (instance)
51{
52 if (!instance || instance.kind !== "potion")
53 { return null; }
54 const effectKey = instance.effectKey
55 ?? (instance.effect ? JSON.stringify(instance.effect) : "");
56 return `${instance.potionKey ?? ""}|${effectKey}`;
57}
58
50export function stacksMatch (left, right, definition, { inVault = false } = {})
59export function stacksMatch (left, right, definition, { inVault = false } = {})
51{
60{
52 if (!left || !right || left.itemId !== right.itemId)
61 if (!left || !right || left.itemId !== right.itemId)
@@ -56,6 +65,14 @@ export function stacksMatch (left, right, definition, { inVault = false } = {})
56 {
65 {
57 return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
66 return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
58 }
67 }
68 if (definition?.potion)
69 {
70 const a = potionStackIdentity(left.instance);
71 const b = potionStackIdentity(right.instance);
72 return a != null && a === b;
73 }
74 if (left.instance != null || right.instance != null)
75 { return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null); }
59 return rules.stackable;
76 return rules.stackable;
60}
77}
61
78
@@ -85,9 +102,7 @@ export function insertStack (slots, stack, definition, options = {})
85 {
102 {
86 for (const slot of next)
103 for (const slot of next)
87 {
104 {
88 if (!slot || slot.itemId !== stack.itemId)
105 if (!slot || !stacksMatch(slot, stack, definition, options))
89 { continue; }
90 if (slot.instance != null || stack.instance != null)
91 { continue; }
106 { continue; }
92 const space = rules.maxStackSize - stackQuantity(slot.quantity);
107 const space = rules.maxStackSize - stackQuantity(slot.quantity);
93 if (space <= 0)
108 if (space <= 0)
@@ -96,6 +111,8 @@ export function insertStack (slots, stack, definition, options = {})
96 const split = splitOrigins(pendingOrigins, add);
111 const split = splitOrigins(pendingOrigins, add);
97 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
112 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
98 slot.quantity = stackQuantity(slot.quantity) + add;
113 slot.quantity = stackQuantity(slot.quantity) + add;
114 if (stack.instance != null && slot.instance == null)
115 { slot.instance = cloneStack(stack.instance); }
99 delete slot.origin;
116 delete slot.origin;
100 pendingOrigins = split.remain;
117 pendingOrigins = split.remain;
101 remaining -= add;
118 remaining -= add;
@@ -163,7 +180,7 @@ export function insertStackGrowable (slots, stack, definition)
163 {
180 {
164 for (const slot of next)
181 for (const slot of next)
165 {
182 {
166 if (!slot || slot.itemId !== stack.itemId || slot.instance != null || stack.instance != null)
183 if (!slot || !stacksMatch(slot, stack, definition, { inVault: true }))
167 { continue; }
184 { continue; }
168 const space = rules.maxStackSize - stackQuantity(slot.quantity);
185 const space = rules.maxStackSize - stackQuantity(slot.quantity);
169 if (space <= 0)
186 if (space <= 0)
@@ -172,6 +189,8 @@ export function insertStackGrowable (slots, stack, definition)
172 const split = splitOrigins(pendingOrigins, add);
189 const split = splitOrigins(pendingOrigins, add);
173 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
190 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
174 slot.quantity = stackQuantity(slot.quantity) + add;
191 slot.quantity = stackQuantity(slot.quantity) + add;
192 if (stack.instance != null && slot.instance == null)
193 { slot.instance = cloneStack(stack.instance); }
175 delete slot.origin;
194 delete slot.origin;
176 pendingOrigins = split.remain;
195 pendingOrigins = split.remain;
177 remaining -= add;
196 remaining -= add;
@@ -196,8 +215,8 @@ export function insertStackGrowable (slots, stack, definition)
196 return { ok: remaining === 0, slots: next, remainder: remaining };
215 return { ok: remaining === 0, slots: next, remainder: remaining };
197}
216}
198
217
199/** Take `quantity` of matching goods from vault slots (any slots). */
218/** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
200export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null })
219export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
201{
220{
202 let remaining = Math.max(0, stackQuantity(quantity));
221 let remaining = Math.max(0, stackQuantity(quantity));
203 if (!remaining)
222 if (!remaining)
@@ -227,12 +246,11 @@ export function takeMatchingFromSlots (slots, { itemId, quantity, instance = nul
227 }
246 }
228 remaining -= amount;
247 remaining -= amount;
229 }
248 }
230 const compact = next.filter((slot) => slot);
231 if (remaining > 0)
249 if (remaining > 0)
232 { return { ok: false, slots, taken: null }; }
250 { return { ok: false, slots, taken: null }; }
233 return {
251 return {
234 ok: true,
252 ok: true,
235 slots: compact,
253 slots: compact ? next.filter((slot) => slot) : next,
236 taken: attachOrigins({
254 taken: attachOrigins({
237 itemId,
255 itemId,
238 quantity: stackQuantity(quantity),
256 quantity: stackQuantity(quantity),
shared/lighting/tilePassable.js +4 −1
@@ -1,5 +1,5 @@
1 1 import { CHUNK_SIZE } from "../protocol/constants.js";
2 import { isBlockPassable } from "../definitions/tiles.js";
2 import { isBlockPassable, isGroundPassable, normalizeGround } from "../definitions/tiles.js";
3 3
4 4 /** Passability from a chunk snapshot map keyed by "chunkX,chunkY". */
5 5 export function makeSnapshotPassable (chunks)
@@ -14,6 +14,9 @@ export function makeSnapshotPassable (chunks)
14 14 const localX = tileX - chunkX * CHUNK_SIZE;
15 15 const localY = tileY - chunkY * CHUNK_SIZE;
16 16 const index = localY * CHUNK_SIZE + localX;
17 const ground = normalizeGround(snapshot.grounds?.[index]);
18 if (!isGroundPassable(ground.typeId))
19 { return false; }
17 20 const block = snapshot.blocks?.[index];
18 21 return isBlockPassable(block?.typeId ?? null);
19 22 };
@@ -1,5 +1,5 @@
1import { CHUNK_SIZE } from "../protocol/constants.js";
1import { CHUNK_SIZE } from "../protocol/constants.js";
2import { isBlockPassable } from "../definitions/tiles.js";
2import { isBlockPassable, isGroundPassable, normalizeGround } from "../definitions/tiles.js";
3
3
4/** Passability from a chunk snapshot map keyed by "chunkX,chunkY". */
4/** Passability from a chunk snapshot map keyed by "chunkX,chunkY". */
5export function makeSnapshotPassable (chunks)
5export function makeSnapshotPassable (chunks)
@@ -14,6 +14,9 @@ export function makeSnapshotPassable (chunks)
14 const localX = tileX - chunkX * CHUNK_SIZE;
14 const localX = tileX - chunkX * CHUNK_SIZE;
15 const localY = tileY - chunkY * CHUNK_SIZE;
15 const localY = tileY - chunkY * CHUNK_SIZE;
16 const index = localY * CHUNK_SIZE + localX;
16 const index = localY * CHUNK_SIZE + localX;
17 const ground = normalizeGround(snapshot.grounds?.[index]);
18 if (!isGroundPassable(ground.typeId))
19 { return false; }
17 const block = snapshot.blocks?.[index];
20 const block = snapshot.blocks?.[index];
18 return isBlockPassable(block?.typeId ?? null);
21 return isBlockPassable(block?.typeId ?? null);
19 };
22 };
shared/protocol/constants.js +10 −1
@@ -133,6 +133,15 @@ export const MessageType = Object.freeze({
133 133 eatItem: "EAT_ITEM",
134 134 startCraft: "START_CRAFT",
135 135 cancelCraft: "CANCEL_CRAFT",
136 craftResult: "CRAFT_RESULT"
136 craftResult: "CRAFT_RESULT",
137 openCauldron: "OPEN_CAULDRON",
138 cauldronSnapshot: "CAULDRON_SNAPSHOT",
139 cauldronSetSlot: "CAULDRON_SET_SLOT",
140 cauldronInsert: "CAULDRON_INSERT",
141 cauldronAction: "CAULDRON_ACTION",
142 cauldronBottle: "CAULDRON_BOTTLE",
143 cauldronClear: "CAULDRON_CLEAR",
144 cauldronSaveRecipe: "CAULDRON_SAVE_RECIPE",
145 cauldronClose: "CAULDRON_CLOSE"
137 146 });
138 147
@@ -133,6 +133,15 @@ export const MessageType = Object.freeze({
133 eatItem: "EAT_ITEM",
133 eatItem: "EAT_ITEM",
134 startCraft: "START_CRAFT",
134 startCraft: "START_CRAFT",
135 cancelCraft: "CANCEL_CRAFT",
135 cancelCraft: "CANCEL_CRAFT",
136 craftResult: "CRAFT_RESULT"
136 craftResult: "CRAFT_RESULT",
137 openCauldron: "OPEN_CAULDRON",
138 cauldronSnapshot: "CAULDRON_SNAPSHOT",
139 cauldronSetSlot: "CAULDRON_SET_SLOT",
140 cauldronInsert: "CAULDRON_INSERT",
141 cauldronAction: "CAULDRON_ACTION",
142 cauldronBottle: "CAULDRON_BOTTLE",
143 cauldronClear: "CAULDRON_CLEAR",
144 cauldronSaveRecipe: "CAULDRON_SAVE_RECIPE",
145 cauldronClose: "CAULDRON_CLOSE"
137});
146});
138
147