BlueGit

timfa questward

Files

questward / server / src / itemSpawners / service.js

service.js

service.js 18.0 KiB Download Raw
1/**
2 * Item Spawner runtime: refill ground-item piles or openable containers,
3 * channelled open with shove-every-second, condition gates, respawn delay.
4 */
5import { Component } from "../ecs/components.js";
6import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
7import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
8import { tileToChunk, tileToRegion, parseChunkKey } from "../world/coordinates.js";
9import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";
10import
11 {
12 isItemSpawnerConfig,
13 normalizeItemSpawnerConfig,
14 isItemSpawnerContainerAppearance,
15 itemSpawnerContainerDisplayName,
16 itemSpawnerContainerSpriteName,
17 ITEM_SPAWNER_LOCKED_MESSAGE,
18 ITEM_SPAWNER_SPACE_TOAST,
19 ITEM_SPAWNER_OPEN_DURATION_MS,
20 ITEM_SPAWNER_SHOVE_MS,
21 ItemSpawnerAppearance
22 } from "../../../shared/definitions/itemSpawners.js";
23import { emptyConditionSet, evaluateConditionSet } from "../../../shared/quests/conditions.js";
24import { itemDefinition } from "../../../shared/definitions/items.js";
25import { insertStack } from "../../../shared/items/inventory.js";
26import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
27import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
28import { buildEntityConditionContext } from "../doors/conditionContext.js";
29import { tileShoveEvent } from "../simulation/tileInteract.js";
30import
31 {
32 placeOrMergeGroundStack,
33 removeGroundItem,
34 bagView,
35 publicGroundItem
36 } from "../items/bags.js";
37
38function userError (message)
39{
40 const error = new Error(message);
41 error.userFacing = true;
42 return error;
43}
44
45function ensureState (world)
46{
47 if (!world.itemSpawnerState)
48 {
49 world.itemSpawnerState = {
50 /** @type {Map<string, object>} spawnerId → live instance */
51 active: new Map(),
52 /** @type {Map<string, number>} spawnerId → respawnAt ms */
53 pendingRespawn: new Map(),
54 /** @type {Map<number, string>} groundItemId → spawnerId */
55 groundToSpawner: new Map(),
56 /** @type {Map<number, object>} characterId → open session */
57 openSessions: new Map()
58 };
59 }
60 return world.itemSpawnerState;
61}
62
63export function itemContainersInChunk (world, chunkX, chunkY, dimensionId = OVERWORLD_ID)
64{
65 const dim = normalizeDimensionId(dimensionId);
66 const state = ensureState(world);
67 const out = [];
68 for (const entry of state.active.values())
69 {
70 if (entry.mode !== "container")
71 { continue; }
72 if (normalizeDimensionId(entry.dimensionId) !== dim)
73 { continue; }
74 if (tileToChunk(entry.tileX) !== chunkX || tileToChunk(entry.tileY) !== chunkY)
75 { continue; }
76 out.push(publicItemContainer(entry));
77 }
78 return out;
79}
80
81export function publicItemContainer (entry)
82{
83 return {
84 containerId: entry.containerId,
85 spawnerId: entry.spawnerId,
86 tileX: entry.tileX,
87 tileY: entry.tileY,
88 dimensionId: normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID),
89 appearance: entry.appearance,
90 material: entry.material,
91 displayName: itemSpawnerContainerDisplayName(entry.appearance),
92 sprite: itemSpawnerContainerSpriteName(entry.appearance, entry.material)
93 };
94}
95
96function allocateContainerId (world)
97{
98 world.nextItemContainerId = (world.nextItemContainerId ?? 1) + 1;
99 return world.nextItemContainerId;
100}
101
102function scopedSpawnerId (rawId, dimensionId, chunkX, chunkY, index)
103{
104 const dim = normalizeDimensionId(dimensionId);
105 const raw = typeof rawId === "string" && rawId
106 ? rawId
107 : `${chunkX}:${chunkY}:${index}`;
108 return raw.startsWith(`${dim}:`) ? raw : `${dim}:${raw}`;
109}
110
111function pickTile (world, originX, originY, range, dimensionId, reserved = null)
112{
113 const dim = normalizeDimensionId(dimensionId);
114 const radius = Math.max(0, range | 0);
115 const tryTile = (tileX, tileY) =>
116 {
117 const key = `${dim}:${tileX},${tileY}`;
118 if (reserved?.has(key))
119 { return null; }
120 if (!world.ownsRegion?.(tileToRegion(tileX), tileToRegion(tileY), dim))
121 {
122 // Editor / single-worker worlds may lack ownsRegion — fall through.
123 if (typeof world.ownsRegion === "function")
124 { return null; }
125 }
126 if (typeof world.isEnterable === "function")
127 {
128 if (!world.isEnterable(tileX, tileY, dim))
129 { return null; }
130 }
131 return { tileX, tileY, dimensionId: dim };
132 };
133 if (radius === 0)
134 { return tryTile(originX, originY); }
135 for (let attempt = 0; attempt < 48; attempt++)
136 {
137 const tileX = originX + randInt(-radius, radius);
138 const tileY = originY + randInt(-radius, radius);
139 const tile = tryTile(tileX, tileY);
140 if (tile)
141 { return tile; }
142 }
143 return tryTile(originX, originY);
144}
145
146function randInt (min, max)
147{
148 return min + Math.floor(Math.random() * (max - min + 1));
149}
150
151function cloneStacks (items)
152{
153 return (items ?? []).map((line) => ({
154 itemId: line.itemId | 0,
155 quantity: Math.max(1, line.quantity | 0)
156 }));
157}
158
159/**
160 * Spawn (or refill) one item spawner instance. Returns events.
161 */
162function spawnInstance (world, entryMeta, config, now, events)
163{
164 const state = ensureState(world);
165 const spawnerId = config.spawnerId;
166 if (state.active.has(spawnerId))
167 { return; }
168 if ((state.pendingRespawn.get(spawnerId) ?? 0) > now)
169 { return; }
170 state.pendingRespawn.delete(spawnerId);
171
172 const tile = pickTile(
173 world,
174 entryMeta.originX,
175 entryMeta.originY,
176 config.spawnRangeTiles,
177 entryMeta.dimensionId
178 );
179 if (!tile)
180 { return; }
181
182 if (config.appearance === ItemSpawnerAppearance.item)
183 {
184 const groundIds = [];
185 for (const line of config.items)
186 {
187 const def = itemDefinition(line.itemId);
188 if (!def)
189 { continue; }
190 const stack = attachOrigins({
191 itemId: line.itemId,
192 quantity: line.quantity,
193 origins: [{ origin: godsOrigin(), quantity: line.quantity }]
194 });
195 const placed = placeOrMergeGroundStack(world, {
196 tileX: tile.tileX,
197 tileY: tile.tileY,
198 dimensionId: tile.dimensionId,
199 stack,
200 now,
201 source: "item-spawner",
202 // Never auto-despawn authored spawner loot.
203 despawnDurationMs: Number.MAX_SAFE_INTEGER
204 });
205 for (const ev of placed.events)
206 {
207 events.push(ev);
208 if (ev.type === "ground-item-appear" && ev.groundItemId != null)
209 {
210 const item = world.groundItems.get(ev.groundItemId);
211 if (item)
212 {
213 item.itemSpawnerId = spawnerId;
214 item.source = "item-spawner";
215 // Far-future expiry (DB column is NOT NULL); expireGroundItems also skips these.
216 item.expiresAt = Number.MAX_SAFE_INTEGER;
217 state.groundToSpawner.set(ev.groundItemId, spawnerId);
218 groundIds.push(ev.groundItemId);
219 }
220 }
221 }
222 }
223 if (!groundIds.length)
224 { return; }
225 state.active.set(spawnerId, {
226 mode: "items",
227 spawnerId,
228 dimensionId: tile.dimensionId,
229 originX: entryMeta.originX,
230 originY: entryMeta.originY,
231 spawnRangeTiles: config.spawnRangeTiles,
232 respawnDelaySeconds: config.respawnDelaySeconds,
233 appearance: config.appearance,
234 items: cloneStacks(config.items),
235 groundItemIds: groundIds,
236 when: emptyConditionSet()
237 });
238 return;
239 }
240
241 const containerId = allocateContainerId(world);
242 const live = {
243 mode: "container",
244 containerId,
245 spawnerId,
246 tileX: tile.tileX,
247 tileY: tile.tileY,
248 dimensionId: tile.dimensionId,
249 originX: entryMeta.originX,
250 originY: entryMeta.originY,
251 spawnRangeTiles: config.spawnRangeTiles,
252 respawnDelaySeconds: config.respawnDelaySeconds,
253 appearance: config.appearance,
254 material: config.material,
255 items: cloneStacks(config.items),
256 when: config.when ?? emptyConditionSet()
257 };
258 state.active.set(spawnerId, live);
259 events.push({
260 type: "item-container-appear",
261 ...publicItemContainer(live)
262 });
263}
264
265function clearActive (world, spawnerId, events, { scheduleRespawn = true } = {})
266{
267 const state = ensureState(world);
268 const live = state.active.get(spawnerId);
269 if (!live)
270 { return; }
271 state.active.delete(spawnerId);
272
273 if (live.mode === "items")
274 {
275 for (const id of live.groundItemIds ?? [])
276 { state.groundToSpawner.delete(id); }
277 }
278 else if (live.mode === "container")
279 {
280 events.push({
281 type: "item-container-despawn",
282 containerId: live.containerId,
283 spawnerId,
284 tileX: live.tileX,
285 tileY: live.tileY,
286 dimensionId: live.dimensionId
287 });
288 }
289
290 if (scheduleRespawn)
291 {
292 const delayMs = Math.max(0, (live.respawnDelaySeconds | 0) * 1000);
293 const clock = typeof world.now === "function" ? world.now() : Date.now();
294 state.pendingRespawn.set(spawnerId, clock + delayMs);
295 }
296}
297
298/**
299 * Called whenever a ground item leaves the world (pickup, transform, burn, …).
300 */
301export function notifyGroundItemRemoved (world, groundItemId, events = [])
302{
303 const state = ensureState(world);
304 const spawnerId = state.groundToSpawner.get(groundItemId);
305 if (!spawnerId)
306 { return events; }
307 state.groundToSpawner.delete(groundItemId);
308 const live = state.active.get(spawnerId);
309 if (!live || live.mode !== "items")
310 { return events; }
311 live.groundItemIds = (live.groundItemIds ?? []).filter((id) => id !== groundItemId);
312 // Remaining piles stay in the world but are unlinked (orphaned normal items).
313 if (live.groundItemIds.length === 0)
314 { clearActive(world, spawnerId, events, { scheduleRespawn: true }); }
315 return events;
316}
317
318/**
319 * Wrap removeGroundItem so item-spawner tracking stays in sync.
320 */
321export function removeGroundItemTracked (world, groundItemId)
322{
323 const events = [];
324 notifyGroundItemRemoved(world, groundItemId, events);
325 removeGroundItem(world, groundItemId);
326 return events;
327}
328
329function listAuthoredItemSpawners (world)
330{
331 const list = [];
332 for (const [key, chunk] of world.chunks)
333 {
334 if (chunk.replica || !chunk.simulating || !chunk.data?.open)
335 { continue; }
336 const { chunkX, chunkY, dimensionId: keyDimensionId } = parseChunkKey(key);
337 const dimensionId = normalizeDimensionId(chunk.dimensionId ?? keyDimensionId ?? OVERWORLD_ID);
338 for (const entry of chunk.data.spawners ?? [])
339 {
340 if (!isItemSpawnerConfig(entry.config))
341 { continue; }
342 const localX = entry.localX;
343 const localY = entry.localY;
344 const index = localY * CHUNK_SIZE + localX;
345 const config = normalizeItemSpawnerConfig(
346 entry.config,
347 scopedSpawnerId(entry.config?.spawnerId, dimensionId, chunkX, chunkY, index)
348 );
349 config.spawnerId = scopedSpawnerId(config.spawnerId, dimensionId, chunkX, chunkY, index);
350 list.push({
351 config,
352 originX: chunkX * CHUNK_SIZE + localX,
353 originY: chunkY * CHUNK_SIZE + localY,
354 dimensionId
355 });
356 }
357 }
358 return list;
359}
360
361/**
362 * Tick: refill empty spawners whose respawn timer elapsed; advance open channels.
363 */
364export function stepItemSpawners (world, now = Date.now())
365{
366 const state = ensureState(world);
367 const events = [];
368 const privates = [];
369
370 // Drop active entries whose authored spawner vanished.
371 const authoredIds = new Set(listAuthoredItemSpawners(world).map((row) => row.config.spawnerId));
372 for (const spawnerId of [...state.active.keys()])
373 {
374 if (!authoredIds.has(spawnerId))
375 { clearActive(world, spawnerId, events, { scheduleRespawn: false }); }
376 }
377
378 for (const row of listAuthoredItemSpawners(world))
379 {
380 const { config } = row;
381 if (state.active.has(config.spawnerId))
382 { continue; }
383 const readyAt = state.pendingRespawn.get(config.spawnerId) ?? 0;
384 if (readyAt > now)
385 { continue; }
386 spawnInstance(world, row, config, now, events);
387 }
388
389 const openResult = stepOpenSessions(world, now);
390 events.push(...openResult.events);
391 privates.push(...openResult.privates);
392
393 return { events, privates };
394}
395
396function clearOpenSession (world, characterId)
397{
398 ensureState(world).openSessions.delete(characterId);
399}
400
401export function cancelItemContainerOpen (world, characterId)
402{
403 clearOpenSession(world, characterId);
404}
405
406/**
407 * Start a 2s shove channel to open a container (adjacent tile required).
408 */
409export function startOpenItemContainer (world, sessionId, characterId, containerId, now = Date.now())
410{
411 const entityId = world.characterEntities.get(characterId);
412 if (entityId == null)
413 { throw userError("Character is not in the world."); }
414 const handle = world.ecs.handleOf(entityId);
415 const identity = world.ecs.get(handle, Component.networkIdentity);
416 if (!identity || identity.sessionId !== sessionId)
417 { throw userError("Character is not in the world."); }
418 if (world.ecs.has(handle, Component.dead))
419 { throw userError("You are dead."); }
420
421 const state = ensureState(world);
422 let live = null;
423 for (const entry of state.active.values())
424 {
425 if (entry.mode === "container" && entry.containerId === (containerId | 0))
426 {
427 live = entry;
428 break;
429 }
430 }
431 if (!live)
432 { throw userError("That container is gone."); }
433
434 const position = world.ecs.get(handle, Component.position);
435 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
436 if (normalizeDimensionId(live.dimensionId) !== dim)
437 { throw userError("That container is gone."); }
438 if (position.tileX === live.tileX && position.tileY === live.tileY)
439 { throw userError("Stand next to the container."); }
440 if (!isAdjacentTile(position.tileX, position.tileY, live.tileX, live.tileY))
441 { throw userError("Stand next to the container."); }
442
443 if (world.ecs.has(handle, Component.gather))
444 { world.ecs.remove(handle, Component.gather); }
445 const path = world.ecs.get(handle, Component.path);
446 if (path)
447 { path.tiles = []; }
448
449 clearOpenSession(world, characterId);
450 state.openSessions.set(characterId, {
451 sessionId,
452 containerId: live.containerId,
453 spawnerId: live.spawnerId,
454 tileX: live.tileX,
455 tileY: live.tileY,
456 dimensionId: live.dimensionId,
457 appearance: live.appearance,
458 startedAt: now,
459 endsAt: now + ITEM_SPAWNER_OPEN_DURATION_MS,
460 nextShoveAt: now
461 });
462
463 return { events: [] };
464}
465
466function containerConditionsMet (world, entityId, live)
467{
468 const when = live.when ?? emptyConditionSet();
469 if (!(when.all?.length > 0))
470 { return true; }
471 const ctx = buildEntityConditionContext(world, entityId);
472 if (!ctx)
473 { return false; }
474 return evaluateConditionSet(when, ctx);
475}
476
477function giveStacksToPlayer (world, handle, entityId, stacks, now, events)
478{
479 const inventory = world.ecs.get(handle, Component.inventory);
480 if (!inventory)
481 { return { dropped: false }; }
482 let dropped = false;
483 const position = world.ecs.get(handle, Component.position);
484 const dim = normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
485 for (const line of stacks)
486 {
487 const def = itemDefinition(line.itemId);
488 if (!def)
489 { continue; }
490 let remaining = Math.max(1, line.quantity | 0);
491 const stack = attachOrigins({
492 itemId: line.itemId,
493 quantity: remaining,
494 origins: [{ origin: godsOrigin(), quantity: remaining }]
495 });
496 const inserted = insertStack(inventory.slots, stack, def);
497 inventory.slots = inserted.slots;
498 remaining = inserted.remainder | 0;
499 if (remaining > 0)
500 {
501 dropped = true;
502 const leftover = attachOrigins({
503 itemId: line.itemId,
504 quantity: remaining,
505 origins: [{ origin: godsOrigin(), quantity: remaining }]
506 });
507 const placed = placeOrMergeGroundStack(world, {
508 tileX: position.tileX,
509 tileY: position.tileY,
510 dimensionId: dim,
511 stack: leftover,
512 now,
513 source: "item-spawner-overflow"
514 });
515 events.push(...placed.events);
516 }
517 }
518 return { dropped };
519}
520
521function completeOpen (world, handle, entityId, characterId, session, events, privates, now)
522{
523 const state = ensureState(world);
524 const live = state.active.get(session.spawnerId);
525 clearOpenSession(world, characterId);
526 if (!live || live.mode !== "container" || live.containerId !== session.containerId)
527 { return; }
528
529 if (!containerConditionsMet(world, entityId, live))
530 {
531 events.push({
532 type: "toast",
533 sessionId: session.sessionId,
534 characterId,
535 message: ITEM_SPAWNER_LOCKED_MESSAGE
536 });
537 return;
538 }
539
540 const stacks = cloneStacks(live.items);
541 const { dropped } = giveStacksToPlayer(world, handle, entityId, stacks, now, events);
542 privates.push({ characterId, bag: bagView(world.ecs, handle) });
543 if (dropped)
544 {
545 events.push({
546 type: "toast",
547 sessionId: session.sessionId,
548 characterId,
549 message: ITEM_SPAWNER_SPACE_TOAST
550 });
551 }
552 clearActive(world, live.spawnerId, events, { scheduleRespawn: true });
553}
554
555function stepOpenSessions (world, now)
556{
557 const state = ensureState(world);
558 const events = [];
559 const privates = [];
560 for (const [characterId, session] of [...state.openSessions.entries()])
561 {
562 const entityId = world.characterEntities.get(characterId);
563 if (entityId == null)
564 {
565 clearOpenSession(world, characterId);
566 continue;
567 }
568 const handle = world.ecs.handleOf(entityId);
569 if (world.ecs.has(handle, Component.dead))
570 {
571 clearOpenSession(world, characterId);
572 continue;
573 }
574 const live = state.active.get(session.spawnerId);
575 if (!live || live.mode !== "container" || live.containerId !== session.containerId)
576 {
577 clearOpenSession(world, characterId);
578 continue;
579 }
580 const position = world.ecs.get(handle, Component.position);
581 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
582 if (normalizeDimensionId(live.dimensionId) !== dim
583 || position.tileX === live.tileX && position.tileY === live.tileY
584 || !isAdjacentTile(position.tileX, position.tileY, live.tileX, live.tileY))
585 {
586 clearOpenSession(world, characterId);
587 continue;
588 }
589
590 if (now >= session.nextShoveAt && now < session.endsAt)
591 {
592 session.nextShoveAt = now + ITEM_SPAWNER_SHOVE_MS;
593 events.push(tileShoveEvent(
594 entityId,
595 position.tileX,
596 position.tileY,
597 live.tileX,
598 live.tileY,
599 dim
600 ));
601 }
602
603 if (now < session.endsAt)
604 { continue; }
605
606 completeOpen(world, handle, entityId, characterId, session, events, privates, now);
607 }
608 return { events, privates };
609}
610
611export function handleItemSpawnerCommand (world, sessionId, command, now = Date.now())
612{
613 if (command.type === "open-item-container")
614 {
615 return startOpenItemContainer(
616 world,
617 sessionId,
618 command.characterId,
619 command.containerId,
620 now
621 );
622 }
623 if (command.type === "cancel-open-item-container")
624 {
625 cancelItemContainerOpen(world, command.characterId);
626 return { events: [] };
627 }
628 return null;
629}
630
631/** Find container at a world tile (for client click helpers / tests). */
632export function itemContainerAtTile (world, tileX, tileY, dimensionId = OVERWORLD_ID)
633{
634 const dim = normalizeDimensionId(dimensionId);
635 const state = ensureState(world);
636 for (const entry of state.active.values())
637 {
638 if (entry.mode !== "container")
639 { continue; }
640 if (entry.tileX === tileX && entry.tileY === tileY
641 && normalizeDimensionId(entry.dimensionId) === dim)
642 { return entry; }
643 }
644 return null;
645}
646
647export { ensureState as ensureItemSpawnerState };