Add shears, shearable animals, and flax gathering.
Smith shears from one bar and plant clippers from bar+leather; sheep/goats yield wool/cashmere with fleece regrowth; flax plants clip into Flax for linen yarn.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -38,6 +38,8 @@ import { formatQuantity } from "/shared/items/formatQuantity.js";
38
38
import { ItemId, itemDefinition } from "/shared/definitions/items.js";
39
39
import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
40
40
import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
41
import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
42
import { mobDefinition } from "/shared/definitions/mobs.js";
41
43
import { countCoinsInSlots } from "/shared/items/inventory.js";
42
44
43
45
const game = new Game();
@@ -581,6 +583,48 @@ function requestTalk (targetEntityId, purpose = null)
581
583
{ flushPendingInteract(); }
582
584
}
583
585
586
function playerHasShears ()
587
{
588
const slots = inventory?.getInventorySlots?.() ?? [];
589
const equipment = inventory?.getEquipment?.() ?? {};
590
for (const stack of [...slots, equipment.weapon])
591
{
592
if (!stack?.itemId)
593
{ continue; }
594
if (itemDefinition(stack.itemId)?.equipment?.kind === EquipmentKind.shears)
595
{ return true; }
596
}
597
return false;
598
}
599
600
function entityCanShear (entity)
601
{
602
if (!entity?.mobTypeId)
603
{ return false; }
604
const def = mobDefinition(entity.mobTypeId);
605
const shearable = def?.shearable;
606
if (!shearable)
607
{ return false; }
608
const sprite = entity.layers?.[0]?.sprite ?? entity.sprite ?? "";
609
if (String(sprite).endsWith(`:${shearable.shornState}`))
610
{ return false; }
611
return playerHasShears();
612
}
613
614
function requestShear (targetEntityId)
615
{
616
clearAllPendingActions();
617
pendingInteract = { kind: "shear", targetEntityId };
618
const target = view?.entities.get(targetEntityId);
619
if (!target)
620
{
621
clearPendingInteract();
622
return;
623
}
624
if (approachAdjacentTile(target.tileX, target.tileY))
625
{ flushPendingInteract(); }
626
}
627
584
628
function setUiFocus (focus)
585
629
{
586
630
uiFocus = focus;
@@ -884,6 +928,26 @@ function flushPendingInteract ()
884
928
});
885
929
clearPendingInteract();
886
930
}
931
932
if (pendingInteract.kind === "shear")
933
{
934
const target = view.entities.get(pendingInteract.targetEntityId);
935
if (!target)
936
{
937
clearPendingInteract();
938
return;
939
}
940
if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1)
941
{
942
approachAdjacentTile(target.tileX, target.tileY);
943
return;
944
}
945
socket.send({
946
type: MessageType.shear,
947
targetEntityId: pendingInteract.targetEntityId
948
});
949
clearPendingInteract();
950
}
887
951
}
888
952
889
953
function requestPickup (ground)
@@ -1113,6 +1177,13 @@ function handleRightClick (event, mouseX, mouseY)
1113
1177
onSelect: () => requestTalk(entity.entityId, "talk")
1114
1178
});
1115
1179
}
1180
if (entityCanShear(entity))
1181
{
1182
items.push({
1183
label: `Shear ${targetName}`,
1184
onSelect: () => requestShear(entity.entityId)
1185
});
1186
}
1116
1187
if (entity.characterId)
1117
1188
{
1118
1189
items.push({
@@ -38,6 +38,8 @@ import { formatQuantity } from "/shared/items/formatQuantity.js";38
import { ItemId, itemDefinition } from "/shared/definitions/items.js";38
import { ItemId, itemDefinition } from "/shared/definitions/items.js";39
import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";39
import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";40
import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";40
import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";41
import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";42
import { mobDefinition } from "/shared/definitions/mobs.js";41
import { countCoinsInSlots } from "/shared/items/inventory.js";43
import { countCoinsInSlots } from "/shared/items/inventory.js";42
44
43
const game = new Game();45
const game = new Game();@@ -581,6 +583,48 @@ function requestTalk (targetEntityId, purpose = null)581
{ flushPendingInteract(); }583
{ flushPendingInteract(); }582
}584
}583
585
586
function playerHasShears ()587
{588
const slots = inventory?.getInventorySlots?.() ?? [];589
const equipment = inventory?.getEquipment?.() ?? {};590
for (const stack of [...slots, equipment.weapon])591
{592
if (!stack?.itemId)593
{ continue; }594
if (itemDefinition(stack.itemId)?.equipment?.kind === EquipmentKind.shears)595
{ return true; }596
}597
return false;598
}599
600
function entityCanShear (entity)601
{602
if (!entity?.mobTypeId)603
{ return false; }604
const def = mobDefinition(entity.mobTypeId);605
const shearable = def?.shearable;606
if (!shearable)607
{ return false; }608
const sprite = entity.layers?.[0]?.sprite ?? entity.sprite ?? "";609
if (String(sprite).endsWith(`:${shearable.shornState}`))610
{ return false; }611
return playerHasShears();612
}613
614
function requestShear (targetEntityId)615
{616
clearAllPendingActions();617
pendingInteract = { kind: "shear", targetEntityId };618
const target = view?.entities.get(targetEntityId);619
if (!target)620
{621
clearPendingInteract();622
return;623
}624
if (approachAdjacentTile(target.tileX, target.tileY))625
{ flushPendingInteract(); }626
}627
584
function setUiFocus (focus)628
function setUiFocus (focus)585
{629
{586
uiFocus = focus;630
uiFocus = focus;@@ -884,6 +928,26 @@ function flushPendingInteract ()884
});928
});885
clearPendingInteract();929
clearPendingInteract();886
}930
}931
932
if (pendingInteract.kind === "shear")933
{934
const target = view.entities.get(pendingInteract.targetEntityId);935
if (!target)936
{937
clearPendingInteract();938
return;939
}940
if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1)941
{942
approachAdjacentTile(target.tileX, target.tileY);943
return;944
}945
socket.send({946
type: MessageType.shear,947
targetEntityId: pendingInteract.targetEntityId948
});949
clearPendingInteract();950
}887
}951
}888
952
889
function requestPickup (ground)953
function requestPickup (ground)@@ -1113,6 +1177,13 @@ function handleRightClick (event, mouseX, mouseY)1113
onSelect: () => requestTalk(entity.entityId, "talk")1177
onSelect: () => requestTalk(entity.entityId, "talk")1114
});1178
});1115
}1179
}1180
if (entityCanShear(entity))1181
{1182
items.push({1183
label: `Shear ${targetName}`,1184
onSelect: () => requestShear(entity.entityId)1185
});1186
}1116
if (entity.characterId)1187
if (entity.characterId)1117
{1188
{1118
items.push({1189
items.push({@@ -452,6 +452,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
452
452
groundItemId: message.groundItemId | 0
453
453
});
454
454
break;
455
case MessageType.shear:
456
requirePlaying(session);
457
simulation.enqueue(session.id, {
458
type: "shear",
459
characterId: session.characterId,
460
targetEntityId: message.targetEntityId | 0
461
});
462
break;
455
463
case MessageType.startFish:
456
464
requirePlaying(session);
457
465
simulation.enqueue(session.id, {
@@ -452,6 +452,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,452
groundItemId: message.groundItemId | 0452
groundItemId: message.groundItemId | 0453
});453
});454
break;454
break;455
case MessageType.shear:456
requirePlaying(session);457
simulation.enqueue(session.id, {458
type: "shear",459
characterId: session.characterId,460
targetEntityId: message.targetEntityId | 0461
});462
break;455
case MessageType.startFish:463
case MessageType.startFish:456
requirePlaying(session);464
requirePlaying(session);457
simulation.enqueue(session.id, {465
simulation.enqueue(session.id, {@@ -469,7 +469,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
469
469
inventorySlots: inventory?.slots,
470
470
equipmentSlots: equipment?.slots,
471
471
skills,
472
requireTool: !!plant.requiresClippers
472
requireTool: !!plant.requiresClippers,
473
minClothTier: plant.minClothTier ?? null
473
474
});
474
475
if (!clippers.ok)
475
476
{ throw userError(clippers.reason); }
@@ -711,6 +712,10 @@ function completePlant (world, handle, entityId, character, gather, events, priv
711
712
{
712
713
itemId = rawClothItemId(ClothTier.cotton);
713
714
}
715
else if (gather.plantKind === "flax")
716
{
717
itemId = rawClothItemId(ClothTier.linen);
718
}
714
719
else if (gather.plantKind === "herb")
715
720
{
716
721
const herb = herbDefinition(gather.herbId);
@@ -898,5 +903,7 @@ function defaultPlantState (typeId)
898
903
{
899
904
if (typeId === BlockType.herbPlant)
900
905
{ return "mint"; }
906
if (typeId === BlockType.flaxPlant)
907
{ return "flax-plant"; }
901
908
return "cotton-plant";
902
909
}
@@ -469,7 +469,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)469
inventorySlots: inventory?.slots,469
inventorySlots: inventory?.slots,470
equipmentSlots: equipment?.slots,470
equipmentSlots: equipment?.slots,471
skills,471
skills,472
requireTool: !!plant.requiresClippers472
requireTool: !!plant.requiresClippers,473
minClothTier: plant.minClothTier ?? null473
});474
});474
if (!clippers.ok)475
if (!clippers.ok)475
{ throw userError(clippers.reason); }476
{ throw userError(clippers.reason); }@@ -711,6 +712,10 @@ function completePlant (world, handle, entityId, character, gather, events, priv711
{712
{712
itemId = rawClothItemId(ClothTier.cotton);713
itemId = rawClothItemId(ClothTier.cotton);713
}714
}715
else if (gather.plantKind === "flax")716
{717
itemId = rawClothItemId(ClothTier.linen);718
}714
else if (gather.plantKind === "herb")719
else if (gather.plantKind === "herb")715
{720
{716
const herb = herbDefinition(gather.herbId);721
const herb = herbDefinition(gather.herbId);@@ -898,5 +903,7 @@ function defaultPlantState (typeId)898
{903
{899
if (typeId === BlockType.herbPlant)904
if (typeId === BlockType.herbPlant)900
{ return "mint"; }905
{ return "mint"; }906
if (typeId === BlockType.flaxPlant)907
{ return "flax-plant"; }901
return "cotton-plant";908
return "cotton-plant";902
}909
}@@ -0,0 +1,370 @@
1
import { Component } from "../ecs/components.js";
2
import { mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
3
import { resolveShears } from "../../../shared/definitions/gathering.js";
4
import { rawClothItemId } from "../../../shared/definitions/clothItems.js";
5
import {
6
clothExhaustDurationMs
7
} from "../../../shared/definitions/materialTiers.js";
8
import { itemDefinition } from "../../../shared/definitions/items.js";
9
import { SkillId } from "../../../shared/definitions/skills.js";
10
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
11
import { insertStack } from "../../../shared/items/inventory.js";
12
import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";
13
import { bagView } from "../items/bags.js";
14
import { chebyshev } from "../combat/service.js";
15
import { publicEntityView, replicationAppearance } from "../ecs/serialize.js";
16
import { scaleRegrowDurationMs } from "../../../shared/world/season.js";
17
import { tileShoveEvent } from "../simulation/tileInteract.js";
18
19
const SHEAR_DURATION_MS = 3000;
20
const SHEAR_SHOVE_MS = 1000;
21
22
function userError (message)
23
{
24
const error = new Error(message);
25
error.userFacing = true;
26
return error;
27
}
28
29
function characterDisplayName (world, handle)
30
{
31
const appearance = world.ecs.get(handle, Component.appearance);
32
const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
33
return name || "someone";
34
}
35
36
function ensureShearSessions (world)
37
{
38
if (!world.shearSessions)
39
{ world.shearSessions = new Map(); }
40
return world.shearSessions;
41
}
42
43
function clearShearSession (world, characterId)
44
{
45
const sessions = world.shearSessions;
46
if (!sessions)
47
{ return; }
48
const session = sessions.get(characterId);
49
if (session)
50
{
51
unpinShearTarget(world, session.targetEntityId, characterId);
52
sessions.delete(characterId);
53
}
54
}
55
56
function pinShearTarget (world, entityId, characterId)
57
{
58
const handle = world.ecs.handleOf(entityId | 0);
59
if (handle == null)
60
{ return; }
61
const origin = world.ecs.get(handle, Component.spawnOrigin);
62
if (!origin)
63
{ return; }
64
if (!origin.shearBrowsers || typeof origin.shearBrowsers !== "object")
65
{ origin.shearBrowsers = Object.create(null); }
66
origin.shearBrowsers[characterId | 0] = true;
67
const path = world.ecs.get(handle, Component.path);
68
if (path)
69
{ path.tiles = []; }
70
}
71
72
function unpinShearTarget (world, entityId, characterId)
73
{
74
const handle = world.ecs.handleOf(entityId | 0);
75
if (handle == null)
76
{ return; }
77
const origin = world.ecs.get(handle, Component.spawnOrigin);
78
if (!origin?.shearBrowsers)
79
{ return; }
80
delete origin.shearBrowsers[characterId | 0];
81
}
82
83
function hasShearBrowsers (origin)
84
{
85
const browsers = origin?.shearBrowsers;
86
if (!browsers || typeof browsers !== "object")
87
{ return false; }
88
return Object.keys(browsers).length > 0;
89
}
90
91
export function originIsBusyPinned (origin)
92
{
93
const dialogue = origin?.dialogueBrowsers;
94
const hasDialogue = dialogue && typeof dialogue === "object" && Object.keys(dialogue).length > 0;
95
return hasDialogue || hasShearBrowsers(origin);
96
}
97
98
/**
99
* Start shearing a fleece-bearing mob (3s channel, shears overlay, freeze target).
100
*/
101
export function startShear (world, sessionId, characterId, targetEntityId, now)
102
{
103
const entityId = world.characterEntities.get(characterId);
104
if (entityId == null)
105
{ throw userError("Character is not in the world."); }
106
const handle = world.ecs.handleOf(entityId);
107
const identity = world.ecs.get(handle, Component.networkIdentity);
108
if (!identity || identity.sessionId !== sessionId)
109
{ throw userError("Character is not in the world."); }
110
if (world.ecs.has(handle, Component.dead))
111
{ throw userError("You are dead."); }
112
113
const targetHandle = world.ecs.handleOf(targetEntityId | 0);
114
if (targetHandle == null)
115
{ throw userError("That creature is gone."); }
116
if (world.ecs.has(targetHandle, Component.dead))
117
{ throw userError("That creature is dead."); }
118
119
const creature = world.ecs.get(targetHandle, Component.creature);
120
const mob = mobDefinition(creature?.mobTypeId);
121
const shearable = mob?.shearable;
122
if (!shearable)
123
{ throw userError("You cannot shear that."); }
124
125
const fleeceState = creature.fleeceState ?? shearable.fleeceState;
126
if (fleeceState === shearable.shornState)
127
{ throw userError("That fleece has not grown back yet."); }
128
129
const playerPos = world.ecs.get(handle, Component.position);
130
const targetPos = world.ecs.get(targetHandle, Component.position);
131
if (chebyshev(playerPos.tileX, playerPos.tileY, targetPos.tileX, targetPos.tileY) > 1)
132
{ throw userError("You need to stand next to it."); }
133
134
const inventory = world.ecs.get(handle, Component.inventory);
135
const equipment = world.ecs.get(handle, Component.equipment);
136
const skills = world.ecs.get(handle, Component.skills);
137
const resolved = resolveShears({
138
inventorySlots: inventory?.slots,
139
equipmentSlots: equipment?.slots,
140
skills,
141
clothTier: shearable.clothTier
142
});
143
if (!resolved.ok)
144
{ throw userError(resolved.reason); }
145
146
clearShearSession(world, characterId);
147
if (world.ecs.has(handle, Component.gather))
148
{ world.ecs.remove(handle, Component.gather); }
149
const path = world.ecs.get(handle, Component.path);
150
if (path)
151
{ path.tiles = []; }
152
153
pinShearTarget(world, targetEntityId | 0, characterId);
154
155
ensureShearSessions(world).set(characterId, {
156
sessionId,
157
targetEntityId: targetEntityId | 0,
158
clothTier: shearable.clothTier,
159
fleeceState: shearable.fleeceState,
160
shornState: shearable.shornState,
161
mobTypeId: creature.mobTypeId,
162
toolItemId: resolved.tool.stack.itemId,
163
startedAt: now,
164
endsAt: now + SHEAR_DURATION_MS,
165
nextShoveAt: now
166
});
167
168
return { events: [], private: bagView(world.ecs, handle) };
169
}
170
171
export function cancelShearing (world, characterId)
172
{
173
clearShearSession(world, characterId);
174
}
175
176
export function handleShearingCommand (world, sessionId, command, now = Date.now())
177
{
178
if (command.type === "shear")
179
{
180
return startShear(world, sessionId, command.characterId, command.targetEntityId, now);
181
}
182
if (command.type === "cancel-shear")
183
{
184
cancelShearing(world, command.characterId);
185
return { events: [] };
186
}
187
return null;
188
}
189
190
function completeShear (world, handle, entityId, characterId, session, events, privates, now)
191
{
192
const character = world.ecs.get(handle, Component.character);
193
const inventory = world.ecs.get(handle, Component.inventory);
194
const targetHandle = world.ecs.handleOf(session.targetEntityId);
195
if (targetHandle == null || !inventory || !character)
196
{
197
clearShearSession(world, characterId);
198
return;
199
}
200
201
const itemId = rawClothItemId(session.clothTier);
202
const def = itemDefinition(itemId);
203
if (!def)
204
{
205
clearShearSession(world, characterId);
206
return;
207
}
208
209
const origin = gatherOrigin(GatherOriginVerb.sheared, characterDisplayName(world, handle));
210
const stack = attachOrigins({
211
itemId,
212
quantity: 1,
213
origins: [{ origin, quantity: 1 }]
214
});
215
const inserted = insertStack(inventory.slots, stack, def);
216
if (!inserted.ok || inserted.remainder > 0)
217
{
218
events.push({
219
type: "command-error",
220
sessionId: session.sessionId,
221
message: "Your inventory is full."
222
});
223
clearShearSession(world, characterId);
224
return;
225
}
226
inventory.slots = inserted.slots;
227
228
const creature = world.ecs.get(targetHandle, Component.creature);
229
const appearance = world.ecs.get(targetHandle, Component.appearance);
230
if (creature)
231
{
232
creature.fleeceState = session.shornState;
233
creature.woolReadyAt = now + scaleRegrowDurationMs(
234
clothExhaustDurationMs(session.clothTier),
235
now
236
);
237
}
238
if (appearance)
239
{
240
appearance.sprite = mobSpriteName(session.mobTypeId, session.shornState);
241
const view = publicEntityView(world.ecs, session.targetEntityId);
242
const appearanceEvent = replicationAppearance(view);
243
if (appearanceEvent)
244
{ events.push(appearanceEvent); }
245
}
246
247
const skills = world.ecs.get(handle, Component.skills);
248
let skillsChanged = false;
249
const levelUps = [];
250
if (skills?.xp)
251
{
252
const result = applySkillXp(skills, SkillId.herbalism, 4 + Math.max(1, Math.floor(
253
(clothExhaustDurationMs(session.clothTier) / 10_000)
254
)));
255
if (result.changed)
256
{ skillsChanged = true; }
257
if (result.levelUp)
258
{ levelUps.push(result.levelUp); }
259
}
260
if (skillsChanged)
261
{
262
events.push({
263
type: "skills-updated",
264
entityId,
265
characterId,
266
skills: publicSkillsView(skills),
267
stored: storedSkillXp(skills),
268
levelUps
269
});
270
}
271
272
privates.push({ characterId, bag: bagView(world.ecs, handle) });
273
clearShearSession(world, characterId);
274
}
275
276
/**
277
* Advance shear channels and fleece regrowth.
278
*/
279
export function stepShearing (world, now)
280
{
281
const events = [];
282
const privates = [];
283
284
for (const entity of world.ecs.query(Component.creature, Component.appearance))
285
{
286
const creature = entity.creature;
287
if (creature?.woolReadyAt == null || now < creature.woolReadyAt)
288
{ continue; }
289
const mob = mobDefinition(creature.mobTypeId);
290
const shearable = mob?.shearable;
291
if (!shearable)
292
{
293
creature.woolReadyAt = null;
294
continue;
295
}
296
creature.fleeceState = shearable.fleeceState;
297
creature.woolReadyAt = null;
298
entity.appearance.sprite = mobSpriteName(creature.mobTypeId, shearable.fleeceState);
299
const view = publicEntityView(world.ecs, entity.entityId);
300
const appearanceEvent = replicationAppearance(view);
301
if (appearanceEvent)
302
{ events.push(appearanceEvent); }
303
}
304
305
const sessions = ensureShearSessions(world);
306
for (const [characterId, session] of [...sessions.entries()])
307
{
308
const entityId = world.characterEntities.get(characterId);
309
if (entityId == null)
310
{
311
clearShearSession(world, characterId);
312
continue;
313
}
314
const handle = world.ecs.handleOf(entityId);
315
if (world.ecs.has(handle, Component.dead))
316
{
317
clearShearSession(world, characterId);
318
continue;
319
}
320
321
const targetHandle = world.ecs.handleOf(session.targetEntityId);
322
if (targetHandle == null || world.ecs.has(targetHandle, Component.dead))
323
{
324
events.push({
325
type: "command-error",
326
sessionId: session.sessionId,
327
message: "The creature got away."
328
});
329
clearShearSession(world, characterId);
330
continue;
331
}
332
333
const position = world.ecs.get(handle, Component.position);
334
const targetPos = world.ecs.get(targetHandle, Component.position);
335
if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) > 1)
336
{
337
clearShearSession(world, characterId);
338
continue;
339
}
340
341
if (now >= session.nextShoveAt && now < session.endsAt)
342
{
343
session.nextShoveAt = now + SHEAR_SHOVE_MS;
344
events.push(tileShoveEvent(
345
entityId,
346
position.tileX,
347
position.tileY,
348
targetPos.tileX,
349
targetPos.tileY
350
));
351
events.push({
352
type: "gather-swing",
353
attackerId: entityId,
354
tileX: targetPos.tileX,
355
tileY: targetPos.tileY,
356
fromTileX: position.tileX,
357
fromTileY: position.tileY,
358
toolItemId: session.toolItemId,
359
swipe: false
360
});
361
}
362
363
if (now < session.endsAt)
364
{ continue; }
365
366
completeShear(world, handle, entityId, characterId, session, events, privates, now);
367
}
368
369
return { events, privates };
370
}
@@ -0,0 +1,370 @@1
import { Component } from "../ecs/components.js";2
import { mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";3
import { resolveShears } from "../../../shared/definitions/gathering.js";4
import { rawClothItemId } from "../../../shared/definitions/clothItems.js";5
import {6
clothExhaustDurationMs7
} from "../../../shared/definitions/materialTiers.js";8
import { itemDefinition } from "../../../shared/definitions/items.js";9
import { SkillId } from "../../../shared/definitions/skills.js";10
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";11
import { insertStack } from "../../../shared/items/inventory.js";12
import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";13
import { bagView } from "../items/bags.js";14
import { chebyshev } from "../combat/service.js";15
import { publicEntityView, replicationAppearance } from "../ecs/serialize.js";16
import { scaleRegrowDurationMs } from "../../../shared/world/season.js";17
import { tileShoveEvent } from "../simulation/tileInteract.js";18
19
const SHEAR_DURATION_MS = 3000;20
const SHEAR_SHOVE_MS = 1000;21
22
function userError (message)23
{24
const error = new Error(message);25
error.userFacing = true;26
return error;27
}28
29
function characterDisplayName (world, handle)30
{31
const appearance = world.ecs.get(handle, Component.appearance);32
const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();33
return name || "someone";34
}35
36
function ensureShearSessions (world)37
{38
if (!world.shearSessions)39
{ world.shearSessions = new Map(); }40
return world.shearSessions;41
}42
43
function clearShearSession (world, characterId)44
{45
const sessions = world.shearSessions;46
if (!sessions)47
{ return; }48
const session = sessions.get(characterId);49
if (session)50
{51
unpinShearTarget(world, session.targetEntityId, characterId);52
sessions.delete(characterId);53
}54
}55
56
function pinShearTarget (world, entityId, characterId)57
{58
const handle = world.ecs.handleOf(entityId | 0);59
if (handle == null)60
{ return; }61
const origin = world.ecs.get(handle, Component.spawnOrigin);62
if (!origin)63
{ return; }64
if (!origin.shearBrowsers || typeof origin.shearBrowsers !== "object")65
{ origin.shearBrowsers = Object.create(null); }66
origin.shearBrowsers[characterId | 0] = true;67
const path = world.ecs.get(handle, Component.path);68
if (path)69
{ path.tiles = []; }70
}71
72
function unpinShearTarget (world, entityId, characterId)73
{74
const handle = world.ecs.handleOf(entityId | 0);75
if (handle == null)76
{ return; }77
const origin = world.ecs.get(handle, Component.spawnOrigin);78
if (!origin?.shearBrowsers)79
{ return; }80
delete origin.shearBrowsers[characterId | 0];81
}82
83
function hasShearBrowsers (origin)84
{85
const browsers = origin?.shearBrowsers;86
if (!browsers || typeof browsers !== "object")87
{ return false; }88
return Object.keys(browsers).length > 0;89
}90
91
export function originIsBusyPinned (origin)92
{93
const dialogue = origin?.dialogueBrowsers;94
const hasDialogue = dialogue && typeof dialogue === "object" && Object.keys(dialogue).length > 0;95
return hasDialogue || hasShearBrowsers(origin);96
}97
98
/**99
* Start shearing a fleece-bearing mob (3s channel, shears overlay, freeze target).100
*/101
export function startShear (world, sessionId, characterId, targetEntityId, now)102
{103
const entityId = world.characterEntities.get(characterId);104
if (entityId == null)105
{ throw userError("Character is not in the world."); }106
const handle = world.ecs.handleOf(entityId);107
const identity = world.ecs.get(handle, Component.networkIdentity);108
if (!identity || identity.sessionId !== sessionId)109
{ throw userError("Character is not in the world."); }110
if (world.ecs.has(handle, Component.dead))111
{ throw userError("You are dead."); }112
113
const targetHandle = world.ecs.handleOf(targetEntityId | 0);114
if (targetHandle == null)115
{ throw userError("That creature is gone."); }116
if (world.ecs.has(targetHandle, Component.dead))117
{ throw userError("That creature is dead."); }118
119
const creature = world.ecs.get(targetHandle, Component.creature);120
const mob = mobDefinition(creature?.mobTypeId);121
const shearable = mob?.shearable;122
if (!shearable)123
{ throw userError("You cannot shear that."); }124
125
const fleeceState = creature.fleeceState ?? shearable.fleeceState;126
if (fleeceState === shearable.shornState)127
{ throw userError("That fleece has not grown back yet."); }128
129
const playerPos = world.ecs.get(handle, Component.position);130
const targetPos = world.ecs.get(targetHandle, Component.position);131
if (chebyshev(playerPos.tileX, playerPos.tileY, targetPos.tileX, targetPos.tileY) > 1)132
{ throw userError("You need to stand next to it."); }133
134
const inventory = world.ecs.get(handle, Component.inventory);135
const equipment = world.ecs.get(handle, Component.equipment);136
const skills = world.ecs.get(handle, Component.skills);137
const resolved = resolveShears({138
inventorySlots: inventory?.slots,139
equipmentSlots: equipment?.slots,140
skills,141
clothTier: shearable.clothTier142
});143
if (!resolved.ok)144
{ throw userError(resolved.reason); }145
146
clearShearSession(world, characterId);147
if (world.ecs.has(handle, Component.gather))148
{ world.ecs.remove(handle, Component.gather); }149
const path = world.ecs.get(handle, Component.path);150
if (path)151
{ path.tiles = []; }152
153
pinShearTarget(world, targetEntityId | 0, characterId);154
155
ensureShearSessions(world).set(characterId, {156
sessionId,157
targetEntityId: targetEntityId | 0,158
clothTier: shearable.clothTier,159
fleeceState: shearable.fleeceState,160
shornState: shearable.shornState,161
mobTypeId: creature.mobTypeId,162
toolItemId: resolved.tool.stack.itemId,163
startedAt: now,164
endsAt: now + SHEAR_DURATION_MS,165
nextShoveAt: now166
});167
168
return { events: [], private: bagView(world.ecs, handle) };169
}170
171
export function cancelShearing (world, characterId)172
{173
clearShearSession(world, characterId);174
}175
176
export function handleShearingCommand (world, sessionId, command, now = Date.now())177
{178
if (command.type === "shear")179
{180
return startShear(world, sessionId, command.characterId, command.targetEntityId, now);181
}182
if (command.type === "cancel-shear")183
{184
cancelShearing(world, command.characterId);185
return { events: [] };186
}187
return null;188
}189
190
function completeShear (world, handle, entityId, characterId, session, events, privates, now)191
{192
const character = world.ecs.get(handle, Component.character);193
const inventory = world.ecs.get(handle, Component.inventory);194
const targetHandle = world.ecs.handleOf(session.targetEntityId);195
if (targetHandle == null || !inventory || !character)196
{197
clearShearSession(world, characterId);198
return;199
}200
201
const itemId = rawClothItemId(session.clothTier);202
const def = itemDefinition(itemId);203
if (!def)204
{205
clearShearSession(world, characterId);206
return;207
}208
209
const origin = gatherOrigin(GatherOriginVerb.sheared, characterDisplayName(world, handle));210
const stack = attachOrigins({211
itemId,212
quantity: 1,213
origins: [{ origin, quantity: 1 }]214
});215
const inserted = insertStack(inventory.slots, stack, def);216
if (!inserted.ok || inserted.remainder > 0)217
{218
events.push({219
type: "command-error",220
sessionId: session.sessionId,221
message: "Your inventory is full."222
});223
clearShearSession(world, characterId);224
return;225
}226
inventory.slots = inserted.slots;227
228
const creature = world.ecs.get(targetHandle, Component.creature);229
const appearance = world.ecs.get(targetHandle, Component.appearance);230
if (creature)231
{232
creature.fleeceState = session.shornState;233
creature.woolReadyAt = now + scaleRegrowDurationMs(234
clothExhaustDurationMs(session.clothTier),235
now236
);237
}238
if (appearance)239
{240
appearance.sprite = mobSpriteName(session.mobTypeId, session.shornState);241
const view = publicEntityView(world.ecs, session.targetEntityId);242
const appearanceEvent = replicationAppearance(view);243
if (appearanceEvent)244
{ events.push(appearanceEvent); }245
}246
247
const skills = world.ecs.get(handle, Component.skills);248
let skillsChanged = false;249
const levelUps = [];250
if (skills?.xp)251
{252
const result = applySkillXp(skills, SkillId.herbalism, 4 + Math.max(1, Math.floor(253
(clothExhaustDurationMs(session.clothTier) / 10_000)254
)));255
if (result.changed)256
{ skillsChanged = true; }257
if (result.levelUp)258
{ levelUps.push(result.levelUp); }259
}260
if (skillsChanged)261
{262
events.push({263
type: "skills-updated",264
entityId,265
characterId,266
skills: publicSkillsView(skills),267
stored: storedSkillXp(skills),268
levelUps269
});270
}271
272
privates.push({ characterId, bag: bagView(world.ecs, handle) });273
clearShearSession(world, characterId);274
}275
276
/**277
* Advance shear channels and fleece regrowth.278
*/279
export function stepShearing (world, now)280
{281
const events = [];282
const privates = [];283
284
for (const entity of world.ecs.query(Component.creature, Component.appearance))285
{286
const creature = entity.creature;287
if (creature?.woolReadyAt == null || now < creature.woolReadyAt)288
{ continue; }289
const mob = mobDefinition(creature.mobTypeId);290
const shearable = mob?.shearable;291
if (!shearable)292
{293
creature.woolReadyAt = null;294
continue;295
}296
creature.fleeceState = shearable.fleeceState;297
creature.woolReadyAt = null;298
entity.appearance.sprite = mobSpriteName(creature.mobTypeId, shearable.fleeceState);299
const view = publicEntityView(world.ecs, entity.entityId);300
const appearanceEvent = replicationAppearance(view);301
if (appearanceEvent)302
{ events.push(appearanceEvent); }303
}304
305
const sessions = ensureShearSessions(world);306
for (const [characterId, session] of [...sessions.entries()])307
{308
const entityId = world.characterEntities.get(characterId);309
if (entityId == null)310
{311
clearShearSession(world, characterId);312
continue;313
}314
const handle = world.ecs.handleOf(entityId);315
if (world.ecs.has(handle, Component.dead))316
{317
clearShearSession(world, characterId);318
continue;319
}320
321
const targetHandle = world.ecs.handleOf(session.targetEntityId);322
if (targetHandle == null || world.ecs.has(targetHandle, Component.dead))323
{324
events.push({325
type: "command-error",326
sessionId: session.sessionId,327
message: "The creature got away."328
});329
clearShearSession(world, characterId);330
continue;331
}332
333
const position = world.ecs.get(handle, Component.position);334
const targetPos = world.ecs.get(targetHandle, Component.position);335
if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) > 1)336
{337
clearShearSession(world, characterId);338
continue;339
}340
341
if (now >= session.nextShoveAt && now < session.endsAt)342
{343
session.nextShoveAt = now + SHEAR_SHOVE_MS;344
events.push(tileShoveEvent(345
entityId,346
position.tileX,347
position.tileY,348
targetPos.tileX,349
targetPos.tileY350
));351
events.push({352
type: "gather-swing",353
attackerId: entityId,354
tileX: targetPos.tileX,355
tileY: targetPos.tileY,356
fromTileX: position.tileX,357
fromTileY: position.tileY,358
toolItemId: session.toolItemId,359
swipe: false360
});361
}362
363
if (now < session.endsAt)364
{ continue; }365
366
completeShear(world, handle, entityId, characterId, session, events, privates, now);367
}368
369
return { events, privates };370
}@@ -235,7 +235,8 @@ export function mobComponents (request)
235
235
}
236
236
else
237
237
{
238
const sprite = mobSpriteName(def.mobTypeId);
238
const fleeceState = def.shearable?.fleeceState ?? null;
239
const sprite = mobSpriteName(def.mobTypeId, fleeceState);
239
240
if (sprite)
240
241
{ appearance.sprite = sprite; }
241
242
}
@@ -272,7 +273,13 @@ export function mobComponents (request)
272
273
mobTypeId: def.mobTypeId,
273
274
level,
274
275
...(element ? { element } : {}),
275
...(def.lightRadiusTiles ? { lightRadiusTiles: def.lightRadiusTiles } : {})
276
...(def.lightRadiusTiles ? { lightRadiusTiles: def.lightRadiusTiles } : {}),
277
...(def.shearable
278
? {
279
fleeceState: def.shearable.fleeceState,
280
woolReadyAt: null
281
}
282
: {})
276
283
},
277
284
health: { current: maxHp, max: maxHp }
278
285
};
@@ -235,7 +235,8 @@ export function mobComponents (request)235
}235
}236
else236
else237
{237
{238
const sprite = mobSpriteName(def.mobTypeId);238
const fleeceState = def.shearable?.fleeceState ?? null;239
const sprite = mobSpriteName(def.mobTypeId, fleeceState);239
if (sprite)240
if (sprite)240
{ appearance.sprite = sprite; }241
{ appearance.sprite = sprite; }241
}242
}@@ -272,7 +273,13 @@ export function mobComponents (request)272
mobTypeId: def.mobTypeId,273
mobTypeId: def.mobTypeId,273
level,274
level,274
...(element ? { element } : {}),275
...(element ? { element } : {}),275
...(def.lightRadiusTiles ? { lightRadiusTiles: def.lightRadiusTiles } : {})276
...(def.lightRadiusTiles ? { lightRadiusTiles: def.lightRadiusTiles } : {}),277
...(def.shearable278
? {279
fleeceState: def.shearable.fleeceState,280
woolReadyAt: null281
}282
: {})276
},283
},277
health: { current: maxHp, max: maxHp }284
health: { current: maxHp, max: maxHp }278
};285
};@@ -46,6 +46,7 @@ import {
46
46
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
47
47
import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
48
48
import { handleFishingCommand, stepFishing } from "../fishing/service.js";
49
import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js";
49
50
import { handleAlchemyCommand } from "../alchemy/service.js";
50
51
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
51
52
import {
@@ -502,6 +503,9 @@ export class WorkerWorld
502
503
const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());
503
504
if (fishing)
504
505
{ return fishing; }
506
const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now());
507
if (shearing)
508
{ return shearing; }
505
509
const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
506
510
if (craft)
507
511
{ return craft; }
@@ -1331,6 +1335,16 @@ export class WorkerWorld
1331
1335
...entry.bag
1332
1336
});
1333
1337
}
1338
const shearing = stepShearing(this, now);
1339
events.push(...shearing.events);
1340
for (const entry of shearing.privates ?? [])
1341
{
1342
events.push({
1343
type: "inventory",
1344
characterId: entry.characterId,
1345
...entry.bag
1346
});
1347
}
1334
1348
const craft = stepCrafting(this, now);
1335
1349
events.push(...craft.events);
1336
1350
for (const entry of craft.privates ?? [])
@@ -1550,7 +1564,7 @@ export class WorkerWorld
1550
1564
if (shopHasActiveBrowsers(shop))
1551
1565
{ continue; }
1552
1566
const origin = entity.spawnOrigin;
1553
if (hasDialogueBrowsers(origin))
1567
if (originIsBusyPinned(origin))
1554
1568
{ continue; }
1555
1569
if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1556
1570
{ continue; }
@@ -1720,15 +1734,19 @@ export class WorkerWorld
1720
1734
for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1721
1735
{
1722
1736
const browsers = entity.spawnOrigin?.dialogueBrowsers;
1723
if (!browsers || typeof browsers !== "object")
1724
{ continue; }
1725
const ids = Object.keys(browsers).map((id) => Number(id));
1726
if (!ids.length)
1737
const shearBrowsers = entity.spawnOrigin?.shearBrowsers;
1738
const dialogueIds = browsers && typeof browsers === "object"
1739
? Object.keys(browsers).map((id) => Number(id))
1740
: [];
1741
const shearIds = shearBrowsers && typeof shearBrowsers === "object"
1742
? Object.keys(shearBrowsers).map((id) => Number(id))
1743
: [];
1744
if (!dialogueIds.length && !shearIds.length)
1727
1745
{ continue; }
1728
1746
const path = this.ecs.get(entity.handle, Component.path);
1729
1747
if (path)
1730
1748
{ path.tiles = []; }
1731
for (const characterId of ids)
1749
for (const characterId of dialogueIds)
1732
1750
{
1733
1751
const playerEntityId = this.characterEntities.get(characterId);
1734
1752
if (playerEntityId == null)
@@ -1756,6 +1774,27 @@ export class WorkerWorld
1756
1774
npcEntityId: entity.entityId
1757
1775
});
1758
1776
}
1777
for (const characterId of shearIds)
1778
{
1779
const playerEntityId = this.characterEntities.get(characterId);
1780
if (playerEntityId == null)
1781
{
1782
delete shearBrowsers[characterId];
1783
continue;
1784
}
1785
const playerHandle = this.ecs.handleOf(playerEntityId);
1786
const playerPos = this.ecs.get(playerHandle, Component.position);
1787
const stillNear = playerPos
1788
&& chebyshev(
1789
playerPos.tileX,
1790
playerPos.tileY,
1791
entity.position.tileX,
1792
entity.position.tileY
1793
) <= 1;
1794
if (stillNear)
1795
{ continue; }
1796
delete shearBrowsers[characterId];
1797
}
1759
1798
}
1760
1799
return events;
1761
1800
}
@@ -2140,10 +2179,7 @@ function pickWanderGoalInRange (world, entityId, originX, originY, range)
2140
2179
2141
2180
function hasDialogueBrowsers (origin)
2142
2181
{
2143
const browsers = origin?.dialogueBrowsers;
2144
if (!browsers || typeof browsers !== "object")
2145
{ return false; }
2146
return Object.keys(browsers).length > 0;
2182
return originIsBusyPinned(origin);
2147
2183
}
2148
2184
2149
2185
function randInt (min, max)
@@ -46,6 +46,7 @@ import {46
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";46
import { handleCraftCommand, stepCrafting } from "../crafting/service.js";47
import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";47
import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";48
import { handleFishingCommand, stepFishing } from "../fishing/service.js";48
import { handleFishingCommand, stepFishing } from "../fishing/service.js";49
import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js";49
import { handleAlchemyCommand } from "../alchemy/service.js";50
import { handleAlchemyCommand } from "../alchemy/service.js";50
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";51
import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";51
import {52
import {@@ -502,6 +503,9 @@ export class WorkerWorld502
const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());503
const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());503
if (fishing)504
if (fishing)504
{ return fishing; }505
{ return fishing; }506
const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now());507
if (shearing)508
{ return shearing; }505
const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());509
const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());506
if (craft)510
if (craft)507
{ return craft; }511
{ return craft; }@@ -1331,6 +1335,16 @@ export class WorkerWorld1331
...entry.bag1335
...entry.bag1332
});1336
});1333
}1337
}1338
const shearing = stepShearing(this, now);1339
events.push(...shearing.events);1340
for (const entry of shearing.privates ?? [])1341
{1342
events.push({1343
type: "inventory",1344
characterId: entry.characterId,1345
...entry.bag1346
});1347
}1334
const craft = stepCrafting(this, now);1348
const craft = stepCrafting(this, now);1335
events.push(...craft.events);1349
events.push(...craft.events);1336
for (const entry of craft.privates ?? [])1350
for (const entry of craft.privates ?? [])@@ -1550,7 +1564,7 @@ export class WorkerWorld1550
if (shopHasActiveBrowsers(shop))1564
if (shopHasActiveBrowsers(shop))1551
{ continue; }1565
{ continue; }1552
const origin = entity.spawnOrigin;1566
const origin = entity.spawnOrigin;1553
if (hasDialogueBrowsers(origin))1567
if (originIsBusyPinned(origin))1554
{ continue; }1568
{ continue; }1555
if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))1569
if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))1556
{ continue; }1570
{ continue; }@@ -1720,15 +1734,19 @@ export class WorkerWorld1720
for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))1734
for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))1721
{1735
{1722
const browsers = entity.spawnOrigin?.dialogueBrowsers;1736
const browsers = entity.spawnOrigin?.dialogueBrowsers;1723
if (!browsers || typeof browsers !== "object")1737
const shearBrowsers = entity.spawnOrigin?.shearBrowsers;1724
{ continue; }1738
const dialogueIds = browsers && typeof browsers === "object"1725
const ids = Object.keys(browsers).map((id) => Number(id));1739
? Object.keys(browsers).map((id) => Number(id))1726
if (!ids.length)1740
: [];1741
const shearIds = shearBrowsers && typeof shearBrowsers === "object"1742
? Object.keys(shearBrowsers).map((id) => Number(id))1743
: [];1744
if (!dialogueIds.length && !shearIds.length)1727
{ continue; }1745
{ continue; }1728
const path = this.ecs.get(entity.handle, Component.path);1746
const path = this.ecs.get(entity.handle, Component.path);1729
if (path)1747
if (path)1730
{ path.tiles = []; }1748
{ path.tiles = []; }1731
for (const characterId of ids)1749
for (const characterId of dialogueIds)1732
{1750
{1733
const playerEntityId = this.characterEntities.get(characterId);1751
const playerEntityId = this.characterEntities.get(characterId);1734
if (playerEntityId == null)1752
if (playerEntityId == null)@@ -1756,6 +1774,27 @@ export class WorkerWorld1756
npcEntityId: entity.entityId1774
npcEntityId: entity.entityId1757
});1775
});1758
}1776
}1777
for (const characterId of shearIds)1778
{1779
const playerEntityId = this.characterEntities.get(characterId);1780
if (playerEntityId == null)1781
{1782
delete shearBrowsers[characterId];1783
continue;1784
}1785
const playerHandle = this.ecs.handleOf(playerEntityId);1786
const playerPos = this.ecs.get(playerHandle, Component.position);1787
const stillNear = playerPos1788
&& chebyshev(1789
playerPos.tileX,1790
playerPos.tileY,1791
entity.position.tileX,1792
entity.position.tileY1793
) <= 1;1794
if (stillNear)1795
{ continue; }1796
delete shearBrowsers[characterId];1797
}1759
}1798
}1760
return events;1799
return events;1761
}1800
}@@ -2140,10 +2179,7 @@ function pickWanderGoalInRange (world, entityId, originX, originY, range)2140
2179
2141
function hasDialogueBrowsers (origin)2180
function hasDialogueBrowsers (origin)2142
{2181
{2143
const browsers = origin?.dialogueBrowsers;2182
return originIsBusyPinned(origin);2144
if (!browsers || typeof browsers !== "object")2145
{ return false; }2146
return Object.keys(browsers).length > 0;2147
}2183
}2148
2184
2149
function randInt (min, max)2185
function randInt (min, max)@@ -0,0 +1,185 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { BlockType, plantGatherForBlock } from "../../shared/definitions/tiles.js";
4
import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
5
import { MetalItemId } from "../../shared/definitions/metalItems.js";
6
import { LeatherItemId } from "../../shared/definitions/leatherItems.js";
7
import { ClothItemId, rawClothItemId } from "../../shared/definitions/clothItems.js";
8
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
9
import {
10
ClothTier,
11
MaterialTier,
12
metalTierForCloth,
13
clothExhaustDurationMs,
14
tierRank
15
} from "../../shared/definitions/materialTiers.js";
16
import { MobId, mobDefinition, mobSpriteName } from "../../shared/definitions/mobs.js";
17
import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
18
import { recipeDefinition, recipesForStation } from "../../shared/crafting/stationRecipes.js";
19
import { resolveItemDualTint } from "../../shared/render/tint.js";
20
import { resolvePlantClippers } from "../../shared/definitions/gathering.js";
21
import { SkillId } from "../../shared/definitions/skills.js";
22
import { normalizePlayerSkills } from "../../shared/skills/state.js";
23
import { totalXpForLevel } from "../../shared/skills/progression.js";
24
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
25
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
26
import { Component } from "../src/ecs/components.js";
27
import { mobComponents } from "../src/simulation/spawners.js";
28
29
function workerOf (simulation, playerId)
30
{
31
const record = simulation.entityRecord(playerId);
32
return simulation.workers[record.workerId];
33
}
34
35
function advanceMs (harness, ms)
36
{
37
const ticks = Math.ceil(ms / 50) + 3;
38
for (let i = 0; i < ticks; i++)
39
{
40
harness.advance(50);
41
harness.simulation.step();
42
}
43
}
44
45
function setSkillLevel (worker, playerId, skillId, level)
46
{
47
const handle = worker.world.ecs.handleOf(playerId);
48
const skills = worker.world.ecs.get(handle, Component.skills);
49
skills.xp[skillId] = totalXpForLevel(level);
50
}
51
52
function giveInventory (harness, playerId, items)
53
{
54
const inventory = emptySlots();
55
items.forEach((stack, index) =>
56
{
57
inventory[index] = {
58
itemId: stack.itemId,
59
quantity: stack.quantity,
60
...(stack.instance ? { instance: structuredClone(stack.instance) } : {})
61
};
62
});
63
harness.simulation.applyBag(playerId, {
64
inventory,
65
equipment: emptyEquipment(),
66
vault: [],
67
vaultReserved: []
68
});
69
}
70
71
test("plant clippers use dual metal/leather tint and bar+leather recipe", () =>
72
{
73
const def = itemDefinition(MetalItemId.bronzePlantClippers);
74
assert.equal(def.iconKey, "plant-clippers");
75
assert.equal(def.dualTintFromTier, true);
76
assert.equal(def.leatherTier, "softLeather");
77
const dual = resolveItemDualTint({ itemId: MetalItemId.bronzePlantClippers }, def);
78
assert.ok(dual?.shaft);
79
assert.ok(dual?.tip);
80
const recipe = recipeDefinition("plant-clippers-bronze");
81
assert.deepEqual(recipe.inputs, [
82
{ itemId: ItemId.bronzeBar, quantity: 1 },
83
{ itemId: LeatherItemId.softLeather, quantity: 1 }
84
]);
85
assert.equal(recipe.stationId, CraftingStationId.anvil);
86
});
87
88
test("shears are magenta-tinted metal and craft from one bar", () =>
89
{
90
const def = itemDefinition(MetalItemId.ironShears);
91
assert.equal(def.equipment.kind, EquipmentKind.shears);
92
assert.equal(def.tintFromTier, true);
93
assert.equal(def.dualTintFromTier, undefined);
94
const recipe = recipeDefinition("shears-iron");
95
assert.deepEqual(recipe.inputs, [{ itemId: ItemId.ironBar, quantity: 1 }]);
96
assert.equal(
97
recipesForStation(CraftingStationId.anvil).filter((r) => r.craftGroup === "shears").length,
98
7
99
);
100
});
101
102
test("sheep and cashmere goat are shearable with fleece/shorn sprites", () =>
103
{
104
const sheep = mobDefinition(MobId.sheep);
105
assert.equal(sheep.shearable.clothTier, ClothTier.wool);
106
assert.equal(mobSpriteName(MobId.sheep), "mob:sheep:fleece");
107
assert.equal(mobSpriteName(MobId.sheep, "shorn"), "mob:sheep:shorn");
108
const goat = mobDefinition(MobId.cashmereGoat);
109
assert.equal(goat.shearable.clothTier, ClothTier.cashmere);
110
assert.equal(mobSpriteName(MobId.cashmereGoat, "fleece"), "mob:cashmere-goat:fleece");
111
});
112
113
test("flax needs steel-or-better clippers; linen fibre is named Flax", () =>
114
{
115
assert.equal(itemDefinition(ClothItemId.linen).displayName, "Flax");
116
assert.equal(metalTierForCloth(ClothTier.linen), MaterialTier.steel);
117
const skills = normalizePlayerSkills(null);
118
skills.xp[SkillId.herbalism] = totalXpForLevel(20);
119
const bronze = resolvePlantClippers({
120
inventorySlots: [{ itemId: MetalItemId.bronzePlantClippers, quantity: 1 }],
121
equipmentSlots: emptyEquipment().slots,
122
skills,
123
minClothTier: ClothTier.linen
124
});
125
assert.equal(bronze.ok, false);
126
const steel = resolvePlantClippers({
127
inventorySlots: [{ itemId: MetalItemId.steelPlantClippers, quantity: 1 }],
128
equipmentSlots: emptyEquipment().slots,
129
skills,
130
minClothTier: ClothTier.linen
131
});
132
assert.equal(steel.ok, true);
133
const plant = plantGatherForBlock({ typeId: BlockType.flaxPlant, state: "flax-plant" });
134
assert.equal(plant.kind, "flax");
135
assert.equal(plant.requiresClippers, true);
136
assert.equal(plant.minClothTier, "linen");
137
});
138
139
test("shearing a sheep grants wool and sets shorn state", () =>
140
{
141
const harness = makeSimulation({ workerCount: 1 });
142
try
143
{
144
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
145
const playerId = harness.simulation.spawnCharacter(1, character);
146
const worker = workerOf(harness.simulation, playerId);
147
setSkillLevel(worker, playerId, SkillId.herbalism, 10);
148
giveInventory(harness, playerId, [
149
{ itemId: MetalItemId.ironShears, quantity: 1 }
150
]);
151
152
const sheepId = harness.simulation.spawnEntity(mobComponents({
153
tileX: 9,
154
tileY: 8,
155
mobTypeId: MobId.sheep,
156
spawnerId: "test-sheep",
157
displayName: "Woolly"
158
}));
159
160
harness.simulation.enqueue(1, {
161
type: "shear",
162
characterId: character.character_id,
163
targetEntityId: sheepId
164
});
165
advanceMs(harness, 3500);
166
167
const creature = worker.world.ecs.get(
168
worker.world.ecs.handleOf(sheepId),
169
Component.creature
170
);
171
assert.equal(creature.fleeceState, "shorn");
172
assert.ok(creature.woolReadyAt > harness.now());
173
const bag = harness.simulation.bagOf(playerId);
174
const woolId = rawClothItemId(ClothTier.wool);
175
assert.ok(bag.inventory.some((s) => s?.itemId === woolId));
176
assert.equal(
177
clothExhaustDurationMs(ClothTier.wool),
178
tierRank(ClothTier.wool) * 10_000
179
);
180
}
181
finally
182
{
183
harness.close();
184
}
185
});
@@ -0,0 +1,185 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { BlockType, plantGatherForBlock } from "../../shared/definitions/tiles.js";4
import { CraftingStationId } from "../../shared/definitions/craftingStations.js";5
import { MetalItemId } from "../../shared/definitions/metalItems.js";6
import { LeatherItemId } from "../../shared/definitions/leatherItems.js";7
import { ClothItemId, rawClothItemId } from "../../shared/definitions/clothItems.js";8
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";9
import {10
ClothTier,11
MaterialTier,12
metalTierForCloth,13
clothExhaustDurationMs,14
tierRank15
} from "../../shared/definitions/materialTiers.js";16
import { MobId, mobDefinition, mobSpriteName } from "../../shared/definitions/mobs.js";17
import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";18
import { recipeDefinition, recipesForStation } from "../../shared/crafting/stationRecipes.js";19
import { resolveItemDualTint } from "../../shared/render/tint.js";20
import { resolvePlantClippers } from "../../shared/definitions/gathering.js";21
import { SkillId } from "../../shared/definitions/skills.js";22
import { normalizePlayerSkills } from "../../shared/skills/state.js";23
import { totalXpForLevel } from "../../shared/skills/progression.js";24
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";25
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";26
import { Component } from "../src/ecs/components.js";27
import { mobComponents } from "../src/simulation/spawners.js";28
29
function workerOf (simulation, playerId)30
{31
const record = simulation.entityRecord(playerId);32
return simulation.workers[record.workerId];33
}34
35
function advanceMs (harness, ms)36
{37
const ticks = Math.ceil(ms / 50) + 3;38
for (let i = 0; i < ticks; i++)39
{40
harness.advance(50);41
harness.simulation.step();42
}43
}44
45
function setSkillLevel (worker, playerId, skillId, level)46
{47
const handle = worker.world.ecs.handleOf(playerId);48
const skills = worker.world.ecs.get(handle, Component.skills);49
skills.xp[skillId] = totalXpForLevel(level);50
}51
52
function giveInventory (harness, playerId, items)53
{54
const inventory = emptySlots();55
items.forEach((stack, index) =>56
{57
inventory[index] = {58
itemId: stack.itemId,59
quantity: stack.quantity,60
...(stack.instance ? { instance: structuredClone(stack.instance) } : {})61
};62
});63
harness.simulation.applyBag(playerId, {64
inventory,65
equipment: emptyEquipment(),66
vault: [],67
vaultReserved: []68
});69
}70
71
test("plant clippers use dual metal/leather tint and bar+leather recipe", () =>72
{73
const def = itemDefinition(MetalItemId.bronzePlantClippers);74
assert.equal(def.iconKey, "plant-clippers");75
assert.equal(def.dualTintFromTier, true);76
assert.equal(def.leatherTier, "softLeather");77
const dual = resolveItemDualTint({ itemId: MetalItemId.bronzePlantClippers }, def);78
assert.ok(dual?.shaft);79
assert.ok(dual?.tip);80
const recipe = recipeDefinition("plant-clippers-bronze");81
assert.deepEqual(recipe.inputs, [82
{ itemId: ItemId.bronzeBar, quantity: 1 },83
{ itemId: LeatherItemId.softLeather, quantity: 1 }84
]);85
assert.equal(recipe.stationId, CraftingStationId.anvil);86
});87
88
test("shears are magenta-tinted metal and craft from one bar", () =>89
{90
const def = itemDefinition(MetalItemId.ironShears);91
assert.equal(def.equipment.kind, EquipmentKind.shears);92
assert.equal(def.tintFromTier, true);93
assert.equal(def.dualTintFromTier, undefined);94
const recipe = recipeDefinition("shears-iron");95
assert.deepEqual(recipe.inputs, [{ itemId: ItemId.ironBar, quantity: 1 }]);96
assert.equal(97
recipesForStation(CraftingStationId.anvil).filter((r) => r.craftGroup === "shears").length,98
799
);100
});101
102
test("sheep and cashmere goat are shearable with fleece/shorn sprites", () =>103
{104
const sheep = mobDefinition(MobId.sheep);105
assert.equal(sheep.shearable.clothTier, ClothTier.wool);106
assert.equal(mobSpriteName(MobId.sheep), "mob:sheep:fleece");107
assert.equal(mobSpriteName(MobId.sheep, "shorn"), "mob:sheep:shorn");108
const goat = mobDefinition(MobId.cashmereGoat);109
assert.equal(goat.shearable.clothTier, ClothTier.cashmere);110
assert.equal(mobSpriteName(MobId.cashmereGoat, "fleece"), "mob:cashmere-goat:fleece");111
});112
113
test("flax needs steel-or-better clippers; linen fibre is named Flax", () =>114
{115
assert.equal(itemDefinition(ClothItemId.linen).displayName, "Flax");116
assert.equal(metalTierForCloth(ClothTier.linen), MaterialTier.steel);117
const skills = normalizePlayerSkills(null);118
skills.xp[SkillId.herbalism] = totalXpForLevel(20);119
const bronze = resolvePlantClippers({120
inventorySlots: [{ itemId: MetalItemId.bronzePlantClippers, quantity: 1 }],121
equipmentSlots: emptyEquipment().slots,122
skills,123
minClothTier: ClothTier.linen124
});125
assert.equal(bronze.ok, false);126
const steel = resolvePlantClippers({127
inventorySlots: [{ itemId: MetalItemId.steelPlantClippers, quantity: 1 }],128
equipmentSlots: emptyEquipment().slots,129
skills,130
minClothTier: ClothTier.linen131
});132
assert.equal(steel.ok, true);133
const plant = plantGatherForBlock({ typeId: BlockType.flaxPlant, state: "flax-plant" });134
assert.equal(plant.kind, "flax");135
assert.equal(plant.requiresClippers, true);136
assert.equal(plant.minClothTier, "linen");137
});138
139
test("shearing a sheep grants wool and sets shorn state", () =>140
{141
const harness = makeSimulation({ workerCount: 1 });142
try143
{144
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });145
const playerId = harness.simulation.spawnCharacter(1, character);146
const worker = workerOf(harness.simulation, playerId);147
setSkillLevel(worker, playerId, SkillId.herbalism, 10);148
giveInventory(harness, playerId, [149
{ itemId: MetalItemId.ironShears, quantity: 1 }150
]);151
152
const sheepId = harness.simulation.spawnEntity(mobComponents({153
tileX: 9,154
tileY: 8,155
mobTypeId: MobId.sheep,156
spawnerId: "test-sheep",157
displayName: "Woolly"158
}));159
160
harness.simulation.enqueue(1, {161
type: "shear",162
characterId: character.character_id,163
targetEntityId: sheepId164
});165
advanceMs(harness, 3500);166
167
const creature = worker.world.ecs.get(168
worker.world.ecs.handleOf(sheepId),169
Component.creature170
);171
assert.equal(creature.fleeceState, "shorn");172
assert.ok(creature.woolReadyAt > harness.now());173
const bag = harness.simulation.bagOf(playerId);174
const woolId = rawClothItemId(ClothTier.wool);175
assert.ok(bag.inventory.some((s) => s?.itemId === woolId));176
assert.equal(177
clothExhaustDurationMs(ClothTier.wool),178
tierRank(ClothTier.wool) * 10_000179
);180
}181
finally182
{183
harness.close();184
}185
});