Allow entity pass-through with clear attack stance, tiered plant clippers, and craft material filters.
Spread stacked sprites on a tile circle for readable y-sort; anvil/woodworking match tailor's material dropdown.
@@ -186,12 +186,12 @@
186
186
<div class="craft-detail">
187
187
<p id="craft-detail-empty" class="hint">Select a recipe.</p>
188
188
<div id="craft-detail-body" hidden>
189
<div id="craft-tailor-controls" class="craft-tailor-controls" hidden>
190
<label class="craft-tailor-field">
189
<div id="craft-material-controls" class="craft-material-controls" hidden>
190
<label class="craft-material-field">
191
191
<span>Material</span>
192
<select id="craft-cloth-tier"></select>
192
<select id="craft-material-tier"></select>
193
193
</label>
194
<div class="craft-tailor-dye">
194
<div id="craft-dye-controls" class="craft-tailor-dye" hidden>
195
195
<span>Dye (optional)</span>
196
196
<button id="craft-dye-pick" type="button">Choose dye…</button>
197
197
<button id="craft-dye-clear" type="button" hidden>Clear dye</button>
@@ -186,12 +186,12 @@186
<div class="craft-detail">186
<div class="craft-detail">187
<p id="craft-detail-empty" class="hint">Select a recipe.</p>187
<p id="craft-detail-empty" class="hint">Select a recipe.</p>188
<div id="craft-detail-body" hidden>188
<div id="craft-detail-body" hidden>189
<div id="craft-tailor-controls" class="craft-tailor-controls" hidden>189
<div id="craft-material-controls" class="craft-material-controls" hidden>190
<label class="craft-tailor-field">190
<label class="craft-material-field">191
<span>Material</span>191
<span>Material</span>192
<select id="craft-cloth-tier"></select>192
<select id="craft-material-tier"></select>193
</label>193
</label>194
<div class="craft-tailor-dye">194
<div id="craft-dye-controls" class="craft-tailor-dye" hidden>195
<span>Dye (optional)</span>195
<span>Dye (optional)</span>196
<button id="craft-dye-pick" type="button">Choose dye…</button>196
<button id="craft-dye-pick" type="button">Choose dye…</button>197
<button id="craft-dye-clear" type="button" hidden>Clear dye</button>197
<button id="craft-dye-clear" type="button" hidden>Clear dye</button>@@ -16,6 +16,7 @@ import {
16
16
seasonIdFromVisualState,
17
17
placeableStatesForType
18
18
} from "/shared/world/season.js";
19
import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
19
20
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
20
21
import {
21
22
computeNeighborConnectMask,
@@ -70,6 +71,8 @@ function selectedToolLabel ()
70
71
const layer = tool.kind === "ground" ? "ground" : "block";
71
72
const states = statesForType(catalog, layer, def.key);
72
73
const state = resolveState(states, tool.state);
74
if (tool.kind === "block" && def.id === BlockType.flower)
75
{ return "Flower"; }
73
76
if (tool.kind === "block" && def.id === BlockType.boulder)
74
77
{
75
78
const entry = listPlaceableBlockPaletteEntries(catalog)
@@ -207,9 +210,11 @@ function paintAt (localX, localY)
207
210
else
208
211
{
209
212
const def = BLOCK_DEFINITIONS[tool.typeId];
210
const nextState = definitionUsesNeighborConnect(def)
213
let nextState = definitionUsesNeighborConnect(def)
211
214
? composeNeighborConnectState(def, state, 0)
212
215
: state;
216
if (def?.id === BlockType.flower)
217
{ nextState = flowerBlockState(randomFlowerColorId()); }
213
218
draft.blocks[index] = { typeId: tool.typeId, state: nextState, config: null };
214
219
view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
215
220
ground: draft.grounds[index],
@@ -727,6 +732,8 @@ function cycleToolState (direction)
727
732
const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
728
733
if (definitionUsesNeighborConnect(def))
729
734
{ return; }
735
if (tool.kind === "block" && def?.id === BlockType.flower)
736
{ return; }
730
737
const allStates = statesForType(catalog, layer, def.key);
731
738
const seasonal = seasonalCycleStates(allStates);
732
739
const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
@@ -16,6 +16,7 @@ import {16
seasonIdFromVisualState,16
seasonIdFromVisualState,17
placeableStatesForType17
placeableStatesForType18
} from "/shared/world/season.js";18
} from "/shared/world/season.js";19
import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";19
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";20
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";20
import {21
import {21
computeNeighborConnectMask,22
computeNeighborConnectMask,@@ -70,6 +71,8 @@ function selectedToolLabel ()70
const layer = tool.kind === "ground" ? "ground" : "block";71
const layer = tool.kind === "ground" ? "ground" : "block";71
const states = statesForType(catalog, layer, def.key);72
const states = statesForType(catalog, layer, def.key);72
const state = resolveState(states, tool.state);73
const state = resolveState(states, tool.state);74
if (tool.kind === "block" && def.id === BlockType.flower)75
{ return "Flower"; }73
if (tool.kind === "block" && def.id === BlockType.boulder)76
if (tool.kind === "block" && def.id === BlockType.boulder)74
{77
{75
const entry = listPlaceableBlockPaletteEntries(catalog)78
const entry = listPlaceableBlockPaletteEntries(catalog)@@ -207,9 +210,11 @@ function paintAt (localX, localY)207
else210
else208
{211
{209
const def = BLOCK_DEFINITIONS[tool.typeId];212
const def = BLOCK_DEFINITIONS[tool.typeId];210
const nextState = definitionUsesNeighborConnect(def)213
let nextState = definitionUsesNeighborConnect(def)211
? composeNeighborConnectState(def, state, 0)214
? composeNeighborConnectState(def, state, 0)212
: state;215
: state;216
if (def?.id === BlockType.flower)217
{ nextState = flowerBlockState(randomFlowerColorId()); }213
draft.blocks[index] = { typeId: tool.typeId, state: nextState, config: null };218
draft.blocks[index] = { typeId: tool.typeId, state: nextState, config: null };214
view.updateAuthoredTile(chunkX, chunkY, localX, localY, {219
view.updateAuthoredTile(chunkX, chunkY, localX, localY, {215
ground: draft.grounds[index],220
ground: draft.grounds[index],@@ -727,6 +732,8 @@ function cycleToolState (direction)727
const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];732
const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];728
if (definitionUsesNeighborConnect(def))733
if (definitionUsesNeighborConnect(def))729
{ return; }734
{ return; }735
if (tool.kind === "block" && def?.id === BlockType.flower)736
{ return; }730
const allStates = statesForType(catalog, layer, def.key);737
const allStates = statesForType(catalog, layer, def.key);731
const seasonal = seasonalCycleStates(allStates);738
const seasonal = seasonalCycleStates(allStates);732
const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);739
const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);@@ -14,7 +14,16 @@ import {
14
14
recipesForStation
15
15
} from "/shared/crafting/recipes.js";
16
16
import { resolveTailorCraft } from "/shared/crafting/tailor.js";
17
import { CLOTH_TIER_ORDER, CLOTH_DISPLAY_NAME, ClothTier } from "/shared/definitions/materialTiers.js";
17
import {
18
CLOTH_TIER_ORDER,
19
CLOTH_DISPLAY_NAME,
20
ClothTier,
21
MATERIAL_TIER_ORDER,
22
MATERIAL_DISPLAY_NAME,
23
WOOD_TIER_ORDER,
24
WoodTier,
25
MaterialTier
26
} from "/shared/definitions/materialTiers.js";
18
27
import { craftDurationMs } from "/shared/definitions/gathering.js";
19
28
import { applyItemIcon } from "../render/potionIcon.js";
20
29
@@ -31,8 +40,9 @@ export function initCrafting ({
31
40
const recipeGrid = document.getElementById("craft-recipe-grid");
32
41
const detailEmpty = document.getElementById("craft-detail-empty");
33
42
const detailBody = document.getElementById("craft-detail-body");
34
const tailorControls = document.getElementById("craft-tailor-controls");
35
const clothTierSelect = document.getElementById("craft-cloth-tier");
43
const materialControls = document.getElementById("craft-material-controls");
44
const materialTierSelect = document.getElementById("craft-material-tier");
45
const dyeControls = document.getElementById("craft-dye-controls");
36
46
const dyePickBtn = document.getElementById("craft-dye-pick");
37
47
const dyeClearBtn = document.getElementById("craft-dye-clear");
38
48
const dyePreview = document.getElementById("craft-dye-preview");
@@ -51,7 +61,8 @@ export function initCrafting ({
51
61
let stationId = null;
52
62
let recipes = [];
53
63
let selectedRecipeId = null;
54
let clothTier = ClothTier.cotton;
64
let selectedCraftGroup = null;
65
let selectedMaterial = ClothTier.cotton;
55
66
let dyeSlotIndex = null;
56
67
let crafting = false;
57
68
let craftTimer = null;
@@ -61,9 +72,12 @@ export function initCrafting ({
61
72
document.getElementById("craft-close").addEventListener("click", () => close());
62
73
backdrop.addEventListener("click", () => close());
63
74
craftButton.addEventListener("click", () => startCraft());
64
clothTierSelect?.addEventListener("change", () =>
75
materialTierSelect?.addEventListener("change", () =>
65
76
{
66
clothTier = clothTierSelect.value || ClothTier.cotton;
77
selectedMaterial = materialTierSelect.value || selectedMaterial;
78
if (usesCraftGroups())
79
{ syncSelectedRecipeFromMaterial(); }
80
renderRecipeGrid();
67
81
renderDetail();
68
82
});
69
83
dyePickBtn?.addEventListener("click", () => openDyePicker());
@@ -80,6 +94,32 @@ export function initCrafting ({
80
94
return stationId === CraftingStationId.tailorBench;
81
95
}
82
96
97
function isAnvilStation ()
98
{
99
return stationId === CraftingStationId.anvil;
100
}
101
102
function isWoodworkingStation ()
103
{
104
return stationId === CraftingStationId.woodworkingBench;
105
}
106
107
function usesMaterialDropdown ()
108
{
109
return isTailorStation() || isAnvilStation() || isWoodworkingStation();
110
}
111
112
/** Anvil / woodworking: one grid cell per craft group, material picks the tier variant. */
113
function usesCraftGroups ()
114
{
115
return isAnvilStation() || isWoodworkingStation();
116
}
117
118
function craftGroupKey (recipe)
119
{
120
return recipe.craftGroup ?? recipe.recipeId;
121
}
122
83
123
function selectedRecipe ()
84
124
{
85
125
return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
@@ -102,7 +142,7 @@ export function initCrafting ({
102
142
const dyeStack = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
103
143
const resolved = resolveTailorCraft({
104
144
templateId: base.tailorTemplate,
105
clothTier,
145
clothTier: selectedMaterial,
106
146
dyeStack
107
147
});
108
148
return resolved.ok ? resolved.recipe : base;
@@ -116,38 +156,114 @@ export function initCrafting ({
116
156
renderDetail();
117
157
}
118
158
119
function fillClothTier ()
159
function materialOptionsForStation ()
120
160
{
121
if (!clothTierSelect)
161
if (isTailorStation())
162
{
163
return {
164
order: CLOTH_TIER_ORDER,
165
names: CLOTH_DISPLAY_NAME,
166
fallback: ClothTier.cotton
167
};
168
}
169
if (isWoodworkingStation())
170
{
171
return {
172
order: WOOD_TIER_ORDER,
173
names: MATERIAL_DISPLAY_NAME,
174
fallback: WoodTier.pine
175
};
176
}
177
return {
178
order: MATERIAL_TIER_ORDER,
179
names: MATERIAL_DISPLAY_NAME,
180
fallback: MaterialTier.bronze
181
};
182
}
183
184
function fillMaterialTiers ()
185
{
186
if (!materialTierSelect)
122
187
{ return; }
123
clothTierSelect.replaceChildren();
124
for (const tier of CLOTH_TIER_ORDER)
188
const { order, names, fallback } = materialOptionsForStation();
189
if (!order.includes(selectedMaterial))
190
{ selectedMaterial = fallback; }
191
materialTierSelect.replaceChildren();
192
for (const tier of order)
125
193
{
126
194
const option = document.createElement("option");
127
195
option.value = tier;
128
option.textContent = CLOTH_DISPLAY_NAME[tier] ?? tier;
129
clothTierSelect.append(option);
196
option.textContent = names[tier] ?? tier;
197
materialTierSelect.append(option);
198
}
199
materialTierSelect.value = selectedMaterial;
200
}
201
202
function groupedDisplayRecipes ()
203
{
204
if (!usesCraftGroups())
205
{
206
return recipes.map((recipe) => ({
207
group: craftGroupKey(recipe),
208
recipe
209
}));
210
}
211
const byGroup = new Map();
212
for (const recipe of recipes)
213
{
214
const group = craftGroupKey(recipe);
215
if (!byGroup.has(group))
216
{ byGroup.set(group, []); }
217
byGroup.get(group).push(recipe);
218
}
219
const rows = [];
220
for (const [group, variants] of byGroup)
221
{
222
const recipe = variants.find((entry) => entry.xpMaterial === selectedMaterial)
223
?? variants[0];
224
rows.push({ group, recipe, variants });
130
225
}
131
clothTierSelect.value = clothTier;
226
return rows;
227
}
228
229
function syncSelectedRecipeFromMaterial ()
230
{
231
if (!usesCraftGroups() || !selectedCraftGroup)
232
{ return; }
233
const variants = recipes.filter((recipe) => craftGroupKey(recipe) === selectedCraftGroup);
234
if (!variants.length)
235
{ return; }
236
let match = variants.find((recipe) => recipe.xpMaterial === selectedMaterial);
237
if (!match)
238
{
239
match = variants[0];
240
selectedMaterial = match.xpMaterial ?? selectedMaterial;
241
if (materialTierSelect)
242
{ materialTierSelect.value = selectedMaterial; }
243
}
244
selectedRecipeId = match.recipeId;
132
245
}
133
246
134
247
function renderRecipeGrid ()
135
248
{
136
249
recipeGrid.replaceChildren();
137
for (const recipe of recipes)
250
for (const row of groupedDisplayRecipes())
138
251
{
139
recipeGrid.append(renderRecipeCell(recipe));
252
recipeGrid.append(renderRecipeCell(row));
140
253
}
141
254
}
142
255
143
function renderRecipeCell (recipe)
256
function renderRecipeCell ({ group, recipe })
144
257
{
145
258
const def = itemDefinition(recipe.output.itemId);
146
259
const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 };
147
260
const cell = document.createElement("button");
148
261
cell.type = "button";
149
262
cell.className = "craft-recipe-cell";
150
if (recipe.recipeId === selectedRecipeId)
263
const selected = usesCraftGroups()
264
? group === selectedCraftGroup
265
: recipe.recipeId === selectedRecipeId;
266
if (selected)
151
267
{ cell.classList.add("selected"); }
152
268
153
269
const img = document.createElement("img");
@@ -156,16 +272,23 @@ export function initCrafting ({
156
272
157
273
const label = document.createElement("span");
158
274
label.className = "craft-recipe-name";
159
label.textContent = recipe.tailorTemplate
160
? (def?.displayName?.replace(/^Cotton\s+/i, "") ?? "Garment")
161
: (def?.displayName ?? "Item");
275
if (recipe.tailorTemplate)
276
{ label.textContent = def?.displayName?.replace(/^Cotton\s+/i, "") ?? "Garment"; }
277
else if (recipe.craftGroupLabel)
278
{ label.textContent = recipe.craftGroupLabel; }
279
else
280
{ label.textContent = def?.displayName ?? "Item"; }
162
281
163
282
cell.append(img, label);
164
283
cell.addEventListener("click", () =>
165
284
{
166
285
if (crafting)
167
286
{ return; }
168
selectedRecipeId = recipe.recipeId;
287
selectedCraftGroup = group;
288
if (usesCraftGroups())
289
{ syncSelectedRecipeFromMaterial(); }
290
else
291
{ selectedRecipeId = recipe.recipeId; }
169
292
renderRecipeGrid();
170
293
renderDetail();
171
294
});
@@ -184,8 +307,10 @@ export function initCrafting ({
184
307
detailEmpty.hidden = true;
185
308
detailBody.hidden = false;
186
309
187
if (tailorControls)
188
{ tailorControls.hidden = !isTailorStation(); }
310
if (materialControls)
311
{ materialControls.hidden = !usesMaterialDropdown(); }
312
if (dyeControls)
313
{ dyeControls.hidden = !isTailorStation(); }
189
314
190
315
const outputStack = {
191
316
itemId: recipe.output.itemId,
@@ -359,7 +484,7 @@ export function initCrafting ({
359
484
};
360
485
if (isTailorStation())
361
486
{
362
payload.clothTier = clothTier;
487
payload.clothTier = selectedMaterial;
363
488
payload.dyeSlotIndex = dyeSlotIndex;
364
489
}
365
490
socket.send(payload);
@@ -416,10 +541,16 @@ export function initCrafting ({
416
541
{ return; }
417
542
stationId = nextStationId;
418
543
recipes = recipesForStation(nextStationId);
419
selectedRecipeId = recipes[0]?.recipeId ?? null;
420
clothTier = ClothTier.cotton;
544
const { fallback } = materialOptionsForStation();
545
selectedMaterial = fallback;
421
546
dyeSlotIndex = null;
422
fillClothTier();
547
fillMaterialTiers();
548
const first = groupedDisplayRecipes()[0];
549
selectedCraftGroup = first?.group ?? null;
550
if (usesCraftGroups())
551
{ syncSelectedRecipeFromMaterial(); }
552
else
553
{ selectedRecipeId = first?.recipe?.recipeId ?? recipes[0]?.recipeId ?? null; }
423
554
stationName.textContent = def.displayName;
424
555
open = true;
425
556
panel.hidden = false;
@@ -443,6 +574,7 @@ export function initCrafting ({
443
574
stationId = null;
444
575
recipes = [];
445
576
selectedRecipeId = null;
577
selectedCraftGroup = null;
446
578
dyeSlotIndex = null;
447
579
panel.hidden = true;
448
580
backdrop.hidden = true;
@@ -14,7 +14,16 @@ import {14
recipesForStation14
recipesForStation15
} from "/shared/crafting/recipes.js";15
} from "/shared/crafting/recipes.js";16
import { resolveTailorCraft } from "/shared/crafting/tailor.js";16
import { resolveTailorCraft } from "/shared/crafting/tailor.js";17
import { CLOTH_TIER_ORDER, CLOTH_DISPLAY_NAME, ClothTier } from "/shared/definitions/materialTiers.js";17
import {18
CLOTH_TIER_ORDER,19
CLOTH_DISPLAY_NAME,20
ClothTier,21
MATERIAL_TIER_ORDER,22
MATERIAL_DISPLAY_NAME,23
WOOD_TIER_ORDER,24
WoodTier,25
MaterialTier26
} from "/shared/definitions/materialTiers.js";18
import { craftDurationMs } from "/shared/definitions/gathering.js";27
import { craftDurationMs } from "/shared/definitions/gathering.js";19
import { applyItemIcon } from "../render/potionIcon.js";28
import { applyItemIcon } from "../render/potionIcon.js";20
29
@@ -31,8 +40,9 @@ export function initCrafting ({31
const recipeGrid = document.getElementById("craft-recipe-grid");40
const recipeGrid = document.getElementById("craft-recipe-grid");32
const detailEmpty = document.getElementById("craft-detail-empty");41
const detailEmpty = document.getElementById("craft-detail-empty");33
const detailBody = document.getElementById("craft-detail-body");42
const detailBody = document.getElementById("craft-detail-body");34
const tailorControls = document.getElementById("craft-tailor-controls");43
const materialControls = document.getElementById("craft-material-controls");35
const clothTierSelect = document.getElementById("craft-cloth-tier");44
const materialTierSelect = document.getElementById("craft-material-tier");45
const dyeControls = document.getElementById("craft-dye-controls");36
const dyePickBtn = document.getElementById("craft-dye-pick");46
const dyePickBtn = document.getElementById("craft-dye-pick");37
const dyeClearBtn = document.getElementById("craft-dye-clear");47
const dyeClearBtn = document.getElementById("craft-dye-clear");38
const dyePreview = document.getElementById("craft-dye-preview");48
const dyePreview = document.getElementById("craft-dye-preview");@@ -51,7 +61,8 @@ export function initCrafting ({51
let stationId = null;61
let stationId = null;52
let recipes = [];62
let recipes = [];53
let selectedRecipeId = null;63
let selectedRecipeId = null;54
let clothTier = ClothTier.cotton;64
let selectedCraftGroup = null;65
let selectedMaterial = ClothTier.cotton;55
let dyeSlotIndex = null;66
let dyeSlotIndex = null;56
let crafting = false;67
let crafting = false;57
let craftTimer = null;68
let craftTimer = null;@@ -61,9 +72,12 @@ export function initCrafting ({61
document.getElementById("craft-close").addEventListener("click", () => close());72
document.getElementById("craft-close").addEventListener("click", () => close());62
backdrop.addEventListener("click", () => close());73
backdrop.addEventListener("click", () => close());63
craftButton.addEventListener("click", () => startCraft());74
craftButton.addEventListener("click", () => startCraft());64
clothTierSelect?.addEventListener("change", () =>75
materialTierSelect?.addEventListener("change", () =>65
{76
{66
clothTier = clothTierSelect.value || ClothTier.cotton;77
selectedMaterial = materialTierSelect.value || selectedMaterial;78
if (usesCraftGroups())79
{ syncSelectedRecipeFromMaterial(); }80
renderRecipeGrid();67
renderDetail();81
renderDetail();68
});82
});69
dyePickBtn?.addEventListener("click", () => openDyePicker());83
dyePickBtn?.addEventListener("click", () => openDyePicker());@@ -80,6 +94,32 @@ export function initCrafting ({80
return stationId === CraftingStationId.tailorBench;94
return stationId === CraftingStationId.tailorBench;81
}95
}82
96
97
function isAnvilStation ()98
{99
return stationId === CraftingStationId.anvil;100
}101
102
function isWoodworkingStation ()103
{104
return stationId === CraftingStationId.woodworkingBench;105
}106
107
function usesMaterialDropdown ()108
{109
return isTailorStation() || isAnvilStation() || isWoodworkingStation();110
}111
112
/** Anvil / woodworking: one grid cell per craft group, material picks the tier variant. */113
function usesCraftGroups ()114
{115
return isAnvilStation() || isWoodworkingStation();116
}117
118
function craftGroupKey (recipe)119
{120
return recipe.craftGroup ?? recipe.recipeId;121
}122
83
function selectedRecipe ()123
function selectedRecipe ()84
{124
{85
return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;125
return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;@@ -102,7 +142,7 @@ export function initCrafting ({102
const dyeStack = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;142
const dyeStack = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;103
const resolved = resolveTailorCraft({143
const resolved = resolveTailorCraft({104
templateId: base.tailorTemplate,144
templateId: base.tailorTemplate,105
clothTier,145
clothTier: selectedMaterial,106
dyeStack146
dyeStack107
});147
});108
return resolved.ok ? resolved.recipe : base;148
return resolved.ok ? resolved.recipe : base;@@ -116,38 +156,114 @@ export function initCrafting ({116
renderDetail();156
renderDetail();117
}157
}118
158
119
function fillClothTier ()159
function materialOptionsForStation ()120
{160
{121
if (!clothTierSelect)161
if (isTailorStation())162
{163
return {164
order: CLOTH_TIER_ORDER,165
names: CLOTH_DISPLAY_NAME,166
fallback: ClothTier.cotton167
};168
}169
if (isWoodworkingStation())170
{171
return {172
order: WOOD_TIER_ORDER,173
names: MATERIAL_DISPLAY_NAME,174
fallback: WoodTier.pine175
};176
}177
return {178
order: MATERIAL_TIER_ORDER,179
names: MATERIAL_DISPLAY_NAME,180
fallback: MaterialTier.bronze181
};182
}183
184
function fillMaterialTiers ()185
{186
if (!materialTierSelect)122
{ return; }187
{ return; }123
clothTierSelect.replaceChildren();188
const { order, names, fallback } = materialOptionsForStation();124
for (const tier of CLOTH_TIER_ORDER)189
if (!order.includes(selectedMaterial))190
{ selectedMaterial = fallback; }191
materialTierSelect.replaceChildren();192
for (const tier of order)125
{193
{126
const option = document.createElement("option");194
const option = document.createElement("option");127
option.value = tier;195
option.value = tier;128
option.textContent = CLOTH_DISPLAY_NAME[tier] ?? tier;196
option.textContent = names[tier] ?? tier;129
clothTierSelect.append(option);197
materialTierSelect.append(option);198
}199
materialTierSelect.value = selectedMaterial;200
}201
202
function groupedDisplayRecipes ()203
{204
if (!usesCraftGroups())205
{206
return recipes.map((recipe) => ({207
group: craftGroupKey(recipe),208
recipe209
}));210
}211
const byGroup = new Map();212
for (const recipe of recipes)213
{214
const group = craftGroupKey(recipe);215
if (!byGroup.has(group))216
{ byGroup.set(group, []); }217
byGroup.get(group).push(recipe);218
}219
const rows = [];220
for (const [group, variants] of byGroup)221
{222
const recipe = variants.find((entry) => entry.xpMaterial === selectedMaterial)223
?? variants[0];224
rows.push({ group, recipe, variants });130
}225
}131
clothTierSelect.value = clothTier;226
return rows;227
}228
229
function syncSelectedRecipeFromMaterial ()230
{231
if (!usesCraftGroups() || !selectedCraftGroup)232
{ return; }233
const variants = recipes.filter((recipe) => craftGroupKey(recipe) === selectedCraftGroup);234
if (!variants.length)235
{ return; }236
let match = variants.find((recipe) => recipe.xpMaterial === selectedMaterial);237
if (!match)238
{239
match = variants[0];240
selectedMaterial = match.xpMaterial ?? selectedMaterial;241
if (materialTierSelect)242
{ materialTierSelect.value = selectedMaterial; }243
}244
selectedRecipeId = match.recipeId;132
}245
}133
246
134
function renderRecipeGrid ()247
function renderRecipeGrid ()135
{248
{136
recipeGrid.replaceChildren();249
recipeGrid.replaceChildren();137
for (const recipe of recipes)250
for (const row of groupedDisplayRecipes())138
{251
{139
recipeGrid.append(renderRecipeCell(recipe));252
recipeGrid.append(renderRecipeCell(row));140
}253
}141
}254
}142
255
143
function renderRecipeCell (recipe)256
function renderRecipeCell ({ group, recipe })144
{257
{145
const def = itemDefinition(recipe.output.itemId);258
const def = itemDefinition(recipe.output.itemId);146
const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 };259
const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 };147
const cell = document.createElement("button");260
const cell = document.createElement("button");148
cell.type = "button";261
cell.type = "button";149
cell.className = "craft-recipe-cell";262
cell.className = "craft-recipe-cell";150
if (recipe.recipeId === selectedRecipeId)263
const selected = usesCraftGroups()264
? group === selectedCraftGroup265
: recipe.recipeId === selectedRecipeId;266
if (selected)151
{ cell.classList.add("selected"); }267
{ cell.classList.add("selected"); }152
268
153
const img = document.createElement("img");269
const img = document.createElement("img");@@ -156,16 +272,23 @@ export function initCrafting ({156
272
157
const label = document.createElement("span");273
const label = document.createElement("span");158
label.className = "craft-recipe-name";274
label.className = "craft-recipe-name";159
label.textContent = recipe.tailorTemplate275
if (recipe.tailorTemplate)160
? (def?.displayName?.replace(/^Cotton\s+/i, "") ?? "Garment")276
{ label.textContent = def?.displayName?.replace(/^Cotton\s+/i, "") ?? "Garment"; }161
: (def?.displayName ?? "Item");277
else if (recipe.craftGroupLabel)278
{ label.textContent = recipe.craftGroupLabel; }279
else280
{ label.textContent = def?.displayName ?? "Item"; }162
281
163
cell.append(img, label);282
cell.append(img, label);164
cell.addEventListener("click", () =>283
cell.addEventListener("click", () =>165
{284
{166
if (crafting)285
if (crafting)167
{ return; }286
{ return; }168
selectedRecipeId = recipe.recipeId;287
selectedCraftGroup = group;288
if (usesCraftGroups())289
{ syncSelectedRecipeFromMaterial(); }290
else291
{ selectedRecipeId = recipe.recipeId; }169
renderRecipeGrid();292
renderRecipeGrid();170
renderDetail();293
renderDetail();171
});294
});@@ -184,8 +307,10 @@ export function initCrafting ({184
detailEmpty.hidden = true;307
detailEmpty.hidden = true;185
detailBody.hidden = false;308
detailBody.hidden = false;186
309
187
if (tailorControls)310
if (materialControls)188
{ tailorControls.hidden = !isTailorStation(); }311
{ materialControls.hidden = !usesMaterialDropdown(); }312
if (dyeControls)313
{ dyeControls.hidden = !isTailorStation(); }189
314
190
const outputStack = {315
const outputStack = {191
itemId: recipe.output.itemId,316
itemId: recipe.output.itemId,@@ -359,7 +484,7 @@ export function initCrafting ({359
};484
};360
if (isTailorStation())485
if (isTailorStation())361
{486
{362
payload.clothTier = clothTier;487
payload.clothTier = selectedMaterial;363
payload.dyeSlotIndex = dyeSlotIndex;488
payload.dyeSlotIndex = dyeSlotIndex;364
}489
}365
socket.send(payload);490
socket.send(payload);@@ -416,10 +541,16 @@ export function initCrafting ({416
{ return; }541
{ return; }417
stationId = nextStationId;542
stationId = nextStationId;418
recipes = recipesForStation(nextStationId);543
recipes = recipesForStation(nextStationId);419
selectedRecipeId = recipes[0]?.recipeId ?? null;544
const { fallback } = materialOptionsForStation();420
clothTier = ClothTier.cotton;545
selectedMaterial = fallback;421
dyeSlotIndex = null;546
dyeSlotIndex = null;422
fillClothTier();547
fillMaterialTiers();548
const first = groupedDisplayRecipes()[0];549
selectedCraftGroup = first?.group ?? null;550
if (usesCraftGroups())551
{ syncSelectedRecipeFromMaterial(); }552
else553
{ selectedRecipeId = first?.recipe?.recipeId ?? recipes[0]?.recipeId ?? null; }423
stationName.textContent = def.displayName;554
stationName.textContent = def.displayName;424
open = true;555
open = true;425
panel.hidden = false;556
panel.hidden = false;@@ -443,6 +574,7 @@ export function initCrafting ({443
stationId = null;574
stationId = null;444
recipes = [];575
recipes = [];445
selectedRecipeId = null;576
selectedRecipeId = null;577
selectedCraftGroup = null;446
dyeSlotIndex = null;578
dyeSlotIndex = null;447
panel.hidden = true;579
panel.hidden = true;448
backdrop.hidden = true;580
backdrop.hidden = true;@@ -1,4 +1,4 @@
1
import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";
1
import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";
2
2
import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3
3
import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4
4
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
@@ -657,6 +657,7 @@ export class WorldView
657
657
{
658
658
const now = performance.now();
659
659
const size = this.tileSize();
660
this.#refreshStackOffsets();
660
661
for (const entity of this.entities.values())
661
662
{
662
663
const target = entity.targetX != null && entity.targetY != null
@@ -688,6 +689,53 @@ export class WorldView
688
689
this.#updateShade(deltaTime);
689
690
}
690
691
692
/**
693
* Evenly space stacked entities on a circle around the tile centre.
694
* Stable assignment by entityId; free-flight entities stay unshifted.
695
*/
696
#refreshStackOffsets ()
697
{
698
const byTile = new Map();
699
for (const entity of this.entities.values())
700
{
701
if (entity.freeFlight)
702
{
703
entity.stackOffsetX = 0;
704
entity.stackOffsetY = 0;
705
continue;
706
}
707
const key = `${entity.tileX},${entity.tileY}`;
708
let list = byTile.get(key);
709
if (!list)
710
{
711
list = [];
712
byTile.set(key, list);
713
}
714
list.push(entity);
715
}
716
const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;
717
for (const list of byTile.values())
718
{
719
if (list.length <= 1)
720
{
721
for (const entity of list)
722
{
723
entity.stackOffsetX = 0;
724
entity.stackOffsetY = 0;
725
}
726
continue;
727
}
728
list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId)));
729
const n = list.length;
730
for (let i = 0; i < n; i++)
731
{
732
const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;
733
list[i].stackOffsetX = Math.cos(angle) * radius;
734
list[i].stackOffsetY = Math.sin(angle) * radius;
735
}
736
}
737
}
738
691
739
#updateShove (entity, now, tileSize)
692
740
{
693
741
if (!entity.shove)
@@ -721,11 +769,15 @@ export class WorldView
721
769
const target = this.entities.get(payload.targetId);
722
770
if (!attacker || !target)
723
771
{ return; }
724
this.#applyShove(attacker, target.visualX, target.visualY);
725
const midX = (attacker.visualX + target.visualX) / 2;
726
const midY = (attacker.visualY + target.visualY) / 2;
727
const sortY = Math.max(attacker.visualY, target.visualY) + 0.02;
728
const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
772
const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
773
const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
774
const tx = target.visualX + (target.stackOffsetX ?? 0);
775
const ty = target.visualY + (target.stackOffsetY ?? 0);
776
this.#applyShove(attacker, tx, ty);
777
const midX = (ax + tx) / 2;
778
const midY = (ay + ty) / 2;
779
const sortY = Math.max(ay, ty) + 0.02;
780
const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI);
729
781
const spriteName = "fx:melee-swipe:melee-swipe";
730
782
const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
731
783
if (object.transform)
@@ -990,8 +1042,10 @@ export class WorldView
990
1042
const local = this.entities.get(this.localEntityId);
991
1043
if (!local)
992
1044
{ return; }
993
this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX;
994
this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
1045
const x = local.visualX + (local.stackOffsetX ?? 0);
1046
const y = local.visualY + (local.stackOffsetY ?? 0);
1047
this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
1048
this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
995
1049
}
996
1050
997
1051
/**
@@ -1240,8 +1294,8 @@ export class WorldView
1240
1294
const zoom = this.zoom;
1241
1295
const offsetX = entity.shoveOffsetX ?? 0;
1242
1296
const offsetY = entity.shoveOffsetY ?? 0;
1243
const pivotX = entity.visualX + offsetX;
1244
const pivotY = entity.visualY + offsetY;
1297
const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
1298
const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
1245
1299
let walkTilt = 0;
1246
1300
if (entity.lerpStarted != null)
1247
1301
{
@@ -1,4 +1,4 @@1
import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";1
import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";2
import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";2
import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";3
import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";3
import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";4
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";4
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";@@ -657,6 +657,7 @@ export class WorldView657
{657
{658
const now = performance.now();658
const now = performance.now();659
const size = this.tileSize();659
const size = this.tileSize();660
this.#refreshStackOffsets();660
for (const entity of this.entities.values())661
for (const entity of this.entities.values())661
{662
{662
const target = entity.targetX != null && entity.targetY != null663
const target = entity.targetX != null && entity.targetY != null@@ -688,6 +689,53 @@ export class WorldView688
this.#updateShade(deltaTime);689
this.#updateShade(deltaTime);689
}690
}690
691
692
/**693
* Evenly space stacked entities on a circle around the tile centre.694
* Stable assignment by entityId; free-flight entities stay unshifted.695
*/696
#refreshStackOffsets ()697
{698
const byTile = new Map();699
for (const entity of this.entities.values())700
{701
if (entity.freeFlight)702
{703
entity.stackOffsetX = 0;704
entity.stackOffsetY = 0;705
continue;706
}707
const key = `${entity.tileX},${entity.tileY}`;708
let list = byTile.get(key);709
if (!list)710
{711
list = [];712
byTile.set(key, list);713
}714
list.push(entity);715
}716
const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;717
for (const list of byTile.values())718
{719
if (list.length <= 1)720
{721
for (const entity of list)722
{723
entity.stackOffsetX = 0;724
entity.stackOffsetY = 0;725
}726
continue;727
}728
list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId)));729
const n = list.length;730
for (let i = 0; i < n; i++)731
{732
const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;733
list[i].stackOffsetX = Math.cos(angle) * radius;734
list[i].stackOffsetY = Math.sin(angle) * radius;735
}736
}737
}738
691
#updateShove (entity, now, tileSize)739
#updateShove (entity, now, tileSize)692
{740
{693
if (!entity.shove)741
if (!entity.shove)@@ -721,11 +769,15 @@ export class WorldView721
const target = this.entities.get(payload.targetId);769
const target = this.entities.get(payload.targetId);722
if (!attacker || !target)770
if (!attacker || !target)723
{ return; }771
{ return; }724
this.#applyShove(attacker, target.visualX, target.visualY);772
const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);725
const midX = (attacker.visualX + target.visualX) / 2;773
const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);726
const midY = (attacker.visualY + target.visualY) / 2;774
const tx = target.visualX + (target.stackOffsetX ?? 0);727
const sortY = Math.max(attacker.visualY, target.visualY) + 0.02;775
const ty = target.visualY + (target.stackOffsetY ?? 0);728
const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);776
this.#applyShove(attacker, tx, ty);777
const midX = (ax + tx) / 2;778
const midY = (ay + ty) / 2;779
const sortY = Math.max(ay, ty) + 0.02;780
const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI);729
const spriteName = "fx:melee-swipe:melee-swipe";781
const spriteName = "fx:melee-swipe:melee-swipe";730
const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);782
const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);731
if (object.transform)783
if (object.transform)@@ -990,8 +1042,10 @@ export class WorldView990
const local = this.entities.get(this.localEntityId);1042
const local = this.entities.get(this.localEntityId);991
if (!local)1043
if (!local)992
{ return; }1044
{ return; }993
this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX;1045
const x = local.visualX + (local.stackOffsetX ?? 0);994
this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;1046
const y = local.visualY + (local.stackOffsetY ?? 0);1047
this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;1048
this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;995
}1049
}996
1050
997
/**1051
/**@@ -1240,8 +1294,8 @@ export class WorldView1240
const zoom = this.zoom;1294
const zoom = this.zoom;1241
const offsetX = entity.shoveOffsetX ?? 0;1295
const offsetX = entity.shoveOffsetX ?? 0;1242
const offsetY = entity.shoveOffsetY ?? 0;1296
const offsetY = entity.shoveOffsetY ?? 0;1243
const pivotX = entity.visualX + offsetX;1297
const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);1244
const pivotY = entity.visualY + offsetY;1298
const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);1245
let walkTilt = 0;1299
let walkTilt = 0;1246
if (entity.lerpStarted != null)1300
if (entity.lerpStarted != null)1247
{1301
{@@ -868,6 +868,46 @@ a { color: #d4c48a; }
868
868
border: 1px solid #2c3340;
869
869
}
870
870
871
.craft-material-controls {
872
display: flex;
873
flex-direction: column;
874
gap: 0.5rem;
875
margin-bottom: 0.65rem;
876
padding-bottom: 0.5rem;
877
border-bottom: 1px solid #2c3340;
878
}
879
880
.craft-material-field {
881
display: flex;
882
flex-direction: column;
883
gap: 0.25rem;
884
font-size: 0.85rem;
885
color: #c8c2b4;
886
}
887
888
.craft-material-field select {
889
background: #1a1e26;
890
border: 1px solid #3a4252;
891
color: #f0ebe0;
892
padding: 0.35rem 0.45rem;
893
}
894
895
.craft-tailor-dye {
896
display: flex;
897
flex-wrap: wrap;
898
align-items: center;
899
gap: 0.4rem;
900
font-size: 0.85rem;
901
color: #c8c2b4;
902
}
903
904
.craft-tailor-dye img {
905
width: 28px;
906
height: 28px;
907
object-fit: contain;
908
image-rendering: pixelated;
909
}
910
871
911
.craft-output {
872
912
display: flex;
873
913
flex-direction: column;
@@ -868,6 +868,46 @@ a { color: #d4c48a; }868
border: 1px solid #2c3340;868
border: 1px solid #2c3340;869
}869
}870
870
871
.craft-material-controls {872
display: flex;873
flex-direction: column;874
gap: 0.5rem;875
margin-bottom: 0.65rem;876
padding-bottom: 0.5rem;877
border-bottom: 1px solid #2c3340;878
}879
880
.craft-material-field {881
display: flex;882
flex-direction: column;883
gap: 0.25rem;884
font-size: 0.85rem;885
color: #c8c2b4;886
}887
888
.craft-material-field select {889
background: #1a1e26;890
border: 1px solid #3a4252;891
color: #f0ebe0;892
padding: 0.35rem 0.45rem;893
}894
895
.craft-tailor-dye {896
display: flex;897
flex-wrap: wrap;898
align-items: center;899
gap: 0.4rem;900
font-size: 0.85rem;901
color: #c8c2b4;902
}903
904
.craft-tailor-dye img {905
width: 28px;906
height: 28px;907
object-fit: contain;908
image-rendering: pixelated;909
}910
871
.craft-output {911
.craft-output {872
display: flex;912
display: flex;873
flex-direction: column;913
flex-direction: column;@@ -70,7 +70,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
70
70
## World editor (client)
71
71
72
72
**Status:** full
73
**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, save chunk and Apply now. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
73
**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, save chunk and Apply now. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
74
74
**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
75
75
76
76
## Per-chunk changelog
@@ -112,8 +112,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
112
112
## Click-to-move and A\* pathfinding
113
113
114
114
**Status:** full
115
**Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Occupied tiles block. Server commits integer tiles on the movement cadence.
116
**Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`)
115
**Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Entities do **not** block each other’s movement (players and mobs pass through). Occupied tiles are still preferred-away for mob wander goals and required to be clear for melee attack stance. Client spreads stacked entities evenly on a circle (`ENTITY_STACK_SPREAD_DIAMETER_PX`, centred on the tile); within-tile y-sort still uses each sprite’s visual Y. Server commits integer tiles on the movement cadence. Neighbour expansion prefers steps that most reduce Manhattan distance to the goal; remaining ties break by axis — **players prefer vertical**, **mobs prefer horizontal** — so mutual approaches are less likely to oscillate sideways.
116
**Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`, `walkableFor`, `isClearStanding`)
117
117
118
118
## Global walk/run cadence
119
119
@@ -214,7 +214,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
214
214
## Combat, skills, groups, pigeons
215
215
216
216
**Status:** partial
217
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
217
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
218
218
**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
219
219
220
220
## Player death and respawn
@@ -259,7 +259,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
259
259
## Crafting stations
260
260
261
261
**Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
262
**Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring.
262
**Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, and **tailor** craft UIs use a material dropdown so tier variants share one recipe cell (plant clippers = 1 bar per metal tier).
263
263
**TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
264
264
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
265
265
@@ -70,7 +70,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi70
## World editor (client)70
## World editor (client)71
71
72
**Status:** full 72
**Status:** full 73
**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, save chunk and Apply now. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only. 73
**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, save chunk and Apply now. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only. 74
**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`74
**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`75
75
76
## Per-chunk changelog76
## Per-chunk changelog@@ -112,8 +112,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi112
## Click-to-move and A\* pathfinding112
## Click-to-move and A\* pathfinding113
113
114
**Status:** full 114
**Status:** full 115
**Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Occupied tiles block. Server commits integer tiles on the movement cadence. 115
**Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Entities do **not** block each other’s movement (players and mobs pass through). Occupied tiles are still preferred-away for mob wander goals and required to be clear for melee attack stance. Client spreads stacked entities evenly on a circle (`ENTITY_STACK_SPREAD_DIAMETER_PX`, centred on the tile); within-tile y-sort still uses each sprite’s visual Y. Server commits integer tiles on the movement cadence. Neighbour expansion prefers steps that most reduce Manhattan distance to the goal; remaining ties break by axis — **players prefer vertical**, **mobs prefer horizontal** — so mutual approaches are less likely to oscillate sideways. 116
**Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`)116
**Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`, `walkableFor`, `isClearStanding`)117
117
118
## Global walk/run cadence118
## Global walk/run cadence119
119
@@ -214,7 +214,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi214
## Combat, skills, groups, pigeons214
## Combat, skills, groups, pigeons215
215
216
**Status:** partial 216
**Status:** partial 217
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later. 217
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later. 218
**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)218
**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)219
219
220
## Player death and respawn220
## Player death and respawn@@ -259,7 +259,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi259
## Crafting stations259
## Crafting stations260
260
261
**Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live) 261
**Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live) 262
**Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. 262
**Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, and **tailor** craft UIs use a material dropdown so tier variants share one recipe cell (plant clippers = 1 bar per metal tier). 263
**TODO:** oven/campfire burn; dedicated station sprites where still placeholder. 263
**TODO:** oven/campfire burn; dedicated station sprites where still placeholder. 264
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`264
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`265
265
@@ -108,9 +108,10 @@ export function engageTarget (ecs, attackerId, targetId, now = Date.now())
108
108
{ combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
109
109
const targetChanged = combat.targetEntityId !== targetId;
110
110
combat.targetEntityId = targetId;
111
combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
112
111
if (targetChanged)
113
112
{
113
// New engage (or switch): allow an immediate swing; keep cadence if already on this target.
114
combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
114
115
const path = ecs.get(handle, Component.path);
115
116
if (path)
116
117
{ path.tiles = []; }
@@ -268,14 +269,14 @@ export function stepCombat (world, now = Date.now())
268
269
269
270
const targetPos = target.pos;
270
271
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
271
clearCombatApproachPath(world.ecs, entity.handle, dist);
272
if (dist > 1)
272
const canSwing = dist === 1
273
&& world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);
274
if (!canSwing)
273
275
{
274
276
queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
275
277
continue;
276
278
}
277
if (dist !== 1)
278
{ continue; }
279
clearCombatApproachPath(world.ecs, entity.handle);
279
280
const attackerHealth = world.ecs.get(entity.handle, Component.health);
280
281
if (attackerHealth && attackerHealth.current <= 0)
281
282
{ continue; }
@@ -288,10 +289,8 @@ export function stepCombat (world, now = Date.now())
288
289
return events;
289
290
}
290
291
291
function clearCombatApproachPath (ecs, handle, distToTarget)
292
function clearCombatApproachPath (ecs, handle)
292
293
{
293
if (distToTarget > 1)
294
{ return; }
295
294
const path = ecs.get(handle, Component.path);
296
295
if (path?.tiles?.length)
297
296
{ path.tiles = []; }
@@ -305,7 +304,9 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
305
304
if (!path)
306
305
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }
307
306
308
if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) <= 1)
307
const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY)
308
?? true;
309
if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere)
309
310
{
310
311
path.tiles = [];
311
312
return;
@@ -318,20 +319,36 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
318
319
return;
319
320
}
320
321
322
if (goal.x === position.tileX && goal.y === position.tileY)
323
{
324
path.tiles = [];
325
return;
326
}
327
321
328
if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))
322
329
{ return; }
323
330
324
331
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
332
const preferVertical = !!world.ecs.get(handle, Component.character);
325
333
const tiles = findPath(
326
334
position.tileX,
327
335
position.tileY,
328
336
goal.x,
329
337
goal.y,
330
(x, y) => world.walkableFor(entityId, x, y),
338
(x, y) =>
339
{
340
if (x === goal.x && y === goal.y)
341
{
342
return world.isClearStanding?.(entityId, x, y)
343
?? world.walkableFor(entityId, x, y);
344
}
345
return world.walkableFor(entityId, x, y);
346
},
331
347
bounds.minX,
332
348
bounds.minY,
333
349
bounds.maxX,
334
bounds.maxY
350
bounds.maxY,
351
{ preferVertical }
335
352
);
336
353
if (!tiles.length)
337
354
{
@@ -351,12 +368,12 @@ function meleePathStale (world, entityId, position, targetPos, path, goal)
351
368
{ return true; }
352
369
if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
353
370
{ return true; }
371
if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))
372
{ return true; }
354
373
const next = path.tiles[0];
355
374
if (!next)
356
375
{ return true; }
357
const blockedByOther = !world.walkableFor(entityId, next.x, next.y)
358
&& !(next.x === targetPos.tileX && next.y === targetPos.tileY);
359
return blockedByOther;
376
return !world.walkableFor(entityId, next.x, next.y);
360
377
}
361
378
362
379
function bestAdjacentGoal (world, entityId, position, targetPos)
@@ -371,7 +388,12 @@ function bestAdjacentGoal (world, entityId, position, targetPos)
371
388
{
372
389
const x = targetPos.tileX + dir.x;
373
390
const y = targetPos.tileY + dir.y;
374
if (!world.walkableFor(entityId, x, y) && !(x === position.tileX && y === position.tileY))
391
const isHere = x === position.tileX && y === position.tileY;
392
const clear = world.isClearStanding?.(entityId, x, y)
393
?? world.walkableFor(entityId, x, y);
394
if (!clear && !isHere)
395
{ continue; }
396
if (isHere && !(world.isClearStanding?.(entityId, x, y) ?? true))
375
397
{ continue; }
376
398
const dist = chebyshev(position.tileX, position.tileY, x, y);
377
399
if (dist < bestDist)
@@ -398,6 +420,8 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
398
420
{ return events; }
399
421
if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
400
422
{ return events; }
423
if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY))
424
{ return events; }
401
425
402
426
events.push({
403
427
type: "combat-swing",
@@ -457,18 +481,11 @@ export function applyRemoteMeleeSwing (world, payload)
457
481
payload.profile,
458
482
payload.now ?? Date.now(),
459
483
to,
460
payload.attackerLevels
484
payload.attackerLevels,
485
payload.attackerIsPlayer
461
486
);
462
487
463
488
const forwards = [];
464
if (payload.attackerIsPlayer && ensureMobCombat(world.ecs, payload.targetId))
465
{ engageTarget(world.ecs, payload.targetId, payload.attackerId, payload.now ?? Date.now()); }
466
if (!payload.attackerIsPlayer)
467
{
468
const targetCharacter = world.ecs.get(targetHandle, Component.character);
469
if (targetCharacter)
470
{ engageTarget(world.ecs, payload.targetId, payload.attackerId, payload.now ?? Date.now()); }
471
}
472
489
const hitEvent = events.find((event) => event.type === "combat-hit");
473
490
if (hitEvent && payload.attackerIsPlayer)
474
491
{
@@ -490,19 +507,36 @@ function applyLocalMeleeHit (
490
507
profile,
491
508
now,
492
509
to,
493
attackerLevelsOverride = null
510
attackerLevelsOverride = null,
511
attackerIsPlayerOverride = null
494
512
)
495
513
{
496
514
const events = [];
497
515
if (targetHandle == null)
498
516
{ return events; }
499
517
500
if (attackerHandle != null)
518
const attackerIsPlayer = attackerIsPlayerOverride != null
519
? !!attackerIsPlayerOverride
520
: (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
521
522
// Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
523
if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
524
{ engageTarget(world.ecs, targetId, attackerId, now); }
525
if (attackerIsPlayer === false)
501
526
{
502
const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
503
// Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
504
if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
505
{ engageTarget(world.ecs, targetId, attackerId, now); }
527
const targetCharacter = world.ecs.get(targetHandle, Component.character);
528
if (targetCharacter)
529
{
530
engageTarget(world.ecs, targetId, attackerId, now);
531
const follow = world.ecs.get(targetHandle, Component.follow);
532
if (follow)
533
{
534
follow.targetEntityId = null;
535
follow.trail = [];
536
}
537
if (world.ecs.has(targetHandle, Component.gather))
538
{ world.ecs.remove(targetHandle, Component.gather); }
539
}
506
540
}
507
541
508
542
const defenderSkills = world.ecs.get(targetHandle, Component.skills);
@@ -108,9 +108,10 @@ export function engageTarget (ecs, attackerId, targetId, now = Date.now())108
{ combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }108
{ combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }109
const targetChanged = combat.targetEntityId !== targetId;109
const targetChanged = combat.targetEntityId !== targetId;110
combat.targetEntityId = targetId;110
combat.targetEntityId = targetId;111
combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);112
if (targetChanged)111
if (targetChanged)113
{112
{113
// New engage (or switch): allow an immediate swing; keep cadence if already on this target.114
combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);114
const path = ecs.get(handle, Component.path);115
const path = ecs.get(handle, Component.path);115
if (path)116
if (path)116
{ path.tiles = []; }117
{ path.tiles = []; }@@ -268,14 +269,14 @@ export function stepCombat (world, now = Date.now())268
269
269
const targetPos = target.pos;270
const targetPos = target.pos;270
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);271
const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);271
clearCombatApproachPath(world.ecs, entity.handle, dist);272
const canSwing = dist === 1272
if (dist > 1)273
&& world.isClearStanding?.(entity.entityId, entity.position.tileX, entity.position.tileY);274
if (!canSwing)273
{275
{274
queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);276
queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);275
continue;277
continue;276
}278
}277
if (dist !== 1)279
clearCombatApproachPath(world.ecs, entity.handle);278
{ continue; }279
const attackerHealth = world.ecs.get(entity.handle, Component.health);280
const attackerHealth = world.ecs.get(entity.handle, Component.health);280
if (attackerHealth && attackerHealth.current <= 0)281
if (attackerHealth && attackerHealth.current <= 0)281
{ continue; }282
{ continue; }@@ -288,10 +289,8 @@ export function stepCombat (world, now = Date.now())288
return events;289
return events;289
}290
}290
291
291
function clearCombatApproachPath (ecs, handle, distToTarget)292
function clearCombatApproachPath (ecs, handle)292
{293
{293
if (distToTarget > 1)294
{ return; }295
const path = ecs.get(handle, Component.path);294
const path = ecs.get(handle, Component.path);296
if (path?.tiles?.length)295
if (path?.tiles?.length)297
{ path.tiles = []; }296
{ path.tiles = []; }@@ -305,7 +304,9 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)305
if (!path)304
if (!path)306
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }305
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }307
306
308
if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) <= 1)307
const aloneHere = world.isClearStanding?.(entityId, position.tileX, position.tileY)308
?? true;309
if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) === 1 && aloneHere)309
{310
{310
path.tiles = [];311
path.tiles = [];311
return;312
return;@@ -318,20 +319,36 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)318
return;319
return;319
}320
}320
321
322
if (goal.x === position.tileX && goal.y === position.tileY)323
{324
path.tiles = [];325
return;326
}327
321
if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))328
if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))322
{ return; }329
{ return; }323
330
324
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);331
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);332
const preferVertical = !!world.ecs.get(handle, Component.character);325
const tiles = findPath(333
const tiles = findPath(326
position.tileX,334
position.tileX,327
position.tileY,335
position.tileY,328
goal.x,336
goal.x,329
goal.y,337
goal.y,330
(x, y) => world.walkableFor(entityId, x, y),338
(x, y) =>339
{340
if (x === goal.x && y === goal.y)341
{342
return world.isClearStanding?.(entityId, x, y)343
?? world.walkableFor(entityId, x, y);344
}345
return world.walkableFor(entityId, x, y);346
},331
bounds.minX,347
bounds.minX,332
bounds.minY,348
bounds.minY,333
bounds.maxX,349
bounds.maxX,334
bounds.maxY350
bounds.maxY,351
{ preferVertical }335
);352
);336
if (!tiles.length)353
if (!tiles.length)337
{354
{@@ -351,12 +368,12 @@ function meleePathStale (world, entityId, position, targetPos, path, goal)351
{ return true; }368
{ return true; }352
if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)369
if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)353
{ return true; }370
{ return true; }371
if (!(world.isClearStanding?.(entityId, dest.x, dest.y) ?? true))372
{ return true; }354
const next = path.tiles[0];373
const next = path.tiles[0];355
if (!next)374
if (!next)356
{ return true; }375
{ return true; }357
const blockedByOther = !world.walkableFor(entityId, next.x, next.y)376
return !world.walkableFor(entityId, next.x, next.y);358
&& !(next.x === targetPos.tileX && next.y === targetPos.tileY);359
return blockedByOther;360
}377
}361
378
362
function bestAdjacentGoal (world, entityId, position, targetPos)379
function bestAdjacentGoal (world, entityId, position, targetPos)@@ -371,7 +388,12 @@ function bestAdjacentGoal (world, entityId, position, targetPos)371
{388
{372
const x = targetPos.tileX + dir.x;389
const x = targetPos.tileX + dir.x;373
const y = targetPos.tileY + dir.y;390
const y = targetPos.tileY + dir.y;374
if (!world.walkableFor(entityId, x, y) && !(x === position.tileX && y === position.tileY))391
const isHere = x === position.tileX && y === position.tileY;392
const clear = world.isClearStanding?.(entityId, x, y)393
?? world.walkableFor(entityId, x, y);394
if (!clear && !isHere)395
{ continue; }396
if (isHere && !(world.isClearStanding?.(entityId, x, y) ?? true))375
{ continue; }397
{ continue; }376
const dist = chebyshev(position.tileX, position.tileY, x, y);398
const dist = chebyshev(position.tileX, position.tileY, x, y);377
if (dist < bestDist)399
if (dist < bestDist)@@ -398,6 +420,8 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D398
{ return events; }420
{ return events; }399
if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)421
if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)400
{ return events; }422
{ return events; }423
if (world.isClearStanding && !world.isClearStanding(attackerId, from.tileX, from.tileY))424
{ return events; }401
425
402
events.push({426
events.push({403
type: "combat-swing",427
type: "combat-swing",@@ -457,18 +481,11 @@ export function applyRemoteMeleeSwing (world, payload)457
payload.profile,481
payload.profile,458
payload.now ?? Date.now(),482
payload.now ?? Date.now(),459
to,483
to,460
payload.attackerLevels484
payload.attackerLevels,485
payload.attackerIsPlayer461
);486
);462
487
463
const forwards = [];488
const forwards = [];464
if (payload.attackerIsPlayer && ensureMobCombat(world.ecs, payload.targetId))465
{ engageTarget(world.ecs, payload.targetId, payload.attackerId, payload.now ?? Date.now()); }466
if (!payload.attackerIsPlayer)467
{468
const targetCharacter = world.ecs.get(targetHandle, Component.character);469
if (targetCharacter)470
{ engageTarget(world.ecs, payload.targetId, payload.attackerId, payload.now ?? Date.now()); }471
}472
const hitEvent = events.find((event) => event.type === "combat-hit");489
const hitEvent = events.find((event) => event.type === "combat-hit");473
if (hitEvent && payload.attackerIsPlayer)490
if (hitEvent && payload.attackerIsPlayer)474
{491
{@@ -490,19 +507,36 @@ function applyLocalMeleeHit (490
profile,507
profile,491
now,508
now,492
to,509
to,493
attackerLevelsOverride = null510
attackerLevelsOverride = null,511
attackerIsPlayerOverride = null494
)512
)495
{513
{496
const events = [];514
const events = [];497
if (targetHandle == null)515
if (targetHandle == null)498
{ return events; }516
{ return events; }499
517
500
if (attackerHandle != null)518
const attackerIsPlayer = attackerIsPlayerOverride != null519
? !!attackerIsPlayerOverride520
: (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);521
522
// Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.523
if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))524
{ engageTarget(world.ecs, targetId, attackerId, now); }525
if (attackerIsPlayer === false)501
{526
{502
const attackerCharacter = world.ecs.get(attackerHandle, Component.character);527
const targetCharacter = world.ecs.get(targetHandle, Component.character);503
// Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.528
if (targetCharacter)504
if (attackerCharacter && ensureMobCombat(world.ecs, targetId))529
{505
{ engageTarget(world.ecs, targetId, attackerId, now); }530
engageTarget(world.ecs, targetId, attackerId, now);531
const follow = world.ecs.get(targetHandle, Component.follow);532
if (follow)533
{534
follow.targetEntityId = null;535
follow.trail = [];536
}537
if (world.ecs.has(targetHandle, Component.gather))538
{ world.ecs.remove(targetHandle, Component.gather); }539
}506
}540
}507
541
508
const defenderSkills = world.ecs.get(targetHandle, Component.skills);542
const defenderSkills = world.ecs.get(targetHandle, Component.skills);@@ -291,7 +291,8 @@ function queueCatchUp (world, entityId, handle, position, targetPos, path)
291
291
bounds.minX,
292
292
bounds.minY,
293
293
bounds.maxX,
294
bounds.maxY
294
bounds.maxY,
295
{ preferVertical: true }
295
296
);
296
297
const movement = world.ecs.get(handle, Component.movement);
297
298
if (movement)
@@ -291,7 +291,8 @@ function queueCatchUp (world, entityId, handle, position, targetPos, path)291
bounds.minX,291
bounds.minX,292
bounds.minY,292
bounds.minY,293
bounds.maxX,293
bounds.maxX,294
bounds.maxY294
bounds.maxY,295
{ preferVertical: true }295
);296
);296
const movement = world.ecs.get(handle, Component.movement);297
const movement = world.ecs.get(handle, Component.movement);297
if (movement)298
if (movement)@@ -199,11 +199,6 @@ export class WorkerWorld
199
199
return this.#chunkData(chunkX, chunkY);
200
200
}
201
201
202
occupied (tileX, tileY)
203
{
204
return this.#occupied(tileX, tileY);
205
}
206
207
202
#configure (message)
208
203
{
209
204
if (message.settings)
@@ -325,7 +320,14 @@ export class WorkerWorld
325
320
for (const ghost of message.ghosts ?? [])
326
321
{
327
322
this.ghosts.set(ghost.entityId, ghost);
328
this.ghostOccupancy.set(tileKey(ghost.tileX, ghost.tileY), ghost.entityId);
323
const key = tileKey(ghost.tileX, ghost.tileY);
324
let set = this.ghostOccupancy.get(key);
325
if (!set)
326
{
327
set = new Set();
328
this.ghostOccupancy.set(key, set);
329
}
330
set.add(ghost.entityId);
329
331
}
330
332
return { ok: true };
331
333
}
@@ -343,8 +345,7 @@ export class WorkerWorld
343
345
const flying = this.#isFlying(handle);
344
346
if (!flying)
345
347
{
346
const occupant = this.#occupied(position.tileX, position.tileY);
347
if (occupant && occupant !== entityId)
348
if (this.#hasOtherOccupant(entityId, position.tileX, position.tileY))
348
349
{
349
350
this.ecs.destroy(handle);
350
351
const error = new Error("That tile is occupied.");
@@ -511,9 +512,7 @@ export class WorkerWorld
511
512
}
512
513
};
513
514
}
514
const occupant = this.#occupied(message.tileX, message.tileY);
515
if (!this.isEnterable(message.tileX, message.tileY)
516
|| (occupant && occupant !== message.entityId))
515
if (!this.isEnterable(message.tileX, message.tileY))
517
516
{ return { accepted: false }; }
518
517
this.#vacate(message.entityId, fromTileX, fromTileY);
519
518
position.tileX = message.tileX;
@@ -666,7 +665,8 @@ export class WorkerWorld
666
665
bounds.minX,
667
666
bounds.minY,
668
667
bounds.maxX,
669
bounds.maxY
668
bounds.maxY,
669
{ preferVertical: true }
670
670
);
671
671
movement.walkCarry = 0;
672
672
}
@@ -1140,6 +1140,7 @@ export class WorkerWorld
1140
1140
return;
1141
1141
}
1142
1142
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
1143
const stuckHandle = this.ecs.handleOf(entityId);
1143
1144
path.tiles = findPath(
1144
1145
position.tileX,
1145
1146
position.tileY,
@@ -1149,7 +1150,8 @@ export class WorkerWorld
1149
1150
bounds.minX,
1150
1151
bounds.minY,
1151
1152
bounds.maxX,
1152
bounds.maxY
1153
bounds.maxY,
1154
{ preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character) }
1153
1155
);
1154
1156
path.stuckSince = now;
1155
1157
path.stuckTileX = position.tileX;
@@ -1183,7 +1185,7 @@ export class WorkerWorld
1183
1185
const dir = dirs[Math.floor(Math.random() * dirs.length)];
1184
1186
const nextX = entity.position.tileX + dir.x;
1185
1187
const nextY = entity.position.tileY + dir.y;
1186
if (!this.walkableFor(entity.entityId, nextX, nextY))
1188
if (!this.isClearStanding(entity.entityId, nextX, nextY))
1187
1189
{ continue; }
1188
1190
path.tiles = [{ x: nextX, y: nextY }];
1189
1191
}
@@ -1394,7 +1396,7 @@ export class WorkerWorld
1394
1396
if (!data?.open)
1395
1397
{ return { accepted: false, reason: "blocked" }; }
1396
1398
}
1397
else if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
1399
else if (!this.isEnterable(destTileX, destTileY))
1398
1400
{ return { accepted: false, reason: "blocked" }; }
1399
1401
1400
1402
deserializeEntity(this.ecs, payload);
@@ -1521,11 +1523,6 @@ export class WorkerWorld
1521
1523
return !!chunk && !chunk.replica && chunk.simulating;
1522
1524
}
1523
1525
1524
chunkData (chunkX, chunkY)
1525
{
1526
return this.#chunkData(chunkX, chunkY);
1527
}
1528
1529
1526
walkableFor (entityId, tileX, tileY)
1530
1527
{
1531
1528
const handle = this.ecs.handleOf(entityId);
@@ -1534,10 +1531,19 @@ export class WorkerWorld
1534
1531
const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1535
1532
return !!data?.open;
1536
1533
}
1534
// Entities pass through each other; only terrain / closed chunks block movement.
1535
return this.isEnterable(tileX, tileY);
1536
}
1537
1538
/**
1539
* Standing tile with no other mob/player (self allowed). Used for wander goals
1540
* and melee attack stance.
1541
*/
1542
isClearStanding (entityId, tileX, tileY)
1543
{
1537
1544
if (!this.isEnterable(tileX, tileY))
1538
1545
{ return false; }
1539
const occupant = this.#occupied(tileX, tileY);
1540
return !occupant || occupant === entityId;
1546
return !this.#hasOtherOccupant(entityId, tileX, tileY);
1541
1547
}
1542
1548
1543
1549
destroyEntity (entityId)
@@ -1547,7 +1553,7 @@ export class WorkerWorld
1547
1553
1548
1554
occupied (tileX, tileY)
1549
1555
{
1550
return this.#occupied(tileX, tileY);
1556
return this.#anyOccupant(tileX, tileY);
1551
1557
}
1552
1558
1553
1559
#chunkIsSimulating (tileX, tileY)
@@ -1586,21 +1592,67 @@ export class WorkerWorld
1586
1592
1587
1593
#occupy (entityId, tileX, tileY)
1588
1594
{
1589
this.occupancy.set(tileKey(tileX, tileY), entityId);
1595
const key = tileKey(tileX, tileY);
1596
let set = this.occupancy.get(key);
1597
if (!set)
1598
{
1599
set = new Set();
1600
this.occupancy.set(key, set);
1601
}
1602
set.add(entityId);
1590
1603
}
1591
1604
1592
1605
#vacate (entityId, tileX, tileY)
1593
1606
{
1594
1607
const key = tileKey(tileX, tileY);
1595
if (this.occupancy.get(key) === entityId)
1608
const set = this.occupancy.get(key);
1609
if (!set)
1610
{ return; }
1611
set.delete(entityId);
1612
if (set.size === 0)
1596
1613
{ this.occupancy.delete(key); }
1597
1614
}
1598
1615
1616
#anyOccupant (tileX, tileY)
1617
{
1618
const key = tileKey(tileX, tileY);
1619
const local = this.occupancy.get(key);
1620
if (local?.size)
1621
{ return local.values().next().value; }
1622
const ghosts = this.ghostOccupancy.get(key);
1623
if (ghosts?.size)
1624
{ return ghosts.values().next().value; }
1625
return null;
1626
}
1627
1628
#hasOtherOccupant (entityId, tileX, tileY)
1629
{
1630
const key = tileKey(tileX, tileY);
1631
const local = this.occupancy.get(key);
1632
if (local)
1633
{
1634
for (const id of local)
1635
{
1636
if (id !== entityId)
1637
{ return true; }
1638
}
1639
}
1640
const ghosts = this.ghostOccupancy.get(key);
1641
if (ghosts)
1642
{
1643
for (const id of ghosts)
1644
{
1645
if (id !== entityId)
1646
{ return true; }
1647
}
1648
}
1649
return false;
1650
}
1651
1652
/** @deprecated use #anyOccupant — kept name for call sites expecting a single id */
1599
1653
#occupied (tileX, tileY)
1600
1654
{
1601
return this.occupancy.get(tileKey(tileX, tileY))
1602
?? this.ghostOccupancy.get(tileKey(tileX, tileY))
1603
?? null;
1655
return this.#anyOccupant(tileX, tileY);
1604
1656
}
1605
1657
}
1606
1658
@@ -1611,7 +1663,7 @@ function pickWanderGoalInRange (world, entityId, originX, originY, range)
1611
1663
{
1612
1664
const tileX = originX + randInt(-radius, radius);
1613
1665
const tileY = originY + randInt(-radius, radius);
1614
if (!world.walkableFor(entityId, tileX, tileY))
1666
if (!world.isClearStanding(entityId, tileX, tileY))
1615
1667
{ continue; }
1616
1668
return { tileX, tileY };
1617
1669
}
@@ -199,11 +199,6 @@ export class WorkerWorld199
return this.#chunkData(chunkX, chunkY);199
return this.#chunkData(chunkX, chunkY);200
}200
}201
201
202
occupied (tileX, tileY)203
{204
return this.#occupied(tileX, tileY);205
}206
207
#configure (message)202
#configure (message)208
{203
{209
if (message.settings)204
if (message.settings)@@ -325,7 +320,14 @@ export class WorkerWorld325
for (const ghost of message.ghosts ?? [])320
for (const ghost of message.ghosts ?? [])326
{321
{327
this.ghosts.set(ghost.entityId, ghost);322
this.ghosts.set(ghost.entityId, ghost);328
this.ghostOccupancy.set(tileKey(ghost.tileX, ghost.tileY), ghost.entityId);323
const key = tileKey(ghost.tileX, ghost.tileY);324
let set = this.ghostOccupancy.get(key);325
if (!set)326
{327
set = new Set();328
this.ghostOccupancy.set(key, set);329
}330
set.add(ghost.entityId);329
}331
}330
return { ok: true };332
return { ok: true };331
}333
}@@ -343,8 +345,7 @@ export class WorkerWorld343
const flying = this.#isFlying(handle);345
const flying = this.#isFlying(handle);344
if (!flying)346
if (!flying)345
{347
{346
const occupant = this.#occupied(position.tileX, position.tileY);348
if (this.#hasOtherOccupant(entityId, position.tileX, position.tileY))347
if (occupant && occupant !== entityId)348
{349
{349
this.ecs.destroy(handle);350
this.ecs.destroy(handle);350
const error = new Error("That tile is occupied.");351
const error = new Error("That tile is occupied.");@@ -511,9 +512,7 @@ export class WorkerWorld511
}512
}512
};513
};513
}514
}514
const occupant = this.#occupied(message.tileX, message.tileY);515
if (!this.isEnterable(message.tileX, message.tileY))515
if (!this.isEnterable(message.tileX, message.tileY)516
|| (occupant && occupant !== message.entityId))517
{ return { accepted: false }; }516
{ return { accepted: false }; }518
this.#vacate(message.entityId, fromTileX, fromTileY);517
this.#vacate(message.entityId, fromTileX, fromTileY);519
position.tileX = message.tileX;518
position.tileX = message.tileX;@@ -666,7 +665,8 @@ export class WorkerWorld666
bounds.minX,665
bounds.minX,667
bounds.minY,666
bounds.minY,668
bounds.maxX,667
bounds.maxX,669
bounds.maxY668
bounds.maxY,669
{ preferVertical: true }670
);670
);671
movement.walkCarry = 0;671
movement.walkCarry = 0;672
}672
}@@ -1140,6 +1140,7 @@ export class WorkerWorld1140
return;1140
return;1141
}1141
}1142
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);1142
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);1143
const stuckHandle = this.ecs.handleOf(entityId);1143
path.tiles = findPath(1144
path.tiles = findPath(1144
position.tileX,1145
position.tileX,1145
position.tileY,1146
position.tileY,@@ -1149,7 +1150,8 @@ export class WorkerWorld1149
bounds.minX,1150
bounds.minX,1150
bounds.minY,1151
bounds.minY,1151
bounds.maxX,1152
bounds.maxX,1152
bounds.maxY1153
bounds.maxY,1154
{ preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character) }1153
);1155
);1154
path.stuckSince = now;1156
path.stuckSince = now;1155
path.stuckTileX = position.tileX;1157
path.stuckTileX = position.tileX;@@ -1183,7 +1185,7 @@ export class WorkerWorld1183
const dir = dirs[Math.floor(Math.random() * dirs.length)];1185
const dir = dirs[Math.floor(Math.random() * dirs.length)];1184
const nextX = entity.position.tileX + dir.x;1186
const nextX = entity.position.tileX + dir.x;1185
const nextY = entity.position.tileY + dir.y;1187
const nextY = entity.position.tileY + dir.y;1186
if (!this.walkableFor(entity.entityId, nextX, nextY))1188
if (!this.isClearStanding(entity.entityId, nextX, nextY))1187
{ continue; }1189
{ continue; }1188
path.tiles = [{ x: nextX, y: nextY }];1190
path.tiles = [{ x: nextX, y: nextY }];1189
}1191
}@@ -1394,7 +1396,7 @@ export class WorkerWorld1394
if (!data?.open)1396
if (!data?.open)1395
{ return { accepted: false, reason: "blocked" }; }1397
{ return { accepted: false, reason: "blocked" }; }1396
}1398
}1397
else if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))1399
else if (!this.isEnterable(destTileX, destTileY))1398
{ return { accepted: false, reason: "blocked" }; }1400
{ return { accepted: false, reason: "blocked" }; }1399
1401
1400
deserializeEntity(this.ecs, payload);1402
deserializeEntity(this.ecs, payload);@@ -1521,11 +1523,6 @@ export class WorkerWorld1521
return !!chunk && !chunk.replica && chunk.simulating;1523
return !!chunk && !chunk.replica && chunk.simulating;1522
}1524
}1523
1525
1524
chunkData (chunkX, chunkY)1525
{1526
return this.#chunkData(chunkX, chunkY);1527
}1528
1529
walkableFor (entityId, tileX, tileY)1526
walkableFor (entityId, tileX, tileY)1530
{1527
{1531
const handle = this.ecs.handleOf(entityId);1528
const handle = this.ecs.handleOf(entityId);@@ -1534,10 +1531,19 @@ export class WorkerWorld1534
const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));1531
const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));1535
return !!data?.open;1532
return !!data?.open;1536
}1533
}1534
// Entities pass through each other; only terrain / closed chunks block movement.1535
return this.isEnterable(tileX, tileY);1536
}1537
1538
/**1539
* Standing tile with no other mob/player (self allowed). Used for wander goals1540
* and melee attack stance.1541
*/1542
isClearStanding (entityId, tileX, tileY)1543
{1537
if (!this.isEnterable(tileX, tileY))1544
if (!this.isEnterable(tileX, tileY))1538
{ return false; }1545
{ return false; }1539
const occupant = this.#occupied(tileX, tileY);1546
return !this.#hasOtherOccupant(entityId, tileX, tileY);1540
return !occupant || occupant === entityId;1541
}1547
}1542
1548
1543
destroyEntity (entityId)1549
destroyEntity (entityId)@@ -1547,7 +1553,7 @@ export class WorkerWorld1547
1553
1548
occupied (tileX, tileY)1554
occupied (tileX, tileY)1549
{1555
{1550
return this.#occupied(tileX, tileY);1556
return this.#anyOccupant(tileX, tileY);1551
}1557
}1552
1558
1553
#chunkIsSimulating (tileX, tileY)1559
#chunkIsSimulating (tileX, tileY)@@ -1586,21 +1592,67 @@ export class WorkerWorld1586
1592
1587
#occupy (entityId, tileX, tileY)1593
#occupy (entityId, tileX, tileY)1588
{1594
{1589
this.occupancy.set(tileKey(tileX, tileY), entityId);1595
const key = tileKey(tileX, tileY);1596
let set = this.occupancy.get(key);1597
if (!set)1598
{1599
set = new Set();1600
this.occupancy.set(key, set);1601
}1602
set.add(entityId);1590
}1603
}1591
1604
1592
#vacate (entityId, tileX, tileY)1605
#vacate (entityId, tileX, tileY)1593
{1606
{1594
const key = tileKey(tileX, tileY);1607
const key = tileKey(tileX, tileY);1595
if (this.occupancy.get(key) === entityId)1608
const set = this.occupancy.get(key);1609
if (!set)1610
{ return; }1611
set.delete(entityId);1612
if (set.size === 0)1596
{ this.occupancy.delete(key); }1613
{ this.occupancy.delete(key); }1597
}1614
}1598
1615
1616
#anyOccupant (tileX, tileY)1617
{1618
const key = tileKey(tileX, tileY);1619
const local = this.occupancy.get(key);1620
if (local?.size)1621
{ return local.values().next().value; }1622
const ghosts = this.ghostOccupancy.get(key);1623
if (ghosts?.size)1624
{ return ghosts.values().next().value; }1625
return null;1626
}1627
1628
#hasOtherOccupant (entityId, tileX, tileY)1629
{1630
const key = tileKey(tileX, tileY);1631
const local = this.occupancy.get(key);1632
if (local)1633
{1634
for (const id of local)1635
{1636
if (id !== entityId)1637
{ return true; }1638
}1639
}1640
const ghosts = this.ghostOccupancy.get(key);1641
if (ghosts)1642
{1643
for (const id of ghosts)1644
{1645
if (id !== entityId)1646
{ return true; }1647
}1648
}1649
return false;1650
}1651
1652
/** @deprecated use #anyOccupant — kept name for call sites expecting a single id */1599
#occupied (tileX, tileY)1653
#occupied (tileX, tileY)1600
{1654
{1601
return this.occupancy.get(tileKey(tileX, tileY))1655
return this.#anyOccupant(tileX, tileY);1602
?? this.ghostOccupancy.get(tileKey(tileX, tileY))1603
?? null;1604
}1656
}1605
}1657
}1606
1658
@@ -1611,7 +1663,7 @@ function pickWanderGoalInRange (world, entityId, originX, originY, range)1611
{1663
{1612
const tileX = originX + randInt(-radius, radius);1664
const tileX = originX + randInt(-radius, radius);1613
const tileY = originY + randInt(-radius, radius);1665
const tileY = originY + randInt(-radius, radius);1614
if (!world.walkableFor(entityId, tileX, tileY))1666
if (!world.isClearStanding(entityId, tileX, tileY))1615
{ continue; }1667
{ continue; }1616
return { tileX, tileY };1668
return { tileX, tileY };1617
}1669
}@@ -1,6 +1,6 @@
1
1
import test from "node:test";
2
2
import assert from "node:assert/strict";
3
import { findPath } from "../src/navigation/astar.js";
3
import { findPath, orderedCardinals } from "../src/navigation/astar.js";
4
4
5
5
test("A* walks around an impassable tile", () =>
6
6
{
@@ -16,3 +16,28 @@ test("A* returns empty when the goal is blocked", () =>
16
16
const path = findPath(0, 0, 1, 0, (x, y) => x === 0 && y === 0, -2, -2, 2, 2);
17
17
assert.deepEqual(path, []);
18
18
});
19
20
test("ordered cardinals prefer distance reduction then axis", () =>
21
{
22
const horizontalPrefer = orderedCardinals(0, 0, -1, -3, false);
23
assert.deepEqual(horizontalPrefer[0], { x: -1, y: 0 });
24
assert.deepEqual(horizontalPrefer[1], { x: 0, y: -1 });
25
26
const verticalPrefer = orderedCardinals(0, 0, -1, -3, true);
27
assert.deepEqual(verticalPrefer[0], { x: 0, y: -1 });
28
assert.deepEqual(verticalPrefer[1], { x: -1, y: 0 });
29
30
const horizontalOnly = orderedCardinals(0, 0, 3, 0, false);
31
assert.deepEqual(horizontalOnly[0], { x: 1, y: 0 });
32
});
33
34
test("player and mob axis bias diverge on diagonal goals", () =>
35
{
36
const open = () => true;
37
const mobPath = findPath(0, 0, -1, -3, open, -8, -8, 8, 8, { preferVertical: false });
38
const playerPath = findPath(0, 0, -1, -3, open, -8, -8, 8, 8, { preferVertical: true });
39
assert.equal(mobPath.length, 4);
40
assert.equal(playerPath.length, 4);
41
assert.deepEqual(mobPath[0], { x: -1, y: 0 });
42
assert.deepEqual(playerPath[0], { x: 0, y: -1 });
43
});
@@ -1,6 +1,6 @@1
import test from "node:test";1
import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { findPath } from "../src/navigation/astar.js";3
import { findPath, orderedCardinals } from "../src/navigation/astar.js";4
4
5
test("A* walks around an impassable tile", () =>5
test("A* walks around an impassable tile", () =>6
{6
{@@ -16,3 +16,28 @@ test("A* returns empty when the goal is blocked", () =>16
const path = findPath(0, 0, 1, 0, (x, y) => x === 0 && y === 0, -2, -2, 2, 2);16
const path = findPath(0, 0, 1, 0, (x, y) => x === 0 && y === 0, -2, -2, 2, 2);17
assert.deepEqual(path, []);17
assert.deepEqual(path, []);18
});18
});19
20
test("ordered cardinals prefer distance reduction then axis", () =>21
{22
const horizontalPrefer = orderedCardinals(0, 0, -1, -3, false);23
assert.deepEqual(horizontalPrefer[0], { x: -1, y: 0 });24
assert.deepEqual(horizontalPrefer[1], { x: 0, y: -1 });25
26
const verticalPrefer = orderedCardinals(0, 0, -1, -3, true);27
assert.deepEqual(verticalPrefer[0], { x: 0, y: -1 });28
assert.deepEqual(verticalPrefer[1], { x: -1, y: 0 });29
30
const horizontalOnly = orderedCardinals(0, 0, 3, 0, false);31
assert.deepEqual(horizontalOnly[0], { x: 1, y: 0 });32
});33
34
test("player and mob axis bias diverge on diagonal goals", () =>35
{36
const open = () => true;37
const mobPath = findPath(0, 0, -1, -3, open, -8, -8, 8, 8, { preferVertical: false });38
const playerPath = findPath(0, 0, -1, -3, open, -8, -8, 8, 8, { preferVertical: true });39
assert.equal(mobPath.length, 4);40
assert.equal(playerPath.length, 4);41
assert.deepEqual(mobPath[0], { x: -1, y: 0 });42
assert.deepEqual(playerPath[0], { x: 0, y: -1 });43
});@@ -32,10 +32,24 @@ function teleportEntity (worker, entityId, tileX, tileY)
32
32
const world = worker.world;
33
33
const handle = world.ecs.handleOf(entityId);
34
34
const pos = world.ecs.get(handle, Component.position);
35
world.occupancy.delete(tileKey(pos.tileX, pos.tileY));
35
const fromKey = tileKey(pos.tileX, pos.tileY);
36
const fromSet = world.occupancy.get(fromKey);
37
if (fromSet)
38
{
39
fromSet.delete(entityId);
40
if (fromSet.size === 0)
41
{ world.occupancy.delete(fromKey); }
42
}
36
43
pos.tileX = tileX;
37
44
pos.tileY = tileY;
38
world.occupancy.set(tileKey(tileX, tileY), entityId);
45
const toKey = tileKey(tileX, tileY);
46
let toSet = world.occupancy.get(toKey);
47
if (!toSet)
48
{
49
toSet = new Set();
50
world.occupancy.set(toKey, toSet);
51
}
52
toSet.add(entityId);
39
53
}
40
54
41
55
function entityIsAlive (simulation, entityId)
@@ -533,6 +547,46 @@ test("aggressive rats engage players within aggro range and LOS", () =>
533
547
{ harness.close(); }
534
548
});
535
549
550
test("players retaliate when a mob swings at them", () =>
551
{
552
const harness = makeSimulation({ workerCount: 1 });
553
try
554
{
555
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
556
const playerId = harness.simulation.spawnCharacter(1, character);
557
const ratId = harness.simulation.spawnEntity(mobComponents({
558
tileX: 9,
559
tileY: 8,
560
mobTypeId: MobId.rat,
561
spawnerId: null
562
}));
563
564
assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null, null);
565
566
let swung = false;
567
for (let i = 0; i < 80; i++)
568
{
569
harness.advance(50);
570
const events = harness.simulation.step().events;
571
if (events.some((event) =>
572
event.type === "combat-swing" && event.attackerId === ratId && event.targetId === playerId
573
))
574
{
575
swung = true;
576
break;
577
}
578
}
579
assert.ok(swung, "expected the rat to swing at the player");
580
assert.equal(
581
componentsOf(harness.simulation, playerId).combat?.targetEntityId,
582
ratId,
583
"player should auto-retaliate after the mob swing"
584
);
585
}
586
finally
587
{ harness.close(); }
588
});
589
536
590
test("aggressive rats do not aggro through walls or beyond range", () =>
537
591
{
538
592
const harness = makeSimulation({ workerCount: 1 });
@@ -633,7 +687,15 @@ test("combatants keep auto-attacking while adjacent", () =>
633
687
for (let i = 0; i < 50; i++)
634
688
{
635
689
harness.advance(50);
636
swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
690
const events = harness.simulation.step().events;
691
swings += events.filter((event) => event.type === "combat-swing").length;
692
const player = componentsOf(harness.simulation, playerId);
693
const deer = componentsOf(harness.simulation, deerId);
694
if (swings >= 4
695
&& player.combat?.targetEntityId === deerId
696
&& deer.combat?.targetEntityId === playerId
697
&& (player.health?.current ?? 0) > 0)
698
{ break; }
637
699
}
638
700
639
701
assert.ok(swings >= 4, `expected repeated swings, got ${swings}`);
@@ -676,10 +738,12 @@ test("cross-worker adjacent combat keeps engaging and swinging", () =>
676
738
try
677
739
{
678
740
let swings = 0;
679
for (let i = 0; i < 5; i++)
741
for (let i = 0; i < 40; i++)
680
742
{
681
743
harness.advance(50);
682
744
swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
745
if (swings >= 4)
746
{ break; }
683
747
}
684
748
685
749
assert.ok(swings >= 4, `expected cross-worker sustained swings, got ${swings}`);
@@ -32,10 +32,24 @@ function teleportEntity (worker, entityId, tileX, tileY)32
const world = worker.world;32
const world = worker.world;33
const handle = world.ecs.handleOf(entityId);33
const handle = world.ecs.handleOf(entityId);34
const pos = world.ecs.get(handle, Component.position);34
const pos = world.ecs.get(handle, Component.position);35
world.occupancy.delete(tileKey(pos.tileX, pos.tileY));35
const fromKey = tileKey(pos.tileX, pos.tileY);36
const fromSet = world.occupancy.get(fromKey);37
if (fromSet)38
{39
fromSet.delete(entityId);40
if (fromSet.size === 0)41
{ world.occupancy.delete(fromKey); }42
}36
pos.tileX = tileX;43
pos.tileX = tileX;37
pos.tileY = tileY;44
pos.tileY = tileY;38
world.occupancy.set(tileKey(tileX, tileY), entityId);45
const toKey = tileKey(tileX, tileY);46
let toSet = world.occupancy.get(toKey);47
if (!toSet)48
{49
toSet = new Set();50
world.occupancy.set(toKey, toSet);51
}52
toSet.add(entityId);39
}53
}40
54
41
function entityIsAlive (simulation, entityId)55
function entityIsAlive (simulation, entityId)@@ -533,6 +547,46 @@ test("aggressive rats engage players within aggro range and LOS", () =>533
{ harness.close(); }547
{ harness.close(); }534
});548
});535
549
550
test("players retaliate when a mob swings at them", () =>551
{552
const harness = makeSimulation({ workerCount: 1 });553
try554
{555
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });556
const playerId = harness.simulation.spawnCharacter(1, character);557
const ratId = harness.simulation.spawnEntity(mobComponents({558
tileX: 9,559
tileY: 8,560
mobTypeId: MobId.rat,561
spawnerId: null562
}));563
564
assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null, null);565
566
let swung = false;567
for (let i = 0; i < 80; i++)568
{569
harness.advance(50);570
const events = harness.simulation.step().events;571
if (events.some((event) =>572
event.type === "combat-swing" && event.attackerId === ratId && event.targetId === playerId573
))574
{575
swung = true;576
break;577
}578
}579
assert.ok(swung, "expected the rat to swing at the player");580
assert.equal(581
componentsOf(harness.simulation, playerId).combat?.targetEntityId,582
ratId,583
"player should auto-retaliate after the mob swing"584
);585
}586
finally587
{ harness.close(); }588
});589
536
test("aggressive rats do not aggro through walls or beyond range", () =>590
test("aggressive rats do not aggro through walls or beyond range", () =>537
{591
{538
const harness = makeSimulation({ workerCount: 1 });592
const harness = makeSimulation({ workerCount: 1 });@@ -633,7 +687,15 @@ test("combatants keep auto-attacking while adjacent", () =>633
for (let i = 0; i < 50; i++)687
for (let i = 0; i < 50; i++)634
{688
{635
harness.advance(50);689
harness.advance(50);636
swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;690
const events = harness.simulation.step().events;691
swings += events.filter((event) => event.type === "combat-swing").length;692
const player = componentsOf(harness.simulation, playerId);693
const deer = componentsOf(harness.simulation, deerId);694
if (swings >= 4695
&& player.combat?.targetEntityId === deerId696
&& deer.combat?.targetEntityId === playerId697
&& (player.health?.current ?? 0) > 0)698
{ break; }637
}699
}638
700
639
assert.ok(swings >= 4, `expected repeated swings, got ${swings}`);701
assert.ok(swings >= 4, `expected repeated swings, got ${swings}`);@@ -676,10 +738,12 @@ test("cross-worker adjacent combat keeps engaging and swinging", () =>676
try738
try677
{739
{678
let swings = 0;740
let swings = 0;679
for (let i = 0; i < 5; i++)741
for (let i = 0; i < 40; i++)680
{742
{681
harness.advance(50);743
harness.advance(50);682
swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;744
swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;745
if (swings >= 4)746
{ break; }683
}747
}684
748
685
assert.ok(swings >= 4, `expected cross-worker sustained swings, got ${swings}`);749
assert.ok(swings >= 4, `expected cross-worker sustained swings, got ${swings}`);@@ -33,7 +33,7 @@ test("a player at a region edge receives snapshots from both workers", () =>
33
33
{ harness.close(); }
34
34
});
35
35
36
test("border occupancy from another worker blocks pathfinding", () =>
36
test("entities can path through each other across a region border", () =>
37
37
{
38
38
const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
39
39
try
@@ -44,8 +44,8 @@ test("border occupancy from another worker blocks pathfinding", () =>
44
44
harness.simulation.spawnCharacter(2, blocker);
45
45
harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });
46
46
stepTimes(harness.simulation, walkTicks(2));
47
assert.equal(harness.simulation.entityRecord(walkerId).tileX, 63);
48
assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);
47
assert.equal(harness.simulation.entityRecord(walkerId).tileX, 64);
48
assert.equal(harness.simulation.entityRecord(walkerId).tileY, 8);
49
49
}
50
50
finally
51
51
{ harness.close(); }
@@ -33,7 +33,7 @@ test("a player at a region edge receives snapshots from both workers", () =>33
{ harness.close(); }33
{ harness.close(); }34
});34
});35
35
36
test("border occupancy from another worker blocks pathfinding", () =>36
test("entities can path through each other across a region border", () =>37
{37
{38
const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });38
const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });39
try39
try@@ -44,8 +44,8 @@ test("border occupancy from another worker blocks pathfinding", () =>44
harness.simulation.spawnCharacter(2, blocker);44
harness.simulation.spawnCharacter(2, blocker);45
harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });45
harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });46
stepTimes(harness.simulation, walkTicks(2));46
stepTimes(harness.simulation, walkTicks(2));47
assert.equal(harness.simulation.entityRecord(walkerId).tileX, 63);47
assert.equal(harness.simulation.entityRecord(walkerId).tileX, 64);48
assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);48
assert.equal(harness.simulation.entityRecord(walkerId).tileY, 8);49
}49
}50
finally50
finally51
{ harness.close(); }51
{ harness.close(); }