BlueGit

timfa questward

Files

questward / server / src / alchemy / service.js

service.js

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