BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

service.js 12.7 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import {
8 recipeDefinition,
9 canStartCraft,
10 canCraftFitInventory,
11 hasRecipeInputs
12} from "../../../shared/crafting/recipes.js";
13import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
14import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
15import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
16import {
17 attachOrigins,
18 craftOrigin,
19 craftOriginVerbForStation
20} from "../../../shared/items/origin.js";
21import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
22import { bagView } from "../items/bags.js";
23import { tileToChunk, tileToLocal } from "../world/coordinates.js";
24import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
26
27function userError (message)
28{
29 const error = new Error(message);
30 error.userFacing = true;
31 return error;
32}
33
34function characterDisplayName (world, handle)
35{
36 const appearance = world.ecs.get(handle, Component.appearance);
37 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
38 return name || "someone";
39}
40
41function ensureCraftSessions (world)
42{
43 if (!world.craftSessions)
44 { world.craftSessions = new Map(); }
45 return world.craftSessions;
46}
47
48function nearStationBlock (world, tileX, tileY, blockType)
49{
50 for (let dy = -1; dy <= 1; dy++)
51 {
52 for (let dx = -1; dx <= 1; dx++)
53 {
54 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
55 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
56 if (data.blocks[index]?.typeId === blockType)
57 { return true; }
58 }
59 }
60 return false;
61}
62
63function stationBlockType (stationId)
64{
65 if (stationId === CraftingStationId.furnace)
66 { return BlockType.furnace; }
67 if (stationId === CraftingStationId.anvil)
68 { return BlockType.anvil; }
69 if (stationId === CraftingStationId.woodworkingBench)
70 { return BlockType.woodworkingBench; }
71 if (stationId === CraftingStationId.craftingBench)
72 { return BlockType.craftingBench; }
73 if (stationId === CraftingStationId.spinningWheel)
74 { return BlockType.spinningWheel; }
75 if (stationId === CraftingStationId.loom)
76 { return BlockType.loom; }
77 if (stationId === CraftingStationId.tailorBench)
78 { return BlockType.tailorBench; }
79 return null;
80}
81
82function takeInputs (slots, inputs)
83{
84 let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
85 for (const input of inputs ?? [])
86 {
87 let remaining = Math.max(0, stackQuantity(input.quantity));
88 if (!remaining)
89 { continue; }
90 for (let i = 0; i < next.length && remaining > 0; i++)
91 {
92 if (!next[i] || next[i].itemId !== input.itemId)
93 { continue; }
94 const taken = takeFromSlot(next, i, remaining);
95 if (!taken.ok)
96 { continue; }
97 next = taken.slots;
98 remaining -= stackQuantity(taken.taken?.quantity);
99 }
100 if (remaining > 0)
101 { return { ok: false, slots }; }
102 }
103 return { ok: true, slots: next };
104}
105
106/** Spend one fill level of a dye bottle (remove at 0). Never loses the leftover. */
107function consumeDyeUse (slots, slotIndex)
108{
109 return consumeFillCharge(slots, slotIndex, {
110 kind: "dye",
111 itemId: ItemId.dye
112 });
113}
114
115export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})
116{
117 const entityId = world.characterEntities.get(characterId);
118 if (entityId == null)
119 { throw userError("Character is not in the world."); }
120 const handle = world.ecs.handleOf(entityId);
121 const identity = world.ecs.get(handle, Component.networkIdentity);
122 if (!identity || identity.sessionId !== sessionId)
123 { throw userError("Character is not in the world."); }
124 if (world.ecs.has(handle, Component.dead))
125 { throw userError("You are dead."); }
126
127 const stationDef = craftingStationDefinition(stationId);
128 if (!stationDef)
129 { throw userError("Unknown crafting station."); }
130 let recipe = recipeDefinition(recipeId);
131 if (!recipe)
132 { throw userError("Unknown recipe."); }
133 const stationIds = Array.isArray(recipe.stationIds)
134 ? recipe.stationIds
135 : [recipe.stationId];
136 if (!stationIds.includes(stationId))
137 { throw userError("That recipe cannot be made here."); }
138
139 const position = world.ecs.get(handle, Component.position);
140 const blockType = stationBlockType(stationId);
141 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
142 { throw userError("You need to stand next to the station."); }
143
144 const inventory = world.ecs.get(handle, Component.inventory);
145 const skills = world.ecs.get(handle, Component.skills);
146 const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
147
148 let dyeSlotIndex = null;
149 if (recipe.tailorTemplate)
150 {
151 const dyeIdx = options.dyeSlotIndex;
152 let dyeStack = null;
153 if (dyeIdx != null && dyeIdx >= 0)
154 {
155 dyeStack = inventory?.slots?.[dyeIdx | 0] ?? null;
156 dyeSlotIndex = dyeIdx | 0;
157 }
158 const resolved = resolveTailorCraft({
159 templateId: recipe.tailorTemplate,
160 clothTier: options.clothTier,
161 dyeStack
162 });
163 if (!resolved.ok)
164 { throw userError(resolved.reason); }
165 recipe = resolved.recipe;
166 }
167
168 if (!canStartCraft(inventory?.slots ?? [], recipe, level, { dyeSlotIndex }))
169 {
170 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
171 { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
172 if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
173 { throw userError("Missing materials."); }
174 if (recipe.consumeDye && dyeSlotIndex != null)
175 {
176 const dyeProbe = consumeDyeUse(inventory?.slots ?? [], dyeSlotIndex);
177 if (!dyeProbe.ok)
178 { throw userError("Need bag space to separate the partially used dye."); }
179 }
180 throw userError("Not enough bag space for the result.");
181 }
182 if (recipe.consumeDye && dyeSlotIndex != null)
183 {
184 const dye = inventory?.slots?.[dyeSlotIndex];
185 if (!dye || dye.itemId !== ItemId.dye)
186 { throw userError("Selected dye is missing."); }
187 }
188
189 const sessions = ensureCraftSessions(world);
190 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
191 sessions.set(characterId, {
192 sessionId,
193 stationId,
194 recipeId,
195 recipe,
196 dyeSlotIndex,
197 finishesAt: now + durationMs
198 });
199 const events = [];
200 if (blockType)
201 {
202 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
203 if (shove)
204 { events.push(shove); }
205 }
206 events.push({
207 type: "item-bubble",
208 entityId,
209 itemId: recipe.output.itemId,
210 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
211 });
212 events.push({
213 type: "craft-started",
214 sessionId,
215 characterId,
216 recipeId,
217 durationMs
218 });
219 return { events };
220}
221
222export function openStation (world, sessionId, characterId, stationId)
223{
224 const entityId = world.characterEntities.get(characterId);
225 if (entityId == null)
226 { throw userError("Character is not in the world."); }
227 const handle = world.ecs.handleOf(entityId);
228 const identity = world.ecs.get(handle, Component.networkIdentity);
229 if (!identity || identity.sessionId !== sessionId)
230 { throw userError("Character is not in the world."); }
231 if (world.ecs.has(handle, Component.dead))
232 { throw userError("You are dead."); }
233
234 const stationDef = craftingStationDefinition(stationId);
235 if (!stationDef)
236 { throw userError("Unknown crafting station."); }
237 const blockType = stationBlockType(stationId);
238 const position = world.ecs.get(handle, Component.position);
239 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
240 { throw userError("You need to stand next to the station."); }
241
242 const events = [];
243 if (blockType)
244 {
245 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
246 if (shove)
247 { events.push(shove); }
248 }
249 events.push({
250 type: "station-open",
251 sessionId,
252 characterId,
253 stationId
254 });
255 return { events };
256}
257
258export function cancelCraft (world, characterId)
259{
260 ensureCraftSessions(world).delete(characterId);
261 return { events: [] };
262}
263
264export function stepCrafting (world, now)
265{
266 const sessions = ensureCraftSessions(world);
267 const events = [];
268 const privates = [];
269 for (const [characterId, session] of [...sessions.entries()])
270 {
271 if (now < session.finishesAt)
272 { continue; }
273 sessions.delete(characterId);
274 const entityId = world.characterEntities.get(characterId);
275 if (entityId == null)
276 {
277 events.push({
278 type: "craft-result",
279 sessionId: session.sessionId,
280 recipeId: session.recipeId,
281 ok: false,
282 error: "Character left the world."
283 });
284 continue;
285 }
286 const handle = world.ecs.handleOf(entityId);
287 if (world.ecs.has(handle, Component.dead))
288 {
289 events.push({
290 type: "craft-result",
291 sessionId: session.sessionId,
292 recipeId: session.recipeId,
293 ok: false,
294 error: "You are dead."
295 });
296 continue;
297 }
298
299 const recipe = session.recipe ?? recipeDefinition(session.recipeId);
300 const stationDef = craftingStationDefinition(session.stationId);
301 const inventory = world.ecs.get(handle, Component.inventory);
302 const skills = world.ecs.get(handle, Component.skills);
303 const position = world.ecs.get(handle, Component.position);
304 const blockType = stationBlockType(session.stationId);
305 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
306
307 if (!recipe || !stationDef || !inventory
308 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
309 || !canCraftFitInventory(inventory.slots, recipe, { dyeSlotIndex: session.dyeSlotIndex })
310 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
311 {
312 events.push({
313 type: "craft-result",
314 sessionId: session.sessionId,
315 recipeId: session.recipeId,
316 ok: false,
317 error: "Could not finish crafting."
318 });
319 continue;
320 }
321
322 const taken = takeInputs(inventory.slots, recipe.inputs);
323 if (!taken.ok)
324 {
325 events.push({
326 type: "craft-result",
327 sessionId: session.sessionId,
328 recipeId: session.recipeId,
329 ok: false,
330 error: "Missing materials."
331 });
332 continue;
333 }
334 let slotsAfter = taken.slots;
335 if (recipe.consumeDye && session.dyeSlotIndex != null)
336 {
337 const dyeTaken = consumeDyeUse(slotsAfter, session.dyeSlotIndex);
338 if (!dyeTaken.ok)
339 {
340 events.push({
341 type: "craft-result",
342 sessionId: session.sessionId,
343 recipeId: session.recipeId,
344 ok: false,
345 error: dyeTaken.reason === "space"
346 ? "Need bag space to separate the partially used dye."
347 : "Selected dye is missing."
348 });
349 continue;
350 }
351 slotsAfter = dyeTaken.slots;
352 }
353 const outDef = itemDefinition(recipe.output.itemId);
354 const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
355 const origin = craftOrigin(
356 craftOriginVerbForStation(session.stationId),
357 characterDisplayName(world, handle)
358 );
359 const outStack = {
360 itemId: recipe.output.itemId,
361 quantity: outQty,
362 origins: [{ origin, quantity: outQty }],
363 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
364 };
365 const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
366 if (!added.ok || added.remainder > 0)
367 {
368 events.push({
369 type: "craft-result",
370 sessionId: session.sessionId,
371 recipeId: session.recipeId,
372 ok: false,
373 error: "Not enough bag space for the result."
374 });
375 continue;
376 }
377 inventory.slots = added.slots;
378
379 let skillsChanged = false;
380 const levelUps = [];
381 if (skills?.xp && recipe.xpMaterial && stationDef?.skillId)
382 {
383 const result = applySkillXp(
384 skills,
385 stationDef.skillId,
386 smeltingXpForMaterial(recipe.xpMaterial)
387 );
388 if (result.changed)
389 { skillsChanged = true; }
390 if (result.levelUp)
391 { levelUps.push(result.levelUp); }
392 }
393
394 privates.push({ characterId, bag: bagView(world.ecs, handle) });
395 if (skillsChanged)
396 {
397 events.push({
398 type: "skills-updated",
399 entityId,
400 characterId,
401 skills: publicSkillsView(skills),
402 stored: storedSkillXp(skills),
403 levelUps
404 });
405 }
406 events.push({
407 type: "craft-result",
408 sessionId: session.sessionId,
409 recipeId: session.recipeId,
410 ok: true
411 });
412 }
413 return { events, privates };
414}
415
416export function handleCraftCommand (world, sessionId, command, now)
417{
418 switch (command.type)
419 {
420 case "open-station":
421 return openStation(world, sessionId, command.characterId, command.stationId);
422 case "start-craft":
423 return startCraft(
424 world,
425 sessionId,
426 command.characterId,
427 command.stationId,
428 command.recipeId,
429 now,
430 {
431 clothTier: command.clothTier ?? null,
432 dyeSlotIndex: command.dyeSlotIndex ?? null
433 }
434 );
435 case "cancel-craft":
436 return cancelCraft(world, command.characterId);
437 default:
438 return null;
439 }
440}