BlueGit

timfa questward

Files

questward / server / src / alchemy / service.js

service.js

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