BlueGit

timfa questward

Add mining, furnace smelting, stamina, and ore exhaustion.

Players mine tinted ore boulders with pickaxes, smelt at furnaces, and drain stamina while running; nodes exhaust then respawn by tier, with simulation tests covering mine and craft flows.

timfa Tim Falken · pushed by timfa

Authored 2026-08-25 · 2 months ago

Hash
8cdfc957516490b92a03a6118b5ac85dfe8cb5e5
Parent
0ad31421
47 files changed +2901 −179
client/assets/blocks/boulder/boulder-ore.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/boulder/boulder.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/furnace/furnace.png added Binary file +0 −0

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

client/assets/items/pickaxe/pickaxe-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

client/src/editor/main.js +24 −3
@@ -3,8 +3,10 @@ import {
3 3 GROUND_DEFINITIONS,
4 4 BLOCK_DEFINITIONS,
5 5 GroundType,
6 BlockType,
6 7 normalizeGround,
7 normalizeBlock
8 normalizeBlock,
9 listPlaceableBlockPaletteEntries
8 10 } from "/shared/definitions/tiles.js";
9 11 import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
10 12 import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
@@ -55,6 +57,13 @@ function selectedToolLabel ()
55 57 const layer = tool.kind === "ground" ? "ground" : "block";
56 58 const states = statesForType(catalog, layer, def.key);
57 59 const state = resolveState(states, tool.state);
60 if (tool.kind === "block" && def.id === BlockType.boulder)
61 {
62 const entry = listPlaceableBlockPaletteEntries(catalog)
63 .find((row) => row.typeId === def.id && row.state === state);
64 if (entry)
65 { return entry.displayName; }
66 }
58 67 if (states.length > 1)
59 68 { return `${def.displayName} (${state})`; }
60 69 return def.displayName;
@@ -77,7 +86,7 @@ function selectTool (next)
77 86 tool = {
78 87 kind: next.kind,
79 88 typeId: next.typeId,
80 state: defaultStateForType(catalog, layer, def.key)
89 state: next.state ?? defaultStateForType(catalog, layer, def.key)
81 90 };
82 91 }
83 92
@@ -419,7 +428,19 @@ async function main ()
419 428
420 429 paletteModal = initPaletteModal({
421 430 catalog,
422 imageUrlFor: (name) => imageUrlByName.get(name) ?? null,
431 imageUrlFor (name)
432 {
433 const sprite = game.images[name];
434 const html = sprite?.g_image;
435 if (html && typeof html.toDataURL === "function")
436 {
437 try
438 { return html.toDataURL("image/png"); }
439 catch (_)
440 { /* fall through */ }
441 }
442 return imageUrlByName.get(name) ?? null;
443 },
423 444 onSelect (next)
424 445 {
425 446 selectTool(next);
@@ -3,8 +3,10 @@ import {
3 GROUND_DEFINITIONS,
3 GROUND_DEFINITIONS,
4 BLOCK_DEFINITIONS,
4 BLOCK_DEFINITIONS,
5 GroundType,
5 GroundType,
6 BlockType,
6 normalizeGround,
7 normalizeGround,
7 normalizeBlock
8 normalizeBlock,
9 listPlaceableBlockPaletteEntries
8} from "/shared/definitions/tiles.js";
10} from "/shared/definitions/tiles.js";
9import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
11import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
10import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
12import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
@@ -55,6 +57,13 @@ function selectedToolLabel ()
55 const layer = tool.kind === "ground" ? "ground" : "block";
57 const layer = tool.kind === "ground" ? "ground" : "block";
56 const states = statesForType(catalog, layer, def.key);
58 const states = statesForType(catalog, layer, def.key);
57 const state = resolveState(states, tool.state);
59 const state = resolveState(states, tool.state);
60 if (tool.kind === "block" && def.id === BlockType.boulder)
61 {
62 const entry = listPlaceableBlockPaletteEntries(catalog)
63 .find((row) => row.typeId === def.id && row.state === state);
64 if (entry)
65 { return entry.displayName; }
66 }
58 if (states.length > 1)
67 if (states.length > 1)
59 { return `${def.displayName} (${state})`; }
68 { return `${def.displayName} (${state})`; }
60 return def.displayName;
69 return def.displayName;
@@ -77,7 +86,7 @@ function selectTool (next)
77 tool = {
86 tool = {
78 kind: next.kind,
87 kind: next.kind,
79 typeId: next.typeId,
88 typeId: next.typeId,
80 state: defaultStateForType(catalog, layer, def.key)
89 state: next.state ?? defaultStateForType(catalog, layer, def.key)
81 };
90 };
82}
91}
83
92
@@ -419,7 +428,19 @@ async function main ()
419
428
420 paletteModal = initPaletteModal({
429 paletteModal = initPaletteModal({
421 catalog,
430 catalog,
422 imageUrlFor: (name) => imageUrlByName.get(name) ?? null,
431 imageUrlFor (name)
432 {
433 const sprite = game.images[name];
434 const html = sprite?.g_image;
435 if (html && typeof html.toDataURL === "function")
436 {
437 try
438 { return html.toDataURL("image/png"); }
439 catch (_)
440 { /* fall through */ }
441 }
442 return imageUrlByName.get(name) ?? null;
443 },
423 onSelect (next)
444 onSelect (next)
424 {
445 {
425 selectTool(next);
446 selectTool(next);
client/src/editor/paletteModal.js +9 −10
@@ -1,4 +1,4 @@
1 import { listPlaceableGrounds, listPlaceableBlocks } from "/shared/definitions/tiles.js";
1 import { listPlaceableGrounds, listPlaceableBlockPaletteEntries } from "/shared/definitions/tiles.js";
2 2 import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";
3 3 import { defaultStateForType, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4 4
@@ -71,19 +71,18 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
71 71 }
72 72 else if (activeTab === "blocks")
73 73 {
74 for (const def of listPlaceableBlocks())
74 for (const entry of listPlaceableBlockPaletteEntries(catalog))
75 75 {
76 const state = defaultStateForType(catalog, "block", def.key);
77 const name = spriteImageName("block", def.key, resolveState(
78 catalog.blocks?.[def.key]?.states ?? [],
79 state
80 ));
81 76 grid.append(tileCard({
82 label: def.displayName,
83 url: imageUrlFor?.(name),
77 label: entry.displayName,
78 url: imageUrlFor?.(entry.spriteName),
84 79 onClick ()
85 80 {
86 onSelect({ kind: "block", typeId: def.id });
81 onSelect({
82 kind: "block",
83 typeId: entry.typeId,
84 state: entry.state
85 });
87 86 show(false);
88 87 }
89 88 }));
@@ -1,4 +1,4 @@
1import { listPlaceableGrounds, listPlaceableBlocks } from "/shared/definitions/tiles.js";
1import { listPlaceableGrounds, listPlaceableBlockPaletteEntries } from "/shared/definitions/tiles.js";
2import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";
2import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";
3import { defaultStateForType, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
3import { defaultStateForType, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4
4
@@ -71,19 +71,18 @@ export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
71 }
71 }
72 else if (activeTab === "blocks")
72 else if (activeTab === "blocks")
73 {
73 {
74 for (const def of listPlaceableBlocks())
74 for (const entry of listPlaceableBlockPaletteEntries(catalog))
75 {
75 {
76 const state = defaultStateForType(catalog, "block", def.key);
77 const name = spriteImageName("block", def.key, resolveState(
78 catalog.blocks?.[def.key]?.states ?? [],
79 state
80 ));
81 grid.append(tileCard({
76 grid.append(tileCard({
82 label: def.displayName,
77 label: entry.displayName,
83 url: imageUrlFor?.(name),
78 url: imageUrlFor?.(entry.spriteName),
84 onClick ()
79 onClick ()
85 {
80 {
86 onSelect({ kind: "block", typeId: def.id });
81 onSelect({
82 kind: "block",
83 typeId: entry.typeId,
84 state: entry.state
85 });
87 show(false);
86 show(false);
88 }
87 }
89 }));
88 }));
client/src/play/chat.js +59 −16
@@ -1,4 +1,8 @@
1 import { itemAssetPathForStack } from "/shared/definitions/items.js";
2 import { applyItemIcon } from "../render/potionIcon.js";
3
1 4 const BUBBLE_MS = 8000;
5 const ITEM_BUBBLE_MS = 4000;
2 6
3 7 export function initChat ({ socket, MessageType, getSettings })
4 8 {
@@ -6,6 +10,7 @@ export function initChat ({ socket, MessageType, getSettings })
6 10 const input = document.getElementById("chat-input");
7 11 const layer = document.getElementById("chat-bubbles");
8 12 const bubbles = new Map();
13 const itemBubbles = new Map();
9 14 let open = false;
10 15
11 16 function maxChars ()
@@ -79,6 +84,20 @@ export function initChat ({ socket, MessageType, getSettings })
79 84 { openBar(); }
80 85 }, true);
81 86
87 function positionBubble (bubble, view, rect)
88 {
89 const entity = view.entities.get(bubble.entityId);
90 const anchor = entity ? view.nametagAnchor(entity) : null;
91 if (!anchor)
92 {
93 bubble.element.hidden = true;
94 return;
95 }
96 bubble.element.hidden = false;
97 bubble.element.style.left = `${rect.left + anchor.x}px`;
98 bubble.element.style.top = `${rect.top + anchor.y - 36}px`;
99 }
100
82 101 return {
83 102 isOpen: () => open,
84 103 isBlocking ()
@@ -96,6 +115,7 @@ export function initChat ({ socket, MessageType, getSettings })
96 115 close();
97 116 layer.replaceChildren();
98 117 bubbles.clear();
118 itemBubbles.clear();
99 119 },
100 120 showBubble (message)
101 121 {
@@ -104,7 +124,7 @@ export function initChat ({ socket, MessageType, getSettings })
104 124 let bubble = bubbles.get(message.entityId);
105 125 if (!bubble)
106 126 {
107 bubble = { element: document.createElement("div"), until: 0 };
127 bubble = { element: document.createElement("div"), until: 0, entityId: message.entityId };
108 128 bubble.element.className = "chat-bubble";
109 129 layer.append(bubble.element);
110 130 bubbles.set(message.entityId, bubble);
@@ -114,6 +134,35 @@ export function initChat ({ socket, MessageType, getSettings })
114 134 bubble.element.style.opacity = String(readability);
115 135 bubble.until = Date.now() + BUBBLE_MS;
116 136 },
137 showItemBubble (message)
138 {
139 if (message?.itemId == null || message?.entityId == null)
140 { return; }
141 let bubble = itemBubbles.get(message.entityId);
142 if (!bubble)
143 {
144 bubble = {
145 element: document.createElement("div"),
146 until: 0,
147 entityId: message.entityId
148 };
149 bubble.element.className = "item-bubble";
150 const img = document.createElement("img");
151 img.alt = "";
152 bubble.element.append(img);
153 layer.append(bubble.element);
154 itemBubbles.set(message.entityId, bubble);
155 }
156 const stack = {
157 itemId: message.itemId,
158 quantity: Math.max(1, message.quantity | 0 || 1)
159 };
160 const img = bubble.element.querySelector("img");
161 applyItemIcon(img, stack, itemAssetPathForStack(stack));
162 const readability = Math.min(1, Math.max(0, Number(message.readability ?? 1)));
163 bubble.element.style.opacity = String(readability);
164 bubble.until = Date.now() + ITEM_BUBBLE_MS;
165 },
117 166 syncSettings ()
118 167 {
119 168 input.maxLength = maxChars();
@@ -127,24 +176,18 @@ export function initChat ({ socket, MessageType, getSettings })
127 176 if (!canvas)
128 177 { return; }
129 178 const rect = canvas.getBoundingClientRect();
130 for (const [entityId, bubble] of [...bubbles.entries()])
179 for (const map of [bubbles, itemBubbles])
131 180 {
132 if (now >= bubble.until)
133 {
134 bubble.element.remove();
135 bubbles.delete(entityId);
136 continue;
137 }
138 const entity = view.entities.get(entityId);
139 const anchor = entity ? view.nametagAnchor(entity) : null;
140 if (!anchor)
181 for (const [entityId, bubble] of [...map.entries()])
141 182 {
142 bubble.element.hidden = true;
143 continue;
183 if (now >= bubble.until)
184 {
185 bubble.element.remove();
186 map.delete(entityId);
187 continue;
188 }
189 positionBubble(bubble, view, rect);
144 190 }
145 bubble.element.hidden = false;
146 bubble.element.style.left = `${rect.left + anchor.x}px`;
147 bubble.element.style.top = `${rect.top + anchor.y - 36}px`;
148 191 }
149 192 }
150 193 };
@@ -1,4 +1,8 @@
1import { itemAssetPathForStack } from "/shared/definitions/items.js";
2import { applyItemIcon } from "../render/potionIcon.js";
3
1const BUBBLE_MS = 8000;
4const BUBBLE_MS = 8000;
5const ITEM_BUBBLE_MS = 4000;
2
6
3export function initChat ({ socket, MessageType, getSettings })
7export function initChat ({ socket, MessageType, getSettings })
4{
8{
@@ -6,6 +10,7 @@ export function initChat ({ socket, MessageType, getSettings })
6 const input = document.getElementById("chat-input");
10 const input = document.getElementById("chat-input");
7 const layer = document.getElementById("chat-bubbles");
11 const layer = document.getElementById("chat-bubbles");
8 const bubbles = new Map();
12 const bubbles = new Map();
13 const itemBubbles = new Map();
9 let open = false;
14 let open = false;
10
15
11 function maxChars ()
16 function maxChars ()
@@ -79,6 +84,20 @@ export function initChat ({ socket, MessageType, getSettings })
79 { openBar(); }
84 { openBar(); }
80 }, true);
85 }, true);
81
86
87 function positionBubble (bubble, view, rect)
88 {
89 const entity = view.entities.get(bubble.entityId);
90 const anchor = entity ? view.nametagAnchor(entity) : null;
91 if (!anchor)
92 {
93 bubble.element.hidden = true;
94 return;
95 }
96 bubble.element.hidden = false;
97 bubble.element.style.left = `${rect.left + anchor.x}px`;
98 bubble.element.style.top = `${rect.top + anchor.y - 36}px`;
99 }
100
82 return {
101 return {
83 isOpen: () => open,
102 isOpen: () => open,
84 isBlocking ()
103 isBlocking ()
@@ -96,6 +115,7 @@ export function initChat ({ socket, MessageType, getSettings })
96 close();
115 close();
97 layer.replaceChildren();
116 layer.replaceChildren();
98 bubbles.clear();
117 bubbles.clear();
118 itemBubbles.clear();
99 },
119 },
100 showBubble (message)
120 showBubble (message)
101 {
121 {
@@ -104,7 +124,7 @@ export function initChat ({ socket, MessageType, getSettings })
104 let bubble = bubbles.get(message.entityId);
124 let bubble = bubbles.get(message.entityId);
105 if (!bubble)
125 if (!bubble)
106 {
126 {
107 bubble = { element: document.createElement("div"), until: 0 };
127 bubble = { element: document.createElement("div"), until: 0, entityId: message.entityId };
108 bubble.element.className = "chat-bubble";
128 bubble.element.className = "chat-bubble";
109 layer.append(bubble.element);
129 layer.append(bubble.element);
110 bubbles.set(message.entityId, bubble);
130 bubbles.set(message.entityId, bubble);
@@ -114,6 +134,35 @@ export function initChat ({ socket, MessageType, getSettings })
114 bubble.element.style.opacity = String(readability);
134 bubble.element.style.opacity = String(readability);
115 bubble.until = Date.now() + BUBBLE_MS;
135 bubble.until = Date.now() + BUBBLE_MS;
116 },
136 },
137 showItemBubble (message)
138 {
139 if (message?.itemId == null || message?.entityId == null)
140 { return; }
141 let bubble = itemBubbles.get(message.entityId);
142 if (!bubble)
143 {
144 bubble = {
145 element: document.createElement("div"),
146 until: 0,
147 entityId: message.entityId
148 };
149 bubble.element.className = "item-bubble";
150 const img = document.createElement("img");
151 img.alt = "";
152 bubble.element.append(img);
153 layer.append(bubble.element);
154 itemBubbles.set(message.entityId, bubble);
155 }
156 const stack = {
157 itemId: message.itemId,
158 quantity: Math.max(1, message.quantity | 0 || 1)
159 };
160 const img = bubble.element.querySelector("img");
161 applyItemIcon(img, stack, itemAssetPathForStack(stack));
162 const readability = Math.min(1, Math.max(0, Number(message.readability ?? 1)));
163 bubble.element.style.opacity = String(readability);
164 bubble.until = Date.now() + ITEM_BUBBLE_MS;
165 },
117 syncSettings ()
166 syncSettings ()
118 {
167 {
119 input.maxLength = maxChars();
168 input.maxLength = maxChars();
@@ -127,24 +176,18 @@ export function initChat ({ socket, MessageType, getSettings })
127 if (!canvas)
176 if (!canvas)
128 { return; }
177 { return; }
129 const rect = canvas.getBoundingClientRect();
178 const rect = canvas.getBoundingClientRect();
130 for (const [entityId, bubble] of [...bubbles.entries()])
179 for (const map of [bubbles, itemBubbles])
131 {
180 {
132 if (now >= bubble.until)
181 for (const [entityId, bubble] of [...map.entries()])
133 {
134 bubble.element.remove();
135 bubbles.delete(entityId);
136 continue;
137 }
138 const entity = view.entities.get(entityId);
139 const anchor = entity ? view.nametagAnchor(entity) : null;
140 if (!anchor)
141 {
182 {
142 bubble.element.hidden = true;
183 if (now >= bubble.until)
143 continue;
184 {
185 bubble.element.remove();
186 map.delete(entityId);
187 continue;
188 }
189 positionBubble(bubble, view, rect);
144 }
190 }
145 bubble.element.hidden = false;
146 bubble.element.style.left = `${rect.left + anchor.x}px`;
147 bubble.element.style.top = `${rect.top + anchor.y - 36}px`;
148 }
191 }
149 }
192 }
150 };
193 };
client/src/play/crafting.js +4 −3
@@ -12,6 +12,7 @@ import {
12 12 hasRecipeInputs,
13 13 recipesForStation
14 14 } from "/shared/crafting/recipes.js";
15 import { applyItemIcon } from "../render/potionIcon.js";
15 16
16 17 export function initCrafting ({
17 18 socket,
@@ -86,8 +87,8 @@ export function initCrafting ({
86 87 { cell.classList.add("selected"); }
87 88
88 89 const img = document.createElement("img");
89 img.src = itemAssetPathForStack(stack);
90 90 img.alt = def?.displayName ?? "Item";
91 applyItemIcon(img, stack, itemAssetPathForStack(stack));
91 92
92 93 const label = document.createElement("span");
93 94 label.className = "craft-recipe-name";
@@ -121,7 +122,7 @@ export function initCrafting ({
121 122 itemId: recipe.output.itemId,
122 123 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
123 124 };
124 outputImg.src = itemAssetPathForStack(outputStack);
125 applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
125 126 outputImg.alt = itemDisplayName(outputStack);
126 127 const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
127 128 outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
@@ -147,8 +148,8 @@ export function initCrafting ({
147 148 { row.classList.add("short"); }
148 149
149 150 const img = document.createElement("img");
150 img.src = itemAssetPathForStack(stack);
151 151 img.alt = itemDisplayName(stack);
152 applyItemIcon(img, stack, itemAssetPathForStack(stack));
152 153
153 154 const text = document.createElement("span");
154 155 text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
@@ -12,6 +12,7 @@ import {
12 hasRecipeInputs,
12 hasRecipeInputs,
13 recipesForStation
13 recipesForStation
14} from "/shared/crafting/recipes.js";
14} from "/shared/crafting/recipes.js";
15import { applyItemIcon } from "../render/potionIcon.js";
15
16
16export function initCrafting ({
17export function initCrafting ({
17 socket,
18 socket,
@@ -86,8 +87,8 @@ export function initCrafting ({
86 { cell.classList.add("selected"); }
87 { cell.classList.add("selected"); }
87
88
88 const img = document.createElement("img");
89 const img = document.createElement("img");
89 img.src = itemAssetPathForStack(stack);
90 img.alt = def?.displayName ?? "Item";
90 img.alt = def?.displayName ?? "Item";
91 applyItemIcon(img, stack, itemAssetPathForStack(stack));
91
92
92 const label = document.createElement("span");
93 const label = document.createElement("span");
93 label.className = "craft-recipe-name";
94 label.className = "craft-recipe-name";
@@ -121,7 +122,7 @@ export function initCrafting ({
121 itemId: recipe.output.itemId,
122 itemId: recipe.output.itemId,
122 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
123 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
123 };
124 };
124 outputImg.src = itemAssetPathForStack(outputStack);
125 applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
125 outputImg.alt = itemDisplayName(outputStack);
126 outputImg.alt = itemDisplayName(outputStack);
126 const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
127 const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
127 outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
128 outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
@@ -147,8 +148,8 @@ export function initCrafting ({
147 { row.classList.add("short"); }
148 { row.classList.add("short"); }
148
149
149 const img = document.createElement("img");
150 const img = document.createElement("img");
150 img.src = itemAssetPathForStack(stack);
151 img.alt = itemDisplayName(stack);
151 img.alt = itemDisplayName(stack);
152 applyItemIcon(img, stack, itemAssetPathForStack(stack));
152
153
153 const text = document.createElement("span");
154 const text = document.createElement("span");
154 text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
155 text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
client/src/play/main.js +141 −5
@@ -9,9 +9,11 @@ import { initInventory } from "./inventory.js";
9 9 import { initSkills } from "./skills.js";
10 10 import { initCrafting } from "./crafting.js";
11 11 import { initAlchemy } from "./alchemy.js";
12 import { initStamina } from "./stamina.js";
12 13 import { initContextMenu } from "./contextMenu.js";
13 14 import { initDeath } from "./death.js";
14 15 import { CraftingStationId } from "/shared/definitions/craftingStations.js";
16 import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
15 17 import { formatQuantity } from "/shared/items/formatQuantity.js";
16 18
17 19 const game = new Game();
@@ -34,10 +36,11 @@ let inventory;
34 36 let skills;
35 37 let crafting;
36 38 let alchemy;
39 let staminaUi;
37 40 let contextMenu;
38 41 let death;
39 42 let pendingPickup = null;
40 /** @type {{ kind: "bank" | "cauldron", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
43 /** @type {{ kind: "bank" | "cauldron" | "furnace" | "mine", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
41 44 let pendingInteract = null;
42 45 /** Framework can report mousePressed for two frames; latch so one physical click is one command. */
43 46 let leftClickConsumed = false;
@@ -150,6 +153,28 @@ function requestOpenCauldron (tileX, tileY)
150 153 { approachAdjacentTile(tileX, tileY); }
151 154 }
152 155
156 function requestOpenFurnace (tileX, tileY)
157 {
158 clearAllPendingActions();
159 pendingInteract = { kind: "furnace", tileX, tileY };
160 const local = view?.entities.get(view.localEntityId);
161 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
162 { flushPendingInteract(); }
163 else
164 { approachAdjacentTile(tileX, tileY); }
165 }
166
167 function requestMine (tileX, tileY)
168 {
169 clearAllPendingActions();
170 pendingInteract = { kind: "mine", tileX, tileY };
171 const local = view?.entities.get(view.localEntityId);
172 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
173 { flushPendingInteract(); }
174 else
175 { approachAdjacentTile(tileX, tileY); }
176 }
177
153 178 function requestTalk (targetEntityId)
154 179 {
155 180 clearPendingPickup();
@@ -193,6 +218,28 @@ function flushPendingInteract ()
193 218 return;
194 219 }
195 220
221 if (pendingInteract.kind === "furnace")
222 {
223 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
224 { return; }
225 socket.send({ type: MessageType.openFurnace });
226 clearPendingInteract();
227 return;
228 }
229
230 if (pendingInteract.kind === "mine")
231 {
232 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
233 { return; }
234 socket.send({
235 type: MessageType.mine,
236 tileX: pendingInteract.tileX,
237 tileY: pendingInteract.tileY
238 });
239 clearPendingInteract();
240 return;
241 }
242
196 243 if (pendingInteract.kind === "talk")
197 244 {
198 245 const target = view.entities.get(pendingInteract.targetEntityId);
@@ -300,6 +347,10 @@ function handleLeftClick (mouseX, mouseY)
300 347 { requestOpenBank(tile.tileX, tile.tileY); }
301 348 else if (isCauldronTile(view, tile.tileX, tile.tileY))
302 349 { requestOpenCauldron(tile.tileX, tile.tileY); }
350 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
351 { requestOpenFurnace(tile.tileX, tile.tileY); }
352 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
353 { requestMine(tile.tileX, tile.tileY); }
303 354 else
304 355 {
305 356 clearAllPendingActions();
@@ -392,6 +443,22 @@ function handleRightClick (event, mouseX, mouseY)
392 443 });
393 444 }
394 445
446 if (isFurnaceTile(view, tile.tileX, tile.tileY))
447 {
448 items.push({
449 label: "Smelt",
450 onSelect: () => requestOpenFurnace(tile.tileX, tile.tileY)
451 });
452 }
453
454 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
455 {
456 items.push({
457 label: "Mine",
458 onSelect: () => requestMine(tile.tileX, tile.tileY)
459 });
460 }
461
395 462 contextMenu.show(event.clientX, event.clientY, items);
396 463 }
397 464
@@ -421,6 +488,9 @@ function startPlay (payload)
421 488 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
422 489 gait = payload.gait ?? GAIT.walk;
423 490 document.getElementById("gait").textContent = gait;
491 staminaUi?.show();
492 if (payload.stamina != null)
493 { staminaUi?.apply(payload.stamina); }
424 494 if (!scene)
425 495 {
426 496 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
@@ -445,9 +515,16 @@ function startPlay (payload)
445 515 }
446 516 if (GameInput.isPressed(82) && !uiBlocked())
447 517 {
448 gait = gait === GAIT.run ? GAIT.walk : GAIT.run;
449 socket.send({ type: MessageType.setGait, gait });
450 document.getElementById("gait").textContent = gait;
518 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
519 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
520 { return; }
521 socket.send({ type: MessageType.setGait, gait: next });
522 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
523 if (next === GAIT.walk)
524 {
525 gait = next;
526 document.getElementById("gait").textContent = gait;
527 }
451 528 }
452 529 if (playing && !death?.isBlocking())
453 530 {
@@ -546,6 +623,7 @@ async function main ()
546 623 return inventory?.getInventorySlots?.() ?? [];
547 624 }
548 625 });
626 staminaUi = initStamina();
549 627 chat = initChat({
550 628 socket: { send (payload) { socket.send(payload); } },
551 629 MessageType,
@@ -578,6 +656,18 @@ async function main ()
578 656 case MessageType.chunkSnapshot:
579 657 view?.applySnapshot(message);
580 658 break;
659 case MessageType.chunkDelta:
660 for (const tile of message.tiles ?? [])
661 {
662 view?.updateAuthoredTile(
663 message.chunkX,
664 message.chunkY,
665 tile.localX,
666 tile.localY,
667 { ground: tile.ground, block: tile.block, light: tile.light }
668 );
669 }
670 break;
581 671 case MessageType.unsubscribeChunk:
582 672 view?.removeChunk(message.chunkX, message.chunkY);
583 673 break;
@@ -613,6 +703,14 @@ async function main ()
613 703 skills?.render(message.skills);
614 704 crafting?.refresh();
615 705 break;
706 case MessageType.stamina:
707 staminaUi?.apply(message);
708 if (message.gait)
709 {
710 gait = message.gait;
711 document.getElementById("gait").textContent = gait;
712 }
713 break;
616 714 case MessageType.bankSnapshot:
617 715 inventory?.handleBank(message);
618 716 break;
@@ -648,6 +746,20 @@ async function main ()
648 746 case MessageType.combatSwing:
649 747 view?.spawnCombatSwing(message);
650 748 break;
749 case MessageType.gatherSwing:
750 case MessageType.tileShove:
751 view?.spawnGatherSwing(message);
752 break;
753 case MessageType.stationOpen:
754 if (message.stationId)
755 { crafting?.openStation(message.stationId); }
756 break;
757 case MessageType.itemBubble:
758 chat?.showItemBubble(message);
759 break;
760 case MessageType.gatherComplete:
761 crafting?.refresh();
762 break;
651 763 case MessageType.combatHit:
652 764 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
653 765 view?.flashDamage(message.targetId);
@@ -661,6 +773,13 @@ async function main ()
661 773 case MessageType.playerRespawned:
662 774 death?.hide();
663 775 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
776 if (message.stamina != null || message.maxStamina != null)
777 {
778 staminaUi?.apply({
779 current: message.stamina ?? staminaUi.getCurrent?.(),
780 max: message.maxStamina ?? staminaUi.getMax?.()
781 });
782 }
664 783 break;
665 784 case MessageType.error:
666 785 showError(message.message);
@@ -696,6 +815,7 @@ function returnToMenu (reason = "")
696 815 inventory?.reset();
697 816 crafting?.reset();
698 817 alchemy?.reset();
818 staminaUi?.hide();
699 819 skills?.hide();
700 820 contextMenu?.hide();
701 821 death?.reset();
@@ -747,7 +867,23 @@ function isCauldronTile (view, tileX, tileY)
747 867 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
748 868 }
749 869
870 function isFurnaceTile (view, tileX, tileY)
871 {
872 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
873 }
874
875 function isOreBoulderTile (view, tileX, tileY)
876 {
877 const block = blockAt(view, tileX, tileY);
878 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
879 }
880
750 881 function blockTypeAt (view, tileX, tileY)
882 {
883 return blockAt(view, tileX, tileY)?.typeId ?? null;
884 }
885
886 function blockAt (view, tileX, tileY)
751 887 {
752 888 const chunkX = Math.floor(tileX / CHUNK_SIZE);
753 889 const chunkY = Math.floor(tileY / CHUNK_SIZE);
@@ -756,7 +892,7 @@ function blockTypeAt (view, tileX, tileY)
756 892 { return null; }
757 893 const localX = tileX - chunkX * CHUNK_SIZE;
758 894 const localY = tileY - chunkY * CHUNK_SIZE;
759 return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId ?? null;
895 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
760 896 }
761 897
762 898 function chebyshev (ax, ay, bx, by)
@@ -9,9 +9,11 @@ import { 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 { initAlchemy } from "./alchemy.js";
12import { initStamina } from "./stamina.js";
12import { initContextMenu } from "./contextMenu.js";
13import { initContextMenu } from "./contextMenu.js";
13import { initDeath } from "./death.js";
14import { initDeath } from "./death.js";
14import { CraftingStationId } from "/shared/definitions/craftingStations.js";
15import { CraftingStationId } from "/shared/definitions/craftingStations.js";
16import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
15import { formatQuantity } from "/shared/items/formatQuantity.js";
17import { formatQuantity } from "/shared/items/formatQuantity.js";
16
18
17const game = new Game();
19const game = new Game();
@@ -34,10 +36,11 @@ let inventory;
34let skills;
36let skills;
35let crafting;
37let crafting;
36let alchemy;
38let alchemy;
39let staminaUi;
37let contextMenu;
40let contextMenu;
38let death;
41let death;
39let pendingPickup = null;
42let pendingPickup = null;
40/** @type {{ kind: "bank" | "cauldron", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
43/** @type {{ kind: "bank" | "cauldron" | "furnace" | "mine", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
41let pendingInteract = null;
44let pendingInteract = null;
42/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
45/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
43let leftClickConsumed = false;
46let leftClickConsumed = false;
@@ -150,6 +153,28 @@ function requestOpenCauldron (tileX, tileY)
150 { approachAdjacentTile(tileX, tileY); }
153 { approachAdjacentTile(tileX, tileY); }
151}
154}
152
155
156function requestOpenFurnace (tileX, tileY)
157{
158 clearAllPendingActions();
159 pendingInteract = { kind: "furnace", tileX, tileY };
160 const local = view?.entities.get(view.localEntityId);
161 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
162 { flushPendingInteract(); }
163 else
164 { approachAdjacentTile(tileX, tileY); }
165}
166
167function requestMine (tileX, tileY)
168{
169 clearAllPendingActions();
170 pendingInteract = { kind: "mine", tileX, tileY };
171 const local = view?.entities.get(view.localEntityId);
172 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
173 { flushPendingInteract(); }
174 else
175 { approachAdjacentTile(tileX, tileY); }
176}
177
153function requestTalk (targetEntityId)
178function requestTalk (targetEntityId)
154{
179{
155 clearPendingPickup();
180 clearPendingPickup();
@@ -193,6 +218,28 @@ function flushPendingInteract ()
193 return;
218 return;
194 }
219 }
195
220
221 if (pendingInteract.kind === "furnace")
222 {
223 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
224 { return; }
225 socket.send({ type: MessageType.openFurnace });
226 clearPendingInteract();
227 return;
228 }
229
230 if (pendingInteract.kind === "mine")
231 {
232 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
233 { return; }
234 socket.send({
235 type: MessageType.mine,
236 tileX: pendingInteract.tileX,
237 tileY: pendingInteract.tileY
238 });
239 clearPendingInteract();
240 return;
241 }
242
196 if (pendingInteract.kind === "talk")
243 if (pendingInteract.kind === "talk")
197 {
244 {
198 const target = view.entities.get(pendingInteract.targetEntityId);
245 const target = view.entities.get(pendingInteract.targetEntityId);
@@ -300,6 +347,10 @@ function handleLeftClick (mouseX, mouseY)
300 { requestOpenBank(tile.tileX, tile.tileY); }
347 { requestOpenBank(tile.tileX, tile.tileY); }
301 else if (isCauldronTile(view, tile.tileX, tile.tileY))
348 else if (isCauldronTile(view, tile.tileX, tile.tileY))
302 { requestOpenCauldron(tile.tileX, tile.tileY); }
349 { requestOpenCauldron(tile.tileX, tile.tileY); }
350 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
351 { requestOpenFurnace(tile.tileX, tile.tileY); }
352 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
353 { requestMine(tile.tileX, tile.tileY); }
303 else
354 else
304 {
355 {
305 clearAllPendingActions();
356 clearAllPendingActions();
@@ -392,6 +443,22 @@ function handleRightClick (event, mouseX, mouseY)
392 });
443 });
393 }
444 }
394
445
446 if (isFurnaceTile(view, tile.tileX, tile.tileY))
447 {
448 items.push({
449 label: "Smelt",
450 onSelect: () => requestOpenFurnace(tile.tileX, tile.tileY)
451 });
452 }
453
454 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
455 {
456 items.push({
457 label: "Mine",
458 onSelect: () => requestMine(tile.tileX, tile.tileY)
459 });
460 }
461
395 contextMenu.show(event.clientX, event.clientY, items);
462 contextMenu.show(event.clientX, event.clientY, items);
396}
463}
397
464
@@ -421,6 +488,9 @@ function startPlay (payload)
421 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
488 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
422 gait = payload.gait ?? GAIT.walk;
489 gait = payload.gait ?? GAIT.walk;
423 document.getElementById("gait").textContent = gait;
490 document.getElementById("gait").textContent = gait;
491 staminaUi?.show();
492 if (payload.stamina != null)
493 { staminaUi?.apply(payload.stamina); }
424 if (!scene)
494 if (!scene)
425 {
495 {
426 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
496 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
@@ -445,9 +515,16 @@ function startPlay (payload)
445 }
515 }
446 if (GameInput.isPressed(82) && !uiBlocked())
516 if (GameInput.isPressed(82) && !uiBlocked())
447 {
517 {
448 gait = gait === GAIT.run ? GAIT.walk : GAIT.run;
518 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
449 socket.send({ type: MessageType.setGait, gait });
519 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
450 document.getElementById("gait").textContent = gait;
520 { return; }
521 socket.send({ type: MessageType.setGait, gait: next });
522 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
523 if (next === GAIT.walk)
524 {
525 gait = next;
526 document.getElementById("gait").textContent = gait;
527 }
451 }
528 }
452 if (playing && !death?.isBlocking())
529 if (playing && !death?.isBlocking())
453 {
530 {
@@ -546,6 +623,7 @@ async function main ()
546 return inventory?.getInventorySlots?.() ?? [];
623 return inventory?.getInventorySlots?.() ?? [];
547 }
624 }
548 });
625 });
626 staminaUi = initStamina();
549 chat = initChat({
627 chat = initChat({
550 socket: { send (payload) { socket.send(payload); } },
628 socket: { send (payload) { socket.send(payload); } },
551 MessageType,
629 MessageType,
@@ -578,6 +656,18 @@ async function main ()
578 case MessageType.chunkSnapshot:
656 case MessageType.chunkSnapshot:
579 view?.applySnapshot(message);
657 view?.applySnapshot(message);
580 break;
658 break;
659 case MessageType.chunkDelta:
660 for (const tile of message.tiles ?? [])
661 {
662 view?.updateAuthoredTile(
663 message.chunkX,
664 message.chunkY,
665 tile.localX,
666 tile.localY,
667 { ground: tile.ground, block: tile.block, light: tile.light }
668 );
669 }
670 break;
581 case MessageType.unsubscribeChunk:
671 case MessageType.unsubscribeChunk:
582 view?.removeChunk(message.chunkX, message.chunkY);
672 view?.removeChunk(message.chunkX, message.chunkY);
583 break;
673 break;
@@ -613,6 +703,14 @@ async function main ()
613 skills?.render(message.skills);
703 skills?.render(message.skills);
614 crafting?.refresh();
704 crafting?.refresh();
615 break;
705 break;
706 case MessageType.stamina:
707 staminaUi?.apply(message);
708 if (message.gait)
709 {
710 gait = message.gait;
711 document.getElementById("gait").textContent = gait;
712 }
713 break;
616 case MessageType.bankSnapshot:
714 case MessageType.bankSnapshot:
617 inventory?.handleBank(message);
715 inventory?.handleBank(message);
618 break;
716 break;
@@ -648,6 +746,20 @@ async function main ()
648 case MessageType.combatSwing:
746 case MessageType.combatSwing:
649 view?.spawnCombatSwing(message);
747 view?.spawnCombatSwing(message);
650 break;
748 break;
749 case MessageType.gatherSwing:
750 case MessageType.tileShove:
751 view?.spawnGatherSwing(message);
752 break;
753 case MessageType.stationOpen:
754 if (message.stationId)
755 { crafting?.openStation(message.stationId); }
756 break;
757 case MessageType.itemBubble:
758 chat?.showItemBubble(message);
759 break;
760 case MessageType.gatherComplete:
761 crafting?.refresh();
762 break;
651 case MessageType.combatHit:
763 case MessageType.combatHit:
652 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
764 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
653 view?.flashDamage(message.targetId);
765 view?.flashDamage(message.targetId);
@@ -661,6 +773,13 @@ async function main ()
661 case MessageType.playerRespawned:
773 case MessageType.playerRespawned:
662 death?.hide();
774 death?.hide();
663 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
775 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
776 if (message.stamina != null || message.maxStamina != null)
777 {
778 staminaUi?.apply({
779 current: message.stamina ?? staminaUi.getCurrent?.(),
780 max: message.maxStamina ?? staminaUi.getMax?.()
781 });
782 }
664 break;
783 break;
665 case MessageType.error:
784 case MessageType.error:
666 showError(message.message);
785 showError(message.message);
@@ -696,6 +815,7 @@ function returnToMenu (reason = "")
696 inventory?.reset();
815 inventory?.reset();
697 crafting?.reset();
816 crafting?.reset();
698 alchemy?.reset();
817 alchemy?.reset();
818 staminaUi?.hide();
699 skills?.hide();
819 skills?.hide();
700 contextMenu?.hide();
820 contextMenu?.hide();
701 death?.reset();
821 death?.reset();
@@ -747,7 +867,23 @@ function isCauldronTile (view, tileX, tileY)
747 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
867 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
748}
868}
749
869
870function isFurnaceTile (view, tileX, tileY)
871{
872 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
873}
874
875function isOreBoulderTile (view, tileX, tileY)
876{
877 const block = blockAt(view, tileX, tileY);
878 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
879}
880
750function blockTypeAt (view, tileX, tileY)
881function blockTypeAt (view, tileX, tileY)
882{
883 return blockAt(view, tileX, tileY)?.typeId ?? null;
884}
885
886function blockAt (view, tileX, tileY)
751{
887{
752 const chunkX = Math.floor(tileX / CHUNK_SIZE);
888 const chunkX = Math.floor(tileX / CHUNK_SIZE);
753 const chunkY = Math.floor(tileY / CHUNK_SIZE);
889 const chunkY = Math.floor(tileY / CHUNK_SIZE);
@@ -756,7 +892,7 @@ function blockTypeAt (view, tileX, tileY)
756 { return null; }
892 { return null; }
757 const localX = tileX - chunkX * CHUNK_SIZE;
893 const localX = tileX - chunkX * CHUNK_SIZE;
758 const localY = tileY - chunkY * CHUNK_SIZE;
894 const localY = tileY - chunkY * CHUNK_SIZE;
759 return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId ?? null;
895 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
760}
896}
761
897
762function chebyshev (ax, ay, bx, by)
898function chebyshev (ax, ay, bx, by)
client/src/play/stamina.js added +50 −0
@@ -0,0 +1,50 @@
1 export function initStamina ()
2 {
3 let bar = document.getElementById("stamina-bar");
4 if (!bar)
5 {
6 bar = document.createElement("div");
7 bar.id = "stamina-bar";
8 bar.hidden = true;
9 bar.innerHTML = '<div id="stamina-bar-fill"></div><span id="stamina-bar-label" class="stamina-bar-label"></span>';
10 document.body.append(bar);
11 }
12 const fill = document.getElementById("stamina-bar-fill");
13 const label = document.getElementById("stamina-bar-label");
14
15 let current = 1;
16 let max = 1;
17
18 function render ()
19 {
20 const ratio = max > 0 ? Math.min(1, Math.max(0, current / max)) : 0;
21 fill.style.transform = `scaleY(${ratio})`;
22 label.textContent = `${Math.ceil(current)}/${max | 0}`;
23 bar.classList.toggle("empty", current <= 0);
24 bar.classList.toggle("low", current > 0 && current / max <= 0.25);
25 }
26
27 return {
28 show ()
29 {
30 bar.hidden = false;
31 render();
32 },
33 hide ()
34 {
35 bar.hidden = true;
36 },
37 apply (message)
38 {
39 if (message?.max != null)
40 { max = Math.max(1, message.max | 0); }
41 if (message?.current != null)
42 { current = Math.max(0, Number(message.current) || 0); }
43 render();
44 },
45 getCurrent ()
46 { return current; },
47 getMax ()
48 { return max; }
49 };
50 }
@@ -0,0 +1,50 @@
1export function initStamina ()
2{
3 let bar = document.getElementById("stamina-bar");
4 if (!bar)
5 {
6 bar = document.createElement("div");
7 bar.id = "stamina-bar";
8 bar.hidden = true;
9 bar.innerHTML = '<div id="stamina-bar-fill"></div><span id="stamina-bar-label" class="stamina-bar-label"></span>';
10 document.body.append(bar);
11 }
12 const fill = document.getElementById("stamina-bar-fill");
13 const label = document.getElementById("stamina-bar-label");
14
15 let current = 1;
16 let max = 1;
17
18 function render ()
19 {
20 const ratio = max > 0 ? Math.min(1, Math.max(0, current / max)) : 0;
21 fill.style.transform = `scaleY(${ratio})`;
22 label.textContent = `${Math.ceil(current)}/${max | 0}`;
23 bar.classList.toggle("empty", current <= 0);
24 bar.classList.toggle("low", current > 0 && current / max <= 0.25);
25 }
26
27 return {
28 show ()
29 {
30 bar.hidden = false;
31 render();
32 },
33 hide ()
34 {
35 bar.hidden = true;
36 },
37 apply (message)
38 {
39 if (message?.max != null)
40 { max = Math.max(1, message.max | 0); }
41 if (message?.current != null)
42 { current = Math.max(0, Number(message.current) || 0); }
43 render();
44 },
45 getCurrent ()
46 { return current; },
47 getMax ()
48 { return max; }
49 };
50}
client/src/render/sprites.js +19 −1
@@ -1,4 +1,5 @@
1 1 import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2 import { applyMagentaTintToImageData } from "/shared/render/tint.js";
2 3
3 4 export const UTILITY_IMAGES = [
4 5 { name: "night-shade", url: shadeDataUrl("#000000") },
@@ -44,8 +45,11 @@ function loadOneImage (game, imageData)
44 45 const img = new Image();
45 46 img.onload = () =>
46 47 {
48 const source = imageData.tint
49 ? tintedHtmlImage(img, imageData.tint)
50 : img;
47 51 const finalImage = new image(
48 img,
52 source,
49 53 imageData.subImgTotal,
50 54 imageData.perRow,
51 55 imageData.loop,
@@ -63,6 +67,20 @@ function loadOneImage (game, imageData)
63 67 });
64 68 }
65 69
70 function tintedHtmlImage (sourceImg, tintRgb)
71 {
72 const canvas = document.createElement("canvas");
73 canvas.width = sourceImg.naturalWidth || sourceImg.width;
74 canvas.height = sourceImg.naturalHeight || sourceImg.height;
75 const ctx = canvas.getContext("2d");
76 ctx.imageSmoothingEnabled = false;
77 ctx.drawImage(sourceImg, 0, 0);
78 const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
79 applyMagentaTintToImageData(imageData, tintRgb);
80 ctx.putImageData(imageData, 0, 0);
81 return canvas;
82 }
83
66 84 export function applySpriteSheets (images, catalog)
67 85 {
68 86 for (const entry of catalog?.images ?? [])
@@ -1,4 +1,5 @@
1import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
1import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2import { applyMagentaTintToImageData } from "/shared/render/tint.js";
2
3
3export const UTILITY_IMAGES = [
4export const UTILITY_IMAGES = [
4 { name: "night-shade", url: shadeDataUrl("#000000") },
5 { name: "night-shade", url: shadeDataUrl("#000000") },
@@ -44,8 +45,11 @@ function loadOneImage (game, imageData)
44 const img = new Image();
45 const img = new Image();
45 img.onload = () =>
46 img.onload = () =>
46 {
47 {
48 const source = imageData.tint
49 ? tintedHtmlImage(img, imageData.tint)
50 : img;
47 const finalImage = new image(
51 const finalImage = new image(
48 img,
52 source,
49 imageData.subImgTotal,
53 imageData.subImgTotal,
50 imageData.perRow,
54 imageData.perRow,
51 imageData.loop,
55 imageData.loop,
@@ -63,6 +67,20 @@ function loadOneImage (game, imageData)
63 });
67 });
64}
68}
65
69
70function tintedHtmlImage (sourceImg, tintRgb)
71{
72 const canvas = document.createElement("canvas");
73 canvas.width = sourceImg.naturalWidth || sourceImg.width;
74 canvas.height = sourceImg.naturalHeight || sourceImg.height;
75 const ctx = canvas.getContext("2d");
76 ctx.imageSmoothingEnabled = false;
77 ctx.drawImage(sourceImg, 0, 0);
78 const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
79 applyMagentaTintToImageData(imageData, tintRgb);
80 ctx.putImageData(imageData, 0, 0);
81 return canvas;
82}
83
66export function applySpriteSheets (images, catalog)
84export function applySpriteSheets (images, catalog)
67{
85{
68 for (const entry of catalog?.images ?? [])
86 for (const entry of catalog?.images ?? [])
client/src/render/worldView.js +23 −8
@@ -613,14 +613,7 @@ export class WorldView
613 613 const target = this.entities.get(payload.targetId);
614 614 if (!attacker || !target)
615 615 { return; }
616 attacker.shove = {
617 startVisualX: attacker.visualX,
618 startVisualY: attacker.visualY,
619 targetVisualX: target.visualX,
620 targetVisualY: target.visualY,
621 started: performance.now(),
622 durationMs: SHOVE_MS
623 };
616 this.#applyShove(attacker, target.visualX, target.visualY);
624 617 const midX = (attacker.visualX + target.visualX) / 2;
625 618 const midY = (attacker.visualY + target.visualY) / 2;
626 619 const sortY = Math.max(attacker.visualY, target.visualY) + 0.02;
@@ -642,6 +635,28 @@ export class WorldView
642 635 });
643 636 }
644 637
638 /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
639 spawnGatherSwing (payload)
640 {
641 const attacker = this.entities.get(payload.attackerId);
642 if (!attacker)
643 { return; }
644 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
645 this.#applyShove(attacker, pivot.x, pivot.y);
646 }
647
648 #applyShove (entity, targetVisualX, targetVisualY)
649 {
650 entity.shove = {
651 startVisualX: entity.visualX,
652 startVisualY: entity.visualY,
653 targetVisualX,
654 targetVisualY,
655 started: performance.now(),
656 durationMs: SHOVE_MS
657 };
658 }
659
645 660 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
646 661 spawnPhysicalProjectileFx (payload)
647 662 {
@@ -613,14 +613,7 @@ export class WorldView
613 const target = this.entities.get(payload.targetId);
613 const target = this.entities.get(payload.targetId);
614 if (!attacker || !target)
614 if (!attacker || !target)
615 { return; }
615 { return; }
616 attacker.shove = {
616 this.#applyShove(attacker, target.visualX, target.visualY);
617 startVisualX: attacker.visualX,
618 startVisualY: attacker.visualY,
619 targetVisualX: target.visualX,
620 targetVisualY: target.visualY,
621 started: performance.now(),
622 durationMs: SHOVE_MS
623 };
624 const midX = (attacker.visualX + target.visualX) / 2;
617 const midX = (attacker.visualX + target.visualX) / 2;
625 const midY = (attacker.visualY + target.visualY) / 2;
618 const midY = (attacker.visualY + target.visualY) / 2;
626 const sortY = Math.max(attacker.visualY, target.visualY) + 0.02;
619 const sortY = Math.max(attacker.visualY, target.visualY) + 0.02;
@@ -642,6 +635,28 @@ export class WorldView
642 });
635 });
643 }
636 }
644
637
638 /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
639 spawnGatherSwing (payload)
640 {
641 const attacker = this.entities.get(payload.attackerId);
642 if (!attacker)
643 { return; }
644 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
645 this.#applyShove(attacker, pivot.x, pivot.y);
646 }
647
648 #applyShove (entity, targetVisualX, targetVisualY)
649 {
650 entity.shove = {
651 startVisualX: entity.visualX,
652 startVisualY: entity.visualY,
653 targetVisualX,
654 targetVisualY,
655 started: performance.now(),
656 durationMs: SHOVE_MS
657 };
658 }
659
645 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
660 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
646 spawnPhysicalProjectileFx (payload)
661 spawnPhysicalProjectileFx (payload)
647 {
662 {
client/ui/play.css +73 −0
@@ -800,6 +800,55 @@ a { color: #d4c48a; }
800 800 background: rgba(12, 14, 18, 0.92);
801 801 }
802 802
803 #stamina-bar {
804 position: fixed;
805 z-index: 4;
806 right: 1rem;
807 bottom: 1.25rem;
808 width: 14px;
809 height: 120px;
810 padding: 3px;
811 box-sizing: border-box;
812 background: rgba(12, 14, 18, 0.82);
813 border: 1px solid #3a4250;
814 display: flex;
815 flex-direction: column;
816 justify-content: flex-end;
817 align-items: stretch;
818 }
819
820 #stamina-bar[hidden] {
821 display: none !important;
822 }
823
824 #stamina-bar-fill {
825 flex: 1;
826 width: 100%;
827 transform-origin: bottom center;
828 transform: scaleY(1);
829 background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%);
830 border-radius: 1px;
831 transition: transform 80ms linear;
832 }
833
834 #stamina-bar.empty #stamina-bar-fill {
835 background: #4a3030;
836 }
837
838 #stamina-bar.low #stamina-bar-fill {
839 background: linear-gradient(180deg, #d4c48a 0%, #a08040 100%);
840 }
841
842 .stamina-bar-label {
843 position: absolute;
844 right: calc(100% + 0.4rem);
845 bottom: 0;
846 font-size: 0.75rem;
847 color: #9aa3b2;
848 white-space: nowrap;
849 pointer-events: none;
850 }
851
803 852 #damage-numbers {
804 853 position: fixed;
805 854 inset: 0;
@@ -839,3 +888,27 @@ a { color: #d4c48a; }
839 888 .chat-bubble[hidden] {
840 889 display: none !important;
841 890 }
891
892 .item-bubble {
893 position: fixed;
894 z-index: 4;
895 pointer-events: none;
896 transform: translate(-50%, -100%) scale(0.5);
897 transform-origin: bottom center;
898 background: rgba(16, 18, 24, 0.92);
899 border: 1px solid #3a4250;
900 border-radius: 8px;
901 padding: 0.35rem;
902 line-height: 0;
903 }
904
905 .item-bubble img {
906 display: block;
907 width: 32px;
908 height: 32px;
909 image-rendering: pixelated;
910 }
911
912 .item-bubble[hidden] {
913 display: none !important;
914 }
@@ -800,6 +800,55 @@ a { color: #d4c48a; }
800 background: rgba(12, 14, 18, 0.92);
800 background: rgba(12, 14, 18, 0.92);
801}
801}
802
802
803#stamina-bar {
804 position: fixed;
805 z-index: 4;
806 right: 1rem;
807 bottom: 1.25rem;
808 width: 14px;
809 height: 120px;
810 padding: 3px;
811 box-sizing: border-box;
812 background: rgba(12, 14, 18, 0.82);
813 border: 1px solid #3a4250;
814 display: flex;
815 flex-direction: column;
816 justify-content: flex-end;
817 align-items: stretch;
818}
819
820#stamina-bar[hidden] {
821 display: none !important;
822}
823
824#stamina-bar-fill {
825 flex: 1;
826 width: 100%;
827 transform-origin: bottom center;
828 transform: scaleY(1);
829 background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%);
830 border-radius: 1px;
831 transition: transform 80ms linear;
832}
833
834#stamina-bar.empty #stamina-bar-fill {
835 background: #4a3030;
836}
837
838#stamina-bar.low #stamina-bar-fill {
839 background: linear-gradient(180deg, #d4c48a 0%, #a08040 100%);
840}
841
842.stamina-bar-label {
843 position: absolute;
844 right: calc(100% + 0.4rem);
845 bottom: 0;
846 font-size: 0.75rem;
847 color: #9aa3b2;
848 white-space: nowrap;
849 pointer-events: none;
850}
851
803#damage-numbers {
852#damage-numbers {
804 position: fixed;
853 position: fixed;
805 inset: 0;
854 inset: 0;
@@ -839,3 +888,27 @@ a { color: #d4c48a; }
839.chat-bubble[hidden] {
888.chat-bubble[hidden] {
840 display: none !important;
889 display: none !important;
841}
890}
891
892.item-bubble {
893 position: fixed;
894 z-index: 4;
895 pointer-events: none;
896 transform: translate(-50%, -100%) scale(0.5);
897 transform-origin: bottom center;
898 background: rgba(16, 18, 24, 0.92);
899 border: 1px solid #3a4250;
900 border-radius: 8px;
901 padding: 0.35rem;
902 line-height: 0;
903}
904
905.item-bubble img {
906 display: block;
907 width: 32px;
908 height: 32px;
909 image-rendering: pixelated;
910}
911
912.item-bubble[hidden] {
913 display: none !important;
914}
docs/FEATURES.md +17 −47
@@ -228,65 +228,35 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
228 228 ## Equipment tiers and worn stat bonuses
229 229
230 230 **Status:** partial
231 **Spec:** Metal gear exists in six material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**. Bronze has no extra gate (min relevant skill 1). Every higher tier requires a minimum level of the item's **relevant skill** (weapons → their hit skill e.g. Sword fighting; metal armour & shields → Defence; bows → Archery; wizard cloth & staves → Magic; gathering tools → Woodcutting / Mining / Fishing). Tier min levels and per-tier stat bonuses live in `shared/definitions/materialTiers.js`. Worn items add flat bonuses to **effective** combat stats (not base skill XP): metal weapons & clubs → Strength; metal armour & shields → Defence; bows → Dexterity; wizard cloth → Magic; staves → Mind; leather armour → Dexterity (Agility); cloth armour → Defence. Item defs carry `equipment.tier`, `equipment.kind`, optional `equipment.bonus` override, and `attack.attackType`. Equip checks enforce min skill; combat rolls use `shared/equipment/stats.js`.
232
233 **Shared sprites + magenta tint:** Draw one base sprite per shape (sword, ore, bar, …). Tintable pixels use **magenta** (`R == B` and `G < R`); lightness is `R` (e.g. `(50,0,50)` dark … `(255,0,255)` bright); `G > 0` desaturates toward white. Non-magenta pixels stay as-is. World/UI apply `TIER_TINT_COLOR` (or potion `instance.color`) then darkness. See `shared/render/tint.js`.
234
235 **TODO:** full tiered item catalog (all metals, bows, shields, wizard sets, leather, tools); more shared base art; client tooltip showing reqs/bonuses.
236 **Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/equipmentKinds.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `shared/definitions/items.js`, `client/src/render/worldView.js` (tint lit shader), `client/src/render/potionIcon.js`, `server/src/items/bags.js`, `server/src/combat/service.js`, tests in `server/tests/equipment.test.js`, `server/tests/tint.test.js`
231 **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. Coal is a gather material (dark gray tint, iron-tier mine gate) with no bar of its own.
232 **Shared sprites + magenta tint:** one base sprite per shape (ore, bar, pickaxe, boulder-ore); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint.
233 **TODO:** full combat gear catalog; woodcutting wood tiers; tooltips.
234 **Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
237 235
238 236 ## Gathering, crafting, and production skills
239 237
240 **Status:** not implemented
241 **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**.
242 **Code:** `shared/definitions/skills.js` (skill IDs + panel entries), `shared/definitions/equipmentKinds.js` (`plantClippers`), `shared/definitions/alchemy.js`
238 **Status:** partial (mining + smelting live)
239 **Spec:** **Mining:** LMB/RMB on ore boulder (states `bronze-ore` … `dragon-ore`, `coal`). Requires equipped pickaxe with tool rank ≥ resource rank and Mining ≥ mine gate. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX. Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × material rank`, then restores its ore state via runtime `CHUNK_DELTA`. **Smelting:** furnace block opens craft UI; recipes 1 ore → 1 bar except **steel** = 1 iron ore + 1 coal. Smithing XP on success. Server-authoritative `START_CRAFT` / timer. Woodcutting / fishing / other stations later.
240 **Code:** `shared/definitions/gathering.js`, `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`
243 241
244 242 ## Crafting stations
245 243
246 **Status:** UI shell + item/recipe scaffolding; server crafting not implemented
247 **Spec:** Recipes run at a **station** adjacent to or under the player (exact interaction radius TBD). Station IDs and linked skills live in `shared/definitions/craftingStations.js`.
248
249 | Station | Role | Skill |
250 | --- | --- | --- |
251 | **Furnace** | Smelt gathered **ore → bars** | Smithing |
252 | **Spinning wheel** | **Wool → thread** (wool from shorn sheep — sheep/WIP) | Tailoring |
253 | **Loom** | Weave **cloth clothing** | Tailoring |
254 | **Anvil** | Smith **metal items** from bars | Smithing |
255 | **Leatherworking station** | Craft **leather** goods | Leatherworking |
256 | **Crafting bench** | General **Crafting** (e.g. arrows + tips) | Crafting |
257 | **Oven** | Cook **raw meat** | Cooking |
258 | **Fireplace (campfire)** | Same cooking as oven | Cooking |
259
260 **Cooking:** Requires Cooking ≥ recipe minimum or the attempt can **burn** the food (lost). **Oven** uses a lower burn chance than **fireplace** for the same recipe/skill gap.
244 **Status:** partial (furnace smelting live; UI shell for others)
245 **Spec:** Furnace block (placeholder sprite) + adjacency craft panel. Recipes in `stationRecipes.js`. Server craft timer = `CRAFT_DURATION_MS` (2s). Other stations still UI/dev only (`__craftDev`).
246 **TODO:** anvil smithing recipes, oven/campfire burn, spinning wheel once sheep exist.
247 **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
261 248
262 **Fireplace (portable):** Drop a **log** on the ground; **right-click the log → Start Fire** while carrying a **tinderbox** in inventory (consumes tinderbox use TBD). Creates a shared **campfire** on that tile for **10 minutes** (`FIREPLACE_DURATION_MS`). Any player may cook at it. **At most one fireplace per tile.** Fixed **oven** blocks are separate placeables (editor/content later).
263
264 **Station UI (shared across all stations):** Opening a station shows a **recipe grid** on the left — each cell is the output **item icon** with **display name** underneath. Clicking a recipe selects it; the **detail pane on the right** repeats the icon and name, lists **required materials** (icon + quantity per input), and a **Craft** button. Crafting is blocked unless the server confirms room for the product: `canCraftFitInventory()` simulates **consuming inputs first**, then inserting the output, so freed slots from spent materials count toward space (`shared/crafting/recipes.js`). While crafting, a **2 s** progress bar runs (`CRAFT_DURATION_MS`) for every recipe regardless of item. Only one craft at a time per player; closing the panel cancels in-progress craft (sends `CANCEL_CRAFT`). Cooking stations use the same shell; burn failure is an outcome after the timer, not a separate UI.
265
266 **Item scaffolding:** Reserved IDs and stub definitions for gathering/crafting content live in `shared/definitions/craftingItems.js` (`CraftingItemId`, `CRAFTING_ITEM_STUBS` merged into `ITEM_DEFINITIONS`). Replace stubs with full defs (sprites, equipment, tiers) as rules land. Recipe rows go in `shared/crafting/stationRecipes.js` (`CRAFT_RECIPES`); filter with `recipesForStation()`.
267
268 **Dev:** In the browser console, `__craftDev()` opens the crafting bench UI; pass any `CraftingStationId` string for other stations.
249 ## Stamina and running
269 250
270 **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.
271 **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)
251 **Status:** full
252 **Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking / idle with walk gait regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows a vertical stamina bar bottom-right.
253 **Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
272 254
273 255 ## Alchemy / cauldron
274 256
275 257 **Status:** partial (scaffolding)
276 **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**.
277
278 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 with **magenta** liquid pixels; liquid is recolored per potion `color` via the shared magenta tint path (inventory canvas; world ground items use the tint+darkness lit shader).
279
280 Example scaffold recipe: **Green draught** — heat → insert green herb → stir → insert apple → cool → Bottle (ratios 2 green herb : 1 apple).
281
282 **TODO:** more recipes, drink/effect application, herb nodes + Herbalism XP, more clipper tiers, polish cauldron art.
283 **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`
284
285 ## Stamina and running
286
287 **Status:** not implemented
288 **Spec:** **Stamina** skill sets max stamina (= skill level). Each stamina point equals **one second of running**. Running consumes stamina; running awards Stamina XP. Walking does not consume stamina. **TODO:** stamina component sync, run gate when empty, regen rules, Stamina XP on run ticks, client stamina bar.
289 **Code:** `shared/definitions/skills.js` (`playerMaxStamina` helper only)
258 **Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs at a **Cauldron** block. Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules.
259 **Code:** `shared/definitions/alchemy.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`
290 260
291 261 ## Inventory, items, equipment, ground drops
292 262
@@ -228,65 +228,35 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
228## Equipment tiers and worn stat bonuses
228## Equipment tiers and worn stat bonuses
229
229
230**Status:** partial
230**Status:** partial
231**Spec:** Metal gear exists in six material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**. Bronze has no extra gate (min relevant skill 1). Every higher tier requires a minimum level of the item's **relevant skill** (weapons → their hit skill e.g. Sword fighting; metal armour & shields → Defence; bows → Archery; wizard cloth & staves → Magic; gathering tools → Woodcutting / Mining / Fishing). Tier min levels and per-tier stat bonuses live in `shared/definitions/materialTiers.js`. Worn items add flat bonuses to **effective** combat stats (not base skill XP): metal weapons & clubs → Strength; metal armour & shields → Defence; bows → Dexterity; wizard cloth → Magic; staves → Mind; leather armour → Dexterity (Agility); cloth armour → Defence. Item defs carry `equipment.tier`, `equipment.kind`, optional `equipment.bonus` override, and `attack.attackType`. Equip checks enforce min skill; combat rolls use `shared/equipment/stats.js`.
231**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. Coal is a gather material (dark gray tint, iron-tier mine gate) with no bar of its own.
232
232**Shared sprites + magenta tint:** one base sprite per shape (ore, bar, pickaxe, boulder-ore); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint.
233**Shared sprites + magenta tint:** Draw one base sprite per shape (sword, ore, bar, …). Tintable pixels use **magenta** (`R == B` and `G < R`); lightness is `R` (e.g. `(50,0,50)` dark … `(255,0,255)` bright); `G > 0` desaturates toward white. Non-magenta pixels stay as-is. World/UI apply `TIER_TINT_COLOR` (or potion `instance.color`) then darkness. See `shared/render/tint.js`.
233**TODO:** full combat gear catalog; woodcutting wood tiers; tooltips.
234
234**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
235**TODO:** full tiered item catalog (all metals, bows, shields, wizard sets, leather, tools); more shared base art; client tooltip showing reqs/bonuses.
236**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/equipmentKinds.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `shared/definitions/items.js`, `client/src/render/worldView.js` (tint lit shader), `client/src/render/potionIcon.js`, `server/src/items/bags.js`, `server/src/combat/service.js`, tests in `server/tests/equipment.test.js`, `server/tests/tint.test.js`
237
235
238## Gathering, crafting, and production skills
236## Gathering, crafting, and production skills
239
237
240**Status:** not implemented
238**Status:** partial (mining + smelting live)
241**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**.
239**Spec:** **Mining:** LMB/RMB on ore boulder (states `bronze-ore` … `dragon-ore`, `coal`). Requires equipped pickaxe with tool rank ≥ resource rank and Mining ≥ mine gate. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX. Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × material rank`, then restores its ore state via runtime `CHUNK_DELTA`. **Smelting:** furnace block opens craft UI; recipes 1 ore → 1 bar except **steel** = 1 iron ore + 1 coal. Smithing XP on success. Server-authoritative `START_CRAFT` / timer. Woodcutting / fishing / other stations later.
242**Code:** `shared/definitions/skills.js` (skill IDs + panel entries), `shared/definitions/equipmentKinds.js` (`plantClippers`), `shared/definitions/alchemy.js`
240**Code:** `shared/definitions/gathering.js`, `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`
243
241
244## Crafting stations
242## Crafting stations
245
243
246**Status:** UI shell + item/recipe scaffolding; server crafting not implemented
244**Status:** partial (furnace smelting live; UI shell for others)
247**Spec:** Recipes run at a **station** adjacent to or under the player (exact interaction radius TBD). Station IDs and linked skills live in `shared/definitions/craftingStations.js`.
245**Spec:** Furnace block (placeholder sprite) + adjacency craft panel. Recipes in `stationRecipes.js`. Server craft timer = `CRAFT_DURATION_MS` (2s). Other stations still UI/dev only (`__craftDev`).
248
246**TODO:** anvil smithing recipes, oven/campfire burn, spinning wheel once sheep exist.
249| Station | Role | Skill |
247**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
250| --- | --- | --- |
251| **Furnace** | Smelt gathered **ore → bars** | Smithing |
252| **Spinning wheel** | **Wool → thread** (wool from shorn sheep — sheep/WIP) | Tailoring |
253| **Loom** | Weave **cloth clothing** | Tailoring |
254| **Anvil** | Smith **metal items** from bars | Smithing |
255| **Leatherworking station** | Craft **leather** goods | Leatherworking |
256| **Crafting bench** | General **Crafting** (e.g. arrows + tips) | Crafting |
257| **Oven** | Cook **raw meat** | Cooking |
258| **Fireplace (campfire)** | Same cooking as oven | Cooking |
259
260**Cooking:** Requires Cooking ≥ recipe minimum or the attempt can **burn** the food (lost). **Oven** uses a lower burn chance than **fireplace** for the same recipe/skill gap.
261
248
262**Fireplace (portable):** Drop a **log** on the ground; **right-click the log → Start Fire** while carrying a **tinderbox** in inventory (consumes tinderbox use TBD). Creates a shared **campfire** on that tile for **10 minutes** (`FIREPLACE_DURATION_MS`). Any player may cook at it. **At most one fireplace per tile.** Fixed **oven** blocks are separate placeables (editor/content later).
249## Stamina and running
263
264**Station UI (shared across all stations):** Opening a station shows a **recipe grid** on the left — each cell is the output **item icon** with **display name** underneath. Clicking a recipe selects it; the **detail pane on the right** repeats the icon and name, lists **required materials** (icon + quantity per input), and a **Craft** button. Crafting is blocked unless the server confirms room for the product: `canCraftFitInventory()` simulates **consuming inputs first**, then inserting the output, so freed slots from spent materials count toward space (`shared/crafting/recipes.js`). While crafting, a **2 s** progress bar runs (`CRAFT_DURATION_MS`) for every recipe regardless of item. Only one craft at a time per player; closing the panel cancels in-progress craft (sends `CANCEL_CRAFT`). Cooking stations use the same shell; burn failure is an outcome after the timer, not a separate UI.
265
266**Item scaffolding:** Reserved IDs and stub definitions for gathering/crafting content live in `shared/definitions/craftingItems.js` (`CraftingItemId`, `CRAFTING_ITEM_STUBS` merged into `ITEM_DEFINITIONS`). Replace stubs with full defs (sprites, equipment, tiers) as rules land. Recipe rows go in `shared/crafting/stationRecipes.js` (`CRAFT_RECIPES`); filter with `recipesForStation()`.
267
268**Dev:** In the browser console, `__craftDev()` opens the crafting bench UI; pass any `CraftingStationId` string for other stations.
269
250
270**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.
251**Status:** full
271**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)
252**Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking / idle with walk gait regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows a vertical stamina bar bottom-right.
253**Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
272
254
273## Alchemy / cauldron
255## Alchemy / cauldron
274
256
275**Status:** partial (scaffolding)
257**Status:** partial (scaffolding)
276**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**.
258**Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs at a **Cauldron** block. Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules.
277
259**Code:** `shared/definitions/alchemy.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`
278Slots 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 with **magenta** liquid pixels; liquid is recolored per potion `color` via the shared magenta tint path (inventory canvas; world ground items use the tint+darkness lit shader).
279
280Example scaffold recipe: **Green draught** — heat → insert green herb → stir → insert apple → cool → Bottle (ratios 2 green herb : 1 apple).
281
282**TODO:** more recipes, drink/effect application, herb nodes + Herbalism XP, more clipper tiers, polish cauldron art.
283**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`
284
285## Stamina and running
286
287**Status:** not implemented
288**Spec:** **Stamina** skill sets max stamina (= skill level). Each stamina point equals **one second of running**. Running consumes stamina; running awards Stamina XP. Walking does not consume stamina. **TODO:** stamina component sync, run gate when empty, regen rules, Stamina XP on run ticks, client stamina bar.
289**Code:** `shared/definitions/skills.js` (`playerMaxStamina` helper only)
290
260
291## Inventory, items, equipment, ground drops
261## Inventory, items, equipment, ground drops
292
262
server/src/alchemy/service.js +4 −2
@@ -20,6 +20,7 @@ import {
20 20 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
21 21 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22 22 import { randomUUID } from "node:crypto";
23 import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
23 24
24 25 /**
25 26 * Cauldron sessions live on the worker world (per character while the UI is open).
@@ -142,13 +143,14 @@ export function handleAlchemyCommand (world, sessionId, command)
142 143
143 144 function openCauldron (world, sessionId, command)
144 145 {
145 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
146 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
146 147 requireNearCauldron(world, handle);
147 148 const sessions = ensureSessions(world);
148 149 const existing = sessions.get(command.characterId) ?? emptySession();
149 150 sessions.set(command.characterId, existing);
151 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
150 152 return {
151 events: [],
153 events: shove ? [shove] : [],
152 154 private: bagView(world.ecs, handle),
153 155 cauldron: true,
154 156 cauldronState: sessionView(existing)
@@ -20,6 +20,7 @@ import {
20import { tileToChunk, tileToLocal } from "../world/coordinates.js";
20import { tileToChunk, tileToLocal } from "../world/coordinates.js";
21import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
21import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22import { randomUUID } from "node:crypto";
22import { randomUUID } from "node:crypto";
23import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
23
24
24/**
25/**
25 * Cauldron sessions live on the worker world (per character while the UI is open).
26 * Cauldron sessions live on the worker world (per character while the UI is open).
@@ -142,13 +143,14 @@ export function handleAlchemyCommand (world, sessionId, command)
142
143
143function openCauldron (world, sessionId, command)
144function openCauldron (world, sessionId, command)
144{
145{
145 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
146 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
146 requireNearCauldron(world, handle);
147 requireNearCauldron(world, handle);
147 const sessions = ensureSessions(world);
148 const sessions = ensureSessions(world);
148 const existing = sessions.get(command.characterId) ?? emptySession();
149 const existing = sessions.get(command.characterId) ?? emptySession();
149 sessions.set(command.characterId, existing);
150 sessions.set(command.characterId, existing);
151 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
150 return {
152 return {
151 events: [],
153 events: shove ? [shove] : [],
152 private: bagView(world.ecs, handle),
154 private: bagView(world.ecs, handle),
153 cauldron: true,
155 cauldron: true,
154 cauldronState: sessionView(existing)
156 cauldronState: sessionView(existing)
server/src/assets/spriteCatalog.js +39 −3
@@ -3,6 +3,11 @@ import { extname, join } from "node:path";
3 3 import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
4 4 import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
5 5 import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
6 import {
7 ORE_BEARING_MATERIALS,
8 oreBoulderState,
9 materialTintColor
10 } from "../../../shared/definitions/materialTiers.js";
6 11 import {
7 12 bloomImageName,
8 13 equipBloomImageName,
@@ -134,18 +139,46 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
134 139 for (const def of Object.values(definitions))
135 140 {
136 141 const folder = join(layerDir, def.key);
137 const { states, blooms, equips, equipBlooms } = listVisualStates(folder);
138 if (states.length === 0)
142 const { states: fileStates, blooms, equips, equipBlooms } = listVisualStates(folder);
143 if (fileStates.length === 0)
139 144 { throw new Error(`No PNG states in ${folder}`); }
140 145
141 146 const frames = Math.max(1, def.frames ?? 1);
142 147 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
143 148 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
149 let states = [...fileStates];
150 const imagesForType = [];
151
152 if (layer === "block" && def.key === "boulder")
153 {
154 states = states.filter((state) => state !== "boulder-ore");
155 if (!states.includes("boulder"))
156 { states.unshift("boulder"); }
157 for (const material of ORE_BEARING_MATERIALS)
158 {
159 const state = oreBoulderState(material);
160 if (!states.includes(state))
161 { states.push(state); }
162 const tint = materialTintColor(material);
163 imagesForType.push({
164 name: spriteImageName(layer, def.key, state),
165 url: `/assets/${urlFolder}/${def.key}/boulder-ore.png`,
166 subImgTotal: frames,
167 perRow: framesPerRow,
168 loop: animationSpeed > 0,
169 animationSpeed,
170 tint: { r: tint.r, g: tint.g, b: tint.b }
171 });
172 }
173 }
174
144 175 types[def.key] = {
145 176 key: def.key,
146 177 typeId: def.id,
147 178 states,
148 defaultState: states[0],
179 defaultState: def.key === "boulder" && states.includes("boulder")
180 ? "boulder"
181 : states[0],
149 182 blooms,
150 183 equips,
151 184 equipBlooms,
@@ -155,6 +188,8 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
155 188 };
156 189 for (const state of states)
157 190 {
191 if (imagesForType.some((entry) => entry.name === spriteImageName(layer, def.key, state)))
192 { continue; }
158 193 const sheet = {
159 194 subImgTotal: frames,
160 195 perRow: framesPerRow,
@@ -191,6 +226,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
191 226 });
192 227 }
193 228 }
229 images.push(...imagesForType);
194 230 }
195 231 return { types, images };
196 232 }
@@ -3,6 +3,11 @@ import { extname, join } from "node:path";
3import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
3import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
4import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
4import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
5import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
5import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
6import {
7 ORE_BEARING_MATERIALS,
8 oreBoulderState,
9 materialTintColor
10} from "../../../shared/definitions/materialTiers.js";
6import {
11import {
7 bloomImageName,
12 bloomImageName,
8 equipBloomImageName,
13 equipBloomImageName,
@@ -134,18 +139,46 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
134 for (const def of Object.values(definitions))
139 for (const def of Object.values(definitions))
135 {
140 {
136 const folder = join(layerDir, def.key);
141 const folder = join(layerDir, def.key);
137 const { states, blooms, equips, equipBlooms } = listVisualStates(folder);
142 const { states: fileStates, blooms, equips, equipBlooms } = listVisualStates(folder);
138 if (states.length === 0)
143 if (fileStates.length === 0)
139 { throw new Error(`No PNG states in ${folder}`); }
144 { throw new Error(`No PNG states in ${folder}`); }
140
145
141 const frames = Math.max(1, def.frames ?? 1);
146 const frames = Math.max(1, def.frames ?? 1);
142 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
147 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
143 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
148 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
149 let states = [...fileStates];
150 const imagesForType = [];
151
152 if (layer === "block" && def.key === "boulder")
153 {
154 states = states.filter((state) => state !== "boulder-ore");
155 if (!states.includes("boulder"))
156 { states.unshift("boulder"); }
157 for (const material of ORE_BEARING_MATERIALS)
158 {
159 const state = oreBoulderState(material);
160 if (!states.includes(state))
161 { states.push(state); }
162 const tint = materialTintColor(material);
163 imagesForType.push({
164 name: spriteImageName(layer, def.key, state),
165 url: `/assets/${urlFolder}/${def.key}/boulder-ore.png`,
166 subImgTotal: frames,
167 perRow: framesPerRow,
168 loop: animationSpeed > 0,
169 animationSpeed,
170 tint: { r: tint.r, g: tint.g, b: tint.b }
171 });
172 }
173 }
174
144 types[def.key] = {
175 types[def.key] = {
145 key: def.key,
176 key: def.key,
146 typeId: def.id,
177 typeId: def.id,
147 states,
178 states,
148 defaultState: states[0],
179 defaultState: def.key === "boulder" && states.includes("boulder")
180 ? "boulder"
181 : states[0],
149 blooms,
182 blooms,
150 equips,
183 equips,
151 equipBlooms,
184 equipBlooms,
@@ -155,6 +188,8 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
155 };
188 };
156 for (const state of states)
189 for (const state of states)
157 {
190 {
191 if (imagesForType.some((entry) => entry.name === spriteImageName(layer, def.key, state)))
192 { continue; }
158 const sheet = {
193 const sheet = {
159 subImgTotal: frames,
194 subImgTotal: frames,
160 perRow: framesPerRow,
195 perRow: framesPerRow,
@@ -191,6 +226,7 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
191 });
226 });
192 }
227 }
193 }
228 }
229 images.push(...imagesForType);
194 }
230 }
195 return { types, images };
231 return { types, images };
196}
232}
server/src/chat/speech.js +42 −0
@@ -49,3 +49,45 @@ export function broadcastSpeech (sessions, simulation, speakerSession, rawText)
49 49 }
50 50 }
51 51 }
52
53 /**
54 * Product icon above the crafter's head. Same proximity opacity as chat,
55 * but no text and no letter obfuscation.
56 */
57 export function broadcastItemBubble (sessions, simulation, speakerEntityId, itemId, quantity = 1)
58 {
59 const speakerPos = simulation.positionOf(speakerEntityId);
60 if (!speakerPos || itemId == null)
61 { return; }
62
63 const messageId = nextMessageId++;
64 const createdAt = Date.now();
65 for (const other of sessions.values())
66 {
67 if (!other.entityId)
68 { continue; }
69 let readability = 1;
70 if (other.entityId !== speakerEntityId)
71 {
72 const listenerPos = simulation.positionOf(other.entityId);
73 if (!listenerPos)
74 { continue; }
75 const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY);
76 readability = speechReadability(distance, CHUNK_SIZE);
77 if (readability <= 0)
78 { continue; }
79 }
80 if (other.socket.readyState === 1)
81 {
82 other.socket.send(JSON.stringify({
83 type: MessageType.itemBubble,
84 messageId,
85 entityId: speakerEntityId,
86 itemId,
87 quantity: Math.max(1, quantity | 0 || 1),
88 readability,
89 createdAt
90 }));
91 }
92 }
93 }
@@ -49,3 +49,45 @@ export function broadcastSpeech (sessions, simulation, speakerSession, rawText)
49 }
49 }
50 }
50 }
51}
51}
52
53/**
54 * Product icon above the crafter's head. Same proximity opacity as chat,
55 * but no text and no letter obfuscation.
56 */
57export function broadcastItemBubble (sessions, simulation, speakerEntityId, itemId, quantity = 1)
58{
59 const speakerPos = simulation.positionOf(speakerEntityId);
60 if (!speakerPos || itemId == null)
61 { return; }
62
63 const messageId = nextMessageId++;
64 const createdAt = Date.now();
65 for (const other of sessions.values())
66 {
67 if (!other.entityId)
68 { continue; }
69 let readability = 1;
70 if (other.entityId !== speakerEntityId)
71 {
72 const listenerPos = simulation.positionOf(other.entityId);
73 if (!listenerPos)
74 { continue; }
75 const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY);
76 readability = speechReadability(distance, CHUNK_SIZE);
77 if (readability <= 0)
78 { continue; }
79 }
80 if (other.socket.readyState === 1)
81 {
82 other.socket.send(JSON.stringify({
83 type: MessageType.itemBubble,
84 messageId,
85 entityId: speakerEntityId,
86 itemId,
87 quantity: Math.max(1, quantity | 0 || 1),
88 readability,
89 createdAt
90 }));
91 }
92 }
93}
server/src/crafting/service.js added +322 −0
@@ -0,0 +1,322 @@
1 import { Component } from "../ecs/components.js";
2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
4 import { itemDefinition } from "../../../shared/definitions/items.js";
5 import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6 import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7 import {
8 recipeDefinition,
9 canStartCraft,
10 canCraftFitInventory,
11 hasRecipeInputs
12 } from "../../../shared/crafting/recipes.js";
13 import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
14 import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
15 import { smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
16 import { bagView } from "../items/bags.js";
17 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
18 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
19 import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
20
21 function userError (message)
22 {
23 const error = new Error(message);
24 error.userFacing = true;
25 return error;
26 }
27
28 function ensureCraftSessions (world)
29 {
30 if (!world.craftSessions)
31 { world.craftSessions = new Map(); }
32 return world.craftSessions;
33 }
34
35 function nearStationBlock (world, tileX, tileY, blockType)
36 {
37 for (let dy = -1; dy <= 1; dy++)
38 {
39 for (let dx = -1; dx <= 1; dx++)
40 {
41 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
42 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
43 if (data.blocks[index]?.typeId === blockType)
44 { return true; }
45 }
46 }
47 return false;
48 }
49
50 function stationBlockType (stationId)
51 {
52 if (stationId === CraftingStationId.furnace)
53 { return BlockType.furnace; }
54 return null;
55 }
56
57 function takeInputs (slots, inputs)
58 {
59 let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
60 for (const input of inputs ?? [])
61 {
62 let remaining = Math.max(0, stackQuantity(input.quantity));
63 if (!remaining)
64 { continue; }
65 for (let i = 0; i < next.length && remaining > 0; i++)
66 {
67 if (!next[i] || next[i].itemId !== input.itemId)
68 { continue; }
69 const taken = takeFromSlot(next, i, remaining);
70 if (!taken.ok)
71 { continue; }
72 next = taken.slots;
73 remaining -= stackQuantity(taken.taken?.quantity);
74 }
75 if (remaining > 0)
76 { return { ok: false, slots }; }
77 }
78 return { ok: true, slots: next };
79 }
80
81 export function startCraft (world, sessionId, characterId, stationId, recipeId, now)
82 {
83 const entityId = world.characterEntities.get(characterId);
84 if (entityId == null)
85 { throw userError("Character is not in the world."); }
86 const handle = world.ecs.handleOf(entityId);
87 const identity = world.ecs.get(handle, Component.networkIdentity);
88 if (!identity || identity.sessionId !== sessionId)
89 { throw userError("Character is not in the world."); }
90 if (world.ecs.has(handle, Component.dead))
91 { throw userError("You are dead."); }
92
93 const stationDef = craftingStationDefinition(stationId);
94 if (!stationDef)
95 { throw userError("Unknown crafting station."); }
96 const recipe = recipeDefinition(recipeId);
97 if (!recipe)
98 { throw userError("Unknown recipe."); }
99 const stationIds = Array.isArray(recipe.stationIds)
100 ? recipe.stationIds
101 : [recipe.stationId];
102 if (!stationIds.includes(stationId))
103 { throw userError("That recipe cannot be made here."); }
104
105 const position = world.ecs.get(handle, Component.position);
106 const blockType = stationBlockType(stationId);
107 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
108 { throw userError("You need to stand next to the station."); }
109
110 const inventory = world.ecs.get(handle, Component.inventory);
111 const skills = world.ecs.get(handle, Component.skills);
112 const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
113 if (!canStartCraft(inventory?.slots ?? [], recipe, level))
114 {
115 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
116 { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
117 if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
118 { throw userError("Missing materials."); }
119 throw userError("Not enough bag space for the result.");
120 }
121
122 const sessions = ensureCraftSessions(world);
123 sessions.set(characterId, {
124 sessionId,
125 stationId,
126 recipeId,
127 finishesAt: now + CRAFT_DURATION_MS
128 });
129 const events = [];
130 if (blockType)
131 {
132 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
133 if (shove)
134 { events.push(shove); }
135 }
136 events.push({
137 type: "item-bubble",
138 entityId,
139 itemId: recipe.output.itemId,
140 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
141 });
142 return { events };
143 }
144
145 export function openStation (world, sessionId, characterId, stationId)
146 {
147 const entityId = world.characterEntities.get(characterId);
148 if (entityId == null)
149 { throw userError("Character is not in the world."); }
150 const handle = world.ecs.handleOf(entityId);
151 const identity = world.ecs.get(handle, Component.networkIdentity);
152 if (!identity || identity.sessionId !== sessionId)
153 { throw userError("Character is not in the world."); }
154 if (world.ecs.has(handle, Component.dead))
155 { throw userError("You are dead."); }
156
157 const stationDef = craftingStationDefinition(stationId);
158 if (!stationDef)
159 { throw userError("Unknown crafting station."); }
160 const blockType = stationBlockType(stationId);
161 const position = world.ecs.get(handle, Component.position);
162 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
163 { throw userError("You need to stand next to the station."); }
164
165 const events = [];
166 if (blockType)
167 {
168 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
169 if (shove)
170 { events.push(shove); }
171 }
172 events.push({
173 type: "station-open",
174 sessionId,
175 characterId,
176 stationId
177 });
178 return { events };
179 }
180
181 export function cancelCraft (world, characterId)
182 {
183 ensureCraftSessions(world).delete(characterId);
184 return { events: [] };
185 }
186
187 export function stepCrafting (world, now)
188 {
189 const sessions = ensureCraftSessions(world);
190 const events = [];
191 const privates = [];
192 for (const [characterId, session] of [...sessions.entries()])
193 {
194 if (now < session.finishesAt)
195 { continue; }
196 sessions.delete(characterId);
197 const entityId = world.characterEntities.get(characterId);
198 if (entityId == null)
199 {
200 events.push({
201 type: "craft-result",
202 sessionId: session.sessionId,
203 recipeId: session.recipeId,
204 ok: false,
205 error: "Character left the world."
206 });
207 continue;
208 }
209 const handle = world.ecs.handleOf(entityId);
210 if (world.ecs.has(handle, Component.dead))
211 {
212 events.push({
213 type: "craft-result",
214 sessionId: session.sessionId,
215 recipeId: session.recipeId,
216 ok: false,
217 error: "You are dead."
218 });
219 continue;
220 }
221
222 const recipe = recipeDefinition(session.recipeId);
223 const stationDef = craftingStationDefinition(session.stationId);
224 const inventory = world.ecs.get(handle, Component.inventory);
225 const skills = world.ecs.get(handle, Component.skills);
226 const position = world.ecs.get(handle, Component.position);
227 const blockType = stationBlockType(session.stationId);
228 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
229
230 if (!recipe || !stationDef || !inventory
231 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
232 || !canCraftFitInventory(inventory.slots, recipe)
233 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
234 {
235 events.push({
236 type: "craft-result",
237 sessionId: session.sessionId,
238 recipeId: session.recipeId,
239 ok: false,
240 error: "Could not finish crafting."
241 });
242 continue;
243 }
244
245 const taken = takeInputs(inventory.slots, recipe.inputs);
246 if (!taken.ok)
247 {
248 events.push({
249 type: "craft-result",
250 sessionId: session.sessionId,
251 recipeId: session.recipeId,
252 ok: false,
253 error: "Missing materials."
254 });
255 continue;
256 }
257 const outDef = itemDefinition(recipe.output.itemId);
258 const added = insertStack(taken.slots, {
259 itemId: recipe.output.itemId,
260 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
261 }, outDef);
262 if (!added.ok || added.remainder > 0)
263 {
264 events.push({
265 type: "craft-result",
266 sessionId: session.sessionId,
267 recipeId: session.recipeId,
268 ok: false,
269 error: "Not enough bag space for the result."
270 });
271 continue;
272 }
273 inventory.slots = added.slots;
274
275 let skillsChanged = false;
276 if (skills?.xp && recipe.xpMaterial && stationDef.skillId === SkillId.smithing)
277 {
278 if (addSkillXp(skills, SkillId.smithing, smeltingXpForMaterial(recipe.xpMaterial)))
279 { skillsChanged = true; }
280 }
281
282 privates.push({ characterId, bag: bagView(world.ecs, handle) });
283 if (skillsChanged)
284 {
285 events.push({
286 type: "skills-updated",
287 characterId,
288 skills: publicSkillsView(skills),
289 stored: storedSkillXp(skills)
290 });
291 }
292 events.push({
293 type: "craft-result",
294 sessionId: session.sessionId,
295 recipeId: session.recipeId,
296 ok: true
297 });
298 }
299 return { events, privates };
300 }
301
302 export function handleCraftCommand (world, sessionId, command, now)
303 {
304 switch (command.type)
305 {
306 case "open-station":
307 return openStation(world, sessionId, command.characterId, command.stationId);
308 case "start-craft":
309 return startCraft(
310 world,
311 sessionId,
312 command.characterId,
313 command.stationId,
314 command.recipeId,
315 now
316 );
317 case "cancel-craft":
318 return cancelCraft(world, command.characterId);
319 default:
320 return null;
321 }
322 }
@@ -0,0 +1,322 @@
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
4import { itemDefinition } from "../../../shared/definitions/items.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import {
8 recipeDefinition,
9 canStartCraft,
10 canCraftFitInventory,
11 hasRecipeInputs
12} from "../../../shared/crafting/recipes.js";
13import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
14import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
15import { smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
16import { bagView } from "../items/bags.js";
17import { tileToChunk, tileToLocal } from "../world/coordinates.js";
18import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
19import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
20
21function userError (message)
22{
23 const error = new Error(message);
24 error.userFacing = true;
25 return error;
26}
27
28function ensureCraftSessions (world)
29{
30 if (!world.craftSessions)
31 { world.craftSessions = new Map(); }
32 return world.craftSessions;
33}
34
35function nearStationBlock (world, tileX, tileY, blockType)
36{
37 for (let dy = -1; dy <= 1; dy++)
38 {
39 for (let dx = -1; dx <= 1; dx++)
40 {
41 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
42 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
43 if (data.blocks[index]?.typeId === blockType)
44 { return true; }
45 }
46 }
47 return false;
48}
49
50function stationBlockType (stationId)
51{
52 if (stationId === CraftingStationId.furnace)
53 { return BlockType.furnace; }
54 return null;
55}
56
57function takeInputs (slots, inputs)
58{
59 let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
60 for (const input of inputs ?? [])
61 {
62 let remaining = Math.max(0, stackQuantity(input.quantity));
63 if (!remaining)
64 { continue; }
65 for (let i = 0; i < next.length && remaining > 0; i++)
66 {
67 if (!next[i] || next[i].itemId !== input.itemId)
68 { continue; }
69 const taken = takeFromSlot(next, i, remaining);
70 if (!taken.ok)
71 { continue; }
72 next = taken.slots;
73 remaining -= stackQuantity(taken.taken?.quantity);
74 }
75 if (remaining > 0)
76 { return { ok: false, slots }; }
77 }
78 return { ok: true, slots: next };
79}
80
81export function startCraft (world, sessionId, characterId, stationId, recipeId, now)
82{
83 const entityId = world.characterEntities.get(characterId);
84 if (entityId == null)
85 { throw userError("Character is not in the world."); }
86 const handle = world.ecs.handleOf(entityId);
87 const identity = world.ecs.get(handle, Component.networkIdentity);
88 if (!identity || identity.sessionId !== sessionId)
89 { throw userError("Character is not in the world."); }
90 if (world.ecs.has(handle, Component.dead))
91 { throw userError("You are dead."); }
92
93 const stationDef = craftingStationDefinition(stationId);
94 if (!stationDef)
95 { throw userError("Unknown crafting station."); }
96 const recipe = recipeDefinition(recipeId);
97 if (!recipe)
98 { throw userError("Unknown recipe."); }
99 const stationIds = Array.isArray(recipe.stationIds)
100 ? recipe.stationIds
101 : [recipe.stationId];
102 if (!stationIds.includes(stationId))
103 { throw userError("That recipe cannot be made here."); }
104
105 const position = world.ecs.get(handle, Component.position);
106 const blockType = stationBlockType(stationId);
107 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
108 { throw userError("You need to stand next to the station."); }
109
110 const inventory = world.ecs.get(handle, Component.inventory);
111 const skills = world.ecs.get(handle, Component.skills);
112 const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
113 if (!canStartCraft(inventory?.slots ?? [], recipe, level))
114 {
115 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
116 { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
117 if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
118 { throw userError("Missing materials."); }
119 throw userError("Not enough bag space for the result.");
120 }
121
122 const sessions = ensureCraftSessions(world);
123 sessions.set(characterId, {
124 sessionId,
125 stationId,
126 recipeId,
127 finishesAt: now + CRAFT_DURATION_MS
128 });
129 const events = [];
130 if (blockType)
131 {
132 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
133 if (shove)
134 { events.push(shove); }
135 }
136 events.push({
137 type: "item-bubble",
138 entityId,
139 itemId: recipe.output.itemId,
140 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
141 });
142 return { events };
143}
144
145export function openStation (world, sessionId, characterId, stationId)
146{
147 const entityId = world.characterEntities.get(characterId);
148 if (entityId == null)
149 { throw userError("Character is not in the world."); }
150 const handle = world.ecs.handleOf(entityId);
151 const identity = world.ecs.get(handle, Component.networkIdentity);
152 if (!identity || identity.sessionId !== sessionId)
153 { throw userError("Character is not in the world."); }
154 if (world.ecs.has(handle, Component.dead))
155 { throw userError("You are dead."); }
156
157 const stationDef = craftingStationDefinition(stationId);
158 if (!stationDef)
159 { throw userError("Unknown crafting station."); }
160 const blockType = stationBlockType(stationId);
161 const position = world.ecs.get(handle, Component.position);
162 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
163 { throw userError("You need to stand next to the station."); }
164
165 const events = [];
166 if (blockType)
167 {
168 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
169 if (shove)
170 { events.push(shove); }
171 }
172 events.push({
173 type: "station-open",
174 sessionId,
175 characterId,
176 stationId
177 });
178 return { events };
179}
180
181export function cancelCraft (world, characterId)
182{
183 ensureCraftSessions(world).delete(characterId);
184 return { events: [] };
185}
186
187export function stepCrafting (world, now)
188{
189 const sessions = ensureCraftSessions(world);
190 const events = [];
191 const privates = [];
192 for (const [characterId, session] of [...sessions.entries()])
193 {
194 if (now < session.finishesAt)
195 { continue; }
196 sessions.delete(characterId);
197 const entityId = world.characterEntities.get(characterId);
198 if (entityId == null)
199 {
200 events.push({
201 type: "craft-result",
202 sessionId: session.sessionId,
203 recipeId: session.recipeId,
204 ok: false,
205 error: "Character left the world."
206 });
207 continue;
208 }
209 const handle = world.ecs.handleOf(entityId);
210 if (world.ecs.has(handle, Component.dead))
211 {
212 events.push({
213 type: "craft-result",
214 sessionId: session.sessionId,
215 recipeId: session.recipeId,
216 ok: false,
217 error: "You are dead."
218 });
219 continue;
220 }
221
222 const recipe = recipeDefinition(session.recipeId);
223 const stationDef = craftingStationDefinition(session.stationId);
224 const inventory = world.ecs.get(handle, Component.inventory);
225 const skills = world.ecs.get(handle, Component.skills);
226 const position = world.ecs.get(handle, Component.position);
227 const blockType = stationBlockType(session.stationId);
228 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
229
230 if (!recipe || !stationDef || !inventory
231 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
232 || !canCraftFitInventory(inventory.slots, recipe)
233 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
234 {
235 events.push({
236 type: "craft-result",
237 sessionId: session.sessionId,
238 recipeId: session.recipeId,
239 ok: false,
240 error: "Could not finish crafting."
241 });
242 continue;
243 }
244
245 const taken = takeInputs(inventory.slots, recipe.inputs);
246 if (!taken.ok)
247 {
248 events.push({
249 type: "craft-result",
250 sessionId: session.sessionId,
251 recipeId: session.recipeId,
252 ok: false,
253 error: "Missing materials."
254 });
255 continue;
256 }
257 const outDef = itemDefinition(recipe.output.itemId);
258 const added = insertStack(taken.slots, {
259 itemId: recipe.output.itemId,
260 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
261 }, outDef);
262 if (!added.ok || added.remainder > 0)
263 {
264 events.push({
265 type: "craft-result",
266 sessionId: session.sessionId,
267 recipeId: session.recipeId,
268 ok: false,
269 error: "Not enough bag space for the result."
270 });
271 continue;
272 }
273 inventory.slots = added.slots;
274
275 let skillsChanged = false;
276 if (skills?.xp && recipe.xpMaterial && stationDef.skillId === SkillId.smithing)
277 {
278 if (addSkillXp(skills, SkillId.smithing, smeltingXpForMaterial(recipe.xpMaterial)))
279 { skillsChanged = true; }
280 }
281
282 privates.push({ characterId, bag: bagView(world.ecs, handle) });
283 if (skillsChanged)
284 {
285 events.push({
286 type: "skills-updated",
287 characterId,
288 skills: publicSkillsView(skills),
289 stored: storedSkillXp(skills)
290 });
291 }
292 events.push({
293 type: "craft-result",
294 sessionId: session.sessionId,
295 recipeId: session.recipeId,
296 ok: true
297 });
298 }
299 return { events, privates };
300}
301
302export function handleCraftCommand (world, sessionId, command, now)
303{
304 switch (command.type)
305 {
306 case "open-station":
307 return openStation(world, sessionId, command.characterId, command.stationId);
308 case "start-craft":
309 return startCraft(
310 world,
311 sessionId,
312 command.characterId,
313 command.stationId,
314 command.recipeId,
315 now
316 );
317 case "cancel-craft":
318 return cancelCraft(world, command.characterId);
319 default:
320 return null;
321 }
322}
server/src/ecs/components.js +2 −1
@@ -18,5 +18,6 @@ export const Component = Object.freeze({
18 18 skills: "skills",
19 19 follow: "follow",
20 20 dead: "dead",
21 stamina: "stamina"
21 stamina: "stamina",
22 gather: "gather"
22 23 });
@@ -18,5 +18,6 @@ export const Component = Object.freeze({
18 skills: "skills",
18 skills: "skills",
19 follow: "follow",
19 follow: "follow",
20 dead: "dead",
20 dead: "dead",
21 stamina: "stamina"
21 stamina: "stamina",
22 gather: "gather"
22});
23});
server/src/gateway/websocket.js +161 −2
@@ -2,7 +2,8 @@ import { WebSocketServer } from "ws";
2 2 import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3 3 import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4 4 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5 import { broadcastSpeech } from "../chat/speech.js";
5 import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
6 import { CraftingStationId } from "../../../shared/definitions/craftingStations.js";
6 7 import { publicSkillsView } from "../../../shared/skills/state.js";
7 8
8 9 let nextSessionId = 1;
@@ -199,6 +200,46 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
199 200 characterId: session.characterId
200 201 });
201 202 break;
203 case MessageType.openFurnace:
204 requirePlaying(session);
205 simulation.enqueue(session.id, {
206 type: "open-station",
207 characterId: session.characterId,
208 stationId: CraftingStationId.furnace
209 });
210 break;
211 case MessageType.mine:
212 requirePlaying(session);
213 simulation.enqueue(session.id, {
214 type: "mine",
215 characterId: session.characterId,
216 tileX: message.tileX | 0,
217 tileY: message.tileY | 0
218 });
219 break;
220 case MessageType.cancelGather:
221 requirePlaying(session);
222 simulation.enqueue(session.id, {
223 type: "cancel-gather",
224 characterId: session.characterId
225 });
226 break;
227 case MessageType.startCraft:
228 requirePlaying(session);
229 simulation.enqueue(session.id, {
230 type: "start-craft",
231 characterId: session.characterId,
232 stationId: message.stationId,
233 recipeId: message.recipeId
234 });
235 break;
236 case MessageType.cancelCraft:
237 requirePlaying(session);
238 simulation.enqueue(session.id, {
239 type: "cancel-craft",
240 characterId: session.characterId
241 });
242 break;
202 243 case MessageType.cauldronSetSlot:
203 244 requirePlaying(session);
204 245 simulation.enqueue(session.id, {
@@ -503,6 +544,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
503 544 const skills = simulation.skillsOf(session.entityId);
504 545 if (skills)
505 546 { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
547 const stamina = simulation.staminaOf(session.entityId);
548 if (stamina)
549 {
550 send(session, {
551 type: MessageType.stamina,
552 current: stamina.current,
553 max: stamina.max,
554 gait: stamina.gait
555 });
556 }
506 557 if (character.is_dead)
507 558 {
508 559 send(session, {
@@ -672,6 +723,19 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
672 723 send(session, { type: MessageType.skills, skills: event.skills ?? [] });
673 724 continue;
674 725 }
726 if (event.type === "stamina")
727 {
728 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
729 if (!session)
730 { continue; }
731 send(session, {
732 type: MessageType.stamina,
733 current: event.current,
734 max: event.max,
735 gait: event.gait
736 });
737 continue;
738 }
675 739 if (event.type === "pigeon-delivered")
676 740 {
677 741 for (const session of sessions.values())
@@ -721,7 +785,72 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
721 785 }
722 786 continue;
723 787 }
724 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")
788 if (event.type === "craft-result")
789 {
790 const session = sessions.get(event.sessionId);
791 if (session)
792 {
793 send(session, {
794 type: MessageType.craftResult,
795 recipeId: event.recipeId,
796 ok: !!event.ok,
797 error: event.error ?? null,
798 burned: !!event.burned
799 });
800 }
801 continue;
802 }
803 if (event.type === "station-open")
804 {
805 const session = sessions.get(event.sessionId);
806 if (session)
807 {
808 send(session, {
809 type: MessageType.stationOpen,
810 stationId: event.stationId
811 });
812 }
813 continue;
814 }
815 if (event.type === "item-bubble")
816 {
817 broadcastItemBubble(
818 sessions,
819 simulation,
820 event.entityId,
821 event.itemId,
822 event.quantity
823 );
824 continue;
825 }
826 if (event.type === "gather-swing" || event.type === "tile-shove")
827 {
828 publishEntity({
829 ...event,
830 type: event.type
831 });
832 continue;
833 }
834 if (event.type === "chunk-delta")
835 {
836 publishEntity(event);
837 continue;
838 }
839 if (event.type === "gather-complete")
840 {
841 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
842 if (session)
843 {
844 send(session, {
845 type: MessageType.gatherComplete,
846 kind: event.kind,
847 materialId: event.materialId,
848 itemId: event.itemId
849 });
850 }
851 continue;
852 }
853 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta")
725 854 { publishEntity(event); }
726 855 }
727 856 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -812,6 +941,36 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
812 941 });
813 942 continue;
814 943 }
944 if (event.type === "gather-swing" || event.type === "tile-shove")
945 {
946 if (!seesTo && !seesFrom)
947 { continue; }
948 send(session, {
949 type: MessageType.tileShove,
950 attackerId: event.attackerId,
951 tileX: event.tileX,
952 tileY: event.tileY,
953 fromTileX: event.fromTileX,
954 fromTileY: event.fromTileY
955 });
956 continue;
957 }
958 if (event.type === "chunk-delta")
959 {
960 if (!seesTo)
961 { continue; }
962 send(session, {
963 type: MessageType.chunkDelta,
964 chunkX: event.chunkX,
965 chunkY: event.chunkY,
966 tiles: [{
967 localX: event.localX,
968 localY: event.localY,
969 block: event.block
970 }]
971 });
972 continue;
973 }
815 974 if (event.type !== "entity-move")
816 975 { continue; }
817 976 if (seesTo)
@@ -2,7 +2,8 @@ import { WebSocketServer } from "ws";
2import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
2import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
4import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5import { broadcastSpeech } from "../chat/speech.js";
5import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
6import { CraftingStationId } from "../../../shared/definitions/craftingStations.js";
6import { publicSkillsView } from "../../../shared/skills/state.js";
7import { publicSkillsView } from "../../../shared/skills/state.js";
7
8
8let nextSessionId = 1;
9let nextSessionId = 1;
@@ -199,6 +200,46 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
199 characterId: session.characterId
200 characterId: session.characterId
200 });
201 });
201 break;
202 break;
203 case MessageType.openFurnace:
204 requirePlaying(session);
205 simulation.enqueue(session.id, {
206 type: "open-station",
207 characterId: session.characterId,
208 stationId: CraftingStationId.furnace
209 });
210 break;
211 case MessageType.mine:
212 requirePlaying(session);
213 simulation.enqueue(session.id, {
214 type: "mine",
215 characterId: session.characterId,
216 tileX: message.tileX | 0,
217 tileY: message.tileY | 0
218 });
219 break;
220 case MessageType.cancelGather:
221 requirePlaying(session);
222 simulation.enqueue(session.id, {
223 type: "cancel-gather",
224 characterId: session.characterId
225 });
226 break;
227 case MessageType.startCraft:
228 requirePlaying(session);
229 simulation.enqueue(session.id, {
230 type: "start-craft",
231 characterId: session.characterId,
232 stationId: message.stationId,
233 recipeId: message.recipeId
234 });
235 break;
236 case MessageType.cancelCraft:
237 requirePlaying(session);
238 simulation.enqueue(session.id, {
239 type: "cancel-craft",
240 characterId: session.characterId
241 });
242 break;
202 case MessageType.cauldronSetSlot:
243 case MessageType.cauldronSetSlot:
203 requirePlaying(session);
244 requirePlaying(session);
204 simulation.enqueue(session.id, {
245 simulation.enqueue(session.id, {
@@ -503,6 +544,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
503 const skills = simulation.skillsOf(session.entityId);
544 const skills = simulation.skillsOf(session.entityId);
504 if (skills)
545 if (skills)
505 { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
546 { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
547 const stamina = simulation.staminaOf(session.entityId);
548 if (stamina)
549 {
550 send(session, {
551 type: MessageType.stamina,
552 current: stamina.current,
553 max: stamina.max,
554 gait: stamina.gait
555 });
556 }
506 if (character.is_dead)
557 if (character.is_dead)
507 {
558 {
508 send(session, {
559 send(session, {
@@ -672,6 +723,19 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
672 send(session, { type: MessageType.skills, skills: event.skills ?? [] });
723 send(session, { type: MessageType.skills, skills: event.skills ?? [] });
673 continue;
724 continue;
674 }
725 }
726 if (event.type === "stamina")
727 {
728 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
729 if (!session)
730 { continue; }
731 send(session, {
732 type: MessageType.stamina,
733 current: event.current,
734 max: event.max,
735 gait: event.gait
736 });
737 continue;
738 }
675 if (event.type === "pigeon-delivered")
739 if (event.type === "pigeon-delivered")
676 {
740 {
677 for (const session of sessions.values())
741 for (const session of sessions.values())
@@ -721,7 +785,72 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
721 }
785 }
722 continue;
786 continue;
723 }
787 }
724 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")
788 if (event.type === "craft-result")
789 {
790 const session = sessions.get(event.sessionId);
791 if (session)
792 {
793 send(session, {
794 type: MessageType.craftResult,
795 recipeId: event.recipeId,
796 ok: !!event.ok,
797 error: event.error ?? null,
798 burned: !!event.burned
799 });
800 }
801 continue;
802 }
803 if (event.type === "station-open")
804 {
805 const session = sessions.get(event.sessionId);
806 if (session)
807 {
808 send(session, {
809 type: MessageType.stationOpen,
810 stationId: event.stationId
811 });
812 }
813 continue;
814 }
815 if (event.type === "item-bubble")
816 {
817 broadcastItemBubble(
818 sessions,
819 simulation,
820 event.entityId,
821 event.itemId,
822 event.quantity
823 );
824 continue;
825 }
826 if (event.type === "gather-swing" || event.type === "tile-shove")
827 {
828 publishEntity({
829 ...event,
830 type: event.type
831 });
832 continue;
833 }
834 if (event.type === "chunk-delta")
835 {
836 publishEntity(event);
837 continue;
838 }
839 if (event.type === "gather-complete")
840 {
841 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
842 if (session)
843 {
844 send(session, {
845 type: MessageType.gatherComplete,
846 kind: event.kind,
847 materialId: event.materialId,
848 itemId: event.itemId
849 });
850 }
851 continue;
852 }
853 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta")
725 { publishEntity(event); }
854 { publishEntity(event); }
726 }
855 }
727 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
856 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -812,6 +941,36 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
812 });
941 });
813 continue;
942 continue;
814 }
943 }
944 if (event.type === "gather-swing" || event.type === "tile-shove")
945 {
946 if (!seesTo && !seesFrom)
947 { continue; }
948 send(session, {
949 type: MessageType.tileShove,
950 attackerId: event.attackerId,
951 tileX: event.tileX,
952 tileY: event.tileY,
953 fromTileX: event.fromTileX,
954 fromTileY: event.fromTileY
955 });
956 continue;
957 }
958 if (event.type === "chunk-delta")
959 {
960 if (!seesTo)
961 { continue; }
962 send(session, {
963 type: MessageType.chunkDelta,
964 chunkX: event.chunkX,
965 chunkY: event.chunkY,
966 tiles: [{
967 localX: event.localX,
968 localY: event.localY,
969 block: event.block
970 }]
971 });
972 continue;
973 }
815 if (event.type !== "entity-move")
974 if (event.type !== "entity-move")
816 { continue; }
975 { continue; }
817 if (seesTo)
976 if (seesTo)
server/src/gathering/service.js added +325 −0
@@ -0,0 +1,325 @@
1 import { Component } from "../ecs/components.js";
2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 import { itemDefinition } from "../../../shared/definitions/items.js";
4 import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
5 import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6 import {
7 materialFromOreBoulderState,
8 canMineMaterial,
9 oreItemIdForMaterial,
10 miningDurationMs,
11 miningXpForMaterial,
12 oreExhaustDurationMs,
13 oreBoulderState,
14 EXHAUSTED_ORE_BOULDER_STATE
15 } from "../../../shared/definitions/gathering.js";
16 import { insertStack } from "../../../shared/items/inventory.js";
17 import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
18 import { bagView } from "../items/bags.js";
19 import { chebyshev, clearEngage } from "../combat/service.js";
20 import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
21 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22
23 const GATHER_SWING_INTERVAL_MS = 900;
24
25 function userError (message)
26 {
27 const error = new Error(message);
28 error.userFacing = true;
29 return error;
30 }
31
32 function ensureOreRespawns (world)
33 {
34 if (!world.oreRespawns)
35 { world.oreRespawns = new Map(); }
36 return world.oreRespawns;
37 }
38
39 function blockAt (world, tileX, tileY)
40 {
41 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
42 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
43 }
44
45 function setBoulderState (world, tileX, tileY, state)
46 {
47 const chunkX = tileToChunk(tileX);
48 const chunkY = tileToChunk(tileY);
49 const localX = tileToLocal(tileX);
50 const localY = tileToLocal(tileY);
51 const data = world.chunkData(chunkX, chunkY);
52 const index = localY * CHUNK_SIZE + localX;
53 const prev = data?.blocks?.[index];
54 if (!prev || prev.typeId !== BlockType.boulder)
55 { return null; }
56 const block = { typeId: prev.typeId, state, config: prev.config ?? null };
57 data.blocks[index] = block;
58 return {
59 type: "chunk-delta",
60 chunkX,
61 chunkY,
62 tileX,
63 tileY,
64 localX,
65 localY,
66 block
67 };
68 }
69
70 function equippedPickaxe (ecs, handle)
71 {
72 const equipment = ecs.get(handle, Component.equipment);
73 const stack = equipment?.slots?.weapon;
74 if (!stack?.itemId)
75 { return null; }
76 const def = itemDefinition(stack.itemId);
77 if (def?.equipment?.kind !== EquipmentKind.pickaxeTool)
78 { return null; }
79 return { stack, def, tier: def.equipment.tier };
80 }
81
82 function clearGather (ecs, handle)
83 {
84 if (ecs.has(handle, Component.gather))
85 { ecs.remove(handle, Component.gather); }
86 }
87
88 export function cancelGather (ecs, handle)
89 {
90 clearGather(ecs, handle);
91 }
92
93 /** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
94 export function clearOreRespawnsForChunk (world, chunkX, chunkY)
95 {
96 const respawns = world.oreRespawns;
97 if (!respawns?.size)
98 { return; }
99 for (const key of [...respawns.keys()])
100 {
101 const [tileX, tileY] = key.split(",").map(Number);
102 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
103 { respawns.delete(key); }
104 }
105 }
106
107 /**
108 * Restore exhausted ore boulders whose timers have elapsed.
109 */
110 export function stepOreRespawns (world, now)
111 {
112 const respawns = world.oreRespawns;
113 if (!respawns?.size)
114 { return { events: [] }; }
115 const events = [];
116 for (const [key, entry] of [...respawns.entries()])
117 {
118 if (now < entry.respawnsAt)
119 { continue; }
120 respawns.delete(key);
121 const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId));
122 if (delta)
123 { events.push(delta); }
124 }
125 return { events };
126 }
127
128 /**
129 * Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.
130 */
131 export function startMine (world, sessionId, characterId, tileX, tileY, now)
132 {
133 const entityId = world.characterEntities.get(characterId);
134 if (entityId == null)
135 { throw userError("Character is not in the world."); }
136 const handle = world.ecs.handleOf(entityId);
137 const identity = world.ecs.get(handle, Component.networkIdentity);
138 if (!identity || identity.sessionId !== sessionId)
139 { throw userError("Character is not in the world."); }
140 if (world.ecs.has(handle, Component.dead))
141 { throw userError("You are dead."); }
142
143 const position = world.ecs.get(handle, Component.position);
144 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
145 { throw userError("You need to stand next to the rock."); }
146
147 const block = blockAt(world, tileX, tileY);
148 if (!block || block.typeId !== BlockType.boulder)
149 { throw userError("There is nothing to mine there."); }
150 const materialId = materialFromOreBoulderState(block.state);
151 if (!materialId)
152 { throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE
153 ? "That rock is exhausted."
154 : "That rock has no ore."); }
155
156 const pickaxe = equippedPickaxe(world.ecs, handle);
157 if (!pickaxe)
158 { throw userError("Equip a pickaxe to mine."); }
159
160 const skills = world.ecs.get(handle, Component.skills);
161 const miningLevel = skillLevel(skills, SkillId.mining);
162 const gate = canMineMaterial(miningLevel, pickaxe.tier, materialId);
163 if (!gate.ok)
164 { throw userError(gate.reason); }
165
166 const durationMs = miningDurationMs(materialId, pickaxe.tier);
167 clearEngage(world.ecs, entityId);
168 const path = world.ecs.get(handle, Component.path);
169 if (path)
170 { path.tiles = []; }
171 world.ecs.add(handle, Component.gather, {
172 kind: "mining",
173 tileX,
174 tileY,
175 materialId,
176 startedAt: now,
177 finishesAt: now + durationMs,
178 nextSwingAt: now
179 });
180
181 return {
182 events: [{
183 type: "gather-swing",
184 attackerId: entityId,
185 tileX,
186 tileY,
187 fromTileX: position.tileX,
188 fromTileY: position.tileY,
189 swipe: false
190 }]
191 };
192 }
193
194 export function stepGather (world, now)
195 {
196 const events = [];
197 const privates = [];
198 const respawnEvents = stepOreRespawns(world, now);
199 events.push(...respawnEvents.events);
200
201 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
202 {
203 const { handle, gather, position, character, entityId } = entity;
204 if (world.ecs.has(handle, Component.dead))
205 {
206 clearGather(world.ecs, handle);
207 continue;
208 }
209 if (chebyshev(position.tileX, position.tileY, gather.tileX, gather.tileY) > 1)
210 {
211 clearGather(world.ecs, handle);
212 continue;
213 }
214 const block = blockAt(world, gather.tileX, gather.tileY);
215 if (!block || block.typeId !== BlockType.boulder
216 || materialFromOreBoulderState(block.state) !== gather.materialId)
217 {
218 clearGather(world.ecs, handle);
219 continue;
220 }
221
222 if (now >= gather.nextSwingAt && now < gather.finishesAt)
223 {
224 gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
225 events.push({
226 type: "gather-swing",
227 attackerId: entityId,
228 tileX: gather.tileX,
229 tileY: gather.tileY,
230 fromTileX: position.tileX,
231 fromTileY: position.tileY,
232 swipe: false
233 });
234 }
235
236 if (now < gather.finishesAt)
237 { continue; }
238
239 const oreItemId = oreItemIdForMaterial(gather.materialId);
240 const def = itemDefinition(oreItemId);
241 const inventory = world.ecs.get(handle, Component.inventory);
242 if (!oreItemId || !def || !inventory)
243 {
244 clearGather(world.ecs, handle);
245 continue;
246 }
247 const inserted = insertStack(inventory.slots, { itemId: oreItemId, quantity: 1 }, def);
248 if (!inserted.ok || inserted.remainder > 0)
249 {
250 clearGather(world.ecs, handle);
251 events.push({
252 type: "command-error",
253 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
254 message: "Your inventory is full."
255 });
256 continue;
257 }
258 inventory.slots = inserted.slots;
259
260 const skills = world.ecs.get(handle, Component.skills);
261 let skillsChanged = false;
262 if (skills?.xp && addSkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)))
263 { skillsChanged = true; }
264
265 const exhausted = setBoulderState(
266 world,
267 gather.tileX,
268 gather.tileY,
269 EXHAUSTED_ORE_BOULDER_STATE
270 );
271 if (exhausted)
272 {
273 events.push(exhausted);
274 ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
275 tileX: gather.tileX,
276 tileY: gather.tileY,
277 materialId: gather.materialId,
278 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
279 });
280 }
281
282 clearGather(world.ecs, handle);
283 privates.push({
284 characterId: character.characterId,
285 bag: bagView(world.ecs, handle)
286 });
287 if (skillsChanged)
288 {
289 events.push({
290 type: "skills-updated",
291 characterId: character.characterId,
292 skills: publicSkillsView(skills),
293 stored: storedSkillXp(skills)
294 });
295 }
296 events.push({
297 type: "gather-complete",
298 characterId: character.characterId,
299 kind: "mining",
300 materialId: gather.materialId,
301 itemId: oreItemId
302 });
303 }
304 return { events, privates };
305 }
306
307 export function handleGatherCommand (world, sessionId, command, now)
308 {
309 switch (command.type)
310 {
311 case "mine":
312 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
313 case "cancel-gather":
314 {
315 const entityId = world.characterEntities.get(command.characterId);
316 if (entityId == null)
317 { return { events: [] }; }
318 const handle = world.ecs.handleOf(entityId);
319 clearGather(world.ecs, handle);
320 return { events: [] };
321 }
322 default:
323 return null;
324 }
325 }
@@ -0,0 +1,325 @@
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { itemDefinition } from "../../../shared/definitions/items.js";
4import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6import {
7 materialFromOreBoulderState,
8 canMineMaterial,
9 oreItemIdForMaterial,
10 miningDurationMs,
11 miningXpForMaterial,
12 oreExhaustDurationMs,
13 oreBoulderState,
14 EXHAUSTED_ORE_BOULDER_STATE
15} from "../../../shared/definitions/gathering.js";
16import { insertStack } from "../../../shared/items/inventory.js";
17import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
18import { bagView } from "../items/bags.js";
19import { chebyshev, clearEngage } from "../combat/service.js";
20import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
21import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22
23const GATHER_SWING_INTERVAL_MS = 900;
24
25function userError (message)
26{
27 const error = new Error(message);
28 error.userFacing = true;
29 return error;
30}
31
32function ensureOreRespawns (world)
33{
34 if (!world.oreRespawns)
35 { world.oreRespawns = new Map(); }
36 return world.oreRespawns;
37}
38
39function blockAt (world, tileX, tileY)
40{
41 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
42 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
43}
44
45function setBoulderState (world, tileX, tileY, state)
46{
47 const chunkX = tileToChunk(tileX);
48 const chunkY = tileToChunk(tileY);
49 const localX = tileToLocal(tileX);
50 const localY = tileToLocal(tileY);
51 const data = world.chunkData(chunkX, chunkY);
52 const index = localY * CHUNK_SIZE + localX;
53 const prev = data?.blocks?.[index];
54 if (!prev || prev.typeId !== BlockType.boulder)
55 { return null; }
56 const block = { typeId: prev.typeId, state, config: prev.config ?? null };
57 data.blocks[index] = block;
58 return {
59 type: "chunk-delta",
60 chunkX,
61 chunkY,
62 tileX,
63 tileY,
64 localX,
65 localY,
66 block
67 };
68}
69
70function equippedPickaxe (ecs, handle)
71{
72 const equipment = ecs.get(handle, Component.equipment);
73 const stack = equipment?.slots?.weapon;
74 if (!stack?.itemId)
75 { return null; }
76 const def = itemDefinition(stack.itemId);
77 if (def?.equipment?.kind !== EquipmentKind.pickaxeTool)
78 { return null; }
79 return { stack, def, tier: def.equipment.tier };
80}
81
82function clearGather (ecs, handle)
83{
84 if (ecs.has(handle, Component.gather))
85 { ecs.remove(handle, Component.gather); }
86}
87
88export function cancelGather (ecs, handle)
89{
90 clearGather(ecs, handle);
91}
92
93/** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
94export function clearOreRespawnsForChunk (world, chunkX, chunkY)
95{
96 const respawns = world.oreRespawns;
97 if (!respawns?.size)
98 { return; }
99 for (const key of [...respawns.keys()])
100 {
101 const [tileX, tileY] = key.split(",").map(Number);
102 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
103 { respawns.delete(key); }
104 }
105}
106
107/**
108 * Restore exhausted ore boulders whose timers have elapsed.
109 */
110export function stepOreRespawns (world, now)
111{
112 const respawns = world.oreRespawns;
113 if (!respawns?.size)
114 { return { events: [] }; }
115 const events = [];
116 for (const [key, entry] of [...respawns.entries()])
117 {
118 if (now < entry.respawnsAt)
119 { continue; }
120 respawns.delete(key);
121 const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId));
122 if (delta)
123 { events.push(delta); }
124 }
125 return { events };
126}
127
128/**
129 * Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.
130 */
131export function startMine (world, sessionId, characterId, tileX, tileY, now)
132{
133 const entityId = world.characterEntities.get(characterId);
134 if (entityId == null)
135 { throw userError("Character is not in the world."); }
136 const handle = world.ecs.handleOf(entityId);
137 const identity = world.ecs.get(handle, Component.networkIdentity);
138 if (!identity || identity.sessionId !== sessionId)
139 { throw userError("Character is not in the world."); }
140 if (world.ecs.has(handle, Component.dead))
141 { throw userError("You are dead."); }
142
143 const position = world.ecs.get(handle, Component.position);
144 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
145 { throw userError("You need to stand next to the rock."); }
146
147 const block = blockAt(world, tileX, tileY);
148 if (!block || block.typeId !== BlockType.boulder)
149 { throw userError("There is nothing to mine there."); }
150 const materialId = materialFromOreBoulderState(block.state);
151 if (!materialId)
152 { throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE
153 ? "That rock is exhausted."
154 : "That rock has no ore."); }
155
156 const pickaxe = equippedPickaxe(world.ecs, handle);
157 if (!pickaxe)
158 { throw userError("Equip a pickaxe to mine."); }
159
160 const skills = world.ecs.get(handle, Component.skills);
161 const miningLevel = skillLevel(skills, SkillId.mining);
162 const gate = canMineMaterial(miningLevel, pickaxe.tier, materialId);
163 if (!gate.ok)
164 { throw userError(gate.reason); }
165
166 const durationMs = miningDurationMs(materialId, pickaxe.tier);
167 clearEngage(world.ecs, entityId);
168 const path = world.ecs.get(handle, Component.path);
169 if (path)
170 { path.tiles = []; }
171 world.ecs.add(handle, Component.gather, {
172 kind: "mining",
173 tileX,
174 tileY,
175 materialId,
176 startedAt: now,
177 finishesAt: now + durationMs,
178 nextSwingAt: now
179 });
180
181 return {
182 events: [{
183 type: "gather-swing",
184 attackerId: entityId,
185 tileX,
186 tileY,
187 fromTileX: position.tileX,
188 fromTileY: position.tileY,
189 swipe: false
190 }]
191 };
192}
193
194export function stepGather (world, now)
195{
196 const events = [];
197 const privates = [];
198 const respawnEvents = stepOreRespawns(world, now);
199 events.push(...respawnEvents.events);
200
201 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
202 {
203 const { handle, gather, position, character, entityId } = entity;
204 if (world.ecs.has(handle, Component.dead))
205 {
206 clearGather(world.ecs, handle);
207 continue;
208 }
209 if (chebyshev(position.tileX, position.tileY, gather.tileX, gather.tileY) > 1)
210 {
211 clearGather(world.ecs, handle);
212 continue;
213 }
214 const block = blockAt(world, gather.tileX, gather.tileY);
215 if (!block || block.typeId !== BlockType.boulder
216 || materialFromOreBoulderState(block.state) !== gather.materialId)
217 {
218 clearGather(world.ecs, handle);
219 continue;
220 }
221
222 if (now >= gather.nextSwingAt && now < gather.finishesAt)
223 {
224 gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
225 events.push({
226 type: "gather-swing",
227 attackerId: entityId,
228 tileX: gather.tileX,
229 tileY: gather.tileY,
230 fromTileX: position.tileX,
231 fromTileY: position.tileY,
232 swipe: false
233 });
234 }
235
236 if (now < gather.finishesAt)
237 { continue; }
238
239 const oreItemId = oreItemIdForMaterial(gather.materialId);
240 const def = itemDefinition(oreItemId);
241 const inventory = world.ecs.get(handle, Component.inventory);
242 if (!oreItemId || !def || !inventory)
243 {
244 clearGather(world.ecs, handle);
245 continue;
246 }
247 const inserted = insertStack(inventory.slots, { itemId: oreItemId, quantity: 1 }, def);
248 if (!inserted.ok || inserted.remainder > 0)
249 {
250 clearGather(world.ecs, handle);
251 events.push({
252 type: "command-error",
253 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
254 message: "Your inventory is full."
255 });
256 continue;
257 }
258 inventory.slots = inserted.slots;
259
260 const skills = world.ecs.get(handle, Component.skills);
261 let skillsChanged = false;
262 if (skills?.xp && addSkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)))
263 { skillsChanged = true; }
264
265 const exhausted = setBoulderState(
266 world,
267 gather.tileX,
268 gather.tileY,
269 EXHAUSTED_ORE_BOULDER_STATE
270 );
271 if (exhausted)
272 {
273 events.push(exhausted);
274 ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
275 tileX: gather.tileX,
276 tileY: gather.tileY,
277 materialId: gather.materialId,
278 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
279 });
280 }
281
282 clearGather(world.ecs, handle);
283 privates.push({
284 characterId: character.characterId,
285 bag: bagView(world.ecs, handle)
286 });
287 if (skillsChanged)
288 {
289 events.push({
290 type: "skills-updated",
291 characterId: character.characterId,
292 skills: publicSkillsView(skills),
293 stored: storedSkillXp(skills)
294 });
295 }
296 events.push({
297 type: "gather-complete",
298 characterId: character.characterId,
299 kind: "mining",
300 materialId: gather.materialId,
301 itemId: oreItemId
302 });
303 }
304 return { events, privates };
305}
306
307export function handleGatherCommand (world, sessionId, command, now)
308{
309 switch (command.type)
310 {
311 case "mine":
312 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
313 case "cancel-gather":
314 {
315 const entityId = world.characterEntities.get(command.characterId);
316 if (entityId == null)
317 { return { events: [] }; }
318 const handle = world.ecs.handleOf(entityId);
319 clearGather(world.ecs, handle);
320 return { events: [] };
321 }
322 default:
323 return null;
324 }
325}
server/src/items/bags.js +8 −2
@@ -22,6 +22,7 @@ import {
22 22 import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
23 23 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
24 24 import { randomUUID } from "node:crypto";
25 import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
25 26
26 27 export function publicGroundItem (item)
27 28 {
@@ -351,11 +352,16 @@ function eatItem (world, sessionId, command)
351 352
352 353 function openBank (world, sessionId, command)
353 354 {
354 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
355 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
355 356 const position = world.ecs.get(handle, Component.position);
356 357 if (!nearBank(world, position.tileX, position.tileY))
357 358 { throw userError("Stand next to a bank."); }
358 return { events: [], private: bagView(world.ecs, handle), bank: true };
359 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank);
360 return {
361 events: shove ? [shove] : [],
362 private: bagView(world.ecs, handle),
363 bank: true
364 };
359 365 }
360 366
361 367 function bankMove (world, sessionId, command, fromKey, toKey)
@@ -22,6 +22,7 @@ import {
22import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
22import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
23import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
23import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
24import { randomUUID } from "node:crypto";
24import { randomUUID } from "node:crypto";
25import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
25
26
26export function publicGroundItem (item)
27export function publicGroundItem (item)
27{
28{
@@ -351,11 +352,16 @@ function eatItem (world, sessionId, command)
351
352
352function openBank (world, sessionId, command)
353function openBank (world, sessionId, command)
353{
354{
354 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
355 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
355 const position = world.ecs.get(handle, Component.position);
356 const position = world.ecs.get(handle, Component.position);
356 if (!nearBank(world, position.tileX, position.tileY))
357 if (!nearBank(world, position.tileX, position.tileY))
357 { throw userError("Stand next to a bank."); }
358 { throw userError("Stand next to a bank."); }
358 return { events: [], private: bagView(world.ecs, handle), bank: true };
359 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank);
360 return {
361 events: shove ? [shove] : [],
362 private: bagView(world.ecs, handle),
363 bank: true
364 };
359}
365}
360
366
361function bankMove (world, sessionId, command, fromKey, toKey)
367function bankMove (world, sessionId, command, fromKey, toKey)
server/src/simulation/follow.js +15 −2
@@ -7,6 +7,14 @@ const FOLLOW_BREAK_TILES = CHUNK_SIZE;
7 7 const FOLLOW_ALWAYS_RUN_TILES = 3;
8 8 const FOLLOW_TRAIL_MAX = CHUNK_SIZE * 2;
9 9
10 function canEntityRun (ecs, handle)
11 {
12 const stamina = ecs.get(handle, Component.stamina);
13 if (!stamina)
14 { return true; }
15 return Number(stamina.current) > 0;
16 }
17
10 18 export function clearFollow (ecs, entityId)
11 19 {
12 20 const handle = ecs.handleOf(entityId);
@@ -94,10 +102,15 @@ export function stepFollow (world)
94 102 continue;
95 103 }
96 104
105 const canRun = canEntityRun(world.ecs, entity.handle);
97 106 if (dist > FOLLOW_ALWAYS_RUN_TILES)
98 { entity.movement.gait = GAIT.run; }
107 { entity.movement.gait = canRun ? GAIT.run : GAIT.walk; }
99 108 else if (dist > 1)
100 { entity.movement.gait = target.gait === GAIT.run ? GAIT.run : GAIT.walk; }
109 {
110 entity.movement.gait = canRun && target.gait === GAIT.run
111 ? GAIT.run
112 : GAIT.walk;
113 }
101 114
102 115 if (!Array.isArray(follow.trail))
103 116 { follow.trail = []; }
@@ -7,6 +7,14 @@ const FOLLOW_BREAK_TILES = CHUNK_SIZE;
7const FOLLOW_ALWAYS_RUN_TILES = 3;
7const FOLLOW_ALWAYS_RUN_TILES = 3;
8const FOLLOW_TRAIL_MAX = CHUNK_SIZE * 2;
8const FOLLOW_TRAIL_MAX = CHUNK_SIZE * 2;
9
9
10function canEntityRun (ecs, handle)
11{
12 const stamina = ecs.get(handle, Component.stamina);
13 if (!stamina)
14 { return true; }
15 return Number(stamina.current) > 0;
16}
17
10export function clearFollow (ecs, entityId)
18export function clearFollow (ecs, entityId)
11{
19{
12 const handle = ecs.handleOf(entityId);
20 const handle = ecs.handleOf(entityId);
@@ -94,10 +102,15 @@ export function stepFollow (world)
94 continue;
102 continue;
95 }
103 }
96
104
105 const canRun = canEntityRun(world.ecs, entity.handle);
97 if (dist > FOLLOW_ALWAYS_RUN_TILES)
106 if (dist > FOLLOW_ALWAYS_RUN_TILES)
98 { entity.movement.gait = GAIT.run; }
107 { entity.movement.gait = canRun ? GAIT.run : GAIT.walk; }
99 else if (dist > 1)
108 else if (dist > 1)
100 { entity.movement.gait = target.gait === GAIT.run ? GAIT.run : GAIT.walk; }
109 {
110 entity.movement.gait = canRun && target.gait === GAIT.run
111 ? GAIT.run
112 : GAIT.walk;
113 }
101
114
102 if (!Array.isArray(follow.trail))
115 if (!Array.isArray(follow.trail))
103 { follow.trail = []; }
116 { follow.trail = []; }
server/src/simulation/protocol.js +1 −0
@@ -27,6 +27,7 @@ export const WorkerMessage = Object.freeze({
27 27 setGroundItems: "setGroundItems",
28 28 stepSpawners: "stepSpawners",
29 29 stepSystems: "stepSystems",
30 inspectStamina: "inspectStamina",
30 31 remoteCombatEngage: "remoteCombatEngage",
31 32 applyRemoteMelee: "applyRemoteMelee",
32 33 applyCombatHitXp: "applyCombatHitXp",
@@ -27,6 +27,7 @@ export const WorkerMessage = Object.freeze({
27 setGroundItems: "setGroundItems",
27 setGroundItems: "setGroundItems",
28 stepSpawners: "stepSpawners",
28 stepSpawners: "stepSpawners",
29 stepSystems: "stepSystems",
29 stepSystems: "stepSystems",
30 inspectStamina: "inspectStamina",
30 remoteCombatEngage: "remoteCombatEngage",
31 remoteCombatEngage: "remoteCombatEngage",
31 applyRemoteMelee: "applyRemoteMelee",
32 applyRemoteMelee: "applyRemoteMelee",
32 applyCombatHitXp: "applyCombatHitXp",
33 applyCombatHitXp: "applyCombatHitXp",
server/src/simulation/simulation.js +26 −3
@@ -163,7 +163,7 @@ export class Simulation
163 163 const remoteMelee = [];
164 164 for (const worker of this.workers)
165 165 {
166 const result = worker.call({ type: WorkerMessage.stepSystems, now });
166 const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });
167 167 for (const event of result?.events ?? [])
168 168 {
169 169 if (event.type === "remote-melee-resolve")
@@ -177,6 +177,15 @@ export class Simulation
177 177 { this.#forget(event.entityId); }
178 178 if (event.type === "skills-updated")
179 179 { this.#applySkillsUpdated(event); }
180 if (event.type === "inventory" && event.characterId)
181 {
182 this.#saveBagFromView(event.characterId, {
183 inventory: event.inventory,
184 equipment: event.equipment,
185 vault: event.vault,
186 vaultReserved: event.vaultReserved
187 });
188 }
180 189 if (event.type === "player-died")
181 190 {
182 191 events.push(...this.#applyPlayerDeath(event));
@@ -212,8 +221,11 @@ export class Simulation
212 221 {
213 222 if (event.type === "entity-move")
214 223 { this.#applyMoveToDirectory(event); }
224 if (event.type === "skills-updated")
225 { this.#applySkillsUpdated(event); }
215 226 this.#persistGroundEvent(event);
216 events.push(event);
227 if (event.type !== "skills-updated")
228 { events.push(event); }
217 229 }
218 230 for (const request of result?.transferRequests ?? [])
219 231 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
@@ -308,7 +320,7 @@ export class Simulation
308 320 reserved: bag.vaultReserved ?? []
309 321 },
310 322 health: { current: isDead ? 0 : maxHealth, max: maxHealth },
311 stamina: { current: maxStamina, max: maxStamina },
323 stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
312 324 combat: { targetEntityId: null, nextSwingAt: 0 },
313 325 skills,
314 326 };
@@ -468,6 +480,17 @@ export class Simulation
468 480 });
469 481 }
470 482
483 staminaOf (entityId)
484 {
485 const record = this.directory.get(entityId);
486 if (!record)
487 { return null; }
488 return this.workers[record.workerId].call({
489 type: WorkerMessage.inspectStamina,
490 entityId
491 });
492 }
493
471 494 pushInventory (characterId, bag)
472 495 {
473 496 this.pendingPrivate.push({
@@ -163,7 +163,7 @@ export class Simulation
163 const remoteMelee = [];
163 const remoteMelee = [];
164 for (const worker of this.workers)
164 for (const worker of this.workers)
165 {
165 {
166 const result = worker.call({ type: WorkerMessage.stepSystems, now });
166 const result = worker.call({ type: WorkerMessage.stepSystems, now, dt });
167 for (const event of result?.events ?? [])
167 for (const event of result?.events ?? [])
168 {
168 {
169 if (event.type === "remote-melee-resolve")
169 if (event.type === "remote-melee-resolve")
@@ -177,6 +177,15 @@ export class Simulation
177 { this.#forget(event.entityId); }
177 { this.#forget(event.entityId); }
178 if (event.type === "skills-updated")
178 if (event.type === "skills-updated")
179 { this.#applySkillsUpdated(event); }
179 { this.#applySkillsUpdated(event); }
180 if (event.type === "inventory" && event.characterId)
181 {
182 this.#saveBagFromView(event.characterId, {
183 inventory: event.inventory,
184 equipment: event.equipment,
185 vault: event.vault,
186 vaultReserved: event.vaultReserved
187 });
188 }
180 if (event.type === "player-died")
189 if (event.type === "player-died")
181 {
190 {
182 events.push(...this.#applyPlayerDeath(event));
191 events.push(...this.#applyPlayerDeath(event));
@@ -212,8 +221,11 @@ export class Simulation
212 {
221 {
213 if (event.type === "entity-move")
222 if (event.type === "entity-move")
214 { this.#applyMoveToDirectory(event); }
223 { this.#applyMoveToDirectory(event); }
224 if (event.type === "skills-updated")
225 { this.#applySkillsUpdated(event); }
215 this.#persistGroundEvent(event);
226 this.#persistGroundEvent(event);
216 events.push(event);
227 if (event.type !== "skills-updated")
228 { events.push(event); }
217 }
229 }
218 for (const request of result?.transferRequests ?? [])
230 for (const request of result?.transferRequests ?? [])
219 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
231 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
@@ -308,7 +320,7 @@ export class Simulation
308 reserved: bag.vaultReserved ?? []
320 reserved: bag.vaultReserved ?? []
309 },
321 },
310 health: { current: isDead ? 0 : maxHealth, max: maxHealth },
322 health: { current: isDead ? 0 : maxHealth, max: maxHealth },
311 stamina: { current: maxStamina, max: maxStamina },
323 stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
312 combat: { targetEntityId: null, nextSwingAt: 0 },
324 combat: { targetEntityId: null, nextSwingAt: 0 },
313 skills,
325 skills,
314 };
326 };
@@ -468,6 +480,17 @@ export class Simulation
468 });
480 });
469 }
481 }
470
482
483 staminaOf (entityId)
484 {
485 const record = this.directory.get(entityId);
486 if (!record)
487 { return null; }
488 return this.workers[record.workerId].call({
489 type: WorkerMessage.inspectStamina,
490 entityId
491 });
492 }
493
471 pushInventory (characterId, bag)
494 pushInventory (characterId, bag)
472 {
495 {
473 this.pendingPrivate.push({
496 this.pendingPrivate.push({
server/src/simulation/tileInteract.js added +49 −0
@@ -0,0 +1,49 @@
1 import { Component } from "../ecs/components.js";
2 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
3 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
4
5 /** Find a neighbouring (or same) tile with the given block type. Prefer non-self when possible. */
6 export function findAdjacentBlockTile (world, tileX, tileY, blockType)
7 {
8 let fallback = null;
9 for (let dy = -1; dy <= 1; dy++)
10 {
11 for (let dx = -1; dx <= 1; dx++)
12 {
13 const x = tileX + dx;
14 const y = tileY + dy;
15 const data = world.chunkData(tileToChunk(x), tileToChunk(y));
16 const index = tileToLocal(y) * CHUNK_SIZE + tileToLocal(x);
17 if (data.blocks[index]?.typeId !== blockType)
18 { continue; }
19 if (dx !== 0 || dy !== 0)
20 { return { tileX: x, tileY: y }; }
21 fallback = { tileX: x, tileY: y };
22 }
23 }
24 return fallback;
25 }
26
27 /** Shove the actor toward a world tile (bank, furnace, mine, craft, …). */
28 export function tileShoveEvent (entityId, fromTileX, fromTileY, tileX, tileY)
29 {
30 return {
31 type: "tile-shove",
32 attackerId: entityId,
33 fromTileX,
34 fromTileY,
35 tileX,
36 tileY
37 };
38 }
39
40 export function tileShoveTowardBlock (world, handle, entityId, blockType)
41 {
42 const position = world.ecs.get(handle, Component.position);
43 if (!position)
44 { return null; }
45 const target = findAdjacentBlockTile(world, position.tileX, position.tileY, blockType);
46 if (!target)
47 { return null; }
48 return tileShoveEvent(entityId, position.tileX, position.tileY, target.tileX, target.tileY);
49 }
@@ -0,0 +1,49 @@
1import { Component } from "../ecs/components.js";
2import { tileToChunk, tileToLocal } from "../world/coordinates.js";
3import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
4
5/** Find a neighbouring (or same) tile with the given block type. Prefer non-self when possible. */
6export function findAdjacentBlockTile (world, tileX, tileY, blockType)
7{
8 let fallback = null;
9 for (let dy = -1; dy <= 1; dy++)
10 {
11 for (let dx = -1; dx <= 1; dx++)
12 {
13 const x = tileX + dx;
14 const y = tileY + dy;
15 const data = world.chunkData(tileToChunk(x), tileToChunk(y));
16 const index = tileToLocal(y) * CHUNK_SIZE + tileToLocal(x);
17 if (data.blocks[index]?.typeId !== blockType)
18 { continue; }
19 if (dx !== 0 || dy !== 0)
20 { return { tileX: x, tileY: y }; }
21 fallback = { tileX: x, tileY: y };
22 }
23 }
24 return fallback;
25}
26
27/** Shove the actor toward a world tile (bank, furnace, mine, craft, …). */
28export function tileShoveEvent (entityId, fromTileX, fromTileY, tileX, tileY)
29{
30 return {
31 type: "tile-shove",
32 attackerId: entityId,
33 fromTileX,
34 fromTileY,
35 tileX,
36 tileY
37 };
38}
39
40export function tileShoveTowardBlock (world, handle, entityId, blockType)
41{
42 const position = world.ecs.get(handle, Component.position);
43 if (!position)
44 { return null; }
45 const target = findAdjacentBlockTile(world, position.tileX, position.tileY, blockType);
46 if (!target)
47 { return null; }
48 return tileShoveEvent(entityId, position.tileX, position.tileY, target.tileX, target.tileY);
49}
server/src/simulation/workerWorld.js +170 −7
@@ -31,6 +31,13 @@ import {
31 31 setGroundItemsForRegion
32 32 } from "../items/bags.js";
33 33 import { handleAlchemyCommand } from "../alchemy/service.js";
34 import {
35 handleGatherCommand,
36 stepGather,
37 cancelGather,
38 clearOreRespawnsForChunk
39 } from "../gathering/service.js";
40 import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
34 41 import {
35 42 applyRemoteMeleeSwing,
36 43 clearEngage,
@@ -40,7 +47,15 @@ import {
40 47 resolveCombatTarget,
41 48 stepCombat
42 49 } from "../combat/service.js";
43 import { awardCombatHitXp } from "../skills/service.js";
50 import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
51 import { SkillId } from "../../../shared/definitions/skills.js";
52 import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
53 import {
54 STAMINA_REGEN_PER_SECOND,
55 STAMINA_XP_PER_POINT_SPENT,
56 staminaCostPerRunStep,
57 publicStaminaView
58 } from "../../../shared/stamina/rules.js";
44 59 import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
45 60 import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
46 61
@@ -59,6 +74,7 @@ export class WorkerWorld
59 74 this.frozen = new Set();
60 75 this.groundItems = new Map();
61 76 this.groundByTile = new Map();
77 this.oreRespawns = new Map();
62 78 this.settings = { ...DEFAULT_WORLD_SETTINGS };
63 79 this.activeRevisionId = 1;
64 80 }
@@ -92,7 +108,7 @@ export class WorkerWorld
92 108 case WorkerMessage.stepMovement:
93 109 return this.#stepMovement(message.now);
94 110 case WorkerMessage.stepSystems:
95 return this.#stepSystems(message.now);
111 return this.#stepSystems(message.now, message.dt ?? (1 / 20));
96 112 case WorkerMessage.stepSpawners:
97 113 return { spawnRequests: collectSpawnRequests(this) };
98 114 case WorkerMessage.setGroundItems:
@@ -102,6 +118,8 @@ export class WorkerWorld
102 118 return this.#inspectBag(message.entityId);
103 119 case WorkerMessage.inspectSkills:
104 120 return this.#inspectSkills(message.entityId);
121 case WorkerMessage.inspectStamina:
122 return this.#inspectStamina(message.entityId);
105 123 case WorkerMessage.applyBag:
106 124 return this.#applyBag(message.entityId, message.bag);
107 125 case WorkerMessage.updateFlight:
@@ -181,6 +199,7 @@ export class WorkerWorld
181 199 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
182 200 for (const chunk of message.chunks ?? [])
183 201 {
202 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
184 203 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
185 204 data: cloneChunkData(chunk.data),
186 205 simulating: false,
@@ -196,6 +215,7 @@ export class WorkerWorld
196 215 {
197 216 const key = chunkKey(chunk.chunkX, chunk.chunkY);
198 217 const existing = this.chunks.get(key);
218 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
199 219 this.chunks.set(key, {
200 220 data: cloneChunkData(chunk.data),
201 221 simulating: existing?.simulating ?? false,
@@ -225,7 +245,10 @@ export class WorkerWorld
225 245 if (chunk.replica)
226 246 { continue; }
227 247 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
228 { this.chunks.delete(key); }
248 {
249 clearOreRespawnsForChunk(this, chunkX, chunkY);
250 this.chunks.delete(key);
251 }
229 252 }
230 253 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
231 254 return { dropped, groundItems };
@@ -354,8 +377,7 @@ export class WorkerWorld
354 377 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
355 378 return { events: [] };
356 379 case "set-gait":
357 this.#setGait(sessionId, command.characterId, command.gait);
358 return { events: [] };
380 return this.#setGait(sessionId, command.characterId, command.gait);
359 381 case "attack":
360 382 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
361 383 case "cancel-attack":
@@ -368,6 +390,12 @@ export class WorkerWorld
368 390 return this.#cancelFollow(sessionId, command.characterId);
369 391 default:
370 392 {
393 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
394 if (gather)
395 { return gather; }
396 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
397 if (craft)
398 { return craft; }
371 399 const alchemy = handleAlchemyCommand(this, sessionId, command);
372 400 if (alchemy)
373 401 { return alchemy; }
@@ -495,6 +523,21 @@ export class WorkerWorld
495 523 return skills;
496 524 }
497 525
526 #inspectStamina (entityId)
527 {
528 const handle = this.ecs.handleOf(entityId);
529 if (handle == null)
530 { return null; }
531 const stamina = this.ecs.get(handle, Component.stamina);
532 const movement = this.ecs.get(handle, Component.movement);
533 if (!stamina)
534 { return null; }
535 return {
536 ...publicStaminaView(stamina),
537 gait: movement?.gait ?? GAIT.walk
538 };
539 }
540
498 541 #applyBag (entityId, bag)
499 542 {
500 543 const handle = this.ecs.handleOf(entityId);
@@ -566,6 +609,7 @@ export class WorkerWorld
566 609 { return; }
567 610 clearEngage(this.ecs, entityId);
568 611 clearFollow(this.ecs, entityId);
612 cancelGather(this.ecs, handle);
569 613 const position = this.ecs.get(handle, Component.position);
570 614 const movement = this.ecs.get(handle, Component.movement);
571 615 let path = this.ecs.get(handle, Component.path);
@@ -611,6 +655,7 @@ export class WorkerWorld
611 655 if (!this.ecs.get(handle, Component.combat))
612 656 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
613 657 clearFollow(this.ecs, entityId);
658 cancelGather(this.ecs, handle);
614 659 engageTarget(this.ecs, entityId, targetEntityId, now);
615 660 if (target.local)
616 661 {
@@ -755,7 +800,99 @@ export class WorkerWorld
755 800 throw error;
756 801 }
757 802 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
758 this.ecs.get(handle, Component.movement).gait = gait;
803 const movement = this.ecs.get(handle, Component.movement);
804 const stamina = this.ecs.get(handle, Component.stamina);
805 if (gait === GAIT.run && !(Number(stamina?.current) > 0))
806 {
807 const error = new Error("You are too exhausted to run.");
808 error.userFacing = true;
809 throw error;
810 }
811 movement.gait = gait;
812 const character = this.ecs.get(handle, Component.character);
813 return {
814 events: character
815 ? [this.#staminaEvent(handle, character.characterId, movement.gait)]
816 : []
817 };
818 }
819
820 #staminaEvent (handle, characterId, gait = null)
821 {
822 const stamina = this.ecs.get(handle, Component.stamina);
823 const movement = this.ecs.get(handle, Component.movement);
824 return {
825 type: "stamina",
826 characterId,
827 ...publicStaminaView(stamina),
828 gait: gait ?? movement?.gait ?? GAIT.walk
829 };
830 }
831
832 #consumeRunStamina (handle, events)
833 {
834 const character = this.ecs.get(handle, Component.character);
835 if (!character)
836 { return; }
837 let stamina = this.ecs.get(handle, Component.stamina);
838 if (!stamina)
839 {
840 stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 });
841 }
842 const skills = this.ecs.get(handle, Component.skills);
843 syncPlayerStamina(this.ecs, handle);
844 const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond);
845 stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost);
846 stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost;
847 let skillsChanged = false;
848 while (stamina.xpDebt >= 1 && skills?.xp)
849 {
850 stamina.xpDebt -= 1;
851 if (addSkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT))
852 {
853 skillsChanged = true;
854 syncPlayerStamina(this.ecs, handle);
855 }
856 }
857 const movement = this.ecs.get(handle, Component.movement);
858 if (stamina.current <= 0 && movement)
859 {
860 stamina.current = 0;
861 movement.gait = GAIT.walk;
862 }
863 events.push(this.#staminaEvent(handle, character.characterId));
864 if (skillsChanged)
865 {
866 events.push({
867 type: "skills-updated",
868 characterId: character.characterId,
869 skills: publicSkillsView(skills),
870 stored: storedSkillXp(skills)
871 });
872 }
873 }
874
875 #regenStamina (dt, events)
876 {
877 if (!(dt > 0))
878 { return; }
879 for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement))
880 {
881 const { handle, character, stamina, movement } = entity;
882 if (this.ecs.has(handle, Component.dead))
883 { continue; }
884 if (movement.gait === GAIT.run)
885 { continue; }
886 syncPlayerStamina(this.ecs, handle);
887 const before = Number(stamina.current) || 0;
888 if (before >= stamina.max)
889 { continue; }
890 stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND);
891 const after = Number(stamina.current) || 0;
892 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
893 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
894 { events.push(this.#staminaEvent(handle, character.characterId)); }
895 }
759 896 }
760 897
761 898 #requireOwnedEntity (sessionId, characterId)
@@ -784,10 +921,11 @@ export class WorkerWorld
784 921 return { handle, entityId };
785 922 }
786 923
787 #stepSystems (now = Date.now())
924 #stepSystems (now = Date.now(), dt = 1 / 20)
788 925 {
789 926 const events = [];
790 927 const transferRequests = [];
928 this.#regenStamina(dt, events);
791 929 const flight = stepFreeFlight(this, now);
792 930 for (const event of flight)
793 931 {
@@ -810,6 +948,26 @@ export class WorkerWorld
810 948 }
811 949 events.push(...stepCombat(this, now));
812 950 stepFollow(this);
951 const gather = stepGather(this, now);
952 events.push(...gather.events);
953 for (const entry of gather.privates ?? [])
954 {
955 events.push({
956 type: "inventory",
957 characterId: entry.characterId,
958 ...entry.bag
959 });
960 }
961 const craft = stepCrafting(this, now);
962 events.push(...craft.events);
963 for (const entry of craft.privates ?? [])
964 {
965 events.push({
966 type: "inventory",
967 characterId: entry.characterId,
968 ...entry.bag
969 });
970 }
813 971 return { events, transferRequests };
814 972 }
815 973
@@ -833,6 +991,9 @@ export class WorkerWorld
833 991 if (!this.chunkIsSimulating(position.tileX, position.tileY))
834 992 { continue; }
835 993
994 const stamina = this.ecs.get(handle, Component.stamina);
995 if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))
996 { movement.gait = GAIT.walk; }
836 997 const isWalk = movement.gait !== GAIT.run;
837 998 if (isWalk)
838 999 {
@@ -890,6 +1051,8 @@ export class WorkerWorld
890 1051 { this.#occupy(entityId, position.tileX, position.tileY); }
891 1052 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
892 1053 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1054 if (!isWalk)
1055 { this.#consumeRunStamina(handle, events); }
893 1056 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
894 1057 }
895 1058 return { events, transferRequests };
@@ -31,6 +31,13 @@ import {
31 setGroundItemsForRegion
31 setGroundItemsForRegion
32} from "../items/bags.js";
32} from "../items/bags.js";
33import { handleAlchemyCommand } from "../alchemy/service.js";
33import { handleAlchemyCommand } from "../alchemy/service.js";
34import {
35 handleGatherCommand,
36 stepGather,
37 cancelGather,
38 clearOreRespawnsForChunk
39} from "../gathering/service.js";
40import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
34import {
41import {
35 applyRemoteMeleeSwing,
42 applyRemoteMeleeSwing,
36 clearEngage,
43 clearEngage,
@@ -40,7 +47,15 @@ import {
40 resolveCombatTarget,
47 resolveCombatTarget,
41 stepCombat
48 stepCombat
42} from "../combat/service.js";
49} from "../combat/service.js";
43import { awardCombatHitXp } from "../skills/service.js";
50import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
51import { SkillId } from "../../../shared/definitions/skills.js";
52import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
53import {
54 STAMINA_REGEN_PER_SECOND,
55 STAMINA_XP_PER_POINT_SPENT,
56 staminaCostPerRunStep,
57 publicStaminaView
58} from "../../../shared/stamina/rules.js";
44import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
59import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
45import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
60import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
46
61
@@ -59,6 +74,7 @@ export class WorkerWorld
59 this.frozen = new Set();
74 this.frozen = new Set();
60 this.groundItems = new Map();
75 this.groundItems = new Map();
61 this.groundByTile = new Map();
76 this.groundByTile = new Map();
77 this.oreRespawns = new Map();
62 this.settings = { ...DEFAULT_WORLD_SETTINGS };
78 this.settings = { ...DEFAULT_WORLD_SETTINGS };
63 this.activeRevisionId = 1;
79 this.activeRevisionId = 1;
64 }
80 }
@@ -92,7 +108,7 @@ export class WorkerWorld
92 case WorkerMessage.stepMovement:
108 case WorkerMessage.stepMovement:
93 return this.#stepMovement(message.now);
109 return this.#stepMovement(message.now);
94 case WorkerMessage.stepSystems:
110 case WorkerMessage.stepSystems:
95 return this.#stepSystems(message.now);
111 return this.#stepSystems(message.now, message.dt ?? (1 / 20));
96 case WorkerMessage.stepSpawners:
112 case WorkerMessage.stepSpawners:
97 return { spawnRequests: collectSpawnRequests(this) };
113 return { spawnRequests: collectSpawnRequests(this) };
98 case WorkerMessage.setGroundItems:
114 case WorkerMessage.setGroundItems:
@@ -102,6 +118,8 @@ export class WorkerWorld
102 return this.#inspectBag(message.entityId);
118 return this.#inspectBag(message.entityId);
103 case WorkerMessage.inspectSkills:
119 case WorkerMessage.inspectSkills:
104 return this.#inspectSkills(message.entityId);
120 return this.#inspectSkills(message.entityId);
121 case WorkerMessage.inspectStamina:
122 return this.#inspectStamina(message.entityId);
105 case WorkerMessage.applyBag:
123 case WorkerMessage.applyBag:
106 return this.#applyBag(message.entityId, message.bag);
124 return this.#applyBag(message.entityId, message.bag);
107 case WorkerMessage.updateFlight:
125 case WorkerMessage.updateFlight:
@@ -181,6 +199,7 @@ export class WorkerWorld
181 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
199 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
182 for (const chunk of message.chunks ?? [])
200 for (const chunk of message.chunks ?? [])
183 {
201 {
202 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
184 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
203 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
185 data: cloneChunkData(chunk.data),
204 data: cloneChunkData(chunk.data),
186 simulating: false,
205 simulating: false,
@@ -196,6 +215,7 @@ export class WorkerWorld
196 {
215 {
197 const key = chunkKey(chunk.chunkX, chunk.chunkY);
216 const key = chunkKey(chunk.chunkX, chunk.chunkY);
198 const existing = this.chunks.get(key);
217 const existing = this.chunks.get(key);
218 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
199 this.chunks.set(key, {
219 this.chunks.set(key, {
200 data: cloneChunkData(chunk.data),
220 data: cloneChunkData(chunk.data),
201 simulating: existing?.simulating ?? false,
221 simulating: existing?.simulating ?? false,
@@ -225,7 +245,10 @@ export class WorkerWorld
225 if (chunk.replica)
245 if (chunk.replica)
226 { continue; }
246 { continue; }
227 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
247 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
228 { this.chunks.delete(key); }
248 {
249 clearOreRespawnsForChunk(this, chunkX, chunkY);
250 this.chunks.delete(key);
251 }
229 }
252 }
230 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
253 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
231 return { dropped, groundItems };
254 return { dropped, groundItems };
@@ -354,8 +377,7 @@ export class WorkerWorld
354 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
377 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
355 return { events: [] };
378 return { events: [] };
356 case "set-gait":
379 case "set-gait":
357 this.#setGait(sessionId, command.characterId, command.gait);
380 return this.#setGait(sessionId, command.characterId, command.gait);
358 return { events: [] };
359 case "attack":
381 case "attack":
360 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
382 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
361 case "cancel-attack":
383 case "cancel-attack":
@@ -368,6 +390,12 @@ export class WorkerWorld
368 return this.#cancelFollow(sessionId, command.characterId);
390 return this.#cancelFollow(sessionId, command.characterId);
369 default:
391 default:
370 {
392 {
393 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
394 if (gather)
395 { return gather; }
396 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
397 if (craft)
398 { return craft; }
371 const alchemy = handleAlchemyCommand(this, sessionId, command);
399 const alchemy = handleAlchemyCommand(this, sessionId, command);
372 if (alchemy)
400 if (alchemy)
373 { return alchemy; }
401 { return alchemy; }
@@ -495,6 +523,21 @@ export class WorkerWorld
495 return skills;
523 return skills;
496 }
524 }
497
525
526 #inspectStamina (entityId)
527 {
528 const handle = this.ecs.handleOf(entityId);
529 if (handle == null)
530 { return null; }
531 const stamina = this.ecs.get(handle, Component.stamina);
532 const movement = this.ecs.get(handle, Component.movement);
533 if (!stamina)
534 { return null; }
535 return {
536 ...publicStaminaView(stamina),
537 gait: movement?.gait ?? GAIT.walk
538 };
539 }
540
498 #applyBag (entityId, bag)
541 #applyBag (entityId, bag)
499 {
542 {
500 const handle = this.ecs.handleOf(entityId);
543 const handle = this.ecs.handleOf(entityId);
@@ -566,6 +609,7 @@ export class WorkerWorld
566 { return; }
609 { return; }
567 clearEngage(this.ecs, entityId);
610 clearEngage(this.ecs, entityId);
568 clearFollow(this.ecs, entityId);
611 clearFollow(this.ecs, entityId);
612 cancelGather(this.ecs, handle);
569 const position = this.ecs.get(handle, Component.position);
613 const position = this.ecs.get(handle, Component.position);
570 const movement = this.ecs.get(handle, Component.movement);
614 const movement = this.ecs.get(handle, Component.movement);
571 let path = this.ecs.get(handle, Component.path);
615 let path = this.ecs.get(handle, Component.path);
@@ -611,6 +655,7 @@ export class WorkerWorld
611 if (!this.ecs.get(handle, Component.combat))
655 if (!this.ecs.get(handle, Component.combat))
612 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
656 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
613 clearFollow(this.ecs, entityId);
657 clearFollow(this.ecs, entityId);
658 cancelGather(this.ecs, handle);
614 engageTarget(this.ecs, entityId, targetEntityId, now);
659 engageTarget(this.ecs, entityId, targetEntityId, now);
615 if (target.local)
660 if (target.local)
616 {
661 {
@@ -755,7 +800,99 @@ export class WorkerWorld
755 throw error;
800 throw error;
756 }
801 }
757 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
802 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
758 this.ecs.get(handle, Component.movement).gait = gait;
803 const movement = this.ecs.get(handle, Component.movement);
804 const stamina = this.ecs.get(handle, Component.stamina);
805 if (gait === GAIT.run && !(Number(stamina?.current) > 0))
806 {
807 const error = new Error("You are too exhausted to run.");
808 error.userFacing = true;
809 throw error;
810 }
811 movement.gait = gait;
812 const character = this.ecs.get(handle, Component.character);
813 return {
814 events: character
815 ? [this.#staminaEvent(handle, character.characterId, movement.gait)]
816 : []
817 };
818 }
819
820 #staminaEvent (handle, characterId, gait = null)
821 {
822 const stamina = this.ecs.get(handle, Component.stamina);
823 const movement = this.ecs.get(handle, Component.movement);
824 return {
825 type: "stamina",
826 characterId,
827 ...publicStaminaView(stamina),
828 gait: gait ?? movement?.gait ?? GAIT.walk
829 };
830 }
831
832 #consumeRunStamina (handle, events)
833 {
834 const character = this.ecs.get(handle, Component.character);
835 if (!character)
836 { return; }
837 let stamina = this.ecs.get(handle, Component.stamina);
838 if (!stamina)
839 {
840 stamina = this.ecs.add(handle, Component.stamina, { current: 1, max: 1, xpDebt: 0 });
841 }
842 const skills = this.ecs.get(handle, Component.skills);
843 syncPlayerStamina(this.ecs, handle);
844 const cost = staminaCostPerRunStep(this.settings?.walkTilesPerSecond);
845 stamina.current = Math.max(0, (Number(stamina.current) || 0) - cost);
846 stamina.xpDebt = (Number(stamina.xpDebt) || 0) + cost;
847 let skillsChanged = false;
848 while (stamina.xpDebt >= 1 && skills?.xp)
849 {
850 stamina.xpDebt -= 1;
851 if (addSkillXp(skills, SkillId.stamina, STAMINA_XP_PER_POINT_SPENT))
852 {
853 skillsChanged = true;
854 syncPlayerStamina(this.ecs, handle);
855 }
856 }
857 const movement = this.ecs.get(handle, Component.movement);
858 if (stamina.current <= 0 && movement)
859 {
860 stamina.current = 0;
861 movement.gait = GAIT.walk;
862 }
863 events.push(this.#staminaEvent(handle, character.characterId));
864 if (skillsChanged)
865 {
866 events.push({
867 type: "skills-updated",
868 characterId: character.characterId,
869 skills: publicSkillsView(skills),
870 stored: storedSkillXp(skills)
871 });
872 }
873 }
874
875 #regenStamina (dt, events)
876 {
877 if (!(dt > 0))
878 { return; }
879 for (const entity of this.ecs.query(Component.character, Component.stamina, Component.movement))
880 {
881 const { handle, character, stamina, movement } = entity;
882 if (this.ecs.has(handle, Component.dead))
883 { continue; }
884 if (movement.gait === GAIT.run)
885 { continue; }
886 syncPlayerStamina(this.ecs, handle);
887 const before = Number(stamina.current) || 0;
888 if (before >= stamina.max)
889 { continue; }
890 stamina.current = Math.min(stamina.max, before + dt * STAMINA_REGEN_PER_SECOND);
891 const after = Number(stamina.current) || 0;
892 // Sync on display-bucket changes (ceil) or when the bar fills — avoid per-tick spam.
893 if (Math.ceil(before) !== Math.ceil(after) || (after >= stamina.max && before < stamina.max))
894 { events.push(this.#staminaEvent(handle, character.characterId)); }
895 }
759 }
896 }
760
897
761 #requireOwnedEntity (sessionId, characterId)
898 #requireOwnedEntity (sessionId, characterId)
@@ -784,10 +921,11 @@ export class WorkerWorld
784 return { handle, entityId };
921 return { handle, entityId };
785 }
922 }
786
923
787 #stepSystems (now = Date.now())
924 #stepSystems (now = Date.now(), dt = 1 / 20)
788 {
925 {
789 const events = [];
926 const events = [];
790 const transferRequests = [];
927 const transferRequests = [];
928 this.#regenStamina(dt, events);
791 const flight = stepFreeFlight(this, now);
929 const flight = stepFreeFlight(this, now);
792 for (const event of flight)
930 for (const event of flight)
793 {
931 {
@@ -810,6 +948,26 @@ export class WorkerWorld
810 }
948 }
811 events.push(...stepCombat(this, now));
949 events.push(...stepCombat(this, now));
812 stepFollow(this);
950 stepFollow(this);
951 const gather = stepGather(this, now);
952 events.push(...gather.events);
953 for (const entry of gather.privates ?? [])
954 {
955 events.push({
956 type: "inventory",
957 characterId: entry.characterId,
958 ...entry.bag
959 });
960 }
961 const craft = stepCrafting(this, now);
962 events.push(...craft.events);
963 for (const entry of craft.privates ?? [])
964 {
965 events.push({
966 type: "inventory",
967 characterId: entry.characterId,
968 ...entry.bag
969 });
970 }
813 return { events, transferRequests };
971 return { events, transferRequests };
814 }
972 }
815
973
@@ -833,6 +991,9 @@ export class WorkerWorld
833 if (!this.chunkIsSimulating(position.tileX, position.tileY))
991 if (!this.chunkIsSimulating(position.tileX, position.tileY))
834 { continue; }
992 { continue; }
835
993
994 const stamina = this.ecs.get(handle, Component.stamina);
995 if (movement.gait === GAIT.run && stamina && !(Number(stamina.current) > 0))
996 { movement.gait = GAIT.walk; }
836 const isWalk = movement.gait !== GAIT.run;
997 const isWalk = movement.gait !== GAIT.run;
837 if (isWalk)
998 if (isWalk)
838 {
999 {
@@ -890,6 +1051,8 @@ export class WorkerWorld
890 { this.#occupy(entityId, position.tileX, position.tileY); }
1051 { this.#occupy(entityId, position.tileX, position.tileY); }
891 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
1052 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
892 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1053 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
1054 if (!isWalk)
1055 { this.#consumeRunStamina(handle, events); }
893 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
1056 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
894 }
1057 }
895 return { events, transferRequests };
1058 return { events, transferRequests };
server/src/skills/service.js +15 −1
@@ -1,5 +1,5 @@
1 1 import { Component } from "../ecs/components.js";
2 import { SkillId, playerMaxHealth } from "../../../shared/definitions/skills.js";
2 import { SkillId, playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
3 3 import { combatHitXpPerSkill } from "../../../shared/skills/progression.js";
4 4 import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
5 5
@@ -17,6 +17,20 @@ export function syncPlayerHealth (ecs, handle)
17 17 health.current = Math.min(health.current | 0, max);
18 18 }
19 19
20 export function syncPlayerStamina (ecs, handle)
21 {
22 const character = ecs.get(handle, Component.character);
23 if (!character)
24 { return; }
25 const skills = ecs.get(handle, Component.skills);
26 const stamina = ecs.get(handle, Component.stamina);
27 if (!skills || !stamina)
28 { return; }
29 const max = playerMaxStamina(skills);
30 stamina.max = max;
31 stamina.current = Math.min(Number(stamina.current) || 0, max);
32 }
33
20 34 export function awardCombatHitXp (ecs, attackerHandle, profile)
21 35 {
22 36 const skills = ecs.get(attackerHandle, Component.skills);
@@ -1,5 +1,5 @@
1import { Component } from "../ecs/components.js";
1import { Component } from "../ecs/components.js";
2import { SkillId, playerMaxHealth } from "../../../shared/definitions/skills.js";
2import { SkillId, playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
3import { combatHitXpPerSkill } from "../../../shared/skills/progression.js";
3import { combatHitXpPerSkill } from "../../../shared/skills/progression.js";
4import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
4import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
5
5
@@ -17,6 +17,20 @@ export function syncPlayerHealth (ecs, handle)
17 health.current = Math.min(health.current | 0, max);
17 health.current = Math.min(health.current | 0, max);
18}
18}
19
19
20export function syncPlayerStamina (ecs, handle)
21{
22 const character = ecs.get(handle, Component.character);
23 if (!character)
24 { return; }
25 const skills = ecs.get(handle, Component.skills);
26 const stamina = ecs.get(handle, Component.stamina);
27 if (!skills || !stamina)
28 { return; }
29 const max = playerMaxStamina(skills);
30 stamina.max = max;
31 stamina.current = Math.min(Number(stamina.current) || 0, max);
32}
33
20export function awardCombatHitXp (ecs, attackerHandle, profile)
34export function awardCombatHitXp (ecs, attackerHandle, profile)
21{
35{
22 const skills = ecs.get(attackerHandle, Component.skills);
36 const skills = ecs.get(attackerHandle, Component.skills);
server/tests/crafting.test.js added +250 −0
@@ -0,0 +1,250 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { BlockType, blockDefinition } from "../../shared/definitions/tiles.js";
4 import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/craftingStations.js";
5 import { ItemId } from "../../shared/definitions/items.js";
6 import { SkillId } from "../../shared/definitions/skills.js";
7 import { MaterialTier, tierSmeltSkillLevel } from "../../shared/definitions/materialTiers.js";
8 import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
9 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
10 import { totalXpForLevel } from "../../shared/skills/progression.js";
11 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
12 import { Component } from "../src/ecs/components.js";
13
14 function countItem (slots, itemId)
15 {
16 return (slots ?? []).reduce((sum, slot) =>
17 {
18 if (slot?.itemId === itemId)
19 { return sum + (slot.quantity | 0); }
20 return sum;
21 }, 0);
22 }
23
24 function placeFurnace (worker, tileX, tileY)
25 {
26 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
27 const localX = tileX % 16;
28 const localY = tileY % 16;
29 data.blocks[localY * 16 + localX] = {
30 typeId: BlockType.furnace,
31 state: "furnace",
32 config: null
33 };
34 }
35
36 function setSkillLevel (worker, playerId, skillId, level)
37 {
38 const handle = worker.world.ecs.handleOf(playerId);
39 const skills = worker.world.ecs.get(handle, Component.skills);
40 skills.xp[skillId] = totalXpForLevel(level);
41 }
42
43 function giveInventory (harness, playerId, items)
44 {
45 const inventory = emptySlots();
46 items.forEach((stack, index) =>
47 {
48 inventory[index] = { itemId: stack.itemId, quantity: stack.quantity };
49 });
50 harness.simulation.applyBag(playerId, {
51 inventory,
52 equipment: emptyEquipment(),
53 vault: [],
54 vaultReserved: []
55 });
56 }
57
58 function advanceMs (harness, ms)
59 {
60 const ticks = Math.ceil(ms / 50) + 3;
61 for (let i = 0; i < ticks; i++)
62 {
63 harness.advance(50);
64 harness.simulation.step();
65 }
66 }
67
68 test("furnace block and steel recipe exist", () =>
69 {
70 assert.equal(blockDefinition(BlockType.furnace)?.key, "furnace");
71 const recipes = recipesForStation(CraftingStationId.furnace);
72 const steel = recipes.find((recipe) => recipe.recipeId === "smelt-steel");
73 assert.ok(steel);
74 assert.deepEqual(steel.inputs.map((row) => row.itemId).sort(), [
75 ItemId.coal,
76 ItemId.ironOre
77 ].sort());
78 assert.equal(steel.output.itemId, ItemId.steelBar);
79 assert.equal(recipeDefinition("smelt-bronze")?.minSkillLevel, tierSmeltSkillLevel(MaterialTier.bronze));
80 });
81
82 test("open furnace near station emits shove and station-open", () =>
83 {
84 const harness = makeSimulation({ workerCount: 1 });
85 try
86 {
87 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
88 const playerId = harness.simulation.spawnCharacter(1, character);
89 const record = harness.simulation.entityRecord(playerId);
90 const worker = harness.simulation.workers[record.workerId];
91 placeFurnace(worker, 9, 8);
92
93 harness.simulation.enqueue(1, {
94 type: "open-station",
95 characterId: character.character_id,
96 stationId: CraftingStationId.furnace
97 });
98 const result = harness.simulation.step();
99 assert.ok(result.events.some((event) => event.type === "tile-shove"));
100 assert.ok(result.events.some((event) =>
101 event.type === "station-open" && event.stationId === CraftingStationId.furnace));
102 }
103 finally
104 { harness.close(); }
105 });
106
107 test("smelting bronze consumes ore, grants bar and Smithing XP", () =>
108 {
109 const harness = makeSimulation({ workerCount: 1 });
110 try
111 {
112 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
113 const playerId = harness.simulation.spawnCharacter(1, character);
114 const record = harness.simulation.entityRecord(playerId);
115 const worker = harness.simulation.workers[record.workerId];
116 placeFurnace(worker, 9, 8);
117 giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);
118
119 harness.simulation.enqueue(1, {
120 type: "start-craft",
121 characterId: character.character_id,
122 stationId: CraftingStationId.furnace,
123 recipeId: "smelt-bronze"
124 });
125 const start = harness.simulation.step();
126 assert.ok(start.events.some((event) => event.type === "tile-shove"));
127 assert.ok(start.events.some((event) =>
128 event.type === "item-bubble" && event.itemId === ItemId.bronzeBar));
129
130 const smithingBefore = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
131 advanceMs(harness, CRAFT_DURATION_MS);
132
133 const bag = harness.simulation.bagOf(playerId);
134 assert.equal(countItem(bag.inventory, ItemId.bronzeOre), 0);
135 assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 1);
136 const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
137 assert.ok(smithingAfter > smithingBefore);
138 }
139 finally
140 { harness.close(); }
141 });
142
143 test("smelting steel requires iron ore and coal", () =>
144 {
145 const harness = makeSimulation({ workerCount: 1 });
146 try
147 {
148 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
149 const playerId = harness.simulation.spawnCharacter(1, character);
150 const record = harness.simulation.entityRecord(playerId);
151 const worker = harness.simulation.workers[record.workerId];
152 placeFurnace(worker, 9, 8);
153 setSkillLevel(worker, playerId, SkillId.smithing, tierSmeltSkillLevel(MaterialTier.steel));
154 giveInventory(harness, playerId, [
155 { itemId: ItemId.ironOre, quantity: 1 },
156 { itemId: ItemId.coal, quantity: 1 }
157 ]);
158
159 harness.simulation.enqueue(1, {
160 type: "start-craft",
161 characterId: character.character_id,
162 stationId: CraftingStationId.furnace,
163 recipeId: "smelt-steel"
164 });
165 harness.simulation.step();
166 advanceMs(harness, CRAFT_DURATION_MS);
167
168 const bag = harness.simulation.bagOf(playerId);
169 assert.equal(countItem(bag.inventory, ItemId.ironOre), 0);
170 assert.equal(countItem(bag.inventory, ItemId.coal), 0);
171 assert.equal(countItem(bag.inventory, ItemId.steelBar), 1);
172 }
173 finally
174 { harness.close(); }
175 });
176
177 test("craft rejects missing materials", () =>
178 {
179 const harness = makeSimulation({ workerCount: 1 });
180 try
181 {
182 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
183 const playerId = harness.simulation.spawnCharacter(1, character);
184 const record = harness.simulation.entityRecord(playerId);
185 const worker = harness.simulation.workers[record.workerId];
186 placeFurnace(worker, 9, 8);
187 giveInventory(harness, playerId, []);
188
189 harness.simulation.enqueue(1, {
190 type: "start-craft",
191 characterId: character.character_id,
192 stationId: CraftingStationId.furnace,
193 recipeId: "smelt-bronze"
194 });
195 const result = harness.simulation.step();
196 assert.ok(result.events.some((event) =>
197 event.type === "command-error" && /missing|materials/i.test(event.message ?? "")));
198 }
199 finally
200 { harness.close(); }
201 });
202
203 test("craft rejects low Smithing for iron bars", () =>
204 {
205 const harness = makeSimulation({ workerCount: 1 });
206 try
207 {
208 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
209 const playerId = harness.simulation.spawnCharacter(1, character);
210 const record = harness.simulation.entityRecord(playerId);
211 const worker = harness.simulation.workers[record.workerId];
212 placeFurnace(worker, 9, 8);
213 giveInventory(harness, playerId, [{ itemId: ItemId.ironOre, quantity: 1 }]);
214
215 harness.simulation.enqueue(1, {
216 type: "start-craft",
217 characterId: character.character_id,
218 stationId: CraftingStationId.furnace,
219 recipeId: "smelt-iron"
220 });
221 const result = harness.simulation.step();
222 assert.ok(result.events.some((event) =>
223 event.type === "command-error" && /smithing|requires/i.test(event.message ?? "")));
224 }
225 finally
226 { harness.close(); }
227 });
228
229 test("craft rejects furnace recipes when not next to a furnace", () =>
230 {
231 const harness = makeSimulation({ workerCount: 1 });
232 try
233 {
234 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
235 const playerId = harness.simulation.spawnCharacter(1, character);
236 giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);
237
238 harness.simulation.enqueue(1, {
239 type: "start-craft",
240 characterId: character.character_id,
241 stationId: CraftingStationId.furnace,
242 recipeId: "smelt-bronze"
243 });
244 const result = harness.simulation.step();
245 assert.ok(result.events.some((event) =>
246 event.type === "command-error" && /station|next to/i.test(event.message ?? "")));
247 }
248 finally
249 { harness.close(); }
250 });
@@ -0,0 +1,250 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { BlockType, blockDefinition } from "../../shared/definitions/tiles.js";
4import { CraftingStationId, CRAFT_DURATION_MS } from "../../shared/definitions/craftingStations.js";
5import { ItemId } from "../../shared/definitions/items.js";
6import { SkillId } from "../../shared/definitions/skills.js";
7import { MaterialTier, tierSmeltSkillLevel } from "../../shared/definitions/materialTiers.js";
8import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
9import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
10import { totalXpForLevel } from "../../shared/skills/progression.js";
11import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
12import { Component } from "../src/ecs/components.js";
13
14function countItem (slots, itemId)
15{
16 return (slots ?? []).reduce((sum, slot) =>
17 {
18 if (slot?.itemId === itemId)
19 { return sum + (slot.quantity | 0); }
20 return sum;
21 }, 0);
22}
23
24function placeFurnace (worker, tileX, tileY)
25{
26 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
27 const localX = tileX % 16;
28 const localY = tileY % 16;
29 data.blocks[localY * 16 + localX] = {
30 typeId: BlockType.furnace,
31 state: "furnace",
32 config: null
33 };
34}
35
36function setSkillLevel (worker, playerId, skillId, level)
37{
38 const handle = worker.world.ecs.handleOf(playerId);
39 const skills = worker.world.ecs.get(handle, Component.skills);
40 skills.xp[skillId] = totalXpForLevel(level);
41}
42
43function giveInventory (harness, playerId, items)
44{
45 const inventory = emptySlots();
46 items.forEach((stack, index) =>
47 {
48 inventory[index] = { itemId: stack.itemId, quantity: stack.quantity };
49 });
50 harness.simulation.applyBag(playerId, {
51 inventory,
52 equipment: emptyEquipment(),
53 vault: [],
54 vaultReserved: []
55 });
56}
57
58function advanceMs (harness, ms)
59{
60 const ticks = Math.ceil(ms / 50) + 3;
61 for (let i = 0; i < ticks; i++)
62 {
63 harness.advance(50);
64 harness.simulation.step();
65 }
66}
67
68test("furnace block and steel recipe exist", () =>
69{
70 assert.equal(blockDefinition(BlockType.furnace)?.key, "furnace");
71 const recipes = recipesForStation(CraftingStationId.furnace);
72 const steel = recipes.find((recipe) => recipe.recipeId === "smelt-steel");
73 assert.ok(steel);
74 assert.deepEqual(steel.inputs.map((row) => row.itemId).sort(), [
75 ItemId.coal,
76 ItemId.ironOre
77 ].sort());
78 assert.equal(steel.output.itemId, ItemId.steelBar);
79 assert.equal(recipeDefinition("smelt-bronze")?.minSkillLevel, tierSmeltSkillLevel(MaterialTier.bronze));
80});
81
82test("open furnace near station emits shove and station-open", () =>
83{
84 const harness = makeSimulation({ workerCount: 1 });
85 try
86 {
87 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
88 const playerId = harness.simulation.spawnCharacter(1, character);
89 const record = harness.simulation.entityRecord(playerId);
90 const worker = harness.simulation.workers[record.workerId];
91 placeFurnace(worker, 9, 8);
92
93 harness.simulation.enqueue(1, {
94 type: "open-station",
95 characterId: character.character_id,
96 stationId: CraftingStationId.furnace
97 });
98 const result = harness.simulation.step();
99 assert.ok(result.events.some((event) => event.type === "tile-shove"));
100 assert.ok(result.events.some((event) =>
101 event.type === "station-open" && event.stationId === CraftingStationId.furnace));
102 }
103 finally
104 { harness.close(); }
105});
106
107test("smelting bronze consumes ore, grants bar and Smithing XP", () =>
108{
109 const harness = makeSimulation({ workerCount: 1 });
110 try
111 {
112 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
113 const playerId = harness.simulation.spawnCharacter(1, character);
114 const record = harness.simulation.entityRecord(playerId);
115 const worker = harness.simulation.workers[record.workerId];
116 placeFurnace(worker, 9, 8);
117 giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);
118
119 harness.simulation.enqueue(1, {
120 type: "start-craft",
121 characterId: character.character_id,
122 stationId: CraftingStationId.furnace,
123 recipeId: "smelt-bronze"
124 });
125 const start = harness.simulation.step();
126 assert.ok(start.events.some((event) => event.type === "tile-shove"));
127 assert.ok(start.events.some((event) =>
128 event.type === "item-bubble" && event.itemId === ItemId.bronzeBar));
129
130 const smithingBefore = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
131 advanceMs(harness, CRAFT_DURATION_MS);
132
133 const bag = harness.simulation.bagOf(playerId);
134 assert.equal(countItem(bag.inventory, ItemId.bronzeOre), 0);
135 assert.equal(countItem(bag.inventory, ItemId.bronzeBar), 1);
136 const smithingAfter = harness.stateDb.getSkills(character.character_id).xp.smithing ?? 0;
137 assert.ok(smithingAfter > smithingBefore);
138 }
139 finally
140 { harness.close(); }
141});
142
143test("smelting steel requires iron ore and coal", () =>
144{
145 const harness = makeSimulation({ workerCount: 1 });
146 try
147 {
148 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
149 const playerId = harness.simulation.spawnCharacter(1, character);
150 const record = harness.simulation.entityRecord(playerId);
151 const worker = harness.simulation.workers[record.workerId];
152 placeFurnace(worker, 9, 8);
153 setSkillLevel(worker, playerId, SkillId.smithing, tierSmeltSkillLevel(MaterialTier.steel));
154 giveInventory(harness, playerId, [
155 { itemId: ItemId.ironOre, quantity: 1 },
156 { itemId: ItemId.coal, quantity: 1 }
157 ]);
158
159 harness.simulation.enqueue(1, {
160 type: "start-craft",
161 characterId: character.character_id,
162 stationId: CraftingStationId.furnace,
163 recipeId: "smelt-steel"
164 });
165 harness.simulation.step();
166 advanceMs(harness, CRAFT_DURATION_MS);
167
168 const bag = harness.simulation.bagOf(playerId);
169 assert.equal(countItem(bag.inventory, ItemId.ironOre), 0);
170 assert.equal(countItem(bag.inventory, ItemId.coal), 0);
171 assert.equal(countItem(bag.inventory, ItemId.steelBar), 1);
172 }
173 finally
174 { harness.close(); }
175});
176
177test("craft rejects missing materials", () =>
178{
179 const harness = makeSimulation({ workerCount: 1 });
180 try
181 {
182 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
183 const playerId = harness.simulation.spawnCharacter(1, character);
184 const record = harness.simulation.entityRecord(playerId);
185 const worker = harness.simulation.workers[record.workerId];
186 placeFurnace(worker, 9, 8);
187 giveInventory(harness, playerId, []);
188
189 harness.simulation.enqueue(1, {
190 type: "start-craft",
191 characterId: character.character_id,
192 stationId: CraftingStationId.furnace,
193 recipeId: "smelt-bronze"
194 });
195 const result = harness.simulation.step();
196 assert.ok(result.events.some((event) =>
197 event.type === "command-error" && /missing|materials/i.test(event.message ?? "")));
198 }
199 finally
200 { harness.close(); }
201});
202
203test("craft rejects low Smithing for iron bars", () =>
204{
205 const harness = makeSimulation({ workerCount: 1 });
206 try
207 {
208 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
209 const playerId = harness.simulation.spawnCharacter(1, character);
210 const record = harness.simulation.entityRecord(playerId);
211 const worker = harness.simulation.workers[record.workerId];
212 placeFurnace(worker, 9, 8);
213 giveInventory(harness, playerId, [{ itemId: ItemId.ironOre, quantity: 1 }]);
214
215 harness.simulation.enqueue(1, {
216 type: "start-craft",
217 characterId: character.character_id,
218 stationId: CraftingStationId.furnace,
219 recipeId: "smelt-iron"
220 });
221 const result = harness.simulation.step();
222 assert.ok(result.events.some((event) =>
223 event.type === "command-error" && /smithing|requires/i.test(event.message ?? "")));
224 }
225 finally
226 { harness.close(); }
227});
228
229test("craft rejects furnace recipes when not next to a furnace", () =>
230{
231 const harness = makeSimulation({ workerCount: 1 });
232 try
233 {
234 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
235 const playerId = harness.simulation.spawnCharacter(1, character);
236 giveInventory(harness, playerId, [{ itemId: ItemId.bronzeOre, quantity: 1 }]);
237
238 harness.simulation.enqueue(1, {
239 type: "start-craft",
240 characterId: character.character_id,
241 stationId: CraftingStationId.furnace,
242 recipeId: "smelt-bronze"
243 });
244 const result = harness.simulation.step();
245 assert.ok(result.events.some((event) =>
246 event.type === "command-error" && /station|next to/i.test(event.message ?? "")));
247 }
248 finally
249 { harness.close(); }
250});
server/tests/mining.test.js added +283 −0
@@ -0,0 +1,283 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 MaterialTier,
5 GatherMaterialId,
6 tierMinSkillLevel,
7 tierMineSkillLevel,
8 tierSmeltSkillLevel,
9 tierRank,
10 miningDurationMs,
11 oreExhaustDurationMs,
12 oreBoulderState,
13 materialFromOreBoulderState,
14 EXHAUSTED_ORE_BOULDER_STATE
15 } from "../../shared/definitions/materialTiers.js";
16 import {
17 canMineMaterial,
18 oreItemIdForMaterial
19 } from "../../shared/definitions/gathering.js";
20 import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
21 import { SkillId } from "../../shared/definitions/skills.js";
22 import { canEquipItem } from "../../shared/equipment/stats.js";
23 import { normalizePlayerSkills } from "../../shared/skills/state.js";
24 import { totalXpForLevel } from "../../shared/skills/progression.js";
25 import { BlockType, blockDefinition } from "../../shared/definitions/tiles.js";
26 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
27 import { Component } from "../src/ecs/components.js";
28
29 function countItem (slots, itemId)
30 {
31 return (slots ?? []).reduce((sum, slot) =>
32 {
33 if (slot?.itemId === itemId)
34 { return sum + (slot.quantity | 0); }
35 return sum;
36 }, 0);
37 }
38
39 function placeOre (worker, tileX, tileY, state)
40 {
41 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
42 const localX = tileX % 16;
43 const localY = tileY % 16;
44 const index = localY * 16 + localX;
45 data.blocks[index] = { typeId: BlockType.boulder, state, config: null };
46 return { data, index };
47 }
48
49 function equipPickaxe (worker, playerId, itemId)
50 {
51 const handle = worker.world.ecs.handleOf(playerId);
52 const equipment = worker.world.ecs.get(handle, Component.equipment);
53 equipment.slots[EQUIPMENT_SLOT.weapon] = { itemId, quantity: 1 };
54 }
55
56 function setSkillLevel (worker, playerId, skillId, level)
57 {
58 const handle = worker.world.ecs.handleOf(playerId);
59 const skills = worker.world.ecs.get(handle, Component.skills);
60 skills.xp[skillId] = totalXpForLevel(level);
61 }
62
63 function advanceMs (harness, ms)
64 {
65 const ticks = Math.ceil(ms / 50) + 3;
66 for (let i = 0; i < ticks; i++)
67 {
68 harness.advance(50);
69 harness.simulation.step();
70 }
71 }
72
73 test("tier skill gates: equip / mine / smelt", () =>
74 {
75 assert.equal(tierMinSkillLevel(MaterialTier.bronze), 1);
76 assert.equal(tierMinSkillLevel(MaterialTier.mithril), 35);
77 assert.equal(tierMinSkillLevel(MaterialTier.dragon), 90);
78 assert.equal(tierMineSkillLevel(MaterialTier.iron), 5);
79 assert.equal(tierMineSkillLevel(MaterialTier.mithril), 18);
80 assert.equal(tierSmeltSkillLevel(MaterialTier.iron), 8);
81 assert.equal(tierSmeltSkillLevel(MaterialTier.steel), 15);
82 assert.equal(tierRank(MaterialTier.dragon), 7);
83 });
84
85 test("mining duration uses resource and tool ranks", () =>
86 {
87 assert.equal(miningDurationMs(MaterialTier.bronze, MaterialTier.bronze), 5000);
88 assert.equal(miningDurationMs(MaterialTier.iron, MaterialTier.bronze), 13000);
89 assert.ok(miningDurationMs(MaterialTier.bronze, MaterialTier.dragon) >= 500);
90 });
91
92 test("ore exhaust duration is 10s times material rank", () =>
93 {
94 assert.equal(oreExhaustDurationMs(MaterialTier.bronze), 10_000);
95 assert.equal(oreExhaustDurationMs(MaterialTier.iron), 20_000);
96 assert.equal(oreExhaustDurationMs(GatherMaterialId.coal), 20_000);
97 assert.equal(oreExhaustDurationMs(MaterialTier.dragon), 70_000);
98 });
99
100 test("ore boulder states map to materials", () =>
101 {
102 assert.equal(materialFromOreBoulderState("bronze-ore"), MaterialTier.bronze);
103 assert.equal(materialFromOreBoulderState("coal"), GatherMaterialId.coal);
104 assert.equal(materialFromOreBoulderState("boulder"), null);
105 assert.equal(oreBoulderState(MaterialTier.mithril), "mithril-ore");
106 });
107
108 test("boulder block exists", () =>
109 {
110 assert.equal(blockDefinition(BlockType.boulder)?.key, "boulder");
111 });
112
113 test("iron pickaxe requires Mining 10", () =>
114 {
115 const skills = normalizePlayerSkills(null);
116 assert.equal(canEquipItem(skills, itemDefinition(ItemId.ironPickaxe)).ok, false);
117 skills.xp[SkillId.mining] = totalXpForLevel(10);
118 assert.equal(canEquipItem(skills, itemDefinition(ItemId.ironPickaxe)).ok, true);
119 assert.equal(canEquipItem(skills, itemDefinition(ItemId.bronzePickaxe)).ok, true);
120 });
121
122 test("canMineMaterial enforces skill and tool tier", () =>
123 {
124 assert.equal(canMineMaterial(1, MaterialTier.bronze, MaterialTier.iron).ok, false);
125 assert.equal(canMineMaterial(5, MaterialTier.bronze, MaterialTier.iron).ok, false);
126 assert.equal(canMineMaterial(5, MaterialTier.iron, MaterialTier.iron).ok, true);
127 });
128
129 test("mining without a pickaxe is rejected", () =>
130 {
131 const harness = makeSimulation({ workerCount: 1 });
132 try
133 {
134 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
135 const playerId = harness.simulation.spawnCharacter(1, character);
136 const record = harness.simulation.entityRecord(playerId);
137 const worker = harness.simulation.workers[record.workerId];
138 placeOre(worker, 9, 8, "bronze-ore");
139
140 harness.simulation.enqueue(1, {
141 type: "mine",
142 characterId: character.character_id,
143 tileX: 9,
144 tileY: 8
145 });
146 const result = harness.simulation.step();
147 assert.ok(result.events.some((event) =>
148 event.type === "command-error" && /pickaxe/i.test(event.message ?? "")));
149 }
150 finally
151 { harness.close(); }
152 });
153
154 test("plain boulder cannot be mined", () =>
155 {
156 const harness = makeSimulation({ workerCount: 1 });
157 try
158 {
159 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
160 const playerId = harness.simulation.spawnCharacter(1, character);
161 const record = harness.simulation.entityRecord(playerId);
162 const worker = harness.simulation.workers[record.workerId];
163 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
164 placeOre(worker, 9, 8, EXHAUSTED_ORE_BOULDER_STATE);
165
166 harness.simulation.enqueue(1, {
167 type: "mine",
168 characterId: character.character_id,
169 tileX: 9,
170 tileY: 8
171 });
172 const result = harness.simulation.step();
173 assert.ok(result.events.some((event) =>
174 event.type === "command-error"
175 && (/no ore|exhausted/i.test(event.message ?? ""))));
176 }
177 finally
178 { harness.close(); }
179 });
180
181 test("weak pickaxe cannot mine higher-tier ore", () =>
182 {
183 const harness = makeSimulation({ workerCount: 1 });
184 try
185 {
186 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
187 const playerId = harness.simulation.spawnCharacter(1, character);
188 const record = harness.simulation.entityRecord(playerId);
189 const worker = harness.simulation.workers[record.workerId];
190 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
191 setSkillLevel(worker, playerId, SkillId.mining, 10);
192 placeOre(worker, 9, 8, "iron-ore");
193
194 harness.simulation.enqueue(1, {
195 type: "mine",
196 characterId: character.character_id,
197 tileX: 9,
198 tileY: 8
199 });
200 const result = harness.simulation.step();
201 assert.ok(result.events.some((event) =>
202 event.type === "command-error" && /too weak|pickaxe/i.test(event.message ?? "")));
203 }
204 finally
205 { harness.close(); }
206 });
207
208 test("mining grants ore and Mining XP then exhausts and respawns the node", () =>
209 {
210 const harness = makeSimulation({ workerCount: 1 });
211 try
212 {
213 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
214 const playerId = harness.simulation.spawnCharacter(1, character);
215 const record = harness.simulation.entityRecord(playerId);
216 const worker = harness.simulation.workers[record.workerId];
217 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
218 const { data, index } = placeOre(worker, 9, 8, "bronze-ore");
219
220 harness.simulation.enqueue(1, {
221 type: "mine",
222 characterId: character.character_id,
223 tileX: 9,
224 tileY: 8
225 });
226 const start = harness.simulation.step();
227 assert.ok(start.events.some((event) => event.type === "gather-swing" || event.type === "tile-shove"));
228
229 advanceMs(harness, miningDurationMs(MaterialTier.bronze, MaterialTier.bronze));
230
231 const bag = harness.simulation.bagOf(playerId);
232 assert.ok(countItem(bag.inventory, ItemId.bronzeOre) >= 1);
233 const skills = harness.stateDb.getSkills(character.character_id);
234 assert.ok(skills.xp.mining > 0);
235 assert.equal(oreItemIdForMaterial(MaterialTier.bronze), ItemId.bronzeOre);
236 assert.equal(data.blocks[index].state, EXHAUSTED_ORE_BOULDER_STATE);
237
238 harness.simulation.enqueue(1, {
239 type: "mine",
240 characterId: character.character_id,
241 tileX: 9,
242 tileY: 8
243 });
244 const exhaustedResult = harness.simulation.step();
245 assert.ok(exhaustedResult.events.some((event) =>
246 event.type === "command-error" && /exhausted/i.test(event.message ?? "")));
247
248 advanceMs(harness, oreExhaustDurationMs(MaterialTier.bronze));
249 assert.equal(data.blocks[index].state, "bronze-ore");
250 }
251 finally
252 { harness.close(); }
253 });
254
255 test("coal mining yields coal and exhausts the node", () =>
256 {
257 const harness = makeSimulation({ workerCount: 1 });
258 try
259 {
260 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
261 const playerId = harness.simulation.spawnCharacter(1, character);
262 const record = harness.simulation.entityRecord(playerId);
263 const worker = harness.simulation.workers[record.workerId];
264 setSkillLevel(worker, playerId, SkillId.mining, 10);
265 equipPickaxe(worker, playerId, ItemId.ironPickaxe);
266 const { data, index } = placeOre(worker, 9, 8, "coal");
267
268 harness.simulation.enqueue(1, {
269 type: "mine",
270 characterId: character.character_id,
271 tileX: 9,
272 tileY: 8
273 });
274 harness.simulation.step();
275 advanceMs(harness, miningDurationMs(GatherMaterialId.coal, MaterialTier.iron));
276
277 const bag = harness.simulation.bagOf(playerId);
278 assert.ok(countItem(bag.inventory, ItemId.coal) >= 1);
279 assert.equal(data.blocks[index].state, EXHAUSTED_ORE_BOULDER_STATE);
280 }
281 finally
282 { harness.close(); }
283 });
@@ -0,0 +1,283 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 MaterialTier,
5 GatherMaterialId,
6 tierMinSkillLevel,
7 tierMineSkillLevel,
8 tierSmeltSkillLevel,
9 tierRank,
10 miningDurationMs,
11 oreExhaustDurationMs,
12 oreBoulderState,
13 materialFromOreBoulderState,
14 EXHAUSTED_ORE_BOULDER_STATE
15} from "../../shared/definitions/materialTiers.js";
16import {
17 canMineMaterial,
18 oreItemIdForMaterial
19} from "../../shared/definitions/gathering.js";
20import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
21import { SkillId } from "../../shared/definitions/skills.js";
22import { canEquipItem } from "../../shared/equipment/stats.js";
23import { normalizePlayerSkills } from "../../shared/skills/state.js";
24import { totalXpForLevel } from "../../shared/skills/progression.js";
25import { BlockType, blockDefinition } from "../../shared/definitions/tiles.js";
26import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
27import { Component } from "../src/ecs/components.js";
28
29function countItem (slots, itemId)
30{
31 return (slots ?? []).reduce((sum, slot) =>
32 {
33 if (slot?.itemId === itemId)
34 { return sum + (slot.quantity | 0); }
35 return sum;
36 }, 0);
37}
38
39function placeOre (worker, tileX, tileY, state)
40{
41 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
42 const localX = tileX % 16;
43 const localY = tileY % 16;
44 const index = localY * 16 + localX;
45 data.blocks[index] = { typeId: BlockType.boulder, state, config: null };
46 return { data, index };
47}
48
49function equipPickaxe (worker, playerId, itemId)
50{
51 const handle = worker.world.ecs.handleOf(playerId);
52 const equipment = worker.world.ecs.get(handle, Component.equipment);
53 equipment.slots[EQUIPMENT_SLOT.weapon] = { itemId, quantity: 1 };
54}
55
56function setSkillLevel (worker, playerId, skillId, level)
57{
58 const handle = worker.world.ecs.handleOf(playerId);
59 const skills = worker.world.ecs.get(handle, Component.skills);
60 skills.xp[skillId] = totalXpForLevel(level);
61}
62
63function advanceMs (harness, ms)
64{
65 const ticks = Math.ceil(ms / 50) + 3;
66 for (let i = 0; i < ticks; i++)
67 {
68 harness.advance(50);
69 harness.simulation.step();
70 }
71}
72
73test("tier skill gates: equip / mine / smelt", () =>
74{
75 assert.equal(tierMinSkillLevel(MaterialTier.bronze), 1);
76 assert.equal(tierMinSkillLevel(MaterialTier.mithril), 35);
77 assert.equal(tierMinSkillLevel(MaterialTier.dragon), 90);
78 assert.equal(tierMineSkillLevel(MaterialTier.iron), 5);
79 assert.equal(tierMineSkillLevel(MaterialTier.mithril), 18);
80 assert.equal(tierSmeltSkillLevel(MaterialTier.iron), 8);
81 assert.equal(tierSmeltSkillLevel(MaterialTier.steel), 15);
82 assert.equal(tierRank(MaterialTier.dragon), 7);
83});
84
85test("mining duration uses resource and tool ranks", () =>
86{
87 assert.equal(miningDurationMs(MaterialTier.bronze, MaterialTier.bronze), 5000);
88 assert.equal(miningDurationMs(MaterialTier.iron, MaterialTier.bronze), 13000);
89 assert.ok(miningDurationMs(MaterialTier.bronze, MaterialTier.dragon) >= 500);
90});
91
92test("ore exhaust duration is 10s times material rank", () =>
93{
94 assert.equal(oreExhaustDurationMs(MaterialTier.bronze), 10_000);
95 assert.equal(oreExhaustDurationMs(MaterialTier.iron), 20_000);
96 assert.equal(oreExhaustDurationMs(GatherMaterialId.coal), 20_000);
97 assert.equal(oreExhaustDurationMs(MaterialTier.dragon), 70_000);
98});
99
100test("ore boulder states map to materials", () =>
101{
102 assert.equal(materialFromOreBoulderState("bronze-ore"), MaterialTier.bronze);
103 assert.equal(materialFromOreBoulderState("coal"), GatherMaterialId.coal);
104 assert.equal(materialFromOreBoulderState("boulder"), null);
105 assert.equal(oreBoulderState(MaterialTier.mithril), "mithril-ore");
106});
107
108test("boulder block exists", () =>
109{
110 assert.equal(blockDefinition(BlockType.boulder)?.key, "boulder");
111});
112
113test("iron pickaxe requires Mining 10", () =>
114{
115 const skills = normalizePlayerSkills(null);
116 assert.equal(canEquipItem(skills, itemDefinition(ItemId.ironPickaxe)).ok, false);
117 skills.xp[SkillId.mining] = totalXpForLevel(10);
118 assert.equal(canEquipItem(skills, itemDefinition(ItemId.ironPickaxe)).ok, true);
119 assert.equal(canEquipItem(skills, itemDefinition(ItemId.bronzePickaxe)).ok, true);
120});
121
122test("canMineMaterial enforces skill and tool tier", () =>
123{
124 assert.equal(canMineMaterial(1, MaterialTier.bronze, MaterialTier.iron).ok, false);
125 assert.equal(canMineMaterial(5, MaterialTier.bronze, MaterialTier.iron).ok, false);
126 assert.equal(canMineMaterial(5, MaterialTier.iron, MaterialTier.iron).ok, true);
127});
128
129test("mining without a pickaxe is rejected", () =>
130{
131 const harness = makeSimulation({ workerCount: 1 });
132 try
133 {
134 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
135 const playerId = harness.simulation.spawnCharacter(1, character);
136 const record = harness.simulation.entityRecord(playerId);
137 const worker = harness.simulation.workers[record.workerId];
138 placeOre(worker, 9, 8, "bronze-ore");
139
140 harness.simulation.enqueue(1, {
141 type: "mine",
142 characterId: character.character_id,
143 tileX: 9,
144 tileY: 8
145 });
146 const result = harness.simulation.step();
147 assert.ok(result.events.some((event) =>
148 event.type === "command-error" && /pickaxe/i.test(event.message ?? "")));
149 }
150 finally
151 { harness.close(); }
152});
153
154test("plain boulder cannot be mined", () =>
155{
156 const harness = makeSimulation({ workerCount: 1 });
157 try
158 {
159 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
160 const playerId = harness.simulation.spawnCharacter(1, character);
161 const record = harness.simulation.entityRecord(playerId);
162 const worker = harness.simulation.workers[record.workerId];
163 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
164 placeOre(worker, 9, 8, EXHAUSTED_ORE_BOULDER_STATE);
165
166 harness.simulation.enqueue(1, {
167 type: "mine",
168 characterId: character.character_id,
169 tileX: 9,
170 tileY: 8
171 });
172 const result = harness.simulation.step();
173 assert.ok(result.events.some((event) =>
174 event.type === "command-error"
175 && (/no ore|exhausted/i.test(event.message ?? ""))));
176 }
177 finally
178 { harness.close(); }
179});
180
181test("weak pickaxe cannot mine higher-tier ore", () =>
182{
183 const harness = makeSimulation({ workerCount: 1 });
184 try
185 {
186 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
187 const playerId = harness.simulation.spawnCharacter(1, character);
188 const record = harness.simulation.entityRecord(playerId);
189 const worker = harness.simulation.workers[record.workerId];
190 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
191 setSkillLevel(worker, playerId, SkillId.mining, 10);
192 placeOre(worker, 9, 8, "iron-ore");
193
194 harness.simulation.enqueue(1, {
195 type: "mine",
196 characterId: character.character_id,
197 tileX: 9,
198 tileY: 8
199 });
200 const result = harness.simulation.step();
201 assert.ok(result.events.some((event) =>
202 event.type === "command-error" && /too weak|pickaxe/i.test(event.message ?? "")));
203 }
204 finally
205 { harness.close(); }
206});
207
208test("mining grants ore and Mining XP then exhausts and respawns the node", () =>
209{
210 const harness = makeSimulation({ workerCount: 1 });
211 try
212 {
213 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
214 const playerId = harness.simulation.spawnCharacter(1, character);
215 const record = harness.simulation.entityRecord(playerId);
216 const worker = harness.simulation.workers[record.workerId];
217 equipPickaxe(worker, playerId, ItemId.bronzePickaxe);
218 const { data, index } = placeOre(worker, 9, 8, "bronze-ore");
219
220 harness.simulation.enqueue(1, {
221 type: "mine",
222 characterId: character.character_id,
223 tileX: 9,
224 tileY: 8
225 });
226 const start = harness.simulation.step();
227 assert.ok(start.events.some((event) => event.type === "gather-swing" || event.type === "tile-shove"));
228
229 advanceMs(harness, miningDurationMs(MaterialTier.bronze, MaterialTier.bronze));
230
231 const bag = harness.simulation.bagOf(playerId);
232 assert.ok(countItem(bag.inventory, ItemId.bronzeOre) >= 1);
233 const skills = harness.stateDb.getSkills(character.character_id);
234 assert.ok(skills.xp.mining > 0);
235 assert.equal(oreItemIdForMaterial(MaterialTier.bronze), ItemId.bronzeOre);
236 assert.equal(data.blocks[index].state, EXHAUSTED_ORE_BOULDER_STATE);
237
238 harness.simulation.enqueue(1, {
239 type: "mine",
240 characterId: character.character_id,
241 tileX: 9,
242 tileY: 8
243 });
244 const exhaustedResult = harness.simulation.step();
245 assert.ok(exhaustedResult.events.some((event) =>
246 event.type === "command-error" && /exhausted/i.test(event.message ?? "")));
247
248 advanceMs(harness, oreExhaustDurationMs(MaterialTier.bronze));
249 assert.equal(data.blocks[index].state, "bronze-ore");
250 }
251 finally
252 { harness.close(); }
253});
254
255test("coal mining yields coal and exhausts the node", () =>
256{
257 const harness = makeSimulation({ workerCount: 1 });
258 try
259 {
260 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
261 const playerId = harness.simulation.spawnCharacter(1, character);
262 const record = harness.simulation.entityRecord(playerId);
263 const worker = harness.simulation.workers[record.workerId];
264 setSkillLevel(worker, playerId, SkillId.mining, 10);
265 equipPickaxe(worker, playerId, ItemId.ironPickaxe);
266 const { data, index } = placeOre(worker, 9, 8, "coal");
267
268 harness.simulation.enqueue(1, {
269 type: "mine",
270 characterId: character.character_id,
271 tileX: 9,
272 tileY: 8
273 });
274 harness.simulation.step();
275 advanceMs(harness, miningDurationMs(GatherMaterialId.coal, MaterialTier.iron));
276
277 const bag = harness.simulation.bagOf(playerId);
278 assert.ok(countItem(bag.inventory, ItemId.coal) >= 1);
279 assert.equal(data.blocks[index].state, EXHAUSTED_ORE_BOULDER_STATE);
280 }
281 finally
282 { harness.close(); }
283});
server/tests/skills.test.js +3 −1
@@ -28,8 +28,9 @@ test("enforceMinimumSkillLevels raises Health to 10 and leaves higher XP alone",
28 28 assert.equal(enforceMinimumSkillLevels(low), true);
29 29 assert.equal(skillLevel(low, SkillId.health), 10);
30 30 assert.equal(skillLevel(low, SkillId.strength), 1);
31 assert.equal(skillLevel(low, SkillId.stamina), 5);
31 32
32 const high = { xp: { health: totalXpForLevel(12), strength: totalXpForLevel(5) } };
33 const high = { xp: { health: totalXpForLevel(12), strength: totalXpForLevel(5), stamina: totalXpForLevel(5) } };
33 34 assert.equal(enforceMinimumSkillLevels(high), false);
34 35 assert.equal(skillLevel(high, SkillId.health), 12);
35 36 assert.equal(skillLevel(high, SkillId.strength), 5);
@@ -49,6 +50,7 @@ test("login floors under-minimum skills and persists them", () =>
49 50 assert.equal(skillLevel(stored, SkillId.health), 10);
50 51 assert.equal(skillLevel(stored, SkillId.strength), 1);
51 52 assert.equal(skillLevel(stored, SkillId.defence), 1);
53 assert.equal(skillLevel(stored, SkillId.stamina), 5);
52 54 }
53 55 finally
54 56 { harness.close(); }
@@ -28,8 +28,9 @@ test("enforceMinimumSkillLevels raises Health to 10 and leaves higher XP alone",
28 assert.equal(enforceMinimumSkillLevels(low), true);
28 assert.equal(enforceMinimumSkillLevels(low), true);
29 assert.equal(skillLevel(low, SkillId.health), 10);
29 assert.equal(skillLevel(low, SkillId.health), 10);
30 assert.equal(skillLevel(low, SkillId.strength), 1);
30 assert.equal(skillLevel(low, SkillId.strength), 1);
31 assert.equal(skillLevel(low, SkillId.stamina), 5);
31
32
32 const high = { xp: { health: totalXpForLevel(12), strength: totalXpForLevel(5) } };
33 const high = { xp: { health: totalXpForLevel(12), strength: totalXpForLevel(5), stamina: totalXpForLevel(5) } };
33 assert.equal(enforceMinimumSkillLevels(high), false);
34 assert.equal(enforceMinimumSkillLevels(high), false);
34 assert.equal(skillLevel(high, SkillId.health), 12);
35 assert.equal(skillLevel(high, SkillId.health), 12);
35 assert.equal(skillLevel(high, SkillId.strength), 5);
36 assert.equal(skillLevel(high, SkillId.strength), 5);
@@ -49,6 +50,7 @@ test("login floors under-minimum skills and persists them", () =>
49 assert.equal(skillLevel(stored, SkillId.health), 10);
50 assert.equal(skillLevel(stored, SkillId.health), 10);
50 assert.equal(skillLevel(stored, SkillId.strength), 1);
51 assert.equal(skillLevel(stored, SkillId.strength), 1);
51 assert.equal(skillLevel(stored, SkillId.defence), 1);
52 assert.equal(skillLevel(stored, SkillId.defence), 1);
53 assert.equal(skillLevel(stored, SkillId.stamina), 5);
52 }
54 }
53 finally
55 finally
54 { harness.close(); }
56 { harness.close(); }
server/tests/stamina.test.js added +164 −0
@@ -0,0 +1,164 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { GAIT } from "../../shared/protocol/constants.js";
4 import { SkillId, skillLevel } from "../../shared/definitions/skills.js";
5 import { totalXpForLevel } from "../../shared/skills/progression.js";
6 import {
7 staminaCostPerRunStep,
8 STAMINA_REGEN_PER_SECOND
9 } from "../../shared/stamina/rules.js";
10 import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
11
12 function workerOf (simulation, entityId)
13 {
14 const record = simulation.entityRecord(entityId);
15 assert.ok(record);
16 return simulation.workers[record.workerId];
17 }
18
19 function componentsOf (simulation, entityId)
20 {
21 const worker = workerOf(simulation, entityId);
22 const handle = worker.world.ecs.handleOf(entityId);
23 assert.ok(handle != null);
24 return worker.world.ecs.componentsOf(handle);
25 }
26
27 function setStaminaXp (harness, characterId, level)
28 {
29 const skills = harness.stateDb.getSkills(characterId);
30 skills.xp.stamina = totalXpForLevel(level);
31 harness.stateDb.saveSkills(characterId, skills);
32 }
33
34 test("staminaCostPerRunStep drains one point per second of continuous running", () =>
35 {
36 assert.equal(staminaCostPerRunStep(2), 0.25);
37 assert.equal(staminaCostPerRunStep(1), 0.5);
38 });
39
40 test("set-gait to run is rejected when stamina is empty", () =>
41 {
42 const harness = makeSimulation({ workerCount: 1 });
43 try
44 {
45 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
46 const playerId = harness.simulation.spawnCharacter(1, character);
47 const comps = componentsOf(harness.simulation, playerId);
48 comps.stamina.current = 0;
49
50 harness.simulation.enqueue(1, {
51 type: "set-gait",
52 characterId: character.character_id,
53 gait: GAIT.run
54 });
55 const result = harness.simulation.step();
56 assert.ok(result.events.some((event) =>
57 event.type === "command-error" && /exhausted/i.test(event.message)
58 ));
59 assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);
60 }
61 finally
62 { harness.close(); }
63 });
64
65 test("running drains stamina, awards XP, and forces walk at zero", () =>
66 {
67 const harness = makeSimulation({ workerCount: 1 });
68 try
69 {
70 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
71 setStaminaXp(harness, character.character_id, 6);
72 const playerId = harness.simulation.spawnCharacter(1, character);
73 assert.equal(harness.simulation.staminaOf(playerId).max, 6);
74 // Drain a short bar so the test finishes quickly.
75 componentsOf(harness.simulation, playerId).stamina.current = 2;
76
77 harness.simulation.enqueue(1, {
78 type: "set-gait",
79 characterId: character.character_id,
80 gait: GAIT.run
81 });
82 harness.simulation.enqueue(1, {
83 type: "move-to",
84 characterId: character.character_id,
85 tileX: 30,
86 tileY: 8
87 });
88
89 const xpBefore = harness.stateDb.getSkills(character.character_id).xp.stamina;
90 let forcedWalk = false;
91 for (let i = 0; i < 120; i++)
92 {
93 harness.advance(50);
94 const events = harness.simulation.step().events;
95 const stamina = harness.simulation.staminaOf(playerId);
96 if (events.some((event) => event.type === "stamina" && event.gait === GAIT.walk && event.current <= 0))
97 { forcedWalk = true; }
98 if (stamina.current <= 0)
99 {
100 assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);
101 forcedWalk = true;
102 break;
103 }
104 }
105 assert.equal(forcedWalk, true);
106 assert.ok(harness.simulation.staminaOf(playerId).current <= 0);
107 assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);
108
109 const xpAfter = harness.stateDb.getSkills(character.character_id).xp.stamina;
110 assert.ok(xpAfter > xpBefore, "running should award Stamina XP");
111 assert.equal(skillLevel({ xp: { stamina: xpAfter } }, SkillId.stamina) >= 6, true);
112 }
113 finally
114 { harness.close(); }
115 });
116
117 test("walking regenerates stamina over time", () =>
118 {
119 const harness = makeSimulation({ workerCount: 1 });
120 try
121 {
122 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
123 setStaminaXp(harness, character.character_id, 3);
124 const playerId = harness.simulation.spawnCharacter(1, character);
125 const comps = componentsOf(harness.simulation, playerId);
126 comps.stamina.current = 0;
127 comps.movement.gait = GAIT.walk;
128
129 const seconds = 2.2;
130 const ticks = Math.ceil(seconds * 20);
131 for (let i = 0; i < ticks; i++)
132 {
133 harness.advance(50);
134 harness.simulation.step();
135 }
136 const stamina = harness.simulation.staminaOf(playerId);
137 assert.ok(
138 stamina.current >= seconds * STAMINA_REGEN_PER_SECOND - 0.2,
139 `expected ~${seconds} regen, got ${stamina.current}`
140 );
141 assert.ok(stamina.current <= 3);
142 }
143 finally
144 { harness.close(); }
145 });
146
147 test("running does not regenerate stamina", () =>
148 {
149 const harness = makeSimulation({ workerCount: 1 });
150 try
151 {
152 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
153 setStaminaXp(harness, character.character_id, 5);
154 const playerId = harness.simulation.spawnCharacter(1, character);
155 const comps = componentsOf(harness.simulation, playerId);
156 comps.stamina.current = 2;
157 comps.movement.gait = GAIT.run;
158
159 stepTimes(harness.simulation, 40);
160 assert.ok(harness.simulation.staminaOf(playerId).current <= 2.01);
161 }
162 finally
163 { harness.close(); }
164 });
@@ -0,0 +1,164 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { GAIT } from "../../shared/protocol/constants.js";
4import { SkillId, skillLevel } from "../../shared/definitions/skills.js";
5import { totalXpForLevel } from "../../shared/skills/progression.js";
6import {
7 staminaCostPerRunStep,
8 STAMINA_REGEN_PER_SECOND
9} from "../../shared/stamina/rules.js";
10import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
11
12function workerOf (simulation, entityId)
13{
14 const record = simulation.entityRecord(entityId);
15 assert.ok(record);
16 return simulation.workers[record.workerId];
17}
18
19function componentsOf (simulation, entityId)
20{
21 const worker = workerOf(simulation, entityId);
22 const handle = worker.world.ecs.handleOf(entityId);
23 assert.ok(handle != null);
24 return worker.world.ecs.componentsOf(handle);
25}
26
27function setStaminaXp (harness, characterId, level)
28{
29 const skills = harness.stateDb.getSkills(characterId);
30 skills.xp.stamina = totalXpForLevel(level);
31 harness.stateDb.saveSkills(characterId, skills);
32}
33
34test("staminaCostPerRunStep drains one point per second of continuous running", () =>
35{
36 assert.equal(staminaCostPerRunStep(2), 0.25);
37 assert.equal(staminaCostPerRunStep(1), 0.5);
38});
39
40test("set-gait to run is rejected when stamina is empty", () =>
41{
42 const harness = makeSimulation({ workerCount: 1 });
43 try
44 {
45 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
46 const playerId = harness.simulation.spawnCharacter(1, character);
47 const comps = componentsOf(harness.simulation, playerId);
48 comps.stamina.current = 0;
49
50 harness.simulation.enqueue(1, {
51 type: "set-gait",
52 characterId: character.character_id,
53 gait: GAIT.run
54 });
55 const result = harness.simulation.step();
56 assert.ok(result.events.some((event) =>
57 event.type === "command-error" && /exhausted/i.test(event.message)
58 ));
59 assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);
60 }
61 finally
62 { harness.close(); }
63});
64
65test("running drains stamina, awards XP, and forces walk at zero", () =>
66{
67 const harness = makeSimulation({ workerCount: 1 });
68 try
69 {
70 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
71 setStaminaXp(harness, character.character_id, 6);
72 const playerId = harness.simulation.spawnCharacter(1, character);
73 assert.equal(harness.simulation.staminaOf(playerId).max, 6);
74 // Drain a short bar so the test finishes quickly.
75 componentsOf(harness.simulation, playerId).stamina.current = 2;
76
77 harness.simulation.enqueue(1, {
78 type: "set-gait",
79 characterId: character.character_id,
80 gait: GAIT.run
81 });
82 harness.simulation.enqueue(1, {
83 type: "move-to",
84 characterId: character.character_id,
85 tileX: 30,
86 tileY: 8
87 });
88
89 const xpBefore = harness.stateDb.getSkills(character.character_id).xp.stamina;
90 let forcedWalk = false;
91 for (let i = 0; i < 120; i++)
92 {
93 harness.advance(50);
94 const events = harness.simulation.step().events;
95 const stamina = harness.simulation.staminaOf(playerId);
96 if (events.some((event) => event.type === "stamina" && event.gait === GAIT.walk && event.current <= 0))
97 { forcedWalk = true; }
98 if (stamina.current <= 0)
99 {
100 assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);
101 forcedWalk = true;
102 break;
103 }
104 }
105 assert.equal(forcedWalk, true);
106 assert.ok(harness.simulation.staminaOf(playerId).current <= 0);
107 assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);
108
109 const xpAfter = harness.stateDb.getSkills(character.character_id).xp.stamina;
110 assert.ok(xpAfter > xpBefore, "running should award Stamina XP");
111 assert.equal(skillLevel({ xp: { stamina: xpAfter } }, SkillId.stamina) >= 6, true);
112 }
113 finally
114 { harness.close(); }
115});
116
117test("walking regenerates stamina over time", () =>
118{
119 const harness = makeSimulation({ workerCount: 1 });
120 try
121 {
122 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
123 setStaminaXp(harness, character.character_id, 3);
124 const playerId = harness.simulation.spawnCharacter(1, character);
125 const comps = componentsOf(harness.simulation, playerId);
126 comps.stamina.current = 0;
127 comps.movement.gait = GAIT.walk;
128
129 const seconds = 2.2;
130 const ticks = Math.ceil(seconds * 20);
131 for (let i = 0; i < ticks; i++)
132 {
133 harness.advance(50);
134 harness.simulation.step();
135 }
136 const stamina = harness.simulation.staminaOf(playerId);
137 assert.ok(
138 stamina.current >= seconds * STAMINA_REGEN_PER_SECOND - 0.2,
139 `expected ~${seconds} regen, got ${stamina.current}`
140 );
141 assert.ok(stamina.current <= 3);
142 }
143 finally
144 { harness.close(); }
145});
146
147test("running does not regenerate stamina", () =>
148{
149 const harness = makeSimulation({ workerCount: 1 });
150 try
151 {
152 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
153 setStaminaXp(harness, character.character_id, 5);
154 const playerId = harness.simulation.spawnCharacter(1, character);
155 const comps = componentsOf(harness.simulation, playerId);
156 comps.stamina.current = 2;
157 comps.movement.gait = GAIT.run;
158
159 stepTimes(harness.simulation, 40);
160 assert.ok(harness.simulation.staminaOf(playerId).current <= 2.01);
161 }
162 finally
163 { harness.close(); }
164});
shared/crafting/stationRecipes.js +39 −22
@@ -1,20 +1,34 @@
1 1 import { CraftingStationId } from "../definitions/craftingStations.js";
2 2 import { ItemId } from "../definitions/items.js";
3 import { CraftingItemId } from "../definitions/craftingItems.js";
4 import { MetalItemId } from "../definitions/metalItems.js";
5 import { MaterialTier, tierSmeltSkillLevel } from "../definitions/materialTiers.js";
3 6
4 7 /**
5 8 * Craft recipe schema (shared client + server):
6 9 *
7 10 * - recipeId: stable string id
8 * - stationId | stationIds: where the recipe appears (use stationIds for oven + campfire)
11 * - stationId | stationIds: where the recipe appears
9 12 * - output: { itemId, quantity }
10 13 * - inputs: [{ itemId, quantity }, ...]
11 14 * - minSkillLevel: minimum linked station skill (default 1)
12 * - burnChanceOven / burnChanceFireplace: cooking-only, 0–1 when skill is below min (TBD)
13 15 */
14 16
17 function smelt (tier, recipeId, inputs, outputItemId)
18 {
19 return Object.freeze({
20 recipeId,
21 stationId: CraftingStationId.furnace,
22 output: { itemId: outputItemId, quantity: 1 },
23 inputs,
24 minSkillLevel: tierSmeltSkillLevel(tier),
25 skillId: "smithing",
26 xpMaterial: tier
27 });
28 }
29
15 30 /** @type {ReadonlyArray<object>} */
16 31 export const CRAFT_RECIPES = Object.freeze([
17 // UI/dev placeholder — replace with real bench recipes.
18 32 Object.freeze({
19 33 recipeId: "dev-stick-from-paper",
20 34 stationId: CraftingStationId.craftingBench,
@@ -23,31 +37,34 @@ export const CRAFT_RECIPES = Object.freeze([
23 37 minSkillLevel: 1
24 38 }),
25 39
26 // --- Furnace (smelt ore → bars) ---
27 // { recipeId: "smelt-bronze", stationId: CraftingStationId.furnace, ... },
40 smelt(MaterialTier.bronze, "smelt-bronze", [
41 { itemId: CraftingItemId.bronzeOre, quantity: 1 }
42 ], CraftingItemId.bronzeBar),
28 43
29 // --- Spinning wheel (wool → thread) ---
30 // { recipeId: "spin-thread", stationId: CraftingStationId.spinningWheel, ... },
44 smelt(MaterialTier.iron, "smelt-iron", [
45 { itemId: MetalItemId.ironOre, quantity: 1 }
46 ], MetalItemId.ironBar),
31 47
32 // --- Loom (cloth garments) ---
33 // { recipeId: "weave-cloth-shirt", stationId: CraftingStationId.loom, ... },
48 smelt(MaterialTier.steel, "smelt-steel", [
49 { itemId: MetalItemId.ironOre, quantity: 1 },
50 { itemId: MetalItemId.coal, quantity: 1 }
51 ], MetalItemId.steelBar),
34 52
35 // --- Anvil (bars → metal items) ---
36 // { recipeId: "smith-bronze-sword", stationId: CraftingStationId.anvil, ... },
53 smelt(MaterialTier.mithril, "smelt-mithril", [
54 { itemId: MetalItemId.mithrilOre, quantity: 1 }
55 ], MetalItemId.mithrilBar),
37 56
38 // --- Leatherworking station ---
39 // { recipeId: "craft-leather-body", stationId: CraftingStationId.leatherworkingStation, ... },
57 smelt(MaterialTier.adamantium, "smelt-adamantium", [
58 { itemId: MetalItemId.adamantiumOre, quantity: 1 }
59 ], MetalItemId.adamantiumBar),
40 60
41 // --- Crafting bench (arrows, etc.) ---
42 // { recipeId: "fletch-arrow", stationId: CraftingStationId.craftingBench,
43 // output: { itemId: CraftingItemId.arrow, quantity: 1 },
44 // inputs: [{ itemId: CraftingItemId.arrowTip, quantity: 1 }, ...] },
61 smelt(MaterialTier.orichalcum, "smelt-orichalcum", [
62 { itemId: MetalItemId.orichalcumOre, quantity: 1 }
63 ], MetalItemId.orichalcumBar),
45 64
46 // --- Cooking (oven + campfire share recipes via stationIds) ---
47 // { recipeId: "cook-meat", stationIds: [CraftingStationId.oven, CraftingStationId.fireplace],
48 // output: { itemId: CraftingItemId.cookedMeat, quantity: 1 },
49 // inputs: [{ itemId: CraftingItemId.rawMeat, quantity: 1 }],
50 // minSkillLevel: 1, burnChanceOven: 0.1, burnChanceFireplace: 0.25 }
65 smelt(MaterialTier.dragon, "smelt-dragon", [
66 { itemId: MetalItemId.dragonOre, quantity: 1 }
67 ], MetalItemId.dragonBar)
51 68 ]);
52 69
53 70 const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
@@ -1,20 +1,34 @@
1import { CraftingStationId } from "../definitions/craftingStations.js";
1import { CraftingStationId } from "../definitions/craftingStations.js";
2import { ItemId } from "../definitions/items.js";
2import { ItemId } from "../definitions/items.js";
3import { CraftingItemId } from "../definitions/craftingItems.js";
4import { MetalItemId } from "../definitions/metalItems.js";
5import { MaterialTier, tierSmeltSkillLevel } from "../definitions/materialTiers.js";
3
6
4/**
7/**
5 * Craft recipe schema (shared client + server):
8 * Craft recipe schema (shared client + server):
6 *
9 *
7 * - recipeId: stable string id
10 * - recipeId: stable string id
8 * - stationId | stationIds: where the recipe appears (use stationIds for oven + campfire)
11 * - stationId | stationIds: where the recipe appears
9 * - output: { itemId, quantity }
12 * - output: { itemId, quantity }
10 * - inputs: [{ itemId, quantity }, ...]
13 * - inputs: [{ itemId, quantity }, ...]
11 * - minSkillLevel: minimum linked station skill (default 1)
14 * - minSkillLevel: minimum linked station skill (default 1)
12 * - burnChanceOven / burnChanceFireplace: cooking-only, 0–1 when skill is below min (TBD)
13 */
15 */
14
16
17function smelt (tier, recipeId, inputs, outputItemId)
18{
19 return Object.freeze({
20 recipeId,
21 stationId: CraftingStationId.furnace,
22 output: { itemId: outputItemId, quantity: 1 },
23 inputs,
24 minSkillLevel: tierSmeltSkillLevel(tier),
25 skillId: "smithing",
26 xpMaterial: tier
27 });
28}
29
15/** @type {ReadonlyArray<object>} */
30/** @type {ReadonlyArray<object>} */
16export const CRAFT_RECIPES = Object.freeze([
31export const CRAFT_RECIPES = Object.freeze([
17 // UI/dev placeholder — replace with real bench recipes.
18 Object.freeze({
32 Object.freeze({
19 recipeId: "dev-stick-from-paper",
33 recipeId: "dev-stick-from-paper",
20 stationId: CraftingStationId.craftingBench,
34 stationId: CraftingStationId.craftingBench,
@@ -23,31 +37,34 @@ export const CRAFT_RECIPES = Object.freeze([
23 minSkillLevel: 1
37 minSkillLevel: 1
24 }),
38 }),
25
39
26 // --- Furnace (smelt ore → bars) ---
40 smelt(MaterialTier.bronze, "smelt-bronze", [
27 // { recipeId: "smelt-bronze", stationId: CraftingStationId.furnace, ... },
41 { itemId: CraftingItemId.bronzeOre, quantity: 1 }
42 ], CraftingItemId.bronzeBar),
28
43
29 // --- Spinning wheel (wool → thread) ---
44 smelt(MaterialTier.iron, "smelt-iron", [
30 // { recipeId: "spin-thread", stationId: CraftingStationId.spinningWheel, ... },
45 { itemId: MetalItemId.ironOre, quantity: 1 }
46 ], MetalItemId.ironBar),
31
47
32 // --- Loom (cloth garments) ---
48 smelt(MaterialTier.steel, "smelt-steel", [
33 // { recipeId: "weave-cloth-shirt", stationId: CraftingStationId.loom, ... },
49 { itemId: MetalItemId.ironOre, quantity: 1 },
50 { itemId: MetalItemId.coal, quantity: 1 }
51 ], MetalItemId.steelBar),
34
52
35 // --- Anvil (bars → metal items) ---
53 smelt(MaterialTier.mithril, "smelt-mithril", [
36 // { recipeId: "smith-bronze-sword", stationId: CraftingStationId.anvil, ... },
54 { itemId: MetalItemId.mithrilOre, quantity: 1 }
55 ], MetalItemId.mithrilBar),
37
56
38 // --- Leatherworking station ---
57 smelt(MaterialTier.adamantium, "smelt-adamantium", [
39 // { recipeId: "craft-leather-body", stationId: CraftingStationId.leatherworkingStation, ... },
58 { itemId: MetalItemId.adamantiumOre, quantity: 1 }
59 ], MetalItemId.adamantiumBar),
40
60
41 // --- Crafting bench (arrows, etc.) ---
61 smelt(MaterialTier.orichalcum, "smelt-orichalcum", [
42 // { recipeId: "fletch-arrow", stationId: CraftingStationId.craftingBench,
62 { itemId: MetalItemId.orichalcumOre, quantity: 1 }
43 // output: { itemId: CraftingItemId.arrow, quantity: 1 },
63 ], MetalItemId.orichalcumBar),
44 // inputs: [{ itemId: CraftingItemId.arrowTip, quantity: 1 }, ...] },
45
64
46 // --- Cooking (oven + campfire share recipes via stationIds) ---
65 smelt(MaterialTier.dragon, "smelt-dragon", [
47 // { recipeId: "cook-meat", stationIds: [CraftingStationId.oven, CraftingStationId.fireplace],
66 { itemId: MetalItemId.dragonOre, quantity: 1 }
48 // output: { itemId: CraftingItemId.cookedMeat, quantity: 1 },
67 ], MetalItemId.dragonBar)
49 // inputs: [{ itemId: CraftingItemId.rawMeat, quantity: 1 }],
50 // minSkillLevel: 1, burnChanceOven: 0.1, burnChanceFireplace: 0.25 }
51]);
68]);
52
69
53const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
70const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
shared/definitions/craftingItems.js +31 −13
@@ -5,12 +5,8 @@ import { EquipmentKind } from "./equipmentKinds.js";
5 5 const DEFAULT_STACK = 99;
6 6
7 7 /**
8 * Reserved numeric IDs for gathering, crafting, and cooking content.
9 * Fill in full definitions in ITEM_DEFINITIONS (or replace these stubs) once
10 * tier rules, stack caps, equipment stats, and sprites are final.
11 *
12 * Tiered families (ore, bars, metal gear, leather, cloth, wizard cloth) should
13 * follow `{tier}-{kind}` keys — e.g. `iron-ore`, `steel-bar`, `mithril-sword`.
8 * Reserved numeric IDs for gathering, crafting, and cooking content (9–25).
9 * Metal ores/bars/pickaxes above bronze live in metalItems.js (35+).
14 10 */
15 11 export const CraftingItemId = Object.freeze({
16 12 log: 9,
@@ -66,15 +62,31 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
66 62 [CraftingItemId.thread]: stub(CraftingItemId.thread, "thread", "Thread", ItemCategory.intermediate, {
67 63 description: "Spun wool. Used at a loom."
68 64 }),
69 [CraftingItemId.bronzeOre]: stub(CraftingItemId.bronzeOre, "bronze-ore", "Bronze ore", ItemCategory.ingredient, {
65 [CraftingItemId.bronzeOre]: Object.freeze({
66 itemId: CraftingItemId.bronzeOre,
67 key: "bronze-ore",
68 displayName: "Bronze ore",
70 69 description: "Mined ore. Smelt at a furnace into bars.",
70 seedValue: 2,
71 stackable: true,
72 maxStackSize: DEFAULT_STACK,
73 uniqueInstance: false,
74 category: ItemCategory.ingredient,
71 75 iconKey: "ore",
72 76 defaultState: "ore",
73 77 tier: MaterialTier.bronze,
74 78 tintFromTier: true
75 79 }),
76 [CraftingItemId.bronzeBar]: stub(CraftingItemId.bronzeBar, "bronze-bar", "Bronze bar", ItemCategory.intermediate, {
80 [CraftingItemId.bronzeBar]: Object.freeze({
81 itemId: CraftingItemId.bronzeBar,
82 key: "bronze-bar",
83 displayName: "Bronze bar",
77 84 description: "Smelted metal. Smith at an anvil.",
85 seedValue: 4,
86 stackable: true,
87 maxStackSize: DEFAULT_STACK,
88 uniqueInstance: false,
89 category: ItemCategory.intermediate,
78 90 iconKey: "bar",
79 91 defaultState: "bar",
80 92 tier: MaterialTier.bronze,
@@ -98,7 +110,7 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
98 110 [CraftingItemId.bronzeAxe]: stub(CraftingItemId.bronzeAxe, "bronze-axe", "Bronze axe", ItemCategory.tool, {
99 111 stackable: false,
100 112 maxStackSize: 1,
101 description: "Woodcutting tool. Tier and min Woodcutting TBD.",
113 description: "Woodcutting tool.",
102 114 iconKey: "axe",
103 115 defaultState: "axe",
104 116 tintFromTier: true,
@@ -108,12 +120,18 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
108 120 kind: EquipmentKind.axeTool
109 121 })
110 122 }),
111 [CraftingItemId.bronzePickaxe]: stub(CraftingItemId.bronzePickaxe, "bronze-pickaxe", "Bronze pickaxe", ItemCategory.tool, {
123 [CraftingItemId.bronzePickaxe]: Object.freeze({
124 itemId: CraftingItemId.bronzePickaxe,
125 key: "bronze-pickaxe",
126 displayName: "Bronze pickaxe",
127 description: "Mining tool. Bronze may be equipped at any Mining level.",
128 seedValue: 8,
112 129 stackable: false,
113 130 maxStackSize: 1,
114 description: "Mining tool. Tier and min Mining TBD.",
115 iconKey: "axe",
116 defaultState: "axe",
131 uniqueInstance: false,
132 category: ItemCategory.tool,
133 iconKey: "pickaxe",
134 defaultState: "pickaxe",
117 135 tintFromTier: true,
118 136 equipment: Object.freeze({
119 137 slot: "weapon",
@@ -5,12 +5,8 @@ import { EquipmentKind } from "./equipmentKinds.js";
5const DEFAULT_STACK = 99;
5const DEFAULT_STACK = 99;
6
6
7/**
7/**
8 * Reserved numeric IDs for gathering, crafting, and cooking content.
8 * Reserved numeric IDs for gathering, crafting, and cooking content (9–25).
9 * Fill in full definitions in ITEM_DEFINITIONS (or replace these stubs) once
9 * Metal ores/bars/pickaxes above bronze live in metalItems.js (35+).
10 * tier rules, stack caps, equipment stats, and sprites are final.
11 *
12 * Tiered families (ore, bars, metal gear, leather, cloth, wizard cloth) should
13 * follow `{tier}-{kind}` keys — e.g. `iron-ore`, `steel-bar`, `mithril-sword`.
14 */
10 */
15export const CraftingItemId = Object.freeze({
11export const CraftingItemId = Object.freeze({
16 log: 9,
12 log: 9,
@@ -66,15 +62,31 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
66 [CraftingItemId.thread]: stub(CraftingItemId.thread, "thread", "Thread", ItemCategory.intermediate, {
62 [CraftingItemId.thread]: stub(CraftingItemId.thread, "thread", "Thread", ItemCategory.intermediate, {
67 description: "Spun wool. Used at a loom."
63 description: "Spun wool. Used at a loom."
68 }),
64 }),
69 [CraftingItemId.bronzeOre]: stub(CraftingItemId.bronzeOre, "bronze-ore", "Bronze ore", ItemCategory.ingredient, {
65 [CraftingItemId.bronzeOre]: Object.freeze({
66 itemId: CraftingItemId.bronzeOre,
67 key: "bronze-ore",
68 displayName: "Bronze ore",
70 description: "Mined ore. Smelt at a furnace into bars.",
69 description: "Mined ore. Smelt at a furnace into bars.",
70 seedValue: 2,
71 stackable: true,
72 maxStackSize: DEFAULT_STACK,
73 uniqueInstance: false,
74 category: ItemCategory.ingredient,
71 iconKey: "ore",
75 iconKey: "ore",
72 defaultState: "ore",
76 defaultState: "ore",
73 tier: MaterialTier.bronze,
77 tier: MaterialTier.bronze,
74 tintFromTier: true
78 tintFromTier: true
75 }),
79 }),
76 [CraftingItemId.bronzeBar]: stub(CraftingItemId.bronzeBar, "bronze-bar", "Bronze bar", ItemCategory.intermediate, {
80 [CraftingItemId.bronzeBar]: Object.freeze({
81 itemId: CraftingItemId.bronzeBar,
82 key: "bronze-bar",
83 displayName: "Bronze bar",
77 description: "Smelted metal. Smith at an anvil.",
84 description: "Smelted metal. Smith at an anvil.",
85 seedValue: 4,
86 stackable: true,
87 maxStackSize: DEFAULT_STACK,
88 uniqueInstance: false,
89 category: ItemCategory.intermediate,
78 iconKey: "bar",
90 iconKey: "bar",
79 defaultState: "bar",
91 defaultState: "bar",
80 tier: MaterialTier.bronze,
92 tier: MaterialTier.bronze,
@@ -98,7 +110,7 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
98 [CraftingItemId.bronzeAxe]: stub(CraftingItemId.bronzeAxe, "bronze-axe", "Bronze axe", ItemCategory.tool, {
110 [CraftingItemId.bronzeAxe]: stub(CraftingItemId.bronzeAxe, "bronze-axe", "Bronze axe", ItemCategory.tool, {
99 stackable: false,
111 stackable: false,
100 maxStackSize: 1,
112 maxStackSize: 1,
101 description: "Woodcutting tool. Tier and min Woodcutting TBD.",
113 description: "Woodcutting tool.",
102 iconKey: "axe",
114 iconKey: "axe",
103 defaultState: "axe",
115 defaultState: "axe",
104 tintFromTier: true,
116 tintFromTier: true,
@@ -108,12 +120,18 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
108 kind: EquipmentKind.axeTool
120 kind: EquipmentKind.axeTool
109 })
121 })
110 }),
122 }),
111 [CraftingItemId.bronzePickaxe]: stub(CraftingItemId.bronzePickaxe, "bronze-pickaxe", "Bronze pickaxe", ItemCategory.tool, {
123 [CraftingItemId.bronzePickaxe]: Object.freeze({
124 itemId: CraftingItemId.bronzePickaxe,
125 key: "bronze-pickaxe",
126 displayName: "Bronze pickaxe",
127 description: "Mining tool. Bronze may be equipped at any Mining level.",
128 seedValue: 8,
112 stackable: false,
129 stackable: false,
113 maxStackSize: 1,
130 maxStackSize: 1,
114 description: "Mining tool. Tier and min Mining TBD.",
131 uniqueInstance: false,
115 iconKey: "axe",
132 category: ItemCategory.tool,
116 defaultState: "axe",
133 iconKey: "pickaxe",
134 defaultState: "pickaxe",
117 tintFromTier: true,
135 tintFromTier: true,
118 equipment: Object.freeze({
136 equipment: Object.freeze({
119 slot: "weapon",
137 slot: "weapon",
shared/definitions/gathering.js added +98 −0
@@ -0,0 +1,98 @@
1 import { ItemId } from "./items.js";
2 import { CraftingItemId } from "./craftingItems.js";
3 import { MetalItemId } from "./metalItems.js";
4 import {
5 MaterialTier,
6 GatherMaterialId,
7 ORE_BEARING_MATERIALS,
8 tierMineSkillLevel,
9 tierSmeltSkillLevel,
10 tierRank,
11 miningDurationMs,
12 oreExhaustDurationMs,
13 EXHAUSTED_ORE_BOULDER_STATE,
14 oreBoulderState,
15 materialFromOreBoulderState,
16 isOreBoulderState
17 } from "./materialTiers.js";
18
19 export {
20 ORE_BEARING_MATERIALS,
21 tierMineSkillLevel,
22 tierSmeltSkillLevel,
23 miningDurationMs,
24 oreExhaustDurationMs,
25 EXHAUSTED_ORE_BOULDER_STATE,
26 oreBoulderState,
27 materialFromOreBoulderState,
28 isOreBoulderState
29 };
30
31 /** Ore item produced when mining a material node. */
32 export const ORE_ITEM_BY_MATERIAL = Object.freeze({
33 [MaterialTier.bronze]: CraftingItemId.bronzeOre,
34 [MaterialTier.iron]: MetalItemId.ironOre,
35 [MaterialTier.mithril]: MetalItemId.mithrilOre,
36 [MaterialTier.adamantium]: MetalItemId.adamantiumOre,
37 [MaterialTier.orichalcum]: MetalItemId.orichalcumOre,
38 [MaterialTier.dragon]: MetalItemId.dragonOre,
39 [GatherMaterialId.coal]: MetalItemId.coal
40 });
41
42 export const BAR_ITEM_BY_MATERIAL = Object.freeze({
43 [MaterialTier.bronze]: CraftingItemId.bronzeBar,
44 [MaterialTier.iron]: MetalItemId.ironBar,
45 [MaterialTier.steel]: MetalItemId.steelBar,
46 [MaterialTier.mithril]: MetalItemId.mithrilBar,
47 [MaterialTier.adamantium]: MetalItemId.adamantiumBar,
48 [MaterialTier.orichalcum]: MetalItemId.orichalcumBar,
49 [MaterialTier.dragon]: MetalItemId.dragonBar
50 });
51
52 export function oreItemIdForMaterial (materialId)
53 {
54 return ORE_ITEM_BY_MATERIAL[materialId] ?? null;
55 }
56
57 export function barItemIdForMaterial (materialId)
58 {
59 return BAR_ITEM_BY_MATERIAL[materialId] ?? null;
60 }
61
62 /** Mining XP awarded per successful ore (scales with resource rank). */
63 export function miningXpForMaterial (materialId)
64 {
65 return Math.max(1, tierRank(materialId) * 5);
66 }
67
68 /** Smithing XP awarded per successful smelt. */
69 export function smeltingXpForMaterial (materialId)
70 {
71 return Math.max(1, tierRank(materialId) * 5);
72 }
73
74 /** Coal uses iron's equip gate for mining skill / tool checks. */
75 export function gatherEquipTier (materialId)
76 {
77 if (materialId === GatherMaterialId.coal)
78 { return MaterialTier.iron; }
79 return materialId;
80 }
81
82 export function canMineMaterial (miningLevel, toolTier, materialId)
83 {
84 const gateTier = gatherEquipTier(materialId);
85 const needSkill = tierMineSkillLevel(gateTier);
86 if ((miningLevel | 0) < needSkill)
87 {
88 return { ok: false, reason: `Requires Mining ${needSkill}.` };
89 }
90 if (tierRank(toolTier) < tierRank(gateTier))
91 {
92 return { ok: false, reason: "Your pickaxe is too weak for this rock." };
93 }
94 return { ok: true };
95 }
96
97 /** Re-export ItemId helpers used by recipes. */
98 export { ItemId, MaterialTier, GatherMaterialId };
@@ -0,0 +1,98 @@
1import { ItemId } from "./items.js";
2import { CraftingItemId } from "./craftingItems.js";
3import { MetalItemId } from "./metalItems.js";
4import {
5 MaterialTier,
6 GatherMaterialId,
7 ORE_BEARING_MATERIALS,
8 tierMineSkillLevel,
9 tierSmeltSkillLevel,
10 tierRank,
11 miningDurationMs,
12 oreExhaustDurationMs,
13 EXHAUSTED_ORE_BOULDER_STATE,
14 oreBoulderState,
15 materialFromOreBoulderState,
16 isOreBoulderState
17} from "./materialTiers.js";
18
19export {
20 ORE_BEARING_MATERIALS,
21 tierMineSkillLevel,
22 tierSmeltSkillLevel,
23 miningDurationMs,
24 oreExhaustDurationMs,
25 EXHAUSTED_ORE_BOULDER_STATE,
26 oreBoulderState,
27 materialFromOreBoulderState,
28 isOreBoulderState
29};
30
31/** Ore item produced when mining a material node. */
32export const ORE_ITEM_BY_MATERIAL = Object.freeze({
33 [MaterialTier.bronze]: CraftingItemId.bronzeOre,
34 [MaterialTier.iron]: MetalItemId.ironOre,
35 [MaterialTier.mithril]: MetalItemId.mithrilOre,
36 [MaterialTier.adamantium]: MetalItemId.adamantiumOre,
37 [MaterialTier.orichalcum]: MetalItemId.orichalcumOre,
38 [MaterialTier.dragon]: MetalItemId.dragonOre,
39 [GatherMaterialId.coal]: MetalItemId.coal
40});
41
42export const BAR_ITEM_BY_MATERIAL = Object.freeze({
43 [MaterialTier.bronze]: CraftingItemId.bronzeBar,
44 [MaterialTier.iron]: MetalItemId.ironBar,
45 [MaterialTier.steel]: MetalItemId.steelBar,
46 [MaterialTier.mithril]: MetalItemId.mithrilBar,
47 [MaterialTier.adamantium]: MetalItemId.adamantiumBar,
48 [MaterialTier.orichalcum]: MetalItemId.orichalcumBar,
49 [MaterialTier.dragon]: MetalItemId.dragonBar
50});
51
52export function oreItemIdForMaterial (materialId)
53{
54 return ORE_ITEM_BY_MATERIAL[materialId] ?? null;
55}
56
57export function barItemIdForMaterial (materialId)
58{
59 return BAR_ITEM_BY_MATERIAL[materialId] ?? null;
60}
61
62/** Mining XP awarded per successful ore (scales with resource rank). */
63export function miningXpForMaterial (materialId)
64{
65 return Math.max(1, tierRank(materialId) * 5);
66}
67
68/** Smithing XP awarded per successful smelt. */
69export function smeltingXpForMaterial (materialId)
70{
71 return Math.max(1, tierRank(materialId) * 5);
72}
73
74/** Coal uses iron's equip gate for mining skill / tool checks. */
75export function gatherEquipTier (materialId)
76{
77 if (materialId === GatherMaterialId.coal)
78 { return MaterialTier.iron; }
79 return materialId;
80}
81
82export function canMineMaterial (miningLevel, toolTier, materialId)
83{
84 const gateTier = gatherEquipTier(materialId);
85 const needSkill = tierMineSkillLevel(gateTier);
86 if ((miningLevel | 0) < needSkill)
87 {
88 return { ok: false, reason: `Requires Mining ${needSkill}.` };
89 }
90 if (tierRank(toolTier) < tierRank(gateTier))
91 {
92 return { ok: false, reason: "Your pickaxe is too weak for this rock." };
93 }
94 return { ok: true };
95}
96
97/** Re-export ItemId helpers used by recipes. */
98export { ItemId, MaterialTier, GatherMaterialId };
shared/definitions/items.js +5 −2
@@ -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 { MetalItemId, METAL_ITEM_DEFINITIONS } from "./metalItems.js";
9 10 import { POTION_MAX_STACK } from "./alchemy.js";
10 11
11 12 export const ItemId = Object.freeze({
@@ -26,7 +27,8 @@ export const ItemId = Object.freeze({
26 27 redBeet: 31,
27 28 potion: 32,
28 29 recipePaper: 33,
29 bronzePlantClippers: 34
30 bronzePlantClippers: 34,
31 ...MetalItemId
30 32 });
31 33
32 34 export const EQUIPMENT_SLOT = Object.freeze({
@@ -288,7 +290,8 @@ export const ITEM_DEFINITIONS = Object.freeze({
288 290 tintFromTier: true
289 291 })
290 292 }),
291 ...CRAFTING_ITEM_STUBS
293 ...CRAFTING_ITEM_STUBS,
294 ...METAL_ITEM_DEFINITIONS
292 295 });
293 296
294 297 export function itemDefinition (itemId)
@@ -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 { MetalItemId, METAL_ITEM_DEFINITIONS } from "./metalItems.js";
9import { POTION_MAX_STACK } from "./alchemy.js";
10import { POTION_MAX_STACK } from "./alchemy.js";
10
11
11export const ItemId = Object.freeze({
12export const ItemId = Object.freeze({
@@ -26,7 +27,8 @@ export const ItemId = Object.freeze({
26 redBeet: 31,
27 redBeet: 31,
27 potion: 32,
28 potion: 32,
28 recipePaper: 33,
29 recipePaper: 33,
29 bronzePlantClippers: 34
30 bronzePlantClippers: 34,
31 ...MetalItemId
30});
32});
31
33
32export const EQUIPMENT_SLOT = Object.freeze({
34export const EQUIPMENT_SLOT = Object.freeze({
@@ -288,7 +290,8 @@ export const ITEM_DEFINITIONS = Object.freeze({
288 tintFromTier: true
290 tintFromTier: true
289 })
291 })
290 }),
292 }),
291 ...CRAFTING_ITEM_STUBS
293 ...CRAFTING_ITEM_STUBS,
294 ...METAL_ITEM_DEFINITIONS
292});
295});
293
296
294export function itemDefinition (itemId)
297export function itemDefinition (itemId)
shared/definitions/materialTiers.js +148 −8
@@ -1,30 +1,55 @@
1 /** Material tiers from lowest to highest. Bronze has no skill gate beyond level 1. */
1 /**
2 * Metal materials (and coal) — name, tint, rank, and skill gates.
3 * Equip min level is the tier gate; mining = half (ceil), smelting = 75% (ceil).
4 */
2 5 export const MaterialTier = Object.freeze({
3 6 bronze: "bronze",
4 7 iron: "iron",
5 8 steel: "steel",
6 9 mithril: "mithril",
7 10 adamantium: "adamantium",
8 orichalcum: "orichalcum"
11 orichalcum: "orichalcum",
12 dragon: "dragon"
9 13 });
10 14
15 /** Ordered low → high (metal smithing / tools). */
11 16 export const MATERIAL_TIER_ORDER = Object.freeze([
12 17 MaterialTier.bronze,
13 18 MaterialTier.iron,
14 19 MaterialTier.steel,
15 20 MaterialTier.mithril,
16 21 MaterialTier.adamantium,
17 MaterialTier.orichalcum
22 MaterialTier.orichalcum,
23 MaterialTier.dragon
18 24 ]);
19 25
20 /** Minimum relevant skill level required to equip (bronze always 1). */
26 /** Non-metal gatherable that shares ore-boulder art (dark gray tint). */
27 export const GatherMaterialId = Object.freeze({
28 ...MaterialTier,
29 coal: "coal"
30 });
31
32 /** Minimum relevant skill level required to equip tools/gear of this tier. */
21 33 export const TIER_MIN_SKILL_LEVEL = Object.freeze({
22 34 [MaterialTier.bronze]: 1,
23 35 [MaterialTier.iron]: 10,
24 36 [MaterialTier.steel]: 20,
25 [MaterialTier.mithril]: 30,
26 [MaterialTier.adamantium]: 40,
27 [MaterialTier.orichalcum]: 50
37 [MaterialTier.mithril]: 35,
38 [MaterialTier.adamantium]: 50,
39 [MaterialTier.orichalcum]: 70,
40 [MaterialTier.dragon]: 90
41 });
42
43 /** Rank used for mining duration and relative power (1 = bronze … 7 = dragon). */
44 export const TIER_RANK = Object.freeze({
45 [MaterialTier.bronze]: 1,
46 [MaterialTier.iron]: 2,
47 [MaterialTier.steel]: 3,
48 [MaterialTier.mithril]: 4,
49 [MaterialTier.adamantium]: 5,
50 [MaterialTier.orichalcum]: 6,
51 [MaterialTier.dragon]: 7,
52 [GatherMaterialId.coal]: 2
28 53 });
29 54
30 55 /** Stat bonus granted by tier for the equipment's bonus category. */
@@ -34,9 +59,47 @@ export const TIER_STAT_BONUS = Object.freeze({
34 59 [MaterialTier.steel]: 4,
35 60 [MaterialTier.mithril]: 6,
36 61 [MaterialTier.adamantium]: 8,
37 [MaterialTier.orichalcum]: 10
62 [MaterialTier.orichalcum]: 10,
63 [MaterialTier.dragon]: 12
38 64 });
39 65
66 /** Display names for UI / editor. */
67 export const MATERIAL_DISPLAY_NAME = Object.freeze({
68 [MaterialTier.bronze]: "Bronze",
69 [MaterialTier.iron]: "Iron",
70 [MaterialTier.steel]: "Steel",
71 [MaterialTier.mithril]: "Mithril",
72 [MaterialTier.adamantium]: "Adamantium",
73 [MaterialTier.orichalcum]: "Orichalcum",
74 [MaterialTier.dragon]: "Dragon",
75 [GatherMaterialId.coal]: "Coal"
76 });
77
78 /**
79 * Display tint colors (0–1 RGB) for magenta-tinted sprites.
80 * Steel is slightly darker than iron; orichalcum is coppery-gold; dragon is red.
81 */
82 export const MATERIAL_TINT_COLOR = Object.freeze({
83 [MaterialTier.bronze]: Object.freeze({ r: 0.72, g: 0.48, b: 0.28 }),
84 [MaterialTier.iron]: Object.freeze({ r: 0.62, g: 0.64, b: 0.68 }),
85 [MaterialTier.steel]: Object.freeze({ r: 0.48, g: 0.50, b: 0.54 }),
86 [MaterialTier.mithril]: Object.freeze({ r: 0.40, g: 0.55, b: 0.88 }),
87 [MaterialTier.adamantium]: Object.freeze({ r: 0.35, g: 0.75, b: 0.45 }),
88 [MaterialTier.orichalcum]: Object.freeze({ r: 0.90, g: 0.55, b: 0.22 }),
89 [MaterialTier.dragon]: Object.freeze({ r: 0.88, g: 0.18, b: 0.16 }),
90 [GatherMaterialId.coal]: Object.freeze({ r: 0.22, g: 0.22, b: 0.25 })
91 });
92
93 export function materialDisplayName (materialId)
94 {
95 return MATERIAL_DISPLAY_NAME[materialId] ?? materialId;
96 }
97
98 export function materialTintColor (materialId)
99 {
100 return MATERIAL_TINT_COLOR[materialId] ?? MATERIAL_TINT_COLOR[MaterialTier.bronze];
101 }
102
40 103 export function tierStatBonus (tier)
41 104 {
42 105 return TIER_STAT_BONUS[tier] ?? TIER_STAT_BONUS[MaterialTier.bronze];
@@ -46,3 +109,80 @@ export function tierMinSkillLevel (tier)
46 109 {
47 110 return TIER_MIN_SKILL_LEVEL[tier] ?? TIER_MIN_SKILL_LEVEL[MaterialTier.bronze];
48 111 }
112
113 export function tierRank (tier)
114 {
115 return TIER_RANK[tier] ?? 1;
116 }
117
118 /** Mining skill required to mine this material's ore (half of equip gate, ceil). */
119 export function tierMineSkillLevel (tier)
120 {
121 return Math.max(1, Math.ceil(tierMinSkillLevel(tier) / 2));
122 }
123
124 /** Smithing skill required to smelt this metal (75% of equip gate, ceil). */
125 export function tierSmeltSkillLevel (tier)
126 {
127 return Math.max(1, Math.ceil(tierMinSkillLevel(tier) * 0.75));
128 }
129
130 /**
131 * Mining action duration in ms.
132 * (resourceRank * 8s) − (toolRank * 3s), floored at 0.5s.
133 */
134 export function miningDurationMs (resourceMaterialId, toolTier)
135 {
136 const resourceRank = tierRank(resourceMaterialId);
137 const toolRank = tierRank(toolTier);
138 const seconds = Math.max(0.5, resourceRank * 8 - toolRank * 3);
139 return Math.round(seconds * 1000);
140 }
141
142 /** After a successful mine, nodes stay exhausted for 10s × material rank. */
143 export function oreExhaustDurationMs (materialId)
144 {
145 return Math.max(1, tierRank(materialId)) * 10_000;
146 }
147
148 /** Visual / interact state while an ore boulder is depleted (plain rock). */
149 export const EXHAUSTED_ORE_BOULDER_STATE = "boulder";
150
151 /** Metals that have an ore node (steel is smelted from iron + coal). */
152 export const ORE_BEARING_MATERIALS = Object.freeze([
153 MaterialTier.bronze,
154 MaterialTier.iron,
155 MaterialTier.mithril,
156 MaterialTier.adamantium,
157 MaterialTier.orichalcum,
158 MaterialTier.dragon,
159 GatherMaterialId.coal
160 ]);
161
162 /** Boulder visual state for a gatherable ore (editor / world). */
163 export function oreBoulderState (materialId)
164 {
165 if (materialId === GatherMaterialId.coal)
166 { return "coal"; }
167 return `${materialId}-ore`;
168 }
169
170 export function materialFromOreBoulderState (state)
171 {
172 if (!state || state === "boulder")
173 { return null; }
174 if (state === "coal")
175 { return GatherMaterialId.coal; }
176 if (state.endsWith("-ore"))
177 {
178 const id = state.slice(0, -"-ore".length);
179 if (ORE_BEARING_MATERIALS.includes(id))
180 { return id; }
181 }
182 return null;
183 }
184
185 export function isOreBoulderState (state)
186 {
187 return materialFromOreBoulderState(state) != null;
188 }
@@ -1,30 +1,55 @@
1/** Material tiers from lowest to highest. Bronze has no skill gate beyond level 1. */
1/**
2 * Metal materials (and coal) — name, tint, rank, and skill gates.
3 * Equip min level is the tier gate; mining = half (ceil), smelting = 75% (ceil).
4 */
2export const MaterialTier = Object.freeze({
5export const MaterialTier = Object.freeze({
3 bronze: "bronze",
6 bronze: "bronze",
4 iron: "iron",
7 iron: "iron",
5 steel: "steel",
8 steel: "steel",
6 mithril: "mithril",
9 mithril: "mithril",
7 adamantium: "adamantium",
10 adamantium: "adamantium",
8 orichalcum: "orichalcum"
11 orichalcum: "orichalcum",
12 dragon: "dragon"
9});
13});
10
14
15/** Ordered low → high (metal smithing / tools). */
11export const MATERIAL_TIER_ORDER = Object.freeze([
16export const MATERIAL_TIER_ORDER = Object.freeze([
12 MaterialTier.bronze,
17 MaterialTier.bronze,
13 MaterialTier.iron,
18 MaterialTier.iron,
14 MaterialTier.steel,
19 MaterialTier.steel,
15 MaterialTier.mithril,
20 MaterialTier.mithril,
16 MaterialTier.adamantium,
21 MaterialTier.adamantium,
17 MaterialTier.orichalcum
22 MaterialTier.orichalcum,
23 MaterialTier.dragon
18]);
24]);
19
25
20/** Minimum relevant skill level required to equip (bronze always 1). */
26/** Non-metal gatherable that shares ore-boulder art (dark gray tint). */
27export const GatherMaterialId = Object.freeze({
28 ...MaterialTier,
29 coal: "coal"
30});
31
32/** Minimum relevant skill level required to equip tools/gear of this tier. */
21export const TIER_MIN_SKILL_LEVEL = Object.freeze({
33export const TIER_MIN_SKILL_LEVEL = Object.freeze({
22 [MaterialTier.bronze]: 1,
34 [MaterialTier.bronze]: 1,
23 [MaterialTier.iron]: 10,
35 [MaterialTier.iron]: 10,
24 [MaterialTier.steel]: 20,
36 [MaterialTier.steel]: 20,
25 [MaterialTier.mithril]: 30,
37 [MaterialTier.mithril]: 35,
26 [MaterialTier.adamantium]: 40,
38 [MaterialTier.adamantium]: 50,
27 [MaterialTier.orichalcum]: 50
39 [MaterialTier.orichalcum]: 70,
40 [MaterialTier.dragon]: 90
41});
42
43/** Rank used for mining duration and relative power (1 = bronze … 7 = dragon). */
44export const TIER_RANK = Object.freeze({
45 [MaterialTier.bronze]: 1,
46 [MaterialTier.iron]: 2,
47 [MaterialTier.steel]: 3,
48 [MaterialTier.mithril]: 4,
49 [MaterialTier.adamantium]: 5,
50 [MaterialTier.orichalcum]: 6,
51 [MaterialTier.dragon]: 7,
52 [GatherMaterialId.coal]: 2
28});
53});
29
54
30/** Stat bonus granted by tier for the equipment's bonus category. */
55/** Stat bonus granted by tier for the equipment's bonus category. */
@@ -34,9 +59,47 @@ export const TIER_STAT_BONUS = Object.freeze({
34 [MaterialTier.steel]: 4,
59 [MaterialTier.steel]: 4,
35 [MaterialTier.mithril]: 6,
60 [MaterialTier.mithril]: 6,
36 [MaterialTier.adamantium]: 8,
61 [MaterialTier.adamantium]: 8,
37 [MaterialTier.orichalcum]: 10
62 [MaterialTier.orichalcum]: 10,
63 [MaterialTier.dragon]: 12
38});
64});
39
65
66/** Display names for UI / editor. */
67export const MATERIAL_DISPLAY_NAME = Object.freeze({
68 [MaterialTier.bronze]: "Bronze",
69 [MaterialTier.iron]: "Iron",
70 [MaterialTier.steel]: "Steel",
71 [MaterialTier.mithril]: "Mithril",
72 [MaterialTier.adamantium]: "Adamantium",
73 [MaterialTier.orichalcum]: "Orichalcum",
74 [MaterialTier.dragon]: "Dragon",
75 [GatherMaterialId.coal]: "Coal"
76});
77
78/**
79 * Display tint colors (0–1 RGB) for magenta-tinted sprites.
80 * Steel is slightly darker than iron; orichalcum is coppery-gold; dragon is red.
81 */
82export const MATERIAL_TINT_COLOR = Object.freeze({
83 [MaterialTier.bronze]: Object.freeze({ r: 0.72, g: 0.48, b: 0.28 }),
84 [MaterialTier.iron]: Object.freeze({ r: 0.62, g: 0.64, b: 0.68 }),
85 [MaterialTier.steel]: Object.freeze({ r: 0.48, g: 0.50, b: 0.54 }),
86 [MaterialTier.mithril]: Object.freeze({ r: 0.40, g: 0.55, b: 0.88 }),
87 [MaterialTier.adamantium]: Object.freeze({ r: 0.35, g: 0.75, b: 0.45 }),
88 [MaterialTier.orichalcum]: Object.freeze({ r: 0.90, g: 0.55, b: 0.22 }),
89 [MaterialTier.dragon]: Object.freeze({ r: 0.88, g: 0.18, b: 0.16 }),
90 [GatherMaterialId.coal]: Object.freeze({ r: 0.22, g: 0.22, b: 0.25 })
91});
92
93export function materialDisplayName (materialId)
94{
95 return MATERIAL_DISPLAY_NAME[materialId] ?? materialId;
96}
97
98export function materialTintColor (materialId)
99{
100 return MATERIAL_TINT_COLOR[materialId] ?? MATERIAL_TINT_COLOR[MaterialTier.bronze];
101}
102
40export function tierStatBonus (tier)
103export function tierStatBonus (tier)
41{
104{
42 return TIER_STAT_BONUS[tier] ?? TIER_STAT_BONUS[MaterialTier.bronze];
105 return TIER_STAT_BONUS[tier] ?? TIER_STAT_BONUS[MaterialTier.bronze];
@@ -46,3 +109,80 @@ export function tierMinSkillLevel (tier)
46{
109{
47 return TIER_MIN_SKILL_LEVEL[tier] ?? TIER_MIN_SKILL_LEVEL[MaterialTier.bronze];
110 return TIER_MIN_SKILL_LEVEL[tier] ?? TIER_MIN_SKILL_LEVEL[MaterialTier.bronze];
48}
111}
112
113export function tierRank (tier)
114{
115 return TIER_RANK[tier] ?? 1;
116}
117
118/** Mining skill required to mine this material's ore (half of equip gate, ceil). */
119export function tierMineSkillLevel (tier)
120{
121 return Math.max(1, Math.ceil(tierMinSkillLevel(tier) / 2));
122}
123
124/** Smithing skill required to smelt this metal (75% of equip gate, ceil). */
125export function tierSmeltSkillLevel (tier)
126{
127 return Math.max(1, Math.ceil(tierMinSkillLevel(tier) * 0.75));
128}
129
130/**
131 * Mining action duration in ms.
132 * (resourceRank * 8s) − (toolRank * 3s), floored at 0.5s.
133 */
134export function miningDurationMs (resourceMaterialId, toolTier)
135{
136 const resourceRank = tierRank(resourceMaterialId);
137 const toolRank = tierRank(toolTier);
138 const seconds = Math.max(0.5, resourceRank * 8 - toolRank * 3);
139 return Math.round(seconds * 1000);
140}
141
142/** After a successful mine, nodes stay exhausted for 10s × material rank. */
143export function oreExhaustDurationMs (materialId)
144{
145 return Math.max(1, tierRank(materialId)) * 10_000;
146}
147
148/** Visual / interact state while an ore boulder is depleted (plain rock). */
149export const EXHAUSTED_ORE_BOULDER_STATE = "boulder";
150
151/** Metals that have an ore node (steel is smelted from iron + coal). */
152export const ORE_BEARING_MATERIALS = Object.freeze([
153 MaterialTier.bronze,
154 MaterialTier.iron,
155 MaterialTier.mithril,
156 MaterialTier.adamantium,
157 MaterialTier.orichalcum,
158 MaterialTier.dragon,
159 GatherMaterialId.coal
160]);
161
162/** Boulder visual state for a gatherable ore (editor / world). */
163export function oreBoulderState (materialId)
164{
165 if (materialId === GatherMaterialId.coal)
166 { return "coal"; }
167 return `${materialId}-ore`;
168}
169
170export function materialFromOreBoulderState (state)
171{
172 if (!state || state === "boulder")
173 { return null; }
174 if (state === "coal")
175 { return GatherMaterialId.coal; }
176 if (state.endsWith("-ore"))
177 {
178 const id = state.slice(0, -"-ore".length);
179 if (ORE_BEARING_MATERIALS.includes(id))
180 { return id; }
181 }
182 return null;
183}
184
185export function isOreBoulderState (state)
186{
187 return materialFromOreBoulderState(state) != null;
188}
shared/definitions/metalItems.js added +134 −0
@@ -0,0 +1,134 @@
1 import { ItemCategory } from "./itemCategories.js";
2 import {
3 MaterialTier,
4 GatherMaterialId,
5 MATERIAL_DISPLAY_NAME
6 } from "./materialTiers.js";
7 import { EquipmentKind } from "./equipmentKinds.js";
8
9 /**
10 * Metal ores, bars, pickaxes, and coal.
11 * Shared magenta base sprites: iconKey ore / bar / pickaxe.
12 */
13 export const MetalItemId = Object.freeze({
14 coal: 35,
15 ironOre: 36,
16 ironBar: 37,
17 ironPickaxe: 38,
18 steelBar: 39,
19 steelPickaxe: 40,
20 mithrilOre: 41,
21 mithrilBar: 42,
22 mithrilPickaxe: 43,
23 adamantiumOre: 44,
24 adamantiumBar: 45,
25 adamantiumPickaxe: 46,
26 orichalcumOre: 47,
27 orichalcumBar: 48,
28 orichalcumPickaxe: 49,
29 dragonOre: 50,
30 dragonBar: 51,
31 dragonPickaxe: 52
32 });
33
34 const DEFAULT_STACK = 99;
35
36 function oreDef (itemId, tier, key)
37 {
38 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
39 return Object.freeze({
40 itemId,
41 key,
42 displayName: `${name} ore`,
43 description: `Mined ${name.toLowerCase()} ore. Smelt at a furnace.`,
44 seedValue: 2,
45 stackable: true,
46 maxStackSize: DEFAULT_STACK,
47 uniqueInstance: false,
48 category: ItemCategory.ingredient,
49 iconKey: "ore",
50 defaultState: "ore",
51 tier,
52 tintFromTier: true
53 });
54 }
55
56 function barDef (itemId, tier, key)
57 {
58 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
59 return Object.freeze({
60 itemId,
61 key,
62 displayName: `${name} bar`,
63 description: `Smelted ${name.toLowerCase()}. Smith at an anvil.`,
64 seedValue: 4,
65 stackable: true,
66 maxStackSize: DEFAULT_STACK,
67 uniqueInstance: false,
68 category: ItemCategory.intermediate,
69 iconKey: "bar",
70 defaultState: "bar",
71 tier,
72 tintFromTier: true
73 });
74 }
75
76 function pickaxeDef (itemId, tier, key)
77 {
78 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
79 return Object.freeze({
80 itemId,
81 key,
82 displayName: `${name} pickaxe`,
83 description: `Mining tool (${name}).`,
84 seedValue: 8,
85 stackable: false,
86 maxStackSize: 1,
87 uniqueInstance: false,
88 category: ItemCategory.tool,
89 iconKey: "pickaxe",
90 defaultState: "pickaxe",
91 tintFromTier: true,
92 equipment: Object.freeze({
93 slot: "weapon",
94 tier,
95 kind: EquipmentKind.pickaxeTool
96 })
97 });
98 }
99
100 /** Full defs for metal family (merged into ITEM_DEFINITIONS). */
101 export const METAL_ITEM_DEFINITIONS = Object.freeze({
102 [MetalItemId.coal]: Object.freeze({
103 itemId: MetalItemId.coal,
104 key: "coal",
105 displayName: "Coal",
106 description: "Fuel for steel smelting. Mined from coal boulders.",
107 seedValue: 2,
108 stackable: true,
109 maxStackSize: DEFAULT_STACK,
110 uniqueInstance: false,
111 category: ItemCategory.ingredient,
112 iconKey: "ore",
113 defaultState: "ore",
114 tier: GatherMaterialId.coal,
115 tintFromTier: true
116 }),
117 [MetalItemId.ironOre]: oreDef(MetalItemId.ironOre, MaterialTier.iron, "iron-ore"),
118 [MetalItemId.ironBar]: barDef(MetalItemId.ironBar, MaterialTier.iron, "iron-bar"),
119 [MetalItemId.ironPickaxe]: pickaxeDef(MetalItemId.ironPickaxe, MaterialTier.iron, "iron-pickaxe"),
120 [MetalItemId.steelBar]: barDef(MetalItemId.steelBar, MaterialTier.steel, "steel-bar"),
121 [MetalItemId.steelPickaxe]: pickaxeDef(MetalItemId.steelPickaxe, MaterialTier.steel, "steel-pickaxe"),
122 [MetalItemId.mithrilOre]: oreDef(MetalItemId.mithrilOre, MaterialTier.mithril, "mithril-ore"),
123 [MetalItemId.mithrilBar]: barDef(MetalItemId.mithrilBar, MaterialTier.mithril, "mithril-bar"),
124 [MetalItemId.mithrilPickaxe]: pickaxeDef(MetalItemId.mithrilPickaxe, MaterialTier.mithril, "mithril-pickaxe"),
125 [MetalItemId.adamantiumOre]: oreDef(MetalItemId.adamantiumOre, MaterialTier.adamantium, "adamantium-ore"),
126 [MetalItemId.adamantiumBar]: barDef(MetalItemId.adamantiumBar, MaterialTier.adamantium, "adamantium-bar"),
127 [MetalItemId.adamantiumPickaxe]: pickaxeDef(MetalItemId.adamantiumPickaxe, MaterialTier.adamantium, "adamantium-pickaxe"),
128 [MetalItemId.orichalcumOre]: oreDef(MetalItemId.orichalcumOre, MaterialTier.orichalcum, "orichalcum-ore"),
129 [MetalItemId.orichalcumBar]: barDef(MetalItemId.orichalcumBar, MaterialTier.orichalcum, "orichalcum-bar"),
130 [MetalItemId.orichalcumPickaxe]: pickaxeDef(MetalItemId.orichalcumPickaxe, MaterialTier.orichalcum, "orichalcum-pickaxe"),
131 [MetalItemId.dragonOre]: oreDef(MetalItemId.dragonOre, MaterialTier.dragon, "dragon-ore"),
132 [MetalItemId.dragonBar]: barDef(MetalItemId.dragonBar, MaterialTier.dragon, "dragon-bar"),
133 [MetalItemId.dragonPickaxe]: pickaxeDef(MetalItemId.dragonPickaxe, MaterialTier.dragon, "dragon-pickaxe")
134 });
@@ -0,0 +1,134 @@
1import { ItemCategory } from "./itemCategories.js";
2import {
3 MaterialTier,
4 GatherMaterialId,
5 MATERIAL_DISPLAY_NAME
6} from "./materialTiers.js";
7import { EquipmentKind } from "./equipmentKinds.js";
8
9/**
10 * Metal ores, bars, pickaxes, and coal.
11 * Shared magenta base sprites: iconKey ore / bar / pickaxe.
12 */
13export const MetalItemId = Object.freeze({
14 coal: 35,
15 ironOre: 36,
16 ironBar: 37,
17 ironPickaxe: 38,
18 steelBar: 39,
19 steelPickaxe: 40,
20 mithrilOre: 41,
21 mithrilBar: 42,
22 mithrilPickaxe: 43,
23 adamantiumOre: 44,
24 adamantiumBar: 45,
25 adamantiumPickaxe: 46,
26 orichalcumOre: 47,
27 orichalcumBar: 48,
28 orichalcumPickaxe: 49,
29 dragonOre: 50,
30 dragonBar: 51,
31 dragonPickaxe: 52
32});
33
34const DEFAULT_STACK = 99;
35
36function oreDef (itemId, tier, key)
37{
38 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
39 return Object.freeze({
40 itemId,
41 key,
42 displayName: `${name} ore`,
43 description: `Mined ${name.toLowerCase()} ore. Smelt at a furnace.`,
44 seedValue: 2,
45 stackable: true,
46 maxStackSize: DEFAULT_STACK,
47 uniqueInstance: false,
48 category: ItemCategory.ingredient,
49 iconKey: "ore",
50 defaultState: "ore",
51 tier,
52 tintFromTier: true
53 });
54}
55
56function barDef (itemId, tier, key)
57{
58 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
59 return Object.freeze({
60 itemId,
61 key,
62 displayName: `${name} bar`,
63 description: `Smelted ${name.toLowerCase()}. Smith at an anvil.`,
64 seedValue: 4,
65 stackable: true,
66 maxStackSize: DEFAULT_STACK,
67 uniqueInstance: false,
68 category: ItemCategory.intermediate,
69 iconKey: "bar",
70 defaultState: "bar",
71 tier,
72 tintFromTier: true
73 });
74}
75
76function pickaxeDef (itemId, tier, key)
77{
78 const name = MATERIAL_DISPLAY_NAME[tier] ?? tier;
79 return Object.freeze({
80 itemId,
81 key,
82 displayName: `${name} pickaxe`,
83 description: `Mining tool (${name}).`,
84 seedValue: 8,
85 stackable: false,
86 maxStackSize: 1,
87 uniqueInstance: false,
88 category: ItemCategory.tool,
89 iconKey: "pickaxe",
90 defaultState: "pickaxe",
91 tintFromTier: true,
92 equipment: Object.freeze({
93 slot: "weapon",
94 tier,
95 kind: EquipmentKind.pickaxeTool
96 })
97 });
98}
99
100/** Full defs for metal family (merged into ITEM_DEFINITIONS). */
101export const METAL_ITEM_DEFINITIONS = Object.freeze({
102 [MetalItemId.coal]: Object.freeze({
103 itemId: MetalItemId.coal,
104 key: "coal",
105 displayName: "Coal",
106 description: "Fuel for steel smelting. Mined from coal boulders.",
107 seedValue: 2,
108 stackable: true,
109 maxStackSize: DEFAULT_STACK,
110 uniqueInstance: false,
111 category: ItemCategory.ingredient,
112 iconKey: "ore",
113 defaultState: "ore",
114 tier: GatherMaterialId.coal,
115 tintFromTier: true
116 }),
117 [MetalItemId.ironOre]: oreDef(MetalItemId.ironOre, MaterialTier.iron, "iron-ore"),
118 [MetalItemId.ironBar]: barDef(MetalItemId.ironBar, MaterialTier.iron, "iron-bar"),
119 [MetalItemId.ironPickaxe]: pickaxeDef(MetalItemId.ironPickaxe, MaterialTier.iron, "iron-pickaxe"),
120 [MetalItemId.steelBar]: barDef(MetalItemId.steelBar, MaterialTier.steel, "steel-bar"),
121 [MetalItemId.steelPickaxe]: pickaxeDef(MetalItemId.steelPickaxe, MaterialTier.steel, "steel-pickaxe"),
122 [MetalItemId.mithrilOre]: oreDef(MetalItemId.mithrilOre, MaterialTier.mithril, "mithril-ore"),
123 [MetalItemId.mithrilBar]: barDef(MetalItemId.mithrilBar, MaterialTier.mithril, "mithril-bar"),
124 [MetalItemId.mithrilPickaxe]: pickaxeDef(MetalItemId.mithrilPickaxe, MaterialTier.mithril, "mithril-pickaxe"),
125 [MetalItemId.adamantiumOre]: oreDef(MetalItemId.adamantiumOre, MaterialTier.adamantium, "adamantium-ore"),
126 [MetalItemId.adamantiumBar]: barDef(MetalItemId.adamantiumBar, MaterialTier.adamantium, "adamantium-bar"),
127 [MetalItemId.adamantiumPickaxe]: pickaxeDef(MetalItemId.adamantiumPickaxe, MaterialTier.adamantium, "adamantium-pickaxe"),
128 [MetalItemId.orichalcumOre]: oreDef(MetalItemId.orichalcumOre, MaterialTier.orichalcum, "orichalcum-ore"),
129 [MetalItemId.orichalcumBar]: barDef(MetalItemId.orichalcumBar, MaterialTier.orichalcum, "orichalcum-bar"),
130 [MetalItemId.orichalcumPickaxe]: pickaxeDef(MetalItemId.orichalcumPickaxe, MaterialTier.orichalcum, "orichalcum-pickaxe"),
131 [MetalItemId.dragonOre]: oreDef(MetalItemId.dragonOre, MaterialTier.dragon, "dragon-ore"),
132 [MetalItemId.dragonBar]: barDef(MetalItemId.dragonBar, MaterialTier.dragon, "dragon-bar"),
133 [MetalItemId.dragonPickaxe]: pickaxeDef(MetalItemId.dragonPickaxe, MaterialTier.dragon, "dragon-pickaxe")
134});
shared/definitions/skills.js +8 −1
@@ -75,7 +75,14 @@ export const SKILL_DEFINITIONS = Object.freeze({
75 75 });
76 76
77 77 export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze(Object.fromEntries(
78 ALL_SKILL_IDS.map((skillId) => [skillId, skillId === SkillId.health ? 10 : 1])
78 ALL_SKILL_IDS.map((skillId) =>
79 {
80 if (skillId === SkillId.health)
81 { return [skillId, 10]; }
82 if (skillId === SkillId.stamina)
83 { return [skillId, 5]; }
84 return [skillId, 1];
85 })
79 86 ));
80 87
81 88 export const UNARMED_ATTACK = Object.freeze({
@@ -75,7 +75,14 @@ export const SKILL_DEFINITIONS = Object.freeze({
75});
75});
76
76
77export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze(Object.fromEntries(
77export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze(Object.fromEntries(
78 ALL_SKILL_IDS.map((skillId) => [skillId, skillId === SkillId.health ? 10 : 1])
78 ALL_SKILL_IDS.map((skillId) =>
79 {
80 if (skillId === SkillId.health)
81 { return [skillId, 10]; }
82 if (skillId === SkillId.stamina)
83 { return [skillId, 5]; }
84 return [skillId, 1];
85 })
79));
86));
80
87
81export const UNARMED_ATTACK = Object.freeze({
88export const UNARMED_ATTACK = Object.freeze({
shared/definitions/tiles.js +81 −1
@@ -1,3 +1,10 @@
1 import {
2 ORE_BEARING_MATERIALS,
3 oreBoulderState,
4 MATERIAL_DISPLAY_NAME
5 } from "./materialTiers.js";
6 import { spriteImageName, resolveState } from "./tileSprites.js";
7
1 8 export const GroundType = Object.freeze({
2 9 grass: 1,
3 10 wood: 2,
@@ -12,7 +19,9 @@ export const BlockType = Object.freeze({
12 19 spawner: 3,
13 20 bank: 4,
14 21 churchAltar: 5,
15 cauldron: 6
22 cauldron: 6,
23 boulder: 7,
24 furnace: 8
16 25 });
17 26
18 27 export const GROUND_DEFINITIONS = Object.freeze({
@@ -124,6 +133,29 @@ export const BLOCK_DEFINITIONS = Object.freeze({
124 133 frames: 1,
125 134 framesPerRow: 1,
126 135 animationSpeed: 0
136 }),
137 [BlockType.boulder]: Object.freeze({
138 id: BlockType.boulder,
139 key: "boulder",
140 displayName: "Boulder",
141 passable: false,
142 lightRangeTiles: 0,
143 frames: 1,
144 framesPerRow: 1,
145 animationSpeed: 0,
146 /** Ore states are synthesized in the sprite catalog (tinted boulder-ore). */
147 gatherable: true
148 }),
149 [BlockType.furnace]: Object.freeze({
150 id: BlockType.furnace,
151 key: "furnace",
152 displayName: "Furnace",
153 passable: false,
154 lightRangeTiles: 0,
155 frames: 1,
156 framesPerRow: 1,
157 animationSpeed: 0,
158 craftingStationId: "furnace"
127 159 })
128 160 });
129 161
@@ -138,6 +170,54 @@ export function listPlaceableBlocks ()
138 170 return Object.values(BLOCK_DEFINITIONS).filter((def) => !def.editorHidden);
139 171 }
140 172
173 /**
174 * Editor palette cards: one entry per placeable, with boulder expanded into
175 * plain rock + each ore/coal variant (shared BlockType, distinct state).
176 */
177 export function listPlaceableBlockPaletteEntries (catalog = null)
178 {
179 const entries = [];
180 for (const def of listPlaceableBlocks())
181 {
182 if (def.id === BlockType.boulder)
183 {
184 entries.push({
185 typeId: def.id,
186 state: "boulder",
187 key: def.key,
188 displayName: "Boulder",
189 spriteName: spriteImageName("block", def.key, "boulder")
190 });
191 for (const material of ORE_BEARING_MATERIALS)
192 {
193 const state = oreBoulderState(material);
194 const label = MATERIAL_DISPLAY_NAME[material] ?? material;
195 const isCoal = material === "coal";
196 entries.push({
197 typeId: def.id,
198 state,
199 key: def.key,
200 displayName: isCoal ? "Coal boulder" : `${label} ore boulder`,
201 spriteName: spriteImageName("block", def.key, state)
202 });
203 }
204 continue;
205 }
206 const states = catalog?.blocks?.[def.key]?.states ?? [];
207 const state = resolveState(states, null);
208 entries.push({
209 typeId: def.id,
210 state,
211 key: def.key,
212 displayName: def.displayName,
213 spriteName: state
214 ? spriteImageName("block", def.key, state)
215 : spriteImageName("block", def.key, def.key)
216 });
217 }
218 return entries;
219 }
220
141 221 export function groundDefinition (typeId)
142 222 {
143 223 return GROUND_DEFINITIONS[typeId] ?? null;
@@ -1,3 +1,10 @@
1import {
2 ORE_BEARING_MATERIALS,
3 oreBoulderState,
4 MATERIAL_DISPLAY_NAME
5} from "./materialTiers.js";
6import { spriteImageName, resolveState } from "./tileSprites.js";
7
1export const GroundType = Object.freeze({
8export const GroundType = Object.freeze({
2 grass: 1,
9 grass: 1,
3 wood: 2,
10 wood: 2,
@@ -12,7 +19,9 @@ export const BlockType = Object.freeze({
12 spawner: 3,
19 spawner: 3,
13 bank: 4,
20 bank: 4,
14 churchAltar: 5,
21 churchAltar: 5,
15 cauldron: 6
22 cauldron: 6,
23 boulder: 7,
24 furnace: 8
16});
25});
17
26
18export const GROUND_DEFINITIONS = Object.freeze({
27export const GROUND_DEFINITIONS = Object.freeze({
@@ -124,6 +133,29 @@ export const BLOCK_DEFINITIONS = Object.freeze({
124 frames: 1,
133 frames: 1,
125 framesPerRow: 1,
134 framesPerRow: 1,
126 animationSpeed: 0
135 animationSpeed: 0
136 }),
137 [BlockType.boulder]: Object.freeze({
138 id: BlockType.boulder,
139 key: "boulder",
140 displayName: "Boulder",
141 passable: false,
142 lightRangeTiles: 0,
143 frames: 1,
144 framesPerRow: 1,
145 animationSpeed: 0,
146 /** Ore states are synthesized in the sprite catalog (tinted boulder-ore). */
147 gatherable: true
148 }),
149 [BlockType.furnace]: Object.freeze({
150 id: BlockType.furnace,
151 key: "furnace",
152 displayName: "Furnace",
153 passable: false,
154 lightRangeTiles: 0,
155 frames: 1,
156 framesPerRow: 1,
157 animationSpeed: 0,
158 craftingStationId: "furnace"
127 })
159 })
128});
160});
129
161
@@ -138,6 +170,54 @@ export function listPlaceableBlocks ()
138 return Object.values(BLOCK_DEFINITIONS).filter((def) => !def.editorHidden);
170 return Object.values(BLOCK_DEFINITIONS).filter((def) => !def.editorHidden);
139}
171}
140
172
173/**
174 * Editor palette cards: one entry per placeable, with boulder expanded into
175 * plain rock + each ore/coal variant (shared BlockType, distinct state).
176 */
177export function listPlaceableBlockPaletteEntries (catalog = null)
178{
179 const entries = [];
180 for (const def of listPlaceableBlocks())
181 {
182 if (def.id === BlockType.boulder)
183 {
184 entries.push({
185 typeId: def.id,
186 state: "boulder",
187 key: def.key,
188 displayName: "Boulder",
189 spriteName: spriteImageName("block", def.key, "boulder")
190 });
191 for (const material of ORE_BEARING_MATERIALS)
192 {
193 const state = oreBoulderState(material);
194 const label = MATERIAL_DISPLAY_NAME[material] ?? material;
195 const isCoal = material === "coal";
196 entries.push({
197 typeId: def.id,
198 state,
199 key: def.key,
200 displayName: isCoal ? "Coal boulder" : `${label} ore boulder`,
201 spriteName: spriteImageName("block", def.key, state)
202 });
203 }
204 continue;
205 }
206 const states = catalog?.blocks?.[def.key]?.states ?? [];
207 const state = resolveState(states, null);
208 entries.push({
209 typeId: def.id,
210 state,
211 key: def.key,
212 displayName: def.displayName,
213 spriteName: state
214 ? spriteImageName("block", def.key, state)
215 : spriteImageName("block", def.key, def.key)
216 });
217 }
218 return entries;
219}
220
141export function groundDefinition (typeId)
221export function groundDefinition (typeId)
142{
222{
143 return GROUND_DEFINITIONS[typeId] ?? null;
223 return GROUND_DEFINITIONS[typeId] ?? null;
shared/protocol/constants.js +10 −1
@@ -130,6 +130,7 @@ export const MessageType = Object.freeze({
130 130 editLetter: "EDIT_LETTER",
131 131 openLetter: "OPEN_LETTER",
132 132 skills: "SKILLS",
133 stamina: "STAMINA",
133 134 eatItem: "EAT_ITEM",
134 135 startCraft: "START_CRAFT",
135 136 cancelCraft: "CANCEL_CRAFT",
@@ -142,6 +143,14 @@ export const MessageType = Object.freeze({
142 143 cauldronBottle: "CAULDRON_BOTTLE",
143 144 cauldronClear: "CAULDRON_CLEAR",
144 145 cauldronSaveRecipe: "CAULDRON_SAVE_RECIPE",
145 cauldronClose: "CAULDRON_CLOSE"
146 cauldronClose: "CAULDRON_CLOSE",
147 mine: "MINE",
148 cancelGather: "CANCEL_GATHER",
149 gatherSwing: "GATHER_SWING",
150 gatherComplete: "GATHER_COMPLETE",
151 openFurnace: "OPEN_FURNACE",
152 stationOpen: "STATION_OPEN",
153 tileShove: "TILE_SHOVE",
154 itemBubble: "ITEM_BUBBLE"
146 155 });
147 156
@@ -130,6 +130,7 @@ export const MessageType = Object.freeze({
130 editLetter: "EDIT_LETTER",
130 editLetter: "EDIT_LETTER",
131 openLetter: "OPEN_LETTER",
131 openLetter: "OPEN_LETTER",
132 skills: "SKILLS",
132 skills: "SKILLS",
133 stamina: "STAMINA",
133 eatItem: "EAT_ITEM",
134 eatItem: "EAT_ITEM",
134 startCraft: "START_CRAFT",
135 startCraft: "START_CRAFT",
135 cancelCraft: "CANCEL_CRAFT",
136 cancelCraft: "CANCEL_CRAFT",
@@ -142,6 +143,14 @@ export const MessageType = Object.freeze({
142 cauldronBottle: "CAULDRON_BOTTLE",
143 cauldronBottle: "CAULDRON_BOTTLE",
143 cauldronClear: "CAULDRON_CLEAR",
144 cauldronClear: "CAULDRON_CLEAR",
144 cauldronSaveRecipe: "CAULDRON_SAVE_RECIPE",
145 cauldronSaveRecipe: "CAULDRON_SAVE_RECIPE",
145 cauldronClose: "CAULDRON_CLOSE"
146 cauldronClose: "CAULDRON_CLOSE",
147 mine: "MINE",
148 cancelGather: "CANCEL_GATHER",
149 gatherSwing: "GATHER_SWING",
150 gatherComplete: "GATHER_COMPLETE",
151 openFurnace: "OPEN_FURNACE",
152 stationOpen: "STATION_OPEN",
153 tileShove: "TILE_SHOVE",
154 itemBubble: "ITEM_BUBBLE"
146});
155});
147
156
shared/render/tint.js +6 −11
@@ -1,4 +1,4 @@
1 import { MaterialTier, MATERIAL_TIER_ORDER } from "../definitions/materialTiers.js";
1 import { MaterialTier, MATERIAL_TIER_ORDER, MATERIAL_TINT_COLOR, GatherMaterialId } from "../definitions/materialTiers.js";
2 2 import { itemDefinition } from "../definitions/items.js";
3 3
4 4 /**
@@ -11,15 +11,8 @@ import { itemDefinition } from "../definitions/items.js";
11 11
12 12 export const MAGENTA_CHANNEL_EPS = 1 / 255;
13 13
14 /** Display tint colors per material tier (0–1 RGB). */
15 export const TIER_TINT_COLOR = Object.freeze({
16 [MaterialTier.bronze]: Object.freeze({ r: 0.72, g: 0.48, b: 0.28 }),
17 [MaterialTier.iron]: Object.freeze({ r: 0.62, g: 0.64, b: 0.68 }),
18 [MaterialTier.steel]: Object.freeze({ r: 0.78, g: 0.80, b: 0.84 }),
19 [MaterialTier.mithril]: Object.freeze({ r: 0.45, g: 0.55, b: 0.85 }),
20 [MaterialTier.adamantium]: Object.freeze({ r: 0.35, g: 0.75, b: 0.45 }),
21 [MaterialTier.orichalcum]: Object.freeze({ r: 0.85, g: 0.35, b: 0.55 })
22 });
14 /** @deprecated Prefer MATERIAL_TINT_COLOR — kept as alias for call sites. */
15 export const TIER_TINT_COLOR = MATERIAL_TINT_COLOR;
23 16
24 17 export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
25 18 {
@@ -34,7 +27,7 @@ export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
34 27
35 28 export function tierTintColor (tier)
36 29 {
37 return normalizeRgb(TIER_TINT_COLOR[tier] ?? TIER_TINT_COLOR[MaterialTier.bronze]);
30 return normalizeRgb(MATERIAL_TINT_COLOR[tier] ?? MATERIAL_TINT_COLOR[MaterialTier.bronze]);
38 31 }
39 32
40 33 /**
@@ -132,6 +125,8 @@ export function listTierTintPreview ()
132 125 return MATERIAL_TIER_ORDER.map((tier) => ({ tier, color: tierTintColor(tier) }));
133 126 }
134 127
128 export { GatherMaterialId };
129
135 130 function clamp01 (n)
136 131 {
137 132 return Math.min(1, Math.max(0, Number(n) || 0));
@@ -1,4 +1,4 @@
1import { MaterialTier, MATERIAL_TIER_ORDER } from "../definitions/materialTiers.js";
1import { MaterialTier, MATERIAL_TIER_ORDER, MATERIAL_TINT_COLOR, GatherMaterialId } from "../definitions/materialTiers.js";
2import { itemDefinition } from "../definitions/items.js";
2import { itemDefinition } from "../definitions/items.js";
3
3
4/**
4/**
@@ -11,15 +11,8 @@ import { itemDefinition } from "../definitions/items.js";
11
11
12export const MAGENTA_CHANNEL_EPS = 1 / 255;
12export const MAGENTA_CHANNEL_EPS = 1 / 255;
13
13
14/** Display tint colors per material tier (0–1 RGB). */
14/** @deprecated Prefer MATERIAL_TINT_COLOR — kept as alias for call sites. */
15export const TIER_TINT_COLOR = Object.freeze({
15export const TIER_TINT_COLOR = MATERIAL_TINT_COLOR;
16 [MaterialTier.bronze]: Object.freeze({ r: 0.72, g: 0.48, b: 0.28 }),
17 [MaterialTier.iron]: Object.freeze({ r: 0.62, g: 0.64, b: 0.68 }),
18 [MaterialTier.steel]: Object.freeze({ r: 0.78, g: 0.80, b: 0.84 }),
19 [MaterialTier.mithril]: Object.freeze({ r: 0.45, g: 0.55, b: 0.85 }),
20 [MaterialTier.adamantium]: Object.freeze({ r: 0.35, g: 0.75, b: 0.45 }),
21 [MaterialTier.orichalcum]: Object.freeze({ r: 0.85, g: 0.35, b: 0.55 })
22});
23
16
24export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
17export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
25{
18{
@@ -34,7 +27,7 @@ export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
34
27
35export function tierTintColor (tier)
28export function tierTintColor (tier)
36{
29{
37 return normalizeRgb(TIER_TINT_COLOR[tier] ?? TIER_TINT_COLOR[MaterialTier.bronze]);
30 return normalizeRgb(MATERIAL_TINT_COLOR[tier] ?? MATERIAL_TINT_COLOR[MaterialTier.bronze]);
38}
31}
39
32
40/**
33/**
@@ -132,6 +125,8 @@ export function listTierTintPreview ()
132 return MATERIAL_TIER_ORDER.map((tier) => ({ tier, color: tierTintColor(tier) }));
125 return MATERIAL_TIER_ORDER.map((tier) => ({ tier, color: tierTintColor(tier) }));
133}
126}
134
127
128export { GatherMaterialId };
129
135function clamp01 (n)
130function clamp01 (n)
136{
131{
137 return Math.min(1, Math.max(0, Number(n) || 0));
132 return Math.min(1, Math.max(0, Number(n) || 0));
shared/skills/state.js +4 −3
@@ -1,7 +1,7 @@
1 1 import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS, DEFAULT_PLAYER_SKILL_LEVELS } from "../definitions/skills.js";
2 2 import { maxTotalSkillXp, totalXpForLevel, xpProgress, MAX_SKILL_LEVEL } from "./progression.js";
3 3
4 /** Health starts at level 10; other skills at level 1 (0 XP). */
4 /** Health starts at level 10; Stamina at 5; other skills at level 1. */
5 5 export const STARTING_HEALTH_XP = totalXpForLevel(DEFAULT_PLAYER_SKILL_LEVELS[SkillId.health] ?? 10);
6 6
7 7 export function emptySkillXp ()
@@ -52,11 +52,12 @@ export function normalizePlayerSkills (stored)
52 52 return { xp: normalizeSkillXp(stored?.xp ?? stored) };
53 53 }
54 54
55 /** Starting skills for a new character (Health level 10, others level 1). */
55 /** Starting skills for a new character (Health 10, Stamina 5, others 1). */
56 56 export function defaultPlayerSkills ()
57 57 {
58 58 return normalizePlayerSkills({
59 [SkillId.health]: STARTING_HEALTH_XP
59 [SkillId.health]: STARTING_HEALTH_XP,
60 [SkillId.stamina]: totalXpForLevel(DEFAULT_PLAYER_SKILL_LEVELS[SkillId.stamina] ?? 5)
60 61 });
61 62 }
62 63
@@ -1,7 +1,7 @@
1import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS, DEFAULT_PLAYER_SKILL_LEVELS } from "../definitions/skills.js";
1import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS, DEFAULT_PLAYER_SKILL_LEVELS } from "../definitions/skills.js";
2import { maxTotalSkillXp, totalXpForLevel, xpProgress, MAX_SKILL_LEVEL } from "./progression.js";
2import { maxTotalSkillXp, totalXpForLevel, xpProgress, MAX_SKILL_LEVEL } from "./progression.js";
3
3
4/** Health starts at level 10; other skills at level 1 (0 XP). */
4/** Health starts at level 10; Stamina at 5; other skills at level 1. */
5export const STARTING_HEALTH_XP = totalXpForLevel(DEFAULT_PLAYER_SKILL_LEVELS[SkillId.health] ?? 10);
5export const STARTING_HEALTH_XP = totalXpForLevel(DEFAULT_PLAYER_SKILL_LEVELS[SkillId.health] ?? 10);
6
6
7export function emptySkillXp ()
7export function emptySkillXp ()
@@ -52,11 +52,12 @@ export function normalizePlayerSkills (stored)
52 return { xp: normalizeSkillXp(stored?.xp ?? stored) };
52 return { xp: normalizeSkillXp(stored?.xp ?? stored) };
53}
53}
54
54
55/** Starting skills for a new character (Health level 10, others level 1). */
55/** Starting skills for a new character (Health 10, Stamina 5, others 1). */
56export function defaultPlayerSkills ()
56export function defaultPlayerSkills ()
57{
57{
58 return normalizePlayerSkills({
58 return normalizePlayerSkills({
59 [SkillId.health]: STARTING_HEALTH_XP
59 [SkillId.health]: STARTING_HEALTH_XP,
60 [SkillId.stamina]: totalXpForLevel(DEFAULT_PLAYER_SKILL_LEVELS[SkillId.stamina] ?? 5)
60 });
61 });
61}
62}
62
63
shared/stamina/rules.js added +39 −0
@@ -0,0 +1,39 @@
1 import { playerMaxStamina } from "../definitions/skills.js";
2
3 /** Stamina points restored per second while walking (or idle with walk gait). */
4 export const STAMINA_REGEN_PER_SECOND = 1;
5
6 /** Stamina XP granted per full stamina point spent while running. */
7 export const STAMINA_XP_PER_POINT_SPENT = 1;
8
9 /**
10 * Stamina cost for one successful run tile step.
11 * Run steps once per movement tick; movementHz = walkTilesPerSecond * 2,
12 * so continuous running drains 1 stamina per second.
13 */
14 export function staminaCostPerRunStep (walkTilesPerSecond = 2)
15 {
16 const movementHz = Math.max(0.25, (Number(walkTilesPerSecond) || 2) * 2);
17 return 1 / movementHz;
18 }
19
20 export function clampStamina (stamina, skills)
21 {
22 if (!stamina)
23 { return null; }
24 const max = Math.max(1, playerMaxStamina(skills) | 0);
25 stamina.max = max;
26 const current = Number(stamina.current);
27 stamina.current = Math.min(max, Math.max(0, Number.isFinite(current) ? current : max));
28 return stamina;
29 }
30
31 export function publicStaminaView (stamina)
32 {
33 if (!stamina)
34 { return { current: 0, max: 1 }; }
35 return {
36 current: Number(stamina.current) || 0,
37 max: Math.max(1, stamina.max | 0)
38 };
39 }
@@ -0,0 +1,39 @@
1import { playerMaxStamina } from "../definitions/skills.js";
2
3/** Stamina points restored per second while walking (or idle with walk gait). */
4export const STAMINA_REGEN_PER_SECOND = 1;
5
6/** Stamina XP granted per full stamina point spent while running. */
7export const STAMINA_XP_PER_POINT_SPENT = 1;
8
9/**
10 * Stamina cost for one successful run tile step.
11 * Run steps once per movement tick; movementHz = walkTilesPerSecond * 2,
12 * so continuous running drains 1 stamina per second.
13 */
14export function staminaCostPerRunStep (walkTilesPerSecond = 2)
15{
16 const movementHz = Math.max(0.25, (Number(walkTilesPerSecond) || 2) * 2);
17 return 1 / movementHz;
18}
19
20export function clampStamina (stamina, skills)
21{
22 if (!stamina)
23 { return null; }
24 const max = Math.max(1, playerMaxStamina(skills) | 0);
25 stamina.max = max;
26 const current = Number(stamina.current);
27 stamina.current = Math.min(max, Math.max(0, Number.isFinite(current) ? current : max));
28 return stamina;
29}
30
31export function publicStaminaView (stamina)
32{
33 if (!stamina)
34 { return { current: 0, max: 1 }; }
35 return {
36 current: Number(stamina.current) || 0,
37 max: Math.max(1, stamina.max | 0)
38 };
39}