BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

service.js 14.2 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, craftXpForConsumedInputs } 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 if (stationId === CraftingStationId.leatherworkingStation)
80 { return BlockType.leatherworkingTable; }
81 return null;
82}
83
84function takeInputs (slots, inputs)
85{
86 let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
87 for (const input of inputs ?? [])
88 {
89 let remaining = Math.max(0, stackQuantity(input.quantity));
90 if (!remaining)
91 { continue; }
92 for (let i = 0; i < next.length && remaining > 0; i++)
93 {
94 if (!next[i] || next[i].itemId !== input.itemId)
95 { continue; }
96 const taken = takeFromSlot(next, i, remaining);
97 if (!taken.ok)
98 { continue; }
99 next = taken.slots;
100 remaining -= stackQuantity(taken.taken?.quantity);
101 }
102 if (remaining > 0)
103 { return { ok: false, slots }; }
104 }
105 return { ok: true, slots: next };
106}
107
108/** Spend one fill level of a dye bottle (remove at 0). Never loses the leftover. */
109function consumeDyeUse (slots, slotIndex)
110{
111 return consumeFillCharge(slots, slotIndex, {
112 kind: "dye",
113 itemId: ItemId.dye
114 });
115}
116
117export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})
118{
119 const entityId = world.characterEntities.get(characterId);
120 if (entityId == null)
121 { throw userError("Character is not in the world."); }
122 const handle = world.ecs.handleOf(entityId);
123 const identity = world.ecs.get(handle, Component.networkIdentity);
124 if (!identity || identity.sessionId !== sessionId)
125 { throw userError("Character is not in the world."); }
126 if (world.ecs.has(handle, Component.dead))
127 { throw userError("You are dead."); }
128
129 const stationDef = craftingStationDefinition(stationId);
130 if (!stationDef)
131 { throw userError("Unknown crafting station."); }
132 let recipe = recipeDefinition(recipeId);
133 if (!recipe)
134 { throw userError("Unknown recipe."); }
135 const stationIds = Array.isArray(recipe.stationIds)
136 ? recipe.stationIds
137 : [recipe.stationId];
138 if (!stationIds.includes(stationId))
139 { throw userError("That recipe cannot be made here."); }
140
141 const position = world.ecs.get(handle, Component.position);
142 const blockType = stationBlockType(stationId);
143 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
144 { throw userError("You need to stand next to the station."); }
145
146 const inventory = world.ecs.get(handle, Component.inventory);
147 const skills = world.ecs.get(handle, Component.skills);
148 const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
149
150 let dyeSlotIndex = null;
151 if (recipe.tailorTemplate)
152 {
153 if (stationId !== CraftingStationId.tailorBench)
154 { throw userError("That garment can only be made at a tailor's bench."); }
155 const dyeIdx = options.dyeSlotIndex;
156 let dyeStack = null;
157 if (dyeIdx != null && dyeIdx >= 0)
158 {
159 dyeStack = inventory?.slots?.[dyeIdx | 0] ?? null;
160 dyeSlotIndex = dyeIdx | 0;
161 }
162 const resolved = resolveTailorCraft({
163 templateId: recipe.tailorTemplate,
164 clothTier: options.clothTier,
165 dyeStack
166 });
167 if (!resolved.ok)
168 { throw userError(resolved.reason); }
169 recipe = resolved.recipe;
170 }
171 else if (options.dyeSlotIndex != null)
172 {
173 // Dye is tailor-only; ignore client-supplied dye on other stations.
174 dyeSlotIndex = null;
175 }
176
177 if (!canStartCraft(inventory?.slots ?? [], recipe, level, { dyeSlotIndex }))
178 {
179 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
180 { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
181 if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
182 { throw userError("Missing materials."); }
183 if (recipe.consumeDye && dyeSlotIndex != null)
184 {
185 const dyeProbe = consumeDyeUse(inventory?.slots ?? [], dyeSlotIndex);
186 if (!dyeProbe.ok)
187 { throw userError("Need bag space to separate the partially used dye."); }
188 }
189 throw userError("Not enough bag space for the result.");
190 }
191 if (recipe.consumeDye && dyeSlotIndex != null)
192 {
193 const dye = inventory?.slots?.[dyeSlotIndex];
194 if (!dye || dye.itemId !== ItemId.dye)
195 { throw userError("Selected dye is missing."); }
196 }
197
198 const sessions = ensureCraftSessions(world);
199 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
200 let batchRemaining = 1;
201 if (stationId === CraftingStationId.craftingBench)
202 {
203 if (options.batchAll)
204 { batchRemaining = Infinity; }
205 else if (options.batchCount != null)
206 {
207 batchRemaining = Math.max(1, options.batchCount | 0);
208 }
209 }
210 sessions.set(characterId, {
211 sessionId,
212 stationId,
213 recipeId,
214 recipe,
215 dyeSlotIndex,
216 batchRemaining,
217 durationMs,
218 finishesAt: now + durationMs
219 });
220 const events = [];
221 if (blockType)
222 {
223 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
224 if (shove)
225 { events.push(shove); }
226 }
227 events.push({
228 type: "item-bubble",
229 entityId,
230 itemId: recipe.output.itemId,
231 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
232 });
233 events.push({
234 type: "craft-started",
235 sessionId,
236 characterId,
237 recipeId,
238 durationMs
239 });
240 return { events };
241}
242
243export function openStation (world, sessionId, characterId, stationId)
244{
245 const entityId = world.characterEntities.get(characterId);
246 if (entityId == null)
247 { throw userError("Character is not in the world."); }
248 const handle = world.ecs.handleOf(entityId);
249 const identity = world.ecs.get(handle, Component.networkIdentity);
250 if (!identity || identity.sessionId !== sessionId)
251 { throw userError("Character is not in the world."); }
252 if (world.ecs.has(handle, Component.dead))
253 { throw userError("You are dead."); }
254
255 const stationDef = craftingStationDefinition(stationId);
256 if (!stationDef)
257 { throw userError("Unknown crafting station."); }
258 const blockType = stationBlockType(stationId);
259 const position = world.ecs.get(handle, Component.position);
260 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
261 { throw userError("You need to stand next to the station."); }
262
263 const events = [];
264 if (blockType)
265 {
266 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
267 if (shove)
268 { events.push(shove); }
269 }
270 events.push({
271 type: "station-open",
272 sessionId,
273 characterId,
274 stationId
275 });
276 return { events };
277}
278
279export function cancelCraft (world, characterId)
280{
281 ensureCraftSessions(world).delete(characterId);
282 return { events: [] };
283}
284
285export function stepCrafting (world, now)
286{
287 const sessions = ensureCraftSessions(world);
288 const events = [];
289 const privates = [];
290 for (const [characterId, session] of [...sessions.entries()])
291 {
292 if (now < session.finishesAt)
293 { continue; }
294 sessions.delete(characterId);
295 const entityId = world.characterEntities.get(characterId);
296 if (entityId == null)
297 {
298 events.push({
299 type: "craft-result",
300 sessionId: session.sessionId,
301 recipeId: session.recipeId,
302 ok: false,
303 error: "Character left the world."
304 });
305 continue;
306 }
307 const handle = world.ecs.handleOf(entityId);
308 if (world.ecs.has(handle, Component.dead))
309 {
310 events.push({
311 type: "craft-result",
312 sessionId: session.sessionId,
313 recipeId: session.recipeId,
314 ok: false,
315 error: "You are dead."
316 });
317 continue;
318 }
319
320 const recipe = session.recipe ?? recipeDefinition(session.recipeId);
321 const stationDef = craftingStationDefinition(session.stationId);
322 const inventory = world.ecs.get(handle, Component.inventory);
323 const skills = world.ecs.get(handle, Component.skills);
324 const position = world.ecs.get(handle, Component.position);
325 const blockType = stationBlockType(session.stationId);
326 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
327
328 if (!recipe || !stationDef || !inventory
329 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
330 || !canCraftFitInventory(inventory.slots, recipe, { dyeSlotIndex: session.dyeSlotIndex })
331 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
332 {
333 events.push({
334 type: "craft-result",
335 sessionId: session.sessionId,
336 recipeId: session.recipeId,
337 ok: false,
338 error: "Could not finish crafting."
339 });
340 continue;
341 }
342
343 const taken = takeInputs(inventory.slots, recipe.inputs);
344 if (!taken.ok)
345 {
346 events.push({
347 type: "craft-result",
348 sessionId: session.sessionId,
349 recipeId: session.recipeId,
350 ok: false,
351 error: "Missing materials."
352 });
353 continue;
354 }
355 let slotsAfter = taken.slots;
356 if (recipe.consumeDye && session.dyeSlotIndex != null)
357 {
358 const dyeTaken = consumeDyeUse(slotsAfter, session.dyeSlotIndex);
359 if (!dyeTaken.ok)
360 {
361 events.push({
362 type: "craft-result",
363 sessionId: session.sessionId,
364 recipeId: session.recipeId,
365 ok: false,
366 error: dyeTaken.reason === "space"
367 ? "Need bag space to separate the partially used dye."
368 : "Selected dye is missing."
369 });
370 continue;
371 }
372 slotsAfter = dyeTaken.slots;
373 }
374 const outDef = itemDefinition(recipe.output.itemId);
375 const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
376 const origin = craftOrigin(
377 craftOriginVerbForStation(session.stationId),
378 characterDisplayName(world, handle)
379 );
380 const outStack = {
381 itemId: recipe.output.itemId,
382 quantity: outQty,
383 origins: [{ origin, quantity: outQty }],
384 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
385 };
386 const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
387 if (!added.ok || added.remainder > 0)
388 {
389 events.push({
390 type: "craft-result",
391 sessionId: session.sessionId,
392 recipeId: session.recipeId,
393 ok: false,
394 error: "Not enough bag space for the result."
395 });
396 continue;
397 }
398 inventory.slots = added.slots;
399
400 let skillsChanged = false;
401 const levelUps = [];
402 if (skills?.xp && stationDef?.skillId)
403 {
404 const result = applySkillXp(
405 skills,
406 stationDef.skillId,
407 craftXpForConsumedInputs(recipe.inputs)
408 );
409 if (result.changed)
410 { skillsChanged = true; }
411 if (result.levelUp)
412 { levelUps.push(result.levelUp); }
413 }
414
415 privates.push({ characterId, bag: bagView(world.ecs, handle) });
416 if (skillsChanged)
417 {
418 events.push({
419 type: "skills-updated",
420 entityId,
421 characterId,
422 skills: publicSkillsView(skills),
423 stored: storedSkillXp(skills),
424 levelUps
425 });
426 }
427
428 let continuing = false;
429 const batchRemaining = session.batchRemaining ?? 1;
430 const nextRemaining = batchRemaining === Infinity
431 ? Infinity
432 : Math.max(0, (batchRemaining | 0) - 1);
433 if (nextRemaining !== 0 && canStartCraft(
434 inventory.slots,
435 recipe,
436 level,
437 { dyeSlotIndex: session.dyeSlotIndex }
438 ))
439 {
440 const durationMs = session.durationMs ?? craftDurationMs(recipe, CRAFT_DURATION_MS);
441 sessions.set(characterId, {
442 ...session,
443 recipe,
444 batchRemaining: nextRemaining,
445 durationMs,
446 finishesAt: now + durationMs
447 });
448 continuing = true;
449 events.push({
450 type: "item-bubble",
451 entityId,
452 itemId: recipe.output.itemId,
453 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
454 });
455 }
456 events.push({
457 type: "craft-result",
458 sessionId: session.sessionId,
459 recipeId: session.recipeId,
460 ok: true,
461 continuing
462 });
463 }
464 return { events, privates };
465}
466
467export function handleCraftCommand (world, sessionId, command, now)
468{
469 switch (command.type)
470 {
471 case "open-station":
472 return openStation(world, sessionId, command.characterId, command.stationId);
473 case "start-craft":
474 return startCraft(
475 world,
476 sessionId,
477 command.characterId,
478 command.stationId,
479 command.recipeId,
480 now,
481 {
482 clothTier: command.clothTier ?? null,
483 dyeSlotIndex: command.dyeSlotIndex ?? null,
484 batchCount: command.batchCount ?? null,
485 batchAll: !!command.batchAll
486 }
487 );
488 case "cancel-craft":
489 return cancelCraft(world, command.characterId);
490 default:
491 return null;
492 }
493}