BlueGit

timfa questward

Files

questward / server / src / alchemy / service.js

service.js

service.js 20.5 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import {
4 AlchemyStepKind,
5 CAULDRON_SLOT_COUNT,
6 DYE_CAULDRON_SLOT_COUNT
7} from "../../../shared/definitions/alchemy.js";
8import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
9import { SkillId } from "../../../shared/definitions/skills.js";
10import {
11 evaluateAlchemyBottle,
12 potionItemInstance,
13 recipePaperBody,
14 resolvedAlchemyPotions,
15 cauldronFlavorText
16} from "../../../shared/alchemy/recipes.js";
17import {
18 DEFAULT_DYE_FILL,
19 FLOWER_MAX_STACK,
20 mixFlowersForDye
21} from "../../../shared/definitions/dyes.js";
22import { bagView } from "../items/bags.js";
23import {
24 countItemInSlots,
25 emptySlots,
26 insertStack,
27 normalizeInventorySlots,
28 takeMatchingFromSlots,
29 stackQuantity
30} from "../../../shared/items/inventory.js";
31import { attachOrigins, craftOrigin, CraftOriginVerb, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
32import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
33import {
34 craftXpForConsumedInputs,
35 craftXpMultiplierForSkill
36} from "../../../shared/definitions/gathering.js";
37import { tileToChunk, tileToLocal } from "../world/coordinates.js";
38import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
39import { randomUUID } from "node:crypto";
40import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
41
42/**
43 * Cauldron UI slot contents live on the client only.
44 * Server sessions track brew *steps* and soft ingredient claims (itemId/qty/instance)
45 * without removing items from the bag until bottle / create-dye succeeds.
46 */
47
48function userError (message)
49{
50 const error = new Error(message);
51 error.userFacing = true;
52 return error;
53}
54
55function characterDisplayName (world, handle)
56{
57 const appearance = world.ecs.get(handle, Component.appearance);
58 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
59 return name || "someone";
60}
61
62function ensureSessions (world)
63{
64 if (!world.cauldronSessions)
65 { world.cauldronSessions = new Map(); }
66 return world.cauldronSessions;
67}
68
69function emptySession ()
70{
71 return {
72 /** Soft claims for alchemy inserts — still in the bag until bottle. */
73 pendingBrew: [],
74 steps: [],
75 lastSuccessRecipe: null
76 };
77}
78
79function sessionView (session)
80{
81 const steps = session.steps ?? [];
82 return {
83 // Slots / dye slots are client-only; never authoritative on the server.
84 slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
85 dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null),
86 brew: (session.pendingBrew ?? []).map((row) => ({
87 itemId: row.itemId,
88 quantity: row.quantity | 0,
89 instance: row.instance ? structuredClone(row.instance) : null
90 })),
91 steps: steps.map((step) => ({ ...step })),
92 flavorText: cauldronFlavorText(steps),
93 canProcessActions: steps.some((step) => step.kind === AlchemyStepKind.insert),
94 /** Top ingredient slots lock after the first brew step until Bottle/Clear. */
95 canAddIngredients: steps.length === 0,
96 canSaveRecipe: !!session.lastSuccessRecipe,
97 lastSuccess: session.lastSuccessRecipe
98 ? {
99 potionKey: session.lastSuccessRecipe.potionKey,
100 displayName: session.lastSuccessRecipe.displayName,
101 minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1
102 }
103 : null
104 };
105}
106
107function nearCauldron (world, tileX, tileY)
108{
109 for (let dy = -1; dy <= 1; dy++)
110 {
111 for (let dx = -1; dx <= 1; dx++)
112 {
113 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
114 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
115 if (data.blocks[index]?.typeId === BlockType.cauldron)
116 { return true; }
117 }
118 }
119 return false;
120}
121
122function requireNearCauldron (world, handle)
123{
124 const position = world.ecs.get(handle, Component.position);
125 if (!nearCauldron(world, position.tileX, position.tileY))
126 { throw userError("Stand next to a cauldron."); }
127}
128
129function requireSession (world, characterId)
130{
131 const session = ensureSessions(world).get(characterId);
132 if (!session)
133 { throw userError("Open a cauldron first."); }
134 return session;
135}
136
137function clearAlchemy (session)
138{
139 session.pendingBrew = [];
140 session.steps = [];
141}
142
143function ensureInventory (world, handle)
144{
145 let inventory = world.ecs.get(handle, Component.inventory);
146 if (!inventory)
147 { inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
148 inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
149 return inventory;
150}
151
152function countMatchingInstance (slots, itemId, instance)
153{
154 let total = 0;
155 const key = JSON.stringify(instance ?? null);
156 for (const slot of slots ?? [])
157 {
158 if (!slot || slot.itemId !== itemId)
159 { continue; }
160 if (JSON.stringify(slot.instance ?? null) !== key)
161 { continue; }
162 total += stackQuantity(slot.quantity);
163 }
164 return total;
165}
166
167function pendingClaimedQuantity (pendingBrew, itemId, instance)
168{
169 const key = JSON.stringify(instance ?? null);
170 let total = 0;
171 for (const row of pendingBrew ?? [])
172 {
173 if (row.itemId !== itemId)
174 { continue; }
175 if (JSON.stringify(row.instance ?? null) !== key)
176 { continue; }
177 total += row.quantity | 0;
178 }
179 return total;
180}
181
182function addPendingBrew (session, brewRow)
183{
184 const existing = session.pendingBrew.find((row) =>
185 row.itemId === brewRow.itemId
186 && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
187 if (existing)
188 { existing.quantity += brewRow.quantity; }
189 else
190 { session.pendingBrew.push(brewRow); }
191}
192
193function refundStacks (inventory, rows)
194{
195 for (const row of rows ?? [])
196 {
197 const def = itemDefinition(row.itemId);
198 const refund = insertStack(inventory.slots, attachOrigins({
199 itemId: row.itemId,
200 quantity: row.quantity,
201 instance: row.instance ? structuredClone(row.instance) : null,
202 origins: row.origins ?? normalizeOrigins(row)
203 }), def);
204 if (refund.ok)
205 { inventory.slots = refund.slots; }
206 }
207}
208
209export function handleAlchemyCommand (world, sessionId, command)
210{
211 switch (command.type)
212 {
213 case "open-cauldron":
214 return openCauldron(world, sessionId, command);
215 case "cauldron-set-slot":
216 case "cauldron-set-dye-slot":
217 // Slot UI is client-only; ignore mutations, echo session for sync.
218 return echoSession(world, sessionId, command);
219 case "cauldron-insert":
220 return insertIngredient(world, sessionId, command);
221 case "cauldron-action":
222 return action(world, sessionId, command);
223 case "cauldron-bottle":
224 return bottle(world, sessionId, command);
225 case "cauldron-create-dye":
226 return createDye(world, sessionId, command);
227 case "cauldron-clear":
228 return clear(world, sessionId, command);
229 case "cauldron-clear-dye":
230 return clearDye(world, sessionId, command);
231 case "cauldron-save-recipe":
232 return saveRecipe(world, sessionId, command);
233 case "cauldron-close":
234 return closeCauldron(world, sessionId, command);
235 default:
236 return null;
237 }
238}
239
240function echoSession (world, sessionId, command)
241{
242 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
243 requireNearCauldron(world, handle);
244 const session = requireSession(world, command.characterId);
245 return {
246 events: [],
247 private: bagView(world.ecs, handle),
248 cauldron: true,
249 cauldronState: sessionView(session)
250 };
251}
252
253function openCauldron (world, sessionId, command)
254{
255 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
256 requireNearCauldron(world, handle);
257 const inventory = ensureInventory(world, handle);
258 if (countItemInSlots(inventory.slots, ItemId.glassBottle) < 1)
259 { throw userError("I don't have any empty bottles."); }
260
261 const sessions = ensureSessions(world);
262 const existing = sessions.get(command.characterId) ?? emptySession();
263 if (!Array.isArray(existing.pendingBrew))
264 { existing.pendingBrew = []; }
265 if (!Array.isArray(existing.steps))
266 { existing.steps = []; }
267 sessions.set(command.characterId, existing);
268 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
269 return {
270 events: shove ? [shove] : [],
271 private: bagView(world.ecs, handle),
272 cauldron: true,
273 cauldronState: sessionView(existing)
274 };
275}
276
277function closeCauldron (world, sessionId, command)
278{
279 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
280 // Soft claims only — bag never held station items.
281 ensureSessions(world).delete(command.characterId);
282 return { events: [], private: bagView(world.ecs, handle), cauldron: false };
283}
284
285function insertIngredient (world, sessionId, command)
286{
287 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
288 requireNearCauldron(world, handle);
289 const session = requireSession(world, command.characterId);
290
291 const itemId = command.itemId | 0;
292 const quantity = Math.max(0, command.quantity | 0);
293 if (!itemId || quantity <= 0)
294 { throw userError("Nothing to insert."); }
295
296 const def = itemDefinition(itemId);
297 if (!def || def.uniqueInstance || def.equipment
298 || itemId === ItemId.potion || itemId === ItemId.glassBottle
299 || itemId === ItemId.flower || itemId === ItemId.dye || def.flower || def.dye)
300 { throw userError("Use the Dyes tab for flowers."); }
301
302 const instance = command.instance ? structuredClone(command.instance) : null;
303 const inventory = ensureInventory(world, handle);
304 const have = instance
305 ? countMatchingInstance(inventory.slots, itemId, instance)
306 : countItemInSlots(inventory.slots, itemId);
307 const alreadyClaimed = pendingClaimedQuantity(session.pendingBrew, itemId, instance);
308 if (have < alreadyClaimed + quantity)
309 { throw userError("Not enough of that item in your inventory."); }
310
311 const uniqueIds = new Set((session.pendingBrew ?? []).map((row) => row.itemId | 0));
312 if (!uniqueIds.has(itemId) && uniqueIds.size >= CAULDRON_SLOT_COUNT)
313 {
314 throw userError(
315 `A brew can use at most ${CAULDRON_SLOT_COUNT} different ingredients.`
316 );
317 }
318
319 addPendingBrew(session, { itemId, quantity, instance });
320 session.steps.push({ kind: AlchemyStepKind.insert, itemId });
321 session.lastSuccessRecipe = null;
322
323 return {
324 events: [],
325 private: bagView(world.ecs, handle),
326 cauldron: true,
327 cauldronState: sessionView(session)
328 };
329}
330
331function action (world, sessionId, command)
332{
333 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
334 requireNearCauldron(world, handle);
335 const session = requireSession(world, command.characterId);
336 const kind = command.action;
337 if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool)
338 { throw userError("Unknown cauldron action."); }
339 if (!session.steps.some((step) => step.kind === AlchemyStepKind.insert))
340 { throw userError("Insert an ingredient first."); }
341 session.steps.push({ kind });
342 session.lastSuccessRecipe = null;
343 return {
344 events: [],
345 private: bagView(world.ecs, handle),
346 cauldron: true,
347 cauldronState: sessionView(session)
348 };
349}
350
351function bottle (world, sessionId, command)
352{
353 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
354 requireNearCauldron(world, handle);
355 const session = requireSession(world, command.characterId);
356 if (!(session.pendingBrew?.length > 0) && !(session.steps?.length > 0))
357 { throw userError("The cauldron is empty."); }
358
359 const inventory = ensureInventory(world, handle);
360 const skills = world.ecs.get(handle, Component.skills) ?? {};
361
362 const evaluation = evaluateAlchemyBottle({
363 skills,
364 brewStacks: session.pendingBrew,
365 takenSteps: session.steps,
366 potions: resolvedAlchemyPotions()
367 });
368
369 const wanted = Math.max(1, evaluation.batch | 0);
370 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
371 const produced = Math.min(wanted, bottles);
372 if (produced <= 0)
373 { throw userError("You need glass bottles to bottle the brew."); }
374
375 for (const row of session.pendingBrew ?? [])
376 {
377 const have = row.instance
378 ? countMatchingInstance(inventory.slots, row.itemId, row.instance)
379 : countItemInSlots(inventory.slots, row.itemId);
380 if (have < (row.quantity | 0))
381 { throw userError("Not enough of that item in your inventory."); }
382 }
383
384 // Consume soft-claimed ingredients only now (success path).
385 const consumed = [];
386 for (const row of session.pendingBrew ?? [])
387 {
388 const pulled = takeMatchingFromSlots(inventory.slots, {
389 itemId: row.itemId,
390 quantity: row.quantity,
391 instance: row.instance ?? null,
392 compact: false
393 });
394 if (!pulled.ok)
395 {
396 refundStacks(inventory, consumed);
397 throw userError("Not enough of that item in your inventory.");
398 }
399 inventory.slots = pulled.slots;
400 consumed.push(pulled.taken);
401 }
402
403 const takeBottles = takeMatchingFromSlots(inventory.slots, {
404 itemId: ItemId.glassBottle,
405 quantity: produced,
406 compact: false
407 });
408 if (!takeBottles.ok)
409 {
410 refundStacks(inventory, consumed);
411 throw userError("You need glass bottles to bottle the brew.");
412 }
413 inventory.slots = takeBottles.slots;
414
415 const instance = potionItemInstance(evaluation.result);
416 const potionDef = itemDefinition(ItemId.potion);
417 const origin = craftOrigin(CraftOriginVerb.brewed, characterDisplayName(world, handle));
418 const inserted = insertStack(inventory.slots, attachOrigins({
419 itemId: ItemId.potion,
420 quantity: produced,
421 instance,
422 origins: [{ origin, quantity: produced }]
423 }), potionDef);
424 if (!inserted.ok)
425 {
426 refundStacks(inventory, consumed);
427 refundStacks(inventory, [takeBottles.taken]);
428 throw userError("Not enough inventory space for potions.");
429 }
430 inventory.slots = inserted.slots;
431
432 session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
433 clearAlchemy(session);
434
435 const events = [];
436 if (evaluation.success && skills?.xp)
437 {
438 const xpInputs = (consumed ?? []).map((row) => ({
439 itemId: row.itemId,
440 quantity: row.quantity
441 }));
442 const amount = craftXpForConsumedInputs(xpInputs, SkillId.alchemy);
443 if (amount > 0)
444 {
445 const result = applySkillXp(skills, SkillId.alchemy, amount);
446 if (result.changed)
447 {
448 events.push({
449 type: "skills-updated",
450 entityId,
451 characterId: command.characterId,
452 ...publicSkillsPayload(skills),
453 stored: storedSkillXp(skills),
454 levelUps: result.levelUp ? [result.levelUp] : []
455 });
456 }
457 }
458 }
459
460 return {
461 events,
462 private: bagView(world.ecs, handle),
463 cauldron: true,
464 cauldronState: sessionView(session),
465 alchemyResult: {
466 success: !!evaluation.success,
467 reason: evaluation.reason ?? null,
468 produced,
469 wanted,
470 lost: Math.max(0, wanted - produced),
471 potion: {
472 potionKey: instance.potionKey,
473 displayName: instance.displayName,
474 unstable: instance.unstable,
475 color: instance.color,
476 fillLevel: instance.fillLevel
477 }
478 }
479 };
480}
481
482function createDye (world, sessionId, command)
483{
484 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
485 requireNearCauldron(world, handle);
486 requireSession(world, command.characterId);
487
488 const rows = normalizeFlowerRows(command.flowers);
489 if (!rows.length)
490 { throw userError("Add flowers to make dye."); }
491
492 const mixed = mixFlowersForDye(rows);
493 if (!mixed.ok)
494 { throw userError(mixed.reason); }
495
496 const wanted = mixed.quantity;
497 const inventory = ensureInventory(world, handle);
498 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
499 if (bottles < wanted && !command.confirmOverflow)
500 {
501 return {
502 events: [],
503 private: bagView(world.ecs, handle),
504 cauldron: true,
505 cauldronState: sessionView(requireSession(world, command.characterId)),
506 dyeConfirm: {
507 wanted,
508 bottles,
509 lost: Math.max(0, wanted - bottles)
510 }
511 };
512 }
513
514 const produced = Math.min(wanted, bottles);
515 if (produced <= 0)
516 { throw userError("You need glass bottles to bottle the dye."); }
517
518 for (const row of rows)
519 {
520 const have = countMatchingInstance(inventory.slots, ItemId.flower, row.instance);
521 if (have < row.quantity)
522 { throw userError("Not enough of those flowers in your inventory."); }
523 }
524
525 for (const row of rows)
526 {
527 const pulled = takeMatchingFromSlots(inventory.slots, {
528 itemId: ItemId.flower,
529 quantity: row.quantity,
530 instance: row.instance,
531 compact: false
532 });
533 if (!pulled.ok)
534 { throw userError("Not enough of those flowers in your inventory."); }
535 inventory.slots = pulled.slots;
536 }
537
538 const takeBottles = takeMatchingFromSlots(inventory.slots, {
539 itemId: ItemId.glassBottle,
540 quantity: produced,
541 compact: false
542 });
543 if (!takeBottles.ok)
544 { throw userError("You need glass bottles to bottle the dye."); }
545 inventory.slots = takeBottles.slots;
546
547 const dyeDef = itemDefinition(ItemId.dye);
548 const origin = craftOrigin(CraftOriginVerb.mixed, characterDisplayName(world, handle));
549 const inserted = insertStack(inventory.slots, attachOrigins({
550 itemId: ItemId.dye,
551 quantity: produced,
552 instance: mixed.instance,
553 origins: [{ origin, quantity: produced }]
554 }), dyeDef);
555 if (!inserted.ok)
556 { throw userError("Not enough inventory space for dye."); }
557 inventory.slots = inserted.slots;
558
559 const events = [];
560 const skills = world.ecs.get(handle, Component.skills);
561 const flowerCount = rows.reduce((sum, row) => sum + (row.quantity | 0), 0);
562 if (skills?.xp && flowerCount > 0)
563 {
564 const result = applySkillXp(
565 skills,
566 SkillId.alchemy,
567 flowerCount * craftXpMultiplierForSkill(SkillId.alchemy)
568 );
569 if (result.changed)
570 {
571 events.push({
572 type: "skills-updated",
573 entityId,
574 characterId: command.characterId,
575 ...publicSkillsPayload(skills),
576 stored: storedSkillXp(skills),
577 levelUps: result.levelUp ? [result.levelUp] : []
578 });
579 }
580 }
581
582 return {
583 events,
584 private: bagView(world.ecs, handle),
585 cauldron: true,
586 cauldronState: sessionView(requireSession(world, command.characterId)),
587 alchemyResult: {
588 success: true,
589 reason: null,
590 produced,
591 wanted,
592 lost: Math.max(0, wanted - produced),
593 potion: {
594 potionKey: "dye",
595 displayName: "Dye",
596 unstable: false,
597 color: mixed.instance?.color ?? null,
598 fillLevel: mixed.instance?.fillLevel ?? DEFAULT_DYE_FILL
599 }
600 }
601 };
602}
603
604function normalizeFlowerRows (flowers)
605{
606 if (!Array.isArray(flowers))
607 { return []; }
608 const rows = [];
609 for (const entry of flowers)
610 {
611 const itemId = entry?.itemId | 0;
612 const quantity = Math.min(FLOWER_MAX_STACK, Math.max(0, entry?.quantity | 0));
613 if (itemId !== ItemId.flower || quantity <= 0)
614 { continue; }
615 const instance = entry.instance ? structuredClone(entry.instance) : null;
616 if (!instance?.color)
617 { continue; }
618 rows.push({ itemId: ItemId.flower, quantity, instance });
619 }
620 return rows;
621}
622
623function clear (world, sessionId, command)
624{
625 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
626 requireNearCauldron(world, handle);
627 const session = requireSession(world, command.characterId);
628 clearAlchemy(session);
629 session.lastSuccessRecipe = null;
630 return {
631 events: [],
632 private: bagView(world.ecs, handle),
633 cauldron: true,
634 cauldronState: sessionView(session)
635 };
636}
637
638function clearDye (world, sessionId, command)
639{
640 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
641 requireNearCauldron(world, handle);
642 const session = requireSession(world, command.characterId);
643 // Dye slots are client-only; nothing to clear server-side.
644 return {
645 events: [],
646 private: bagView(world.ecs, handle),
647 cauldron: true,
648 cauldronState: sessionView(session)
649 };
650}
651
652function saveRecipe (world, sessionId, command)
653{
654 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
655 requireNearCauldron(world, handle);
656 const session = requireSession(world, command.characterId);
657 const recipe = session.lastSuccessRecipe;
658 if (!recipe)
659 { throw userError("No successful recipe to save."); }
660
661 const inventory = ensureInventory(world, handle);
662 const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper);
663 if (paperIndex < 0)
664 { throw userError("You need paper to write a recipe."); }
665 const paperSlot = inventory.slots[paperIndex];
666 const recipeStack = attachOrigins({
667 itemId: ItemId.recipePaper,
668 quantity: 1,
669 origins: [{
670 origin: writtenOrigin(characterDisplayName(world, handle)),
671 quantity: 1
672 }],
673 instance: {
674 kind: "recipe-paper",
675 recipeId: randomUUID(),
676 potionKey: recipe.potionKey,
677 displayName: `${recipe.displayName} recipe`,
678 authorCharacterId: command.characterId,
679 authorDisplayName: characterDisplayName(world, handle),
680 minAlchemyLevel: recipe.minAlchemyLevel ?? 1,
681 body: recipePaperBody(recipe),
682 writtenAt: Date.now()
683 }
684 });
685
686 if (stackQuantity(paperSlot.quantity) <= 1)
687 { inventory.slots[paperIndex] = recipeStack; }
688 else
689 {
690 const free = inventory.slots.findIndex((entry) => !entry);
691 if (free < 0)
692 { throw userError("Need a free inventory slot for the recipe paper."); }
693 paperSlot.quantity -= 1;
694 inventory.slots[free] = recipeStack;
695 }
696
697 session.lastSuccessRecipe = null;
698 return {
699 events: [],
700 private: bagView(world.ecs, handle),
701 cauldron: true,
702 cauldronState: sessionView(session)
703 };
704}