BlueGit

timfa questward

Files

questward / server / src / simulation / spawners.js

spawners.js

spawners.js 6.7 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} from "../../../shared/definitions/mobs.js";
9import { emptyEquipment } from "../../../shared/items/inventory.js";
10import { itemDefinition } from "../../../shared/definitions/items.js";
11import { Component } from "../ecs/components.js";
12import { tileToChunk, tileToRegion } from "../world/coordinates.js";
13
14export function collectSpawnRequests (world)
15{
16 const requests = [];
17 const counts = countBySpawner(world);
18 const reserved = new Set();
19 for (const [key, chunk] of world.chunks)
20 {
21 if (chunk.replica || !chunk.simulating || !chunk.data.open)
22 { continue; }
23 const [chunkX, chunkY] = key.split(",").map(Number);
24 for (const entry of chunk.data.spawners ?? [])
25 {
26 const localX = entry.localX;
27 const localY = entry.localY;
28 const index = localY * CHUNK_SIZE + localX;
29 const config = normalizeSpawnerConfig(
30 entry.config,
31 `${chunkX}:${chunkY}:${index}`
32 );
33 const flying = !!mobDefinition(config.mobTypeId)?.flying;
34 const originX = chunkX * CHUNK_SIZE + localX;
35 const originY = chunkY * CHUNK_SIZE + localY;
36 const persistent = !!mobDefinition(config.mobTypeId)?.persistent;
37 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
38 {
39 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
40 if (!tile)
41 { break; }
42 reserved.add(`${tile.tileX},${tile.tileY}`);
43 requests.push({
44 ...tile,
45 mobTypeId: config.mobTypeId,
46 spawnerId: config.spawnerId,
47 originTileX: originX,
48 originTileY: originY,
49 wanderRangeTiles: config.maxWanderRangeTiles,
50 persistent,
51 sex: config.sex,
52 displayName: config.displayName,
53 equipment: config.equipment,
54 sells: config.sells,
55 hiddenDiscount: config.hiddenDiscount
56 });
57 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
58 }
59 }
60 }
61 requests.push(...collectAmbientRequests(world, reserved));
62 return requests;
63}
64
65export function mobComponents (request)
66{
67 const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer");
68 const sex = request.sex === "female" || request.sex === "male"
69 ? request.sex
70 : (def.sex ?? "male");
71 const displayName = String(request.displayName || def.displayName || "NPC").trim() || def.displayName;
72 const appearance = {
73 sex,
74 firstName: displayName,
75 lastName: ""
76 };
77 if (!def.usePlayerBody)
78 {
79 const sprite = mobSpriteName(def.mobTypeId);
80 if (sprite)
81 { appearance.sprite = sprite; }
82 }
83
84 const components = {
85 position: { tileX: request.tileX, tileY: request.tileY },
86 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
87 path: { tiles: [] },
88 appearance,
89 creature: { mobTypeId: def.mobTypeId },
90 health: { current: def.health ?? 8, max: def.health ?? 8 }
91 };
92 if (request.spawnerId)
93 {
94 components.spawnOrigin = {
95 spawnerId: request.spawnerId,
96 originTileX: request.originTileX ?? request.tileX,
97 originTileY: request.originTileY ?? request.tileY,
98 wanderRangeTiles: request.wanderRangeTiles ?? 4
99 };
100 }
101 if (def.persistent)
102 { components.persistent = {}; }
103 if (def.freeFlight)
104 {
105 components.flight = {
106 x: request.tileX + 0.5,
107 y: request.tileY + 0.5,
108 targetX: request.tileX + 0.5,
109 targetY: request.tileY + 0.5,
110 speed: def.flightSpeedTilesPerSec ?? 2.5,
111 nextPickAt: 0,
112 lastAt: 0
113 };
114 }
115 if (mobCanFight(def))
116 {
117 components.combat = { targetEntityId: null, nextSwingAt: 0 };
118 components.skills = { levels: mobSkillLevels(def) };
119 }
120
121 const equipmentSlots = emptyEquipment().slots;
122 const authored = request.equipment ?? {};
123 for (const slot of Object.keys(equipmentSlots))
124 {
125 const itemId = authored[slot] | 0;
126 if (!itemId)
127 { continue; }
128 const itemDef = itemDefinition(itemId);
129 if (!itemDef?.equipment || itemDef.equipment.slot !== slot)
130 { continue; }
131 equipmentSlots[slot] = { itemId, quantity: 1 };
132 }
133 if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))
134 { components.equipment = { slots: equipmentSlots }; }
135
136 const stock = Array.isArray(request.sells) && request.sells.length
137 ? request.sells
138 : [...(def.sells ?? [])];
139 if (stock.length || def.talkable)
140 {
141 components.shop = {
142 stock: stock.map((id) => id | 0).filter((id) => id > 0),
143 hiddenDiscount: Number(request.hiddenDiscount) || 0.9,
144 displayName
145 };
146 }
147 return components;
148}
149
150function collectAmbientRequests (world, reserved = new Set())
151{
152 const requests = [];
153 const ambientTypes = listAmbientMobTypes();
154 if (!ambientTypes.length)
155 { return requests; }
156
157 const loaders = world.ecs.query(Component.position, Component.chunkLoader);
158 if (!loaders.length)
159 { return requests; }
160
161 for (const def of ambientTypes)
162 {
163 const maxPerLoader = Math.max(0, def.ambientMaxPerLoader ?? 1);
164 const alive = countCreatures(world, def.mobTypeId);
165 const budget = maxPerLoader * loaders.length;
166 if (alive >= budget)
167 { continue; }
168
169 for (const loader of loaders)
170 {
171 if (requests.length + alive >= budget)
172 { break; }
173 const tile = pickSpawnTile(
174 world,
175 loader.position.tileX,
176 loader.position.tileY,
177 8,
178 !!def.flying,
179 reserved
180 );
181 if (!tile)
182 { continue; }
183 reserved.add(`${tile.tileX},${tile.tileY}`);
184 requests.push({
185 ...tile,
186 mobTypeId: def.mobTypeId,
187 spawnerId: null,
188 persistent: false
189 });
190 }
191 }
192 return requests;
193}
194
195function countBySpawner (world)
196{
197 const counts = new Map();
198 for (const entity of world.ecs.query(Component.spawnOrigin))
199 {
200 const id = entity.spawnOrigin.spawnerId;
201 counts.set(id, (counts.get(id) ?? 0) + 1);
202 }
203 return counts;
204}
205
206function countCreatures (world, mobTypeId)
207{
208 let count = 0;
209 for (const entity of world.ecs.query(Component.creature))
210 {
211 if (entity.creature.mobTypeId === mobTypeId)
212 { count += 1; }
213 }
214 return count;
215}
216
217function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null)
218{
219 const radius = Math.max(1, range | 0);
220 for (let attempt = 0; attempt < 48; attempt++)
221 {
222 const tileX = originX + randInt(-radius, radius);
223 const tileY = originY + randInt(-radius, radius);
224 const key = `${tileX},${tileY}`;
225 if (reserved?.has(key))
226 { continue; }
227 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
228 { continue; }
229 if (flying)
230 {
231 if (!chunkIsOpen(world, tileX, tileY))
232 { continue; }
233 return { tileX, tileY };
234 }
235 if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY))
236 { continue; }
237 return { tileX, tileY };
238 }
239 return null;
240}
241
242function chunkIsOpen (world, tileX, tileY)
243{
244 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
245 return !!data?.open;
246}
247
248function randInt (min, max)
249{
250 return min + Math.floor(Math.random() * (max - min + 1));
251}