BlueGit

timfa questward

Files

questward / server / src / simulation / spawners.js

spawners.js

spawners.js 11.4 KiB Download Raw
1import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { mobCanFight, mobSkillLevels, mobHealthForLevel } from "../../../shared/definitions/mobCombat.js";
3import {
4 normalizeSpawnerConfig,
5 listAmbientMobTypes,
6 mobDefinition,
7 mobSpriteName,
8 MobId,
9 spawnerEquipmentSlot,
10 isTownGuardMob
11} from "../../../shared/definitions/mobs.js";
12import { spellDefinition } from "../../../shared/definitions/spells.js";
13import { LeatherItemId } from "../../../shared/definitions/leatherItems.js";
14import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
15import { emptyEquipment } from "../../../shared/items/inventory.js";
16import { itemDefinition } from "../../../shared/definitions/items.js";
17import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";
18import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js";
19import { Component } from "../ecs/components.js";
20import { tileToChunk, tileToRegion } from "../world/coordinates.js";
21
22export function collectSpawnRequests (world)
23{
24 const requests = [];
25 const counts = countBySpawner(world);
26 const staffAlive = staffNamesBySpawner(world);
27 const reserved = new Set();
28 for (const [key, chunk] of world.chunks)
29 {
30 if (chunk.replica || !chunk.simulating || !chunk.data.open)
31 { continue; }
32 const [chunkX, chunkY] = key.split(",").map(Number);
33 for (const entry of chunk.data.spawners ?? [])
34 {
35 const localX = entry.localX;
36 const localY = entry.localY;
37 const index = localY * CHUNK_SIZE + localX;
38 const config = normalizeSpawnerConfig(
39 entry.config,
40 `${chunkX}:${chunkY}:${index}`
41 );
42 const flying = !!mobDefinition(config.mobTypeId)?.flying;
43 const originX = chunkX * CHUNK_SIZE + localX;
44 const originY = chunkY * CHUNK_SIZE + localY;
45 const persistent = !!mobDefinition(config.mobTypeId)?.persistent;
46
47 if (config.centralExchange)
48 {
49 const alive = staffAlive.get(config.spawnerId) ?? new Set();
50 for (const staff of CENTRAL_EXCHANGE_STAFF)
51 {
52 if (alive.has(staff.name))
53 { continue; }
54 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
55 { break; }
56 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
57 if (!tile)
58 { break; }
59 reserved.add(`${tile.tileX},${tile.tileY}`);
60 alive.add(staff.name);
61 staffAlive.set(config.spawnerId, alive);
62 requests.push({
63 ...tile,
64 mobTypeId: MobId.centralExchange,
65 spawnerId: config.spawnerId,
66 originTileX: originX,
67 originTileY: originY,
68 wanderRangeTiles: config.maxWanderRangeTiles,
69 level: config.level,
70 bounty: config.bounty,
71 spells: config.spells,
72 persistent,
73 sex: staff.sex,
74 displayName: staff.name,
75 equipment: config.equipment,
76 sells: [],
77 buysItems: false,
78 hiddenDiscount: config.hiddenDiscount,
79 centralExchange: true,
80 townGuard: false
81 });
82 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
83 }
84 continue;
85 }
86
87 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
88 {
89 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
90 if (!tile)
91 { break; }
92 reserved.add(`${tile.tileX},${tile.tileY}`);
93 requests.push({
94 ...tile,
95 mobTypeId: config.mobTypeId,
96 spawnerId: config.spawnerId,
97 originTileX: originX,
98 originTileY: originY,
99 wanderRangeTiles: config.maxWanderRangeTiles,
100 level: config.level,
101 bounty: config.bounty,
102 spells: config.spells,
103 persistent,
104 sex: config.sex,
105 displayName: config.displayName,
106 equipment: config.equipment,
107 sells: config.sells,
108 buysItems: config.buysItems,
109 hiddenDiscount: config.hiddenDiscount,
110 centralExchange: false,
111 townGuard: !!config.townGuard || isTownGuardMob(config.mobTypeId)
112 });
113 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
114 }
115 }
116 }
117 requests.push(...collectAmbientRequests(world, reserved));
118 return requests;
119}
120
121export function mobComponents (request)
122{
123 const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer");
124 const sex = request.sex === "female" || request.sex === "male"
125 ? request.sex
126 : (def.sex ?? "male");
127 const displayName = String(request.displayName || def.displayName || "NPC").trim() || def.displayName;
128 const level = Math.max(1, Math.min(99, Number(request.level) || 1)) | 0;
129 const appearance = {
130 sex,
131 firstName: displayName,
132 lastName: ""
133 };
134 if (def.usePlayerBody)
135 {
136 Object.assign(appearance, appearanceHairFields(hairFromNameSeed(displayName, sex)));
137 }
138 else
139 {
140 const sprite = mobSpriteName(def.mobTypeId);
141 if (sprite)
142 { appearance.sprite = sprite; }
143 }
144
145 const maxHp = mobHealthForLevel(def, level);
146 const components = {
147 position: { tileX: request.tileX, tileY: request.tileY },
148 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
149 path: { tiles: [] },
150 appearance,
151 creature: { mobTypeId: def.mobTypeId, level },
152 health: { current: maxHp, max: maxHp }
153 };
154 if (request.spawnerId)
155 {
156 components.spawnOrigin = {
157 spawnerId: request.spawnerId,
158 originTileX: request.originTileX ?? request.tileX,
159 originTileY: request.originTileY ?? request.tileY,
160 wanderRangeTiles: request.wanderRangeTiles ?? 4,
161 bounty: Math.max(0, Number(request.bounty) || 0) | 0,
162 level,
163 centralExchange: !!request.centralExchange,
164 townGuard: !!request.townGuard || isTownGuardMob(def.mobTypeId),
165 stationTileX: null,
166 stationTileY: null
167 };
168 }
169 if (def.persistent)
170 { components.persistent = {}; }
171 if (def.freeFlight)
172 {
173 components.flight = {
174 x: request.tileX + 0.5,
175 y: request.tileY + 0.5,
176 targetX: request.tileX + 0.5,
177 targetY: request.tileY + 0.5,
178 speed: def.flightSpeedTilesPerSec ?? 2.5,
179 nextPickAt: 0,
180 lastAt: 0
181 };
182 }
183 if (mobCanFight(def))
184 {
185 components.combat = { targetEntityId: null, nextSwingAt: 0 };
186 components.skills = { levels: mobSkillLevels(def, level) };
187 }
188
189 const knownSpells = normalizeMobSpells(request.spells, level);
190 if (knownSpells.length)
191 {
192 components.spells = {
193 known: knownSpells.map((entry) => entry.spellId),
194 favorites: [],
195 autoCast: false,
196 castChances: Object.fromEntries(knownSpells.map((entry) => [entry.spellId, entry.chance]))
197 };
198 components.spellcasting = {
199 armedSpellId: null,
200 repeatSpellId: null,
201 repeatTargetEntityId: null,
202 nextCastAt: 0,
203 pendingCast: null
204 };
205 }
206
207 const equipmentSlots = emptyEquipment().slots;
208 const authored = request.equipment ?? {};
209 const defaults = def.usePlayerBody ? npcDefaultEquipment(displayName, sex) : null;
210 for (const slot of Object.keys(equipmentSlots))
211 {
212 const authoredEntry = authored[slot];
213 let { itemId, dyeColor } = spawnerEquipmentSlot(authoredEntry);
214 if (!itemId && defaults?.[slot])
215 {
216 itemId = defaults[slot].itemId;
217 dyeColor = defaults[slot].dyeColor ?? null;
218 }
219 if (!itemId)
220 { continue; }
221 const itemDef = itemDefinition(itemId);
222 if (!itemDef?.equipment || itemDef.equipment.slot !== slot)
223 { continue; }
224 const stack = { itemId, quantity: 1 };
225 if (dyeColor && itemDef.dyeable)
226 { stack.instance = { kind: "clothing", dyeColor }; }
227 equipmentSlots[slot] = stack;
228 }
229 if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))
230 { components.equipment = { slots: equipmentSlots }; }
231
232 const catalog = Array.isArray(request.sells)
233 ? request.sells.map((entry) =>
234 {
235 if (entry && typeof entry === "object")
236 {
237 return {
238 itemId: entry.itemId | 0,
239 quantity: Math.max(0, entry.quantity | 0 || 0)
240 };
241 }
242 return { itemId: entry | 0, quantity: 0 };
243 }).filter((line) => line.itemId > 0)
244 : [];
245 const buysItems = !!request.buysItems;
246 const isExchange = !!request.centralExchange || def.centralExchange;
247 if (!isExchange && (catalog.length || buysItems || def.talkable))
248 {
249 components.shop = {
250 catalog,
251 buysItems,
252 hiddenDiscount: Number(request.hiddenDiscount) || 0.9,
253 displayName,
254 remaining: Object.create(null),
255 boughtStock: Object.create(null),
256 restockDay: null
257 };
258 }
259 return components;
260}
261
262function normalizeMobSpells (raw, level)
263{
264 if (!Array.isArray(raw))
265 { return []; }
266 const out = [];
267 const seen = new Set();
268 const lv = Math.max(1, level | 0 || 1);
269 for (const entry of raw)
270 {
271 if (!entry || typeof entry !== "object")
272 { continue; }
273 const spellId = String(entry.spellId ?? "").trim();
274 if (!spellId || seen.has(spellId))
275 { continue; }
276 const def = spellDefinition(spellId);
277 if (!def)
278 { continue; }
279 const minLevel = Math.max(1, def.minMagicLevel | 0 || 1);
280 if (lv < minLevel)
281 { continue; }
282 seen.add(spellId);
283 out.push({
284 spellId,
285 chance: Math.max(0, Math.min(100, Number(entry.chance) || 0)) | 0
286 });
287 }
288 return out;
289}
290
291function collectAmbientRequests (world, reserved = new Set())
292{
293 const requests = [];
294 const ambientTypes = listAmbientMobTypes();
295 if (!ambientTypes.length)
296 { return requests; }
297
298 const loaders = world.ecs.query(Component.position, Component.chunkLoader);
299 if (!loaders.length)
300 { return requests; }
301
302 for (const def of ambientTypes)
303 {
304 const maxPerLoader = Math.max(0, def.ambientMaxPerLoader ?? 1);
305 const alive = countCreatures(world, def.mobTypeId);
306 const budget = maxPerLoader * loaders.length;
307 if (alive >= budget)
308 { continue; }
309
310 for (const loader of loaders)
311 {
312 if (requests.length + alive >= budget)
313 { break; }
314 const tile = pickSpawnTile(
315 world,
316 loader.position.tileX,
317 loader.position.tileY,
318 8,
319 !!def.flying,
320 reserved
321 );
322 if (!tile)
323 { continue; }
324 reserved.add(`${tile.tileX},${tile.tileY}`);
325 requests.push({
326 ...tile,
327 mobTypeId: def.mobTypeId,
328 spawnerId: null,
329 level: 1,
330 bounty: 0,
331 spells: [],
332 persistent: false
333 });
334 }
335 }
336 return requests;
337}
338
339function countBySpawner (world)
340{
341 const counts = new Map();
342 for (const entity of world.ecs.query(Component.spawnOrigin))
343 {
344 const id = entity.spawnOrigin.spawnerId;
345 counts.set(id, (counts.get(id) ?? 0) + 1);
346 }
347 return counts;
348}
349
350function staffNamesBySpawner (world)
351{
352 const map = new Map();
353 for (const entity of world.ecs.query(Component.spawnOrigin, Component.appearance))
354 {
355 if (!entity.spawnOrigin?.centralExchange)
356 { continue; }
357 const id = entity.spawnOrigin.spawnerId;
358 const name = entity.appearance?.firstName;
359 if (!id || !name)
360 { continue; }
361 const set = map.get(id) ?? new Set();
362 set.add(name);
363 map.set(id, set);
364 }
365 return map;
366}
367
368function countCreatures (world, mobTypeId)
369{
370 let count = 0;
371 for (const entity of world.ecs.query(Component.creature))
372 {
373 if (entity.creature.mobTypeId === mobTypeId)
374 { count += 1; }
375 }
376 return count;
377}
378
379function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null)
380{
381 const radius = Math.max(1, range | 0);
382 for (let attempt = 0; attempt < 48; attempt++)
383 {
384 const tileX = originX + randInt(-radius, radius);
385 const tileY = originY + randInt(-radius, radius);
386 const key = `${tileX},${tileY}`;
387 if (reserved?.has(key))
388 { continue; }
389 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
390 { continue; }
391 if (flying)
392 {
393 if (!chunkIsOpen(world, tileX, tileY))
394 { continue; }
395 return { tileX, tileY };
396 }
397 if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY))
398 { continue; }
399 return { tileX, tileY };
400 }
401 return null;
402}
403
404function chunkIsOpen (world, tileX, tileY)
405{
406 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
407 return !!data?.open;
408}
409
410function randInt (min, max)
411{
412 return min + Math.floor(Math.random() * (max - min + 1));
413}