BlueGit

timfa questward

Files

questward / server / src / simulation / spawners.js

spawners.js

rweaks
timfa Tim Falken · pushed by timfa · 2 months ago
2b34e2dd History
spawners.js 8.9 KiB Download Raw
1import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { mobCanFight, mobSkillLevels } from "../../../shared/definitions/mobCombat.js";
3import {
4 normalizeSpawnerConfig,
5 listAmbientMobTypes,
6 mobDefinition,
7 mobSpriteName,
8 MobId
9} from "../../../shared/definitions/mobs.js";
10import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
11import { emptyEquipment } from "../../../shared/items/inventory.js";
12import { itemDefinition } from "../../../shared/definitions/items.js";
13import { Component } from "../ecs/components.js";
14import { tileToChunk, tileToRegion } from "../world/coordinates.js";
15
16export function collectSpawnRequests (world)
17{
18 const requests = [];
19 const counts = countBySpawner(world);
20 const staffAlive = staffNamesBySpawner(world);
21 const reserved = new Set();
22 for (const [key, chunk] of world.chunks)
23 {
24 if (chunk.replica || !chunk.simulating || !chunk.data.open)
25 { continue; }
26 const [chunkX, chunkY] = key.split(",").map(Number);
27 for (const entry of chunk.data.spawners ?? [])
28 {
29 const localX = entry.localX;
30 const localY = entry.localY;
31 const index = localY * CHUNK_SIZE + localX;
32 const config = normalizeSpawnerConfig(
33 entry.config,
34 `${chunkX}:${chunkY}:${index}`
35 );
36 const flying = !!mobDefinition(config.mobTypeId)?.flying;
37 const originX = chunkX * CHUNK_SIZE + localX;
38 const originY = chunkY * CHUNK_SIZE + localY;
39 const persistent = !!mobDefinition(config.mobTypeId)?.persistent;
40
41 if (config.centralExchange)
42 {
43 const alive = staffAlive.get(config.spawnerId) ?? new Set();
44 for (const staff of CENTRAL_EXCHANGE_STAFF)
45 {
46 if (alive.has(staff.name))
47 { continue; }
48 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
49 { break; }
50 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
51 if (!tile)
52 { break; }
53 reserved.add(`${tile.tileX},${tile.tileY}`);
54 alive.add(staff.name);
55 staffAlive.set(config.spawnerId, alive);
56 requests.push({
57 ...tile,
58 mobTypeId: MobId.centralExchange,
59 spawnerId: config.spawnerId,
60 originTileX: originX,
61 originTileY: originY,
62 wanderRangeTiles: config.maxWanderRangeTiles,
63 persistent,
64 sex: staff.sex,
65 displayName: staff.name,
66 equipment: config.equipment,
67 sells: [],
68 buysItems: false,
69 hiddenDiscount: config.hiddenDiscount,
70 centralExchange: true
71 });
72 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
73 }
74 continue;
75 }
76
77 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
78 {
79 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
80 if (!tile)
81 { break; }
82 reserved.add(`${tile.tileX},${tile.tileY}`);
83 requests.push({
84 ...tile,
85 mobTypeId: config.mobTypeId,
86 spawnerId: config.spawnerId,
87 originTileX: originX,
88 originTileY: originY,
89 wanderRangeTiles: config.maxWanderRangeTiles,
90 persistent,
91 sex: config.sex,
92 displayName: config.displayName,
93 equipment: config.equipment,
94 sells: config.sells,
95 buysItems: config.buysItems,
96 hiddenDiscount: config.hiddenDiscount,
97 centralExchange: false
98 });
99 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
100 }
101 }
102 }
103 requests.push(...collectAmbientRequests(world, reserved));
104 return requests;
105}
106
107export function mobComponents (request)
108{
109 const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer");
110 const sex = request.sex === "female" || request.sex === "male"
111 ? request.sex
112 : (def.sex ?? "male");
113 const displayName = String(request.displayName || def.displayName || "NPC").trim() || def.displayName;
114 const appearance = {
115 sex,
116 firstName: displayName,
117 lastName: ""
118 };
119 if (!def.usePlayerBody)
120 {
121 const sprite = mobSpriteName(def.mobTypeId);
122 if (sprite)
123 { appearance.sprite = sprite; }
124 }
125
126 const components = {
127 position: { tileX: request.tileX, tileY: request.tileY },
128 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
129 path: { tiles: [] },
130 appearance,
131 creature: { mobTypeId: def.mobTypeId },
132 health: { current: def.health ?? 8, max: def.health ?? 8 }
133 };
134 if (request.spawnerId)
135 {
136 components.spawnOrigin = {
137 spawnerId: request.spawnerId,
138 originTileX: request.originTileX ?? request.tileX,
139 originTileY: request.originTileY ?? request.tileY,
140 wanderRangeTiles: request.wanderRangeTiles ?? 4,
141 centralExchange: !!request.centralExchange,
142 stationTileX: null,
143 stationTileY: null
144 };
145 }
146 if (def.persistent)
147 { components.persistent = {}; }
148 if (def.freeFlight)
149 {
150 components.flight = {
151 x: request.tileX + 0.5,
152 y: request.tileY + 0.5,
153 targetX: request.tileX + 0.5,
154 targetY: request.tileY + 0.5,
155 speed: def.flightSpeedTilesPerSec ?? 2.5,
156 nextPickAt: 0,
157 lastAt: 0
158 };
159 }
160 if (mobCanFight(def))
161 {
162 components.combat = { targetEntityId: null, nextSwingAt: 0 };
163 components.skills = { levels: mobSkillLevels(def) };
164 }
165
166 const equipmentSlots = emptyEquipment().slots;
167 const authored = request.equipment ?? {};
168 for (const slot of Object.keys(equipmentSlots))
169 {
170 const itemId = authored[slot] | 0;
171 if (!itemId)
172 { continue; }
173 const itemDef = itemDefinition(itemId);
174 if (!itemDef?.equipment || itemDef.equipment.slot !== slot)
175 { continue; }
176 equipmentSlots[slot] = { itemId, quantity: 1 };
177 }
178 if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))
179 { components.equipment = { slots: equipmentSlots }; }
180
181 const catalog = Array.isArray(request.sells)
182 ? request.sells.map((entry) =>
183 {
184 if (entry && typeof entry === "object")
185 {
186 return {
187 itemId: entry.itemId | 0,
188 quantity: Math.max(0, entry.quantity | 0 || 0)
189 };
190 }
191 return { itemId: entry | 0, quantity: 0 };
192 }).filter((line) => line.itemId > 0)
193 : [];
194 const buysItems = !!request.buysItems;
195 const isExchange = !!request.centralExchange || def.centralExchange;
196 if (!isExchange && (catalog.length || buysItems || def.talkable))
197 {
198 components.shop = {
199 catalog,
200 buysItems,
201 hiddenDiscount: Number(request.hiddenDiscount) || 0.9,
202 displayName,
203 remaining: Object.create(null),
204 boughtStock: Object.create(null),
205 restockDay: null
206 };
207 }
208 return components;
209}
210
211function collectAmbientRequests (world, reserved = new Set())
212{
213 const requests = [];
214 const ambientTypes = listAmbientMobTypes();
215 if (!ambientTypes.length)
216 { return requests; }
217
218 const loaders = world.ecs.query(Component.position, Component.chunkLoader);
219 if (!loaders.length)
220 { return requests; }
221
222 for (const def of ambientTypes)
223 {
224 const maxPerLoader = Math.max(0, def.ambientMaxPerLoader ?? 1);
225 const alive = countCreatures(world, def.mobTypeId);
226 const budget = maxPerLoader * loaders.length;
227 if (alive >= budget)
228 { continue; }
229
230 for (const loader of loaders)
231 {
232 if (requests.length + alive >= budget)
233 { break; }
234 const tile = pickSpawnTile(
235 world,
236 loader.position.tileX,
237 loader.position.tileY,
238 8,
239 !!def.flying,
240 reserved
241 );
242 if (!tile)
243 { continue; }
244 reserved.add(`${tile.tileX},${tile.tileY}`);
245 requests.push({
246 ...tile,
247 mobTypeId: def.mobTypeId,
248 spawnerId: null,
249 persistent: false
250 });
251 }
252 }
253 return requests;
254}
255
256function countBySpawner (world)
257{
258 const counts = new Map();
259 for (const entity of world.ecs.query(Component.spawnOrigin))
260 {
261 const id = entity.spawnOrigin.spawnerId;
262 counts.set(id, (counts.get(id) ?? 0) + 1);
263 }
264 return counts;
265}
266
267function staffNamesBySpawner (world)
268{
269 const map = new Map();
270 for (const entity of world.ecs.query(Component.spawnOrigin, Component.appearance))
271 {
272 if (!entity.spawnOrigin?.centralExchange)
273 { continue; }
274 const id = entity.spawnOrigin.spawnerId;
275 const name = entity.appearance?.firstName;
276 if (!id || !name)
277 { continue; }
278 const set = map.get(id) ?? new Set();
279 set.add(name);
280 map.set(id, set);
281 }
282 return map;
283}
284
285function countCreatures (world, mobTypeId)
286{
287 let count = 0;
288 for (const entity of world.ecs.query(Component.creature))
289 {
290 if (entity.creature.mobTypeId === mobTypeId)
291 { count += 1; }
292 }
293 return count;
294}
295
296function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null)
297{
298 const radius = Math.max(1, range | 0);
299 for (let attempt = 0; attempt < 48; attempt++)
300 {
301 const tileX = originX + randInt(-radius, radius);
302 const tileY = originY + randInt(-radius, radius);
303 const key = `${tileX},${tileY}`;
304 if (reserved?.has(key))
305 { continue; }
306 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
307 { continue; }
308 if (flying)
309 {
310 if (!chunkIsOpen(world, tileX, tileY))
311 { continue; }
312 return { tileX, tileY };
313 }
314 if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY))
315 { continue; }
316 return { tileX, tileY };
317 }
318 return null;
319}
320
321function chunkIsOpen (world, tileX, tileY)
322{
323 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
324 return !!data?.open;
325}
326
327function randInt (min, max)
328{
329 return min + Math.floor(Math.random() * (max - min + 1));
330}