| 1 | import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js"; |
| 2 | import |
| 3 | { |
| 4 | mobCanFight, |
| 5 | mobSkillLevels, |
| 6 | mobHealthForLevel, |
| 7 | mobSpellCastChancePercent |
| 8 | } from "../../../shared/definitions/mobCombat.js"; |
| 9 | import |
| 10 | { |
| 11 | normalizeSpawnerConfig, |
| 12 | listAmbientMobTypes, |
| 13 | mobDefinition, |
| 14 | mobSpriteName, |
| 15 | MobId, |
| 16 | spawnerEquipmentSlot, |
| 17 | isTownGuardMob, |
| 18 | isHumanoidMob |
| 19 | } from "../../../shared/definitions/mobs.js"; |
| 20 | import { spellDefinition, spellMinMagicLevel, SPRITE_BOLT_SPELL_BY_ELEMENT } from "../../../shared/definitions/spells.js"; |
| 21 | import { MAGIC_ELEMENT_ORDER, magicElementTint } from "../../../shared/definitions/attackTypes.js"; |
| 22 | import { essenceElementDisplayName } from "../../../shared/definitions/essenceItems.js"; |
| 23 | import { LeatherItemId } from "../../../shared/definitions/leatherItems.js"; |
| 24 | import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js"; |
| 25 | import { emptyEquipment } from "../../../shared/items/inventory.js"; |
| 26 | import { itemDefinition } from "../../../shared/definitions/items.js"; |
| 27 | import { appearanceHairFields, hairFromNameSeed, randomNpcHairColor, randomBrightOrPastelColor } from "../../../shared/appearance/hair.js"; |
| 28 | import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js"; |
| 29 | import { Component } from "../ecs/components.js"; |
| 30 | import { tileToChunk, tileToRegion, parseChunkKey } from "../world/coordinates.js"; |
| 31 | import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; |
| 32 | |
| 33 | export function collectSpawnRequests (world, now = Date.now()) |
| 34 | { |
| 35 | const requests = []; |
| 36 | const counts = countBySpawner(world); |
| 37 | const staffAlive = staffNamesBySpawner(world); |
| 38 | const reserved = new Set(); |
| 39 | ensurePendingRespawns(world); |
| 40 | for (const [key, chunk] of world.chunks) |
| 41 | { |
| 42 | if (chunk.replica || !chunk.simulating || !chunk.data.open) |
| 43 | { continue; } |
| 44 | const { chunkX, chunkY, dimensionId: keyDimensionId } = parseChunkKey(key); |
| 45 | const dimensionId = normalizeDimensionId(chunk.dimensionId ?? keyDimensionId ?? OVERWORLD_ID); |
| 46 | for (const entry of chunk.data.spawners ?? []) |
| 47 | { |
| 48 | const localX = entry.localX; |
| 49 | const localY = entry.localY; |
| 50 | const index = localY * CHUNK_SIZE + localX; |
| 51 | const config = normalizeSpawnerConfig( |
| 52 | entry.config, |
| 53 | `${chunkX}:${chunkY}:${index}` |
| 54 | ); |
| 55 | const flying = !!mobDefinition(config.mobTypeId)?.flying; |
| 56 | const originX = chunkX * CHUNK_SIZE + localX; |
| 57 | const originY = chunkY * CHUNK_SIZE + localY; |
| 58 | const persistent = !!mobDefinition(config.mobTypeId)?.persistent; |
| 59 | const delayMs = Math.max(0, (config.respawnDelaySeconds | 0) * 1000); |
| 60 | |
| 61 | if (config.centralExchange) |
| 62 | { |
| 63 | const alive = staffAlive.get(config.spawnerId) ?? new Set(); |
| 64 | for (const staff of CENTRAL_EXCHANGE_STAFF) |
| 65 | { |
| 66 | if (alive.has(staff.name)) |
| 67 | { continue; } |
| 68 | if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive) |
| 69 | { break; } |
| 70 | if (!consumeSpawnSlot(world, config.spawnerId, delayMs, now)) |
| 71 | { break; } |
| 72 | const tile = pickSpawnTile( |
| 73 | world, |
| 74 | originX, |
| 75 | originY, |
| 76 | config.spawnRangeTiles, |
| 77 | flying, |
| 78 | reserved, |
| 79 | dimensionId |
| 80 | ); |
| 81 | if (!tile) |
| 82 | { break; } |
| 83 | reserved.add(`${tile.tileX},${tile.tileY}`); |
| 84 | alive.add(staff.name); |
| 85 | staffAlive.set(config.spawnerId, alive); |
| 86 | requests.push({ |
| 87 | ...tile, |
| 88 | dimensionId, |
| 89 | mobTypeId: MobId.centralExchange, |
| 90 | spawnerId: config.spawnerId, |
| 91 | originTileX: originX, |
| 92 | originTileY: originY, |
| 93 | wanderRangeTiles: config.maxWanderRangeTiles, |
| 94 | level: config.level, |
| 95 | bounty: config.bounty, |
| 96 | aggressive: !!config.aggressive, |
| 97 | spells: config.spells, |
| 98 | persistent, |
| 99 | sex: staff.sex, |
| 100 | displayName: staff.name, |
| 101 | equipment: config.equipment, |
| 102 | sells: [], |
| 103 | drops: config.drops, |
| 104 | buysItems: false, |
| 105 | hiddenDiscount: config.hiddenDiscount, |
| 106 | centralExchange: true, |
| 107 | townGuard: false, |
| 108 | dialogueId: config.dialogueId || null, |
| 109 | respawnDelaySeconds: config.respawnDelaySeconds |
| 110 | }); |
| 111 | counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1); |
| 112 | } |
| 113 | continue; |
| 114 | } |
| 115 | |
| 116 | while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive) |
| 117 | { |
| 118 | if (!consumeSpawnSlot(world, config.spawnerId, delayMs, now)) |
| 119 | { break; } |
| 120 | const tile = pickSpawnTile( |
| 121 | world, |
| 122 | originX, |
| 123 | originY, |
| 124 | config.spawnRangeTiles, |
| 125 | flying, |
| 126 | reserved, |
| 127 | dimensionId |
| 128 | ); |
| 129 | if (!tile) |
| 130 | { break; } |
| 131 | reserved.add(`${tile.tileX},${tile.tileY}`); |
| 132 | requests.push({ |
| 133 | ...tile, |
| 134 | dimensionId, |
| 135 | mobTypeId: config.mobTypeId, |
| 136 | spawnerId: config.spawnerId, |
| 137 | originTileX: originX, |
| 138 | originTileY: originY, |
| 139 | wanderRangeTiles: config.maxWanderRangeTiles, |
| 140 | level: config.level, |
| 141 | bounty: config.bounty, |
| 142 | aggressive: isHumanoidMob(config.mobTypeId) || config.townGuard |
| 143 | ? !!config.aggressive |
| 144 | : undefined, |
| 145 | spells: config.spells, |
| 146 | persistent, |
| 147 | sex: config.sex, |
| 148 | displayName: config.displayName, |
| 149 | equipment: config.equipment, |
| 150 | sells: config.sells, |
| 151 | drops: config.drops, |
| 152 | buysItems: config.buysItems, |
| 153 | hiddenDiscount: config.hiddenDiscount, |
| 154 | centralExchange: false, |
| 155 | townGuard: !!config.townGuard || isTownGuardMob(config.mobTypeId), |
| 156 | dialogueId: config.dialogueId || null, |
| 157 | respawnDelaySeconds: config.respawnDelaySeconds |
| 158 | }); |
| 159 | counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1); |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | requests.push(...collectAmbientRequests(world, reserved)); |
| 164 | return requests; |
| 165 | } |
| 166 | |
| 167 | function ensurePendingRespawns (world) |
| 168 | { |
| 169 | if (!world.pendingSpawnerRespawns) |
| 170 | { world.pendingSpawnerRespawns = new Map(); } |
| 171 | return world.pendingSpawnerRespawns; |
| 172 | } |
| 173 | |
| 174 | /** |
| 175 | * Schedule a delayed refill slot after a spawned mob dies. |
| 176 | * Delay 0 means the next collect pass may refill immediately (no pending entry). |
| 177 | */ |
| 178 | export function scheduleSpawnerRespawn (world, spawnerId, respawnDelaySeconds, now = Date.now()) |
| 179 | { |
| 180 | if (!spawnerId) |
| 181 | { return; } |
| 182 | const delayMs = Math.max(0, (respawnDelaySeconds | 0) * 1000); |
| 183 | if (delayMs <= 0) |
| 184 | { return; } |
| 185 | const pending = ensurePendingRespawns(world); |
| 186 | const list = pending.get(spawnerId) ?? []; |
| 187 | list.push(now + delayMs); |
| 188 | list.sort((a, b) => a - b); |
| 189 | pending.set(spawnerId, list); |
| 190 | } |
| 191 | |
| 192 | /** |
| 193 | * Decide whether one more mob may spawn for this spawner right now. |
| 194 | * - delay 0 / empty pending: allow (initial populate + instant refill) |
| 195 | * - otherwise: only if a pending timer is due; consume one due timer |
| 196 | */ |
| 197 | function consumeSpawnSlot (world, spawnerId, delayMs, now) |
| 198 | { |
| 199 | if (delayMs <= 0) |
| 200 | { return true; } |
| 201 | const pending = ensurePendingRespawns(world); |
| 202 | const list = pending.get(spawnerId); |
| 203 | if (!list?.length) |
| 204 | { |
| 205 | // No death timers yet — first populate / recovery after unload. |
| 206 | return true; |
| 207 | } |
| 208 | const readyIndex = list.findIndex((readyAt) => readyAt <= now); |
| 209 | if (readyIndex < 0) |
| 210 | { return false; } |
| 211 | list.splice(readyIndex, 1); |
| 212 | if (!list.length) |
| 213 | { pending.delete(spawnerId); } |
| 214 | else |
| 215 | { pending.set(spawnerId, list); } |
| 216 | return true; |
| 217 | } |
| 218 | |
| 219 | export function mobComponents (request) |
| 220 | { |
| 221 | const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer"); |
| 222 | const sex = request.sex === "female" || request.sex === "male" |
| 223 | ? request.sex |
| 224 | : (def.sex ?? "male"); |
| 225 | const displayName = String(request.displayName || def.displayName || "NPC").trim() || def.displayName; |
| 226 | const level = Math.max(1, Math.min(99, Number(request.level) || 1)) | 0; |
| 227 | const appearance = { |
| 228 | sex, |
| 229 | firstName: displayName, |
| 230 | lastName: "" |
| 231 | }; |
| 232 | if (def.usePlayerBody) |
| 233 | { |
| 234 | Object.assign(appearance, appearanceHairFields(hairFromNameSeed(displayName, sex))); |
| 235 | } |
| 236 | else |
| 237 | { |
| 238 | const fleeceState = def.shearable?.fleeceState ?? null; |
| 239 | const sprite = mobSpriteName(def.mobTypeId, fleeceState); |
| 240 | if (sprite) |
| 241 | { appearance.sprite = sprite; } |
| 242 | } |
| 243 | |
| 244 | if (def.dualChannelAppearance || def.mobTypeId === MobId.fairy) |
| 245 | { |
| 246 | appearance.dualTint = { |
| 247 | /** Red channel — shirt. */ |
| 248 | shaft: randomBrightOrPastelColor(), |
| 249 | /** Blue channel — skirt. */ |
| 250 | tip: randomBrightOrPastelColor(), |
| 251 | /** Green channel — hair. */ |
| 252 | coat: randomNpcHairColor() |
| 253 | }; |
| 254 | appearance.bloomBody = !!def.bloomBody; |
| 255 | } |
| 256 | |
| 257 | let element = request.element ?? null; |
| 258 | if ((def.randomElementOnSpawn || def.mobTypeId === MobId.sprite) && !element) |
| 259 | { |
| 260 | element = MAGIC_ELEMENT_ORDER[Math.floor(Math.random() * MAGIC_ELEMENT_ORDER.length)]; |
| 261 | } |
| 262 | if (element) |
| 263 | { |
| 264 | const tint = magicElementTint(element); |
| 265 | appearance.tint = { r: tint.r, g: tint.g, b: tint.b }; |
| 266 | appearance.bloomBody = !!def.bloomBody; |
| 267 | if (def.mobTypeId === MobId.sprite || def.randomElementOnSpawn) |
| 268 | { |
| 269 | const label = essenceElementDisplayName(element); |
| 270 | appearance.firstName = `${label} Sprite`; |
| 271 | appearance.lastName = ""; |
| 272 | } |
| 273 | } |
| 274 | else if (def.bloomBody) |
| 275 | { appearance.bloomBody = true; } |
| 276 | |
| 277 | const maxHp = mobHealthForLevel(def, level); |
| 278 | const components = { |
| 279 | position: { |
| 280 | tileX: request.tileX, |
| 281 | tileY: request.tileY, |
| 282 | dimensionId: normalizeDimensionId(request.dimensionId ?? OVERWORLD_ID) |
| 283 | }, |
| 284 | movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 }, |
| 285 | path: { tiles: [] }, |
| 286 | appearance, |
| 287 | creature: { |
| 288 | mobTypeId: def.mobTypeId, |
| 289 | level, |
| 290 | ...(element ? { element } : {}), |
| 291 | ...(def.lightRadiusTiles ? { lightRadiusTiles: def.lightRadiusTiles } : {}), |
| 292 | ...(def.shearable |
| 293 | ? { |
| 294 | fleeceState: def.shearable.fleeceState, |
| 295 | woolReadyAt: null |
| 296 | } |
| 297 | : {}) |
| 298 | }, |
| 299 | health: { current: maxHp, max: maxHp } |
| 300 | }; |
| 301 | if (request.spawnerId) |
| 302 | { |
| 303 | const aggressive = request.aggressive != null |
| 304 | ? !!request.aggressive |
| 305 | : !!def.aggressive; |
| 306 | // Humanoid Aggressive flag forces bounty 0; wildlife can be aggressive and still pay kill bounty. |
| 307 | const bounty = request.aggressive === true |
| 308 | ? 0 |
| 309 | : (Math.max(0, Number(request.bounty) || 0) | 0); |
| 310 | components.spawnOrigin = { |
| 311 | spawnerId: request.spawnerId, |
| 312 | originTileX: request.originTileX ?? request.tileX, |
| 313 | originTileY: request.originTileY ?? request.tileY, |
| 314 | wanderRangeTiles: request.wanderRangeTiles ?? 4, |
| 315 | bounty, |
| 316 | level, |
| 317 | aggressive, |
| 318 | centralExchange: !!request.centralExchange, |
| 319 | townGuard: !!request.townGuard || isTownGuardMob(def.mobTypeId), |
| 320 | stationTileX: null, |
| 321 | stationTileY: null, |
| 322 | dialogueId: request.dialogueId ? String(request.dialogueId) : null, |
| 323 | drops: Array.isArray(request.drops) ? request.drops : [], |
| 324 | respawnDelaySeconds: Math.max(0, request.respawnDelaySeconds | 0) |
| 325 | }; |
| 326 | } |
| 327 | if (def.persistent) |
| 328 | { components.persistent = {}; } |
| 329 | if (def.freeFlight) |
| 330 | { |
| 331 | components.flight = { |
| 332 | x: request.tileX + 0.5, |
| 333 | y: request.tileY + 0.5, |
| 334 | targetX: request.tileX + 0.5, |
| 335 | targetY: request.tileY + 0.5, |
| 336 | speed: def.flightSpeedTilesPerSec ?? 2.5, |
| 337 | nextPickAt: 0, |
| 338 | lastAt: 0 |
| 339 | }; |
| 340 | } |
| 341 | if (mobCanFight(def)) |
| 342 | { |
| 343 | components.combat = { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null }; |
| 344 | components.skills = { levels: mobSkillLevels(def, level) }; |
| 345 | } |
| 346 | |
| 347 | const knownSpells = normalizeMobSpells(request.spells, level); |
| 348 | if (def.randomElementSpell) |
| 349 | { |
| 350 | /** Fairies know every elemental sprite bolt and pick one at random each cast. */ |
| 351 | for (const boltId of Object.values(SPRITE_BOLT_SPELL_BY_ELEMENT)) |
| 352 | { |
| 353 | if (!knownSpells.some((entry) => entry.spellId === boltId)) |
| 354 | { knownSpells.push({ spellId: boltId }); } |
| 355 | } |
| 356 | } |
| 357 | else if (element && SPRITE_BOLT_SPELL_BY_ELEMENT[element]) |
| 358 | { |
| 359 | const boltId = SPRITE_BOLT_SPELL_BY_ELEMENT[element]; |
| 360 | if (!knownSpells.some((entry) => entry.spellId === boltId)) |
| 361 | { knownSpells.push({ spellId: boltId }); } |
| 362 | } |
| 363 | if (knownSpells.length) |
| 364 | { |
| 365 | const castChance = (element || def.randomElementSpell) ? 100 : mobSpellCastChancePercent(level); |
| 366 | components.spells = { |
| 367 | known: knownSpells.map((entry) => entry.spellId), |
| 368 | favorites: [], |
| 369 | autoCast: false, |
| 370 | castChances: Object.fromEntries(knownSpells.map((entry) => [entry.spellId, castChance])) |
| 371 | }; |
| 372 | components.spellcasting = { |
| 373 | armedSpellId: null, |
| 374 | repeatSpellId: null, |
| 375 | repeatTargetEntityId: null, |
| 376 | nextCastAt: 0, |
| 377 | pendingCast: null |
| 378 | }; |
| 379 | } |
| 380 | |
| 381 | const equipmentSlots = emptyEquipment().slots; |
| 382 | const authored = request.equipment ?? {}; |
| 383 | const defaults = def.usePlayerBody ? npcDefaultEquipment(displayName, sex) : null; |
| 384 | for (const slot of Object.keys(equipmentSlots)) |
| 385 | { |
| 386 | const authoredEntry = authored[slot]; |
| 387 | let { itemId, dyeColor } = spawnerEquipmentSlot(authoredEntry); |
| 388 | if (!itemId && defaults?.[slot]) |
| 389 | { |
| 390 | itemId = defaults[slot].itemId; |
| 391 | dyeColor = defaults[slot].dyeColor ?? null; |
| 392 | } |
| 393 | if (!itemId) |
| 394 | { continue; } |
| 395 | const itemDef = itemDefinition(itemId); |
| 396 | if (!itemDef?.equipment || itemDef.equipment.slot !== slot) |
| 397 | { continue; } |
| 398 | const stack = { itemId, quantity: 1 }; |
| 399 | if (dyeColor && itemDef.dyeable) |
| 400 | { stack.instance = { kind: "clothing", dyeColor }; } |
| 401 | equipmentSlots[slot] = stack; |
| 402 | } |
| 403 | if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean)) |
| 404 | { components.equipment = { slots: equipmentSlots }; } |
| 405 | |
| 406 | const catalog = Array.isArray(request.sells) |
| 407 | ? request.sells.map((entry) => |
| 408 | { |
| 409 | if (entry && typeof entry === "object") |
| 410 | { |
| 411 | return { |
| 412 | itemId: entry.itemId | 0, |
| 413 | quantity: Math.max(0, entry.quantity | 0 || 0) |
| 414 | }; |
| 415 | } |
| 416 | return { itemId: entry | 0, quantity: 0 }; |
| 417 | }).filter((line) => line.itemId > 0) |
| 418 | : []; |
| 419 | const buysItems = !!request.buysItems; |
| 420 | const isExchange = !!request.centralExchange || def.centralExchange; |
| 421 | if (!isExchange && (catalog.length || buysItems || def.talkable)) |
| 422 | { |
| 423 | components.shop = { |
| 424 | catalog, |
| 425 | buysItems, |
| 426 | hiddenDiscount: Number(request.hiddenDiscount) || 0.9, |
| 427 | displayName, |
| 428 | remaining: Object.create(null), |
| 429 | boughtStock: Object.create(null), |
| 430 | restockDay: null |
| 431 | }; |
| 432 | } |
| 433 | return components; |
| 434 | } |
| 435 | |
| 436 | function normalizeMobSpells (raw, level) |
| 437 | { |
| 438 | if (!Array.isArray(raw)) |
| 439 | { return []; } |
| 440 | const out = []; |
| 441 | const seen = new Set(); |
| 442 | const lv = Math.max(1, level | 0 || 1); |
| 443 | for (const entry of raw) |
| 444 | { |
| 445 | if (!entry || typeof entry !== "object") |
| 446 | { continue; } |
| 447 | const spellId = String(entry.spellId ?? "").trim(); |
| 448 | if (!spellId || seen.has(spellId)) |
| 449 | { continue; } |
| 450 | const def = spellDefinition(spellId); |
| 451 | if (!def) |
| 452 | { continue; } |
| 453 | const minLevel = spellMinMagicLevel(def); |
| 454 | if (lv < minLevel) |
| 455 | { continue; } |
| 456 | seen.add(spellId); |
| 457 | out.push({ spellId }); |
| 458 | } |
| 459 | return out; |
| 460 | } |
| 461 | |
| 462 | function collectAmbientRequests (world, reserved = new Set()) |
| 463 | { |
| 464 | const requests = []; |
| 465 | const ambientTypes = listAmbientMobTypes(); |
| 466 | if (!ambientTypes.length) |
| 467 | { return requests; } |
| 468 | |
| 469 | const loaders = world.ecs.query(Component.position, Component.chunkLoader); |
| 470 | if (!loaders.length) |
| 471 | { return requests; } |
| 472 | |
| 473 | for (const def of ambientTypes) |
| 474 | { |
| 475 | const maxPerLoader = Math.max(0, def.ambientMaxPerLoader ?? 1); |
| 476 | const alive = countCreatures(world, def.mobTypeId); |
| 477 | const budget = maxPerLoader * loaders.length; |
| 478 | if (alive >= budget) |
| 479 | { continue; } |
| 480 | |
| 481 | for (const loader of loaders) |
| 482 | { |
| 483 | if (requests.length + alive >= budget) |
| 484 | { break; } |
| 485 | const dim = normalizeDimensionId(loader.position.dimensionId ?? OVERWORLD_ID); |
| 486 | const tile = pickSpawnTile( |
| 487 | world, |
| 488 | loader.position.tileX, |
| 489 | loader.position.tileY, |
| 490 | 8, |
| 491 | !!def.flying, |
| 492 | reserved, |
| 493 | dim |
| 494 | ); |
| 495 | if (!tile) |
| 496 | { continue; } |
| 497 | reserved.add(`${tile.tileX},${tile.tileY}`); |
| 498 | requests.push({ |
| 499 | ...tile, |
| 500 | dimensionId: dim, |
| 501 | mobTypeId: def.mobTypeId, |
| 502 | spawnerId: null, |
| 503 | level: 1, |
| 504 | bounty: 0, |
| 505 | spells: [], |
| 506 | persistent: false |
| 507 | }); |
| 508 | } |
| 509 | } |
| 510 | return requests; |
| 511 | } |
| 512 | |
| 513 | function countBySpawner (world) |
| 514 | { |
| 515 | const counts = new Map(); |
| 516 | for (const entity of world.ecs.query(Component.spawnOrigin)) |
| 517 | { |
| 518 | const id = entity.spawnOrigin.spawnerId; |
| 519 | counts.set(id, (counts.get(id) ?? 0) + 1); |
| 520 | } |
| 521 | return counts; |
| 522 | } |
| 523 | |
| 524 | function staffNamesBySpawner (world) |
| 525 | { |
| 526 | const map = new Map(); |
| 527 | for (const entity of world.ecs.query(Component.spawnOrigin, Component.appearance)) |
| 528 | { |
| 529 | if (!entity.spawnOrigin?.centralExchange) |
| 530 | { continue; } |
| 531 | const id = entity.spawnOrigin.spawnerId; |
| 532 | const name = entity.appearance?.firstName; |
| 533 | if (!id || !name) |
| 534 | { continue; } |
| 535 | const set = map.get(id) ?? new Set(); |
| 536 | set.add(name); |
| 537 | map.set(id, set); |
| 538 | } |
| 539 | return map; |
| 540 | } |
| 541 | |
| 542 | function countCreatures (world, mobTypeId) |
| 543 | { |
| 544 | let count = 0; |
| 545 | for (const entity of world.ecs.query(Component.creature)) |
| 546 | { |
| 547 | if (entity.creature.mobTypeId === mobTypeId) |
| 548 | { count += 1; } |
| 549 | } |
| 550 | return count; |
| 551 | } |
| 552 | |
| 553 | function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null, dimensionId = OVERWORLD_ID) |
| 554 | { |
| 555 | const dim = normalizeDimensionId(dimensionId); |
| 556 | const radius = Math.max(1, range | 0); |
| 557 | for (let attempt = 0; attempt < 48; attempt++) |
| 558 | { |
| 559 | const tileX = originX + randInt(-radius, radius); |
| 560 | const tileY = originY + randInt(-radius, radius); |
| 561 | const key = `${tileX},${tileY}`; |
| 562 | if (reserved?.has(key)) |
| 563 | { continue; } |
| 564 | if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY), dim)) |
| 565 | { continue; } |
| 566 | if (flying) |
| 567 | { |
| 568 | if (!chunkIsOpen(world, tileX, tileY, dim)) |
| 569 | { continue; } |
| 570 | return { tileX, tileY, dimensionId: dim }; |
| 571 | } |
| 572 | if (!world.isEnterable(tileX, tileY, dim) || world.occupied(tileX, tileY, dim)) |
| 573 | { continue; } |
| 574 | return { tileX, tileY, dimensionId: dim }; |
| 575 | } |
| 576 | return null; |
| 577 | } |
| 578 | |
| 579 | function chunkIsOpen (world, tileX, tileY, dimensionId = OVERWORLD_ID) |
| 580 | { |
| 581 | const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId); |
| 582 | return !!data?.open; |
| 583 | } |
| 584 | |
| 585 | function randInt (min, max) |
| 586 | { |
| 587 | return min + Math.floor(Math.random() * (max - min + 1)); |
| 588 | } |