BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

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