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