BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

service.js 13.8 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 let batchRemaining = 1;
192 if (stationId === CraftingStationId.craftingBench)
193 {
194 if (options.batchAll)
195 { batchRemaining = Infinity; }
196 else if (options.batchCount != null)
197 {
198 batchRemaining = Math.max(1, options.batchCount | 0);
199 }
200 }
201 sessions.set(characterId, {
202 sessionId,
203 stationId,
204 recipeId,
205 recipe,
206 dyeSlotIndex,
207 batchRemaining,
208 durationMs,
209 finishesAt: now + durationMs
210 });
211 const events = [];
212 if (blockType)
213 {
214 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
215 if (shove)
216 { events.push(shove); }
217 }
218 events.push({
219 type: "item-bubble",
220 entityId,
221 itemId: recipe.output.itemId,
222 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
223 });
224 events.push({
225 type: "craft-started",
226 sessionId,
227 characterId,
228 recipeId,
229 durationMs
230 });
231 return { events };
232}
233
234export function openStation (world, sessionId, characterId, stationId)
235{
236 const entityId = world.characterEntities.get(characterId);
237 if (entityId == null)
238 { throw userError("Character is not in the world."); }
239 const handle = world.ecs.handleOf(entityId);
240 const identity = world.ecs.get(handle, Component.networkIdentity);
241 if (!identity || identity.sessionId !== sessionId)
242 { throw userError("Character is not in the world."); }
243 if (world.ecs.has(handle, Component.dead))
244 { throw userError("You are dead."); }
245
246 const stationDef = craftingStationDefinition(stationId);
247 if (!stationDef)
248 { throw userError("Unknown crafting station."); }
249 const blockType = stationBlockType(stationId);
250 const position = world.ecs.get(handle, Component.position);
251 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
252 { throw userError("You need to stand next to the station."); }
253
254 const events = [];
255 if (blockType)
256 {
257 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
258 if (shove)
259 { events.push(shove); }
260 }
261 events.push({
262 type: "station-open",
263 sessionId,
264 characterId,
265 stationId
266 });
267 return { events };
268}
269
270export function cancelCraft (world, characterId)
271{
272 ensureCraftSessions(world).delete(characterId);
273 return { events: [] };
274}
275
276export function stepCrafting (world, now)
277{
278 const sessions = ensureCraftSessions(world);
279 const events = [];
280 const privates = [];
281 for (const [characterId, session] of [...sessions.entries()])
282 {
283 if (now < session.finishesAt)
284 { continue; }
285 sessions.delete(characterId);
286 const entityId = world.characterEntities.get(characterId);
287 if (entityId == null)
288 {
289 events.push({
290 type: "craft-result",
291 sessionId: session.sessionId,
292 recipeId: session.recipeId,
293 ok: false,
294 error: "Character left the world."
295 });
296 continue;
297 }
298 const handle = world.ecs.handleOf(entityId);
299 if (world.ecs.has(handle, Component.dead))
300 {
301 events.push({
302 type: "craft-result",
303 sessionId: session.sessionId,
304 recipeId: session.recipeId,
305 ok: false,
306 error: "You are dead."
307 });
308 continue;
309 }
310
311 const recipe = session.recipe ?? recipeDefinition(session.recipeId);
312 const stationDef = craftingStationDefinition(session.stationId);
313 const inventory = world.ecs.get(handle, Component.inventory);
314 const skills = world.ecs.get(handle, Component.skills);
315 const position = world.ecs.get(handle, Component.position);
316 const blockType = stationBlockType(session.stationId);
317 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
318
319 if (!recipe || !stationDef || !inventory
320 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
321 || !canCraftFitInventory(inventory.slots, recipe, { dyeSlotIndex: session.dyeSlotIndex })
322 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
323 {
324 events.push({
325 type: "craft-result",
326 sessionId: session.sessionId,
327 recipeId: session.recipeId,
328 ok: false,
329 error: "Could not finish crafting."
330 });
331 continue;
332 }
333
334 const taken = takeInputs(inventory.slots, recipe.inputs);
335 if (!taken.ok)
336 {
337 events.push({
338 type: "craft-result",
339 sessionId: session.sessionId,
340 recipeId: session.recipeId,
341 ok: false,
342 error: "Missing materials."
343 });
344 continue;
345 }
346 let slotsAfter = taken.slots;
347 if (recipe.consumeDye && session.dyeSlotIndex != null)
348 {
349 const dyeTaken = consumeDyeUse(slotsAfter, session.dyeSlotIndex);
350 if (!dyeTaken.ok)
351 {
352 events.push({
353 type: "craft-result",
354 sessionId: session.sessionId,
355 recipeId: session.recipeId,
356 ok: false,
357 error: dyeTaken.reason === "space"
358 ? "Need bag space to separate the partially used dye."
359 : "Selected dye is missing."
360 });
361 continue;
362 }
363 slotsAfter = dyeTaken.slots;
364 }
365 const outDef = itemDefinition(recipe.output.itemId);
366 const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
367 const origin = craftOrigin(
368 craftOriginVerbForStation(session.stationId),
369 characterDisplayName(world, handle)
370 );
371 const outStack = {
372 itemId: recipe.output.itemId,
373 quantity: outQty,
374 origins: [{ origin, quantity: outQty }],
375 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
376 };
377 const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
378 if (!added.ok || added.remainder > 0)
379 {
380 events.push({
381 type: "craft-result",
382 sessionId: session.sessionId,
383 recipeId: session.recipeId,
384 ok: false,
385 error: "Not enough bag space for the result."
386 });
387 continue;
388 }
389 inventory.slots = added.slots;
390
391 let skillsChanged = false;
392 const levelUps = [];
393 if (skills?.xp && recipe.xpMaterial && stationDef?.skillId)
394 {
395 const result = applySkillXp(
396 skills,
397 stationDef.skillId,
398 smeltingXpForMaterial(recipe.xpMaterial)
399 );
400 if (result.changed)
401 { skillsChanged = true; }
402 if (result.levelUp)
403 { levelUps.push(result.levelUp); }
404 }
405
406 privates.push({ characterId, bag: bagView(world.ecs, handle) });
407 if (skillsChanged)
408 {
409 events.push({
410 type: "skills-updated",
411 entityId,
412 characterId,
413 skills: publicSkillsView(skills),
414 stored: storedSkillXp(skills),
415 levelUps
416 });
417 }
418
419 let continuing = false;
420 const batchRemaining = session.batchRemaining ?? 1;
421 const nextRemaining = batchRemaining === Infinity
422 ? Infinity
423 : Math.max(0, (batchRemaining | 0) - 1);
424 if (nextRemaining !== 0 && canStartCraft(
425 inventory.slots,
426 recipe,
427 level,
428 { dyeSlotIndex: session.dyeSlotIndex }
429 ))
430 {
431 const durationMs = session.durationMs ?? craftDurationMs(recipe, CRAFT_DURATION_MS);
432 sessions.set(characterId, {
433 ...session,
434 recipe,
435 batchRemaining: nextRemaining,
436 durationMs,
437 finishesAt: now + durationMs
438 });
439 continuing = true;
440 events.push({
441 type: "item-bubble",
442 entityId,
443 itemId: recipe.output.itemId,
444 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
445 });
446 }
447 events.push({
448 type: "craft-result",
449 sessionId: session.sessionId,
450 recipeId: session.recipeId,
451 ok: true,
452 continuing
453 });
454 }
455 return { events, privates };
456}
457
458export function handleCraftCommand (world, sessionId, command, now)
459{
460 switch (command.type)
461 {
462 case "open-station":
463 return openStation(world, sessionId, command.characterId, command.stationId);
464 case "start-craft":
465 return startCraft(
466 world,
467 sessionId,
468 command.characterId,
469 command.stationId,
470 command.recipeId,
471 now,
472 {
473 clothTier: command.clothTier ?? null,
474 dyeSlotIndex: command.dyeSlotIndex ?? null,
475 batchCount: command.batchCount ?? null,
476 batchAll: !!command.batchAll
477 }
478 );
479 case "cancel-craft":
480 return cancelCraft(world, command.characterId);
481 default:
482 return null;
483 }
484}