BlueGit

timfa questward

Make spellbooks learnable from the bag context menu.

Shop stock lacked spellbook instances, so Study never appeared; Learn now resolves the spell from the item def, shop buys attach defaultInstance, and reading consumes the book.

timfa Tim Falken · pushed by timfa

Authored 2026-08-30 · 2 months ago

Hash
27056543ccb5a21ee3b41ae19aa4c7c0c1cb33b6
Parent
b5f71590
4 files changed +162 −7
client/src/play/inventory.js +6 −2
@@ -11,6 +11,8 @@ import
11 11 LETTER_MAX_BODY_CHARS
12 12 } from "/shared/definitions/items.js";
13 13 import { formatLetterSignature } from "/shared/courier/systemLetters.js";
14 import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";
15 import { spellDefinition } from "/shared/definitions/spells.js";
14 16 import { applyItemIcon } from "../render/potionIcon.js";
15 17
16 18 const EQUIP_LABELS = {
@@ -320,10 +322,12 @@ export function initInventory ({
320 322 });
321 323 }
322 324 }
323 if (slot.instance?.kind === "spellbook")
325 const learnSpellId = spellIdFromSpellbookStack(slot, def);
326 if (learnSpellId)
324 327 {
328 const spellName = spellDefinition(learnSpellId)?.displayName ?? "spell";
325 329 items.push({
326 label: "Study",
330 label: `Learn ${spellName}`,
327 331 onSelect: () => socket.send({ type: MessageType.readSpellbook, slotIndex })
328 332 });
329 333 }
@@ -11,6 +11,8 @@ import
11 LETTER_MAX_BODY_CHARS
11 LETTER_MAX_BODY_CHARS
12} from "/shared/definitions/items.js";
12} from "/shared/definitions/items.js";
13import { formatLetterSignature } from "/shared/courier/systemLetters.js";
13import { formatLetterSignature } from "/shared/courier/systemLetters.js";
14import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";
15import { spellDefinition } from "/shared/definitions/spells.js";
14import { applyItemIcon } from "../render/potionIcon.js";
16import { applyItemIcon } from "../render/potionIcon.js";
15
17
16const EQUIP_LABELS = {
18const EQUIP_LABELS = {
@@ -320,10 +322,12 @@ export function initInventory ({
320 });
322 });
321 }
323 }
322 }
324 }
323 if (slot.instance?.kind === "spellbook")
325 const learnSpellId = spellIdFromSpellbookStack(slot, def);
326 if (learnSpellId)
324 {
327 {
328 const spellName = spellDefinition(learnSpellId)?.displayName ?? "spell";
325 items.push({
329 items.push({
326 label: "Study",
330 label: `Learn ${spellName}`,
327 onSelect: () => socket.send({ type: MessageType.readSpellbook, slotIndex })
331 onSelect: () => socket.send({ type: MessageType.readSpellbook, slotIndex })
328 });
332 });
329 }
333 }
server/src/spells/service.js +5 −3
@@ -45,7 +45,8 @@ import
45 45 import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
46 46 import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
47 47 import { publicSpellLight, SpellLightRegistry } from "./lights.js";
48 import { spellbookInstance, spellbookItemIdForSpell } from "../../../shared/definitions/spellItems.js";
48 import { spellbookInstance, spellbookItemIdForSpell, spellIdFromSpellbookStack } from "../../../shared/definitions/spellItems.js";
49 import { itemDefinition } from "../../../shared/definitions/items.js";
49 50 import { bagView } from "../items/bags.js";
50 51 import { applyTindersAtTile } from "./tinders.js";
51 52
@@ -868,13 +869,14 @@ function readSpellbook (world, sessionId, command, now)
868 869 const inventory = world.ecs.get(handle, Component.inventory);
869 870 const slotIndex = command.slotIndex | 0;
870 871 const slot = inventory?.slots?.[slotIndex];
871 if (!slot?.instance || slot.instance.kind !== "spellbook")
872 const itemDef = itemDefinition(slot?.itemId);
873 const spellId = spellIdFromSpellbookStack(slot, itemDef);
874 if (!spellId)
872 875 {
873 876 const error = new Error("That is not a spellbook.");
874 877 error.userFacing = true;
875 878 throw error;
876 879 }
877 const spellId = slot.instance.spellId;
878 880 const spells = world.ecs.get(handle, Component.spells);
879 881 const skills = world.ecs.get(handle, Component.skills);
880 882 const learned = learnSpell(spells, spellId);
@@ -45,7 +45,8 @@ import
45import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
45import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
46import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
46import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
47import { publicSpellLight, SpellLightRegistry } from "./lights.js";
47import { publicSpellLight, SpellLightRegistry } from "./lights.js";
48import { spellbookInstance, spellbookItemIdForSpell } from "../../../shared/definitions/spellItems.js";
48import { spellbookInstance, spellbookItemIdForSpell, spellIdFromSpellbookStack } from "../../../shared/definitions/spellItems.js";
49import { itemDefinition } from "../../../shared/definitions/items.js";
49import { bagView } from "../items/bags.js";
50import { bagView } from "../items/bags.js";
50import { applyTindersAtTile } from "./tinders.js";
51import { applyTindersAtTile } from "./tinders.js";
51
52
@@ -868,13 +869,14 @@ function readSpellbook (world, sessionId, command, now)
868 const inventory = world.ecs.get(handle, Component.inventory);
869 const inventory = world.ecs.get(handle, Component.inventory);
869 const slotIndex = command.slotIndex | 0;
870 const slotIndex = command.slotIndex | 0;
870 const slot = inventory?.slots?.[slotIndex];
871 const slot = inventory?.slots?.[slotIndex];
871 if (!slot?.instance || slot.instance.kind !== "spellbook")
872 const itemDef = itemDefinition(slot?.itemId);
873 const spellId = spellIdFromSpellbookStack(slot, itemDef);
874 if (!spellId)
872 {
875 {
873 const error = new Error("That is not a spellbook.");
876 const error = new Error("That is not a spellbook.");
874 error.userFacing = true;
877 error.userFacing = true;
875 throw error;
878 throw error;
876 }
879 }
877 const spellId = slot.instance.spellId;
878 const spells = world.ecs.get(handle, Component.spells);
880 const spells = world.ecs.get(handle, Component.spells);
879 const skills = world.ecs.get(handle, Component.skills);
881 const skills = world.ecs.get(handle, Component.skills);
880 const learned = learnSpell(spells, spellId);
882 const learned = learnSpell(spells, spellId);
server/tests/spells.test.js +123 −1
@@ -1,10 +1,31 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 import { SpellId } from "../../shared/definitions/spells.js";
3 import { SpellId, spellDefinition } from "../../shared/definitions/spells.js";
4 4 import { SPELL_PROJECTILE_MS } from "../../shared/spells/constants.js";
5 5 import { mobComponents } from "../src/simulation/spawners.js";
6 6 import { MobId } from "../../shared/definitions/mobs.js";
7 7 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
8 import { Component } from "../src/ecs/components.js";
9 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
10 import
11 {
12 spellIdFromSpellbookStack,
13 spellbookItemIdForSpell,
14 SPELLBOOK_ITEM_DEFINITIONS
15 } from "../../shared/definitions/spellItems.js";
16 import { itemDefinition } from "../../shared/definitions/items.js";
17 import { normalizePlayerSpells } from "../../shared/spells/state.js";
18 import { createSpellbookStack } from "../src/spells/service.js";
19
20 function workerOf (simulation, entityId)
21 {
22 for (const worker of simulation.workers.values())
23 {
24 if (worker.world.ecs.handleOf(entityId) != null)
25 { return worker; }
26 }
27 return null;
28 }
8 29
9 30 test("cast light resolves without command error and can place a spell light", () =>
10 31 {
@@ -102,3 +123,104 @@ test("attack from out of range paths toward the target", () =>
102 123 finally
103 124 { harness.close(); }
104 125 });
126
127 test("spellbook stacks resolve a spell id even without an instance", () =>
128 {
129 const itemId = spellbookItemIdForSpell(SpellId.manaBullet);
130 const def = itemDefinition(itemId);
131 assert.ok(def?.defaultInstance?.kind === "spellbook");
132 assert.equal(spellIdFromSpellbookStack({ itemId, quantity: 1 }, def), SpellId.manaBullet);
133 assert.equal(spellIdFromSpellbookStack({ itemId, quantity: 1, instance: null }, def), SpellId.manaBullet);
134 assert.equal(
135 spellIdFromSpellbookStack({ itemId, quantity: 1, instance: def.defaultInstance }, def),
136 SpellId.manaBullet
137 );
138 assert.ok(SPELLBOOK_ITEM_DEFINITIONS[itemId]?.consumableSpellId === SpellId.manaBullet);
139 });
140
141 test("read-spellbook learns the spell and consumes a catalog-style book", () =>
142 {
143 const harness = makeSimulation({ workerCount: 1 });
144 try
145 {
146 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
147 const itemId = spellbookItemIdForSpell(SpellId.manaBullet);
148 const slots = emptySlots();
149 slots[0] = { itemId, quantity: 1, instance: null };
150 harness.stateDb.saveBag(character.character_id, {
151 inventory: slots,
152 equipment: emptyEquipment(),
153 vault: [],
154 vaultReserved: []
155 });
156 const playerId = harness.simulation.spawnCharacter(1, character);
157 const worker = workerOf(harness.simulation, playerId);
158 const handle = worker.world.ecs.handleOf(playerId);
159 const before = normalizePlayerSpells(worker.world.ecs.get(handle, Component.spells));
160 assert.equal(before.known.includes(SpellId.manaBullet), false);
161
162 harness.simulation.enqueue(1, {
163 type: "read-spellbook",
164 characterId: character.character_id,
165 slotIndex: 0
166 });
167 const result = harness.simulation.step();
168 assert.equal(
169 result.events.some((event) => event.type === "command-error"),
170 false,
171 JSON.stringify(result.events)
172 );
173 assert.ok(result.events.some((event) => event.type === "spells"));
174 const updated = result.events.find((event) => event.type === "spells");
175 assert.ok(updated.spells.some((spell) => spell.spellId === SpellId.manaBullet));
176 assert.equal(spellDefinition(SpellId.manaBullet).displayName, "Mana Bullet");
177
178 const inv = worker.world.ecs.get(handle, Component.inventory);
179 assert.equal(inv.slots[0], null);
180 const after = normalizePlayerSpells(worker.world.ecs.get(handle, Component.spells));
181 assert.ok(after.known.includes(SpellId.manaBullet));
182 }
183 finally
184 { harness.close(); }
185 });
186
187 test("read-spellbook with instance stack also works and rejects duplicates", () =>
188 {
189 const harness = makeSimulation({ workerCount: 1 });
190 try
191 {
192 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
193 const stack = createSpellbookStack(SpellId.magicMissile);
194 assert.ok(stack?.instance?.kind === "spellbook");
195 const slots = emptySlots();
196 slots[0] = stack;
197 slots[1] = structuredClone(stack);
198 harness.stateDb.saveBag(character.character_id, {
199 inventory: slots,
200 equipment: emptyEquipment(),
201 vault: [],
202 vaultReserved: []
203 });
204 const playerId = harness.simulation.spawnCharacter(1, character);
205
206 harness.simulation.enqueue(1, {
207 type: "read-spellbook",
208 characterId: character.character_id,
209 slotIndex: 0
210 });
211 const learned = harness.simulation.step();
212 assert.equal(learned.events.some((event) => event.type === "command-error"), false);
213
214 harness.simulation.enqueue(1, {
215 type: "read-spellbook",
216 characterId: character.character_id,
217 slotIndex: 1
218 });
219 const again = harness.simulation.step();
220 assert.ok(again.events.some((event) => event.type === "command-error"));
221 const err = again.events.find((event) => event.type === "command-error");
222 assert.match(err.message ?? "", /already know/i);
223 }
224 finally
225 { harness.close(); }
226 });
@@ -1,10 +1,31 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { SpellId } from "../../shared/definitions/spells.js";
3import { SpellId, spellDefinition } from "../../shared/definitions/spells.js";
4import { SPELL_PROJECTILE_MS } from "../../shared/spells/constants.js";
4import { SPELL_PROJECTILE_MS } from "../../shared/spells/constants.js";
5import { mobComponents } from "../src/simulation/spawners.js";
5import { mobComponents } from "../src/simulation/spawners.js";
6import { MobId } from "../../shared/definitions/mobs.js";
6import { MobId } from "../../shared/definitions/mobs.js";
7import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
7import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
8import { Component } from "../src/ecs/components.js";
9import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
10import
11 {
12 spellIdFromSpellbookStack,
13 spellbookItemIdForSpell,
14 SPELLBOOK_ITEM_DEFINITIONS
15 } from "../../shared/definitions/spellItems.js";
16import { itemDefinition } from "../../shared/definitions/items.js";
17import { normalizePlayerSpells } from "../../shared/spells/state.js";
18import { createSpellbookStack } from "../src/spells/service.js";
19
20function workerOf (simulation, entityId)
21{
22 for (const worker of simulation.workers.values())
23 {
24 if (worker.world.ecs.handleOf(entityId) != null)
25 { return worker; }
26 }
27 return null;
28}
8
29
9test("cast light resolves without command error and can place a spell light", () =>
30test("cast light resolves without command error and can place a spell light", () =>
10{
31{
@@ -102,3 +123,104 @@ test("attack from out of range paths toward the target", () =>
102 finally
123 finally
103 { harness.close(); }
124 { harness.close(); }
104});
125});
126
127test("spellbook stacks resolve a spell id even without an instance", () =>
128{
129 const itemId = spellbookItemIdForSpell(SpellId.manaBullet);
130 const def = itemDefinition(itemId);
131 assert.ok(def?.defaultInstance?.kind === "spellbook");
132 assert.equal(spellIdFromSpellbookStack({ itemId, quantity: 1 }, def), SpellId.manaBullet);
133 assert.equal(spellIdFromSpellbookStack({ itemId, quantity: 1, instance: null }, def), SpellId.manaBullet);
134 assert.equal(
135 spellIdFromSpellbookStack({ itemId, quantity: 1, instance: def.defaultInstance }, def),
136 SpellId.manaBullet
137 );
138 assert.ok(SPELLBOOK_ITEM_DEFINITIONS[itemId]?.consumableSpellId === SpellId.manaBullet);
139});
140
141test("read-spellbook learns the spell and consumes a catalog-style book", () =>
142{
143 const harness = makeSimulation({ workerCount: 1 });
144 try
145 {
146 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
147 const itemId = spellbookItemIdForSpell(SpellId.manaBullet);
148 const slots = emptySlots();
149 slots[0] = { itemId, quantity: 1, instance: null };
150 harness.stateDb.saveBag(character.character_id, {
151 inventory: slots,
152 equipment: emptyEquipment(),
153 vault: [],
154 vaultReserved: []
155 });
156 const playerId = harness.simulation.spawnCharacter(1, character);
157 const worker = workerOf(harness.simulation, playerId);
158 const handle = worker.world.ecs.handleOf(playerId);
159 const before = normalizePlayerSpells(worker.world.ecs.get(handle, Component.spells));
160 assert.equal(before.known.includes(SpellId.manaBullet), false);
161
162 harness.simulation.enqueue(1, {
163 type: "read-spellbook",
164 characterId: character.character_id,
165 slotIndex: 0
166 });
167 const result = harness.simulation.step();
168 assert.equal(
169 result.events.some((event) => event.type === "command-error"),
170 false,
171 JSON.stringify(result.events)
172 );
173 assert.ok(result.events.some((event) => event.type === "spells"));
174 const updated = result.events.find((event) => event.type === "spells");
175 assert.ok(updated.spells.some((spell) => spell.spellId === SpellId.manaBullet));
176 assert.equal(spellDefinition(SpellId.manaBullet).displayName, "Mana Bullet");
177
178 const inv = worker.world.ecs.get(handle, Component.inventory);
179 assert.equal(inv.slots[0], null);
180 const after = normalizePlayerSpells(worker.world.ecs.get(handle, Component.spells));
181 assert.ok(after.known.includes(SpellId.manaBullet));
182 }
183 finally
184 { harness.close(); }
185});
186
187test("read-spellbook with instance stack also works and rejects duplicates", () =>
188{
189 const harness = makeSimulation({ workerCount: 1 });
190 try
191 {
192 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
193 const stack = createSpellbookStack(SpellId.magicMissile);
194 assert.ok(stack?.instance?.kind === "spellbook");
195 const slots = emptySlots();
196 slots[0] = stack;
197 slots[1] = structuredClone(stack);
198 harness.stateDb.saveBag(character.character_id, {
199 inventory: slots,
200 equipment: emptyEquipment(),
201 vault: [],
202 vaultReserved: []
203 });
204 const playerId = harness.simulation.spawnCharacter(1, character);
205
206 harness.simulation.enqueue(1, {
207 type: "read-spellbook",
208 characterId: character.character_id,
209 slotIndex: 0
210 });
211 const learned = harness.simulation.step();
212 assert.equal(learned.events.some((event) => event.type === "command-error"), false);
213
214 harness.simulation.enqueue(1, {
215 type: "read-spellbook",
216 characterId: character.character_id,
217 slotIndex: 1
218 });
219 const again = harness.simulation.step();
220 assert.ok(again.events.some((event) => event.type === "command-error"));
221 const err = again.events.find((event) => event.type === "command-error");
222 assert.match(err.message ?? "", /already know/i);
223 }
224 finally
225 { harness.close(); }
226});
shared/definitions/spellItems.js +28 −1
@@ -79,6 +79,32 @@ export function spellbookInstance (spellId)
79 79 });
80 80 }
81 81
82 /**
83 * Resolve which spell a bag/shop stack teaches.
84 * Prefer instance data; fall back to the item def / stable spellbook id map
85 * so catalog stock without an instance still works.
86 */
87 export function spellIdFromSpellbookStack (stack, itemDef = null)
88 {
89 if (stack?.instance?.kind === "spellbook" && typeof stack.instance.spellId === "string")
90 {
91 const id = stack.instance.spellId;
92 if (spellDefinition(id))
93 { return id; }
94 }
95 if (itemDef?.consumableSpellId && spellDefinition(itemDef.consumableSpellId))
96 { return itemDef.consumableSpellId; }
97 const itemId = stack?.itemId | 0;
98 if (!itemId)
99 { return null; }
100 for (const [spellId, bookId] of Object.entries(SPELLBOOK_ID_BY_SPELL))
101 {
102 if ((bookId | 0) === itemId && spellDefinition(spellId))
103 { return spellId; }
104 }
105 return null;
106 }
107
82 108 function buildSpellbookDefinitions ()
83 109 {
84 110 const out = {};
@@ -100,7 +126,8 @@ function buildSpellbookDefinitions ()
100 126 category: ItemCategory.finished,
101 127 iconKey: "spellbook",
102 128 defaultState: "spark",
103 consumableSpellId: spellId
129 consumableSpellId: spellId,
130 defaultInstance: spellbookInstance(spellId)
104 131 });
105 132 }
106 133 return out;
@@ -79,6 +79,32 @@ export function spellbookInstance (spellId)
79 });
79 });
80}
80}
81
81
82/**
83 * Resolve which spell a bag/shop stack teaches.
84 * Prefer instance data; fall back to the item def / stable spellbook id map
85 * so catalog stock without an instance still works.
86 */
87export function spellIdFromSpellbookStack (stack, itemDef = null)
88{
89 if (stack?.instance?.kind === "spellbook" && typeof stack.instance.spellId === "string")
90 {
91 const id = stack.instance.spellId;
92 if (spellDefinition(id))
93 { return id; }
94 }
95 if (itemDef?.consumableSpellId && spellDefinition(itemDef.consumableSpellId))
96 { return itemDef.consumableSpellId; }
97 const itemId = stack?.itemId | 0;
98 if (!itemId)
99 { return null; }
100 for (const [spellId, bookId] of Object.entries(SPELLBOOK_ID_BY_SPELL))
101 {
102 if ((bookId | 0) === itemId && spellDefinition(spellId))
103 { return spellId; }
104 }
105 return null;
106}
107
82function buildSpellbookDefinitions ()
108function buildSpellbookDefinitions ()
83{
109{
84 const out = {};
110 const out = {};
@@ -100,7 +126,8 @@ function buildSpellbookDefinitions ()
100 category: ItemCategory.finished,
126 category: ItemCategory.finished,
101 iconKey: "spellbook",
127 iconKey: "spellbook",
102 defaultState: "spark",
128 defaultState: "spark",
103 consumableSpellId: spellId
129 consumableSpellId: spellId,
130 defaultInstance: spellbookInstance(spellId)
104 });
131 });
105 }
132 }
106 return out;
133 return out;