BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

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