BlueGit

timfa questward

Files

questward / server / src / alchemy / service.js

service.js

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