BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

service.js 9.7 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
4import { itemDefinition } from "../../../shared/definitions/items.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import {
8 recipeDefinition,
9 canStartCraft,
10 canCraftFitInventory,
11 hasRecipeInputs
12} from "../../../shared/crafting/recipes.js";
13import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
14import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
15import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
16import { bagView } from "../items/bags.js";
17import { tileToChunk, tileToLocal } from "../world/coordinates.js";
18import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
19import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
20
21function userError (message)
22{
23 const error = new Error(message);
24 error.userFacing = true;
25 return error;
26}
27
28function ensureCraftSessions (world)
29{
30 if (!world.craftSessions)
31 { world.craftSessions = new Map(); }
32 return world.craftSessions;
33}
34
35function nearStationBlock (world, tileX, tileY, blockType)
36{
37 for (let dy = -1; dy <= 1; dy++)
38 {
39 for (let dx = -1; dx <= 1; dx++)
40 {
41 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
42 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
43 if (data.blocks[index]?.typeId === blockType)
44 { return true; }
45 }
46 }
47 return false;
48}
49
50function stationBlockType (stationId)
51{
52 if (stationId === CraftingStationId.furnace)
53 { return BlockType.furnace; }
54 if (stationId === CraftingStationId.anvil)
55 { return BlockType.anvil; }
56 if (stationId === CraftingStationId.woodworkingBench)
57 { return BlockType.woodworkingBench; }
58 return null;
59}
60
61function takeInputs (slots, inputs)
62{
63 let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
64 for (const input of inputs ?? [])
65 {
66 let remaining = Math.max(0, stackQuantity(input.quantity));
67 if (!remaining)
68 { continue; }
69 for (let i = 0; i < next.length && remaining > 0; i++)
70 {
71 if (!next[i] || next[i].itemId !== input.itemId)
72 { continue; }
73 const taken = takeFromSlot(next, i, remaining);
74 if (!taken.ok)
75 { continue; }
76 next = taken.slots;
77 remaining -= stackQuantity(taken.taken?.quantity);
78 }
79 if (remaining > 0)
80 { return { ok: false, slots }; }
81 }
82 return { ok: true, slots: next };
83}
84
85export function startCraft (world, sessionId, characterId, stationId, recipeId, now)
86{
87 const entityId = world.characterEntities.get(characterId);
88 if (entityId == null)
89 { throw userError("Character is not in the world."); }
90 const handle = world.ecs.handleOf(entityId);
91 const identity = world.ecs.get(handle, Component.networkIdentity);
92 if (!identity || identity.sessionId !== sessionId)
93 { throw userError("Character is not in the world."); }
94 if (world.ecs.has(handle, Component.dead))
95 { throw userError("You are dead."); }
96
97 const stationDef = craftingStationDefinition(stationId);
98 if (!stationDef)
99 { throw userError("Unknown crafting station."); }
100 const recipe = recipeDefinition(recipeId);
101 if (!recipe)
102 { throw userError("Unknown recipe."); }
103 const stationIds = Array.isArray(recipe.stationIds)
104 ? recipe.stationIds
105 : [recipe.stationId];
106 if (!stationIds.includes(stationId))
107 { throw userError("That recipe cannot be made here."); }
108
109 const position = world.ecs.get(handle, Component.position);
110 const blockType = stationBlockType(stationId);
111 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
112 { throw userError("You need to stand next to the station."); }
113
114 const inventory = world.ecs.get(handle, Component.inventory);
115 const skills = world.ecs.get(handle, Component.skills);
116 const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
117 if (!canStartCraft(inventory?.slots ?? [], recipe, level))
118 {
119 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
120 { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
121 if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
122 { throw userError("Missing materials."); }
123 throw userError("Not enough bag space for the result.");
124 }
125
126 const sessions = ensureCraftSessions(world);
127 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
128 sessions.set(characterId, {
129 sessionId,
130 stationId,
131 recipeId,
132 finishesAt: now + durationMs
133 });
134 const events = [];
135 if (blockType)
136 {
137 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
138 if (shove)
139 { events.push(shove); }
140 }
141 events.push({
142 type: "item-bubble",
143 entityId,
144 itemId: recipe.output.itemId,
145 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
146 });
147 events.push({
148 type: "craft-started",
149 sessionId,
150 characterId,
151 recipeId,
152 durationMs
153 });
154 return { events };
155}
156
157export function openStation (world, sessionId, characterId, stationId)
158{
159 const entityId = world.characterEntities.get(characterId);
160 if (entityId == null)
161 { throw userError("Character is not in the world."); }
162 const handle = world.ecs.handleOf(entityId);
163 const identity = world.ecs.get(handle, Component.networkIdentity);
164 if (!identity || identity.sessionId !== sessionId)
165 { throw userError("Character is not in the world."); }
166 if (world.ecs.has(handle, Component.dead))
167 { throw userError("You are dead."); }
168
169 const stationDef = craftingStationDefinition(stationId);
170 if (!stationDef)
171 { throw userError("Unknown crafting station."); }
172 const blockType = stationBlockType(stationId);
173 const position = world.ecs.get(handle, Component.position);
174 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
175 { throw userError("You need to stand next to the station."); }
176
177 const events = [];
178 if (blockType)
179 {
180 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
181 if (shove)
182 { events.push(shove); }
183 }
184 events.push({
185 type: "station-open",
186 sessionId,
187 characterId,
188 stationId
189 });
190 return { events };
191}
192
193export function cancelCraft (world, characterId)
194{
195 ensureCraftSessions(world).delete(characterId);
196 return { events: [] };
197}
198
199export function stepCrafting (world, now)
200{
201 const sessions = ensureCraftSessions(world);
202 const events = [];
203 const privates = [];
204 for (const [characterId, session] of [...sessions.entries()])
205 {
206 if (now < session.finishesAt)
207 { continue; }
208 sessions.delete(characterId);
209 const entityId = world.characterEntities.get(characterId);
210 if (entityId == null)
211 {
212 events.push({
213 type: "craft-result",
214 sessionId: session.sessionId,
215 recipeId: session.recipeId,
216 ok: false,
217 error: "Character left the world."
218 });
219 continue;
220 }
221 const handle = world.ecs.handleOf(entityId);
222 if (world.ecs.has(handle, Component.dead))
223 {
224 events.push({
225 type: "craft-result",
226 sessionId: session.sessionId,
227 recipeId: session.recipeId,
228 ok: false,
229 error: "You are dead."
230 });
231 continue;
232 }
233
234 const recipe = recipeDefinition(session.recipeId);
235 const stationDef = craftingStationDefinition(session.stationId);
236 const inventory = world.ecs.get(handle, Component.inventory);
237 const skills = world.ecs.get(handle, Component.skills);
238 const position = world.ecs.get(handle, Component.position);
239 const blockType = stationBlockType(session.stationId);
240 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
241
242 if (!recipe || !stationDef || !inventory
243 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
244 || !canCraftFitInventory(inventory.slots, recipe)
245 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
246 {
247 events.push({
248 type: "craft-result",
249 sessionId: session.sessionId,
250 recipeId: session.recipeId,
251 ok: false,
252 error: "Could not finish crafting."
253 });
254 continue;
255 }
256
257 const taken = takeInputs(inventory.slots, recipe.inputs);
258 if (!taken.ok)
259 {
260 events.push({
261 type: "craft-result",
262 sessionId: session.sessionId,
263 recipeId: session.recipeId,
264 ok: false,
265 error: "Missing materials."
266 });
267 continue;
268 }
269 const outDef = itemDefinition(recipe.output.itemId);
270 const added = insertStack(taken.slots, {
271 itemId: recipe.output.itemId,
272 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
273 }, outDef);
274 if (!added.ok || added.remainder > 0)
275 {
276 events.push({
277 type: "craft-result",
278 sessionId: session.sessionId,
279 recipeId: session.recipeId,
280 ok: false,
281 error: "Not enough bag space for the result."
282 });
283 continue;
284 }
285 inventory.slots = added.slots;
286
287 let skillsChanged = false;
288 if (skills?.xp && recipe.xpMaterial && stationDef?.skillId)
289 {
290 if (addSkillXp(skills, stationDef.skillId, smeltingXpForMaterial(recipe.xpMaterial)))
291 { skillsChanged = true; }
292 }
293
294 privates.push({ characterId, bag: bagView(world.ecs, handle) });
295 if (skillsChanged)
296 {
297 events.push({
298 type: "skills-updated",
299 characterId,
300 skills: publicSkillsView(skills),
301 stored: storedSkillXp(skills)
302 });
303 }
304 events.push({
305 type: "craft-result",
306 sessionId: session.sessionId,
307 recipeId: session.recipeId,
308 ok: true
309 });
310 }
311 return { events, privates };
312}
313
314export function handleCraftCommand (world, sessionId, command, now)
315{
316 switch (command.type)
317 {
318 case "open-station":
319 return openStation(world, sessionId, command.characterId, command.stationId);
320 case "start-craft":
321 return startCraft(
322 world,
323 sessionId,
324 command.characterId,
325 command.stationId,
326 command.recipeId,
327 now
328 );
329 case "cancel-craft":
330 return cancelCraft(world, command.characterId);
331 default:
332 return null;
333 }
334}