#include "room_grid.h" #include "capsule.h" #include "entity_player.h" #include "game.h" #include "grid_entity_door.h" #include "grid_entity_pit.h" #include "grid_entity_rock.h" #include "log.h" #include "npc_ai.h" #include "room.h" #include #include #include // The partitions a query bit looks in, in the order QueryRadius goes through them. struct PartitionQuery { uint32_t bit; Partition partition; }; constexpr std::array PARTITION_QUERIES = {{{QUERY_FAMILIARS, PARTITION_FAMILIARS}, {QUERY_TEARS, PARTITION_SHOTS}, {QUERY_ENEMIES, PARTITION_ENEMIES}, {QUERY_PROJECTILES, PARTITION_PROJECTILES}, {QUERY_PICKUPS, PARTITION_PICKUPS}}}; // The free spot search: its tries, the grid path each band of tries accepts (pits allow 3000 more), how far it steps // out each try and where it starts over, the spot a pickup or another entity keeps free, the generator the original // seeds the same each call, and the doors' reach and retries. constexpr int SPOT_TRIES = 125; constexpr int PIT_PATH_EXTRA = 3000; constexpr float SPOT_STEP = 5; constexpr float SPOT_STEP_MAX = 500; constexpr float SPOT_ENTITY_DISTANCE = 20; constexpr float SPOT_FALLBACK_MARGIN = 20; constexpr RNG SPOT_RNG = {0x441c1dfd, 1, 9, 29}; constexpr float DOOR_DISTANCE = 70; constexpr int DOOR_RETRIES = 20; constexpr float DOOR_RETRY_STEP = 40; constexpr float DEGREES_FULL_TURN = 360; // The distance FindFreeTilePosition starts its search from, farther than any cell. constexpr float FREE_TILE_FAR = 1e6f; // The grid path a try accepts, by the tries left below which it does: higher as the search runs out. struct PathBand { int triesLeft; int pathLimit; }; constexpr std::array PATH_BANDS = {{{5, 1000}, {20, 900}, {40, 800}, {60, 700}}}; constexpr int PATH_LIMIT_FIRST = 600; // The grid path a try accepts. static int spot_path_limit(int triesLeft) { for (const PathBand& band : PATH_BANDS) if (triesLeft < band.triesLeft) return band.pathLimit; return PATH_LIMIT_FIRST; } // 0041a790 The entities whose size reaches within a radius of a position and that queries may see: those of the // partitions asked for, then the players, then the effects. EntityList_EL entity_query_radius(const Vector& position, float radius, uint32_t partitions) { EntityList& list = g_game->room->entityList; EntityList_EL found; Vector extent = vector_make(radius, radius); auto isReached = [&](Entity* entity) { float reach = radius + entity->size; return !entity->HasEntityFlags(FLAG_NO_QUERY) && vector_length_squared(vector_sub(entity->pos, position)) < reach * reach; }; for (const PartitionQuery& query : PARTITION_QUERIES) if (partitions & query.bit) list.partitions[query.partition].query_box(found, position, extent); if (partitions & QUERY_PLAYERS) for (Entity_Player* player : g_game->playerManager.playerList) found.push_back(player); std::erase_if(found, [&](Entity* entity) { return !isReached(entity); }); if (partitions & QUERY_EFFECTS) for (Entity* effect : list.effectEL) if (isReached(effect)) found.push_back(effect); return found; } // 0041ab50 (EntityList::query_player_capsule_hits) The entities a capsule touches that queries may see: those of the // partitions asked for within its bounding box, then the players, then the effects. EntityList_EL entity_query_capsule(const Capsule& capsule, uint32_t partitions) { EntityList& list = g_game->room->entityList; EntityList_EL found; Vector low{}; Vector high{}; capsule.get_bounding_box(low, high); Vector center = vector_scale(vector_add(low, high), 0.5f); Vector extent = vector_scale(vector_sub(high, low), 0.5f); auto isTouched = [&](Entity* entity) { return !entity->HasEntityFlags(FLAG_NO_QUERY) && Capsule::Collide(capsule, entity->GetCollisionCapsule({})); }; for (const PartitionQuery& query : PARTITION_QUERIES) if (partitions & query.bit) list.partitions[query.partition].query_box(found, center, extent); if (partitions & QUERY_PLAYERS) for (Entity_Player* player : g_game->playerManager.playerList) found.push_back(player); std::erase_if(found, [&](Entity* entity) { return !isTouched(entity); }); if (partitions & QUERY_EFFECTS) for (Entity* effect : list.effectEL) if (isTouched(effect)) found.push_back(effect); return found; } // 00589f90 (Room::CanSpawnObstacleAtPos) Whether an obstacle could stand on a position's cell (off the grid, as the // room says of cell -1). bool room_can_spawn_obstacle_at(const Vector& position, bool isForced) { Room& room = *g_game->room; int column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); int row = (int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; return room.CanSpawnObstacleAtPosition(isInside ? room.gridWidth * row + column : -1, isForced); } // 004cdd80 (Room::RaiseGridPathAtPos) Raises the path cost of a position's cell to a level below 951, keeping its // thousands, false off the grid. bool room_path_raise_at(const Vector& position, int level) { constexpr int PATH_LEVELS = 1000; constexpr int PATH_LEVEL_MAX = 950; Room& room = *g_game->room; int column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); int row = (int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return false; uint32_t index = (uint32_t)(room.gridWidth * row + column); if (index >= room.gridPaths.size() || level > PATH_LEVEL_MAX) return false; int current = room.gridPaths[index] % PATH_LEVELS; if (current < level) room.gridPaths[index] = room.gridPaths[index] - current + level; return true; } // 00456620 The grid entity on the cell at a position, if any. GridEntity* room_grid_entity_at(const Vector& position) { int gridIndex = g_game->room->GetGridIndex(position); return gridIndex < 0 ? nullptr : g_game->room->GetGridEntity((uint32_t)gridIndex); } // 00812de0 Room::GetClampedGridIndex: the cell under a position, pulled onto the grid when off it. int room_clamped_grid_index_get(Room& room, Vector position) { int column = std::max((int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f), 0); int row = std::max((int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f), 0); return std::min(row, room.gridHeight - 1) * room.gridWidth + std::min(column, room.gridWidth - 1); } // Whether a cell takes a pickup: free of grid collision (or a pit, when allowed) and of trapdoors, stairs, pressure // plates and teleporters. static bool is_cell_free(Room& room, int gridIndex, const FreeSpotSearch& search) { uint32_t collision = room.GetGridCollision(gridIndex); bool isPit = search.isAllowPits && collision == COLLISION_PIT; if (collision != COLLISION_NONE && !isPit) return false; GridEntity* grid = room.GetGridEntity((uint32_t)gridIndex); if (!grid) return true; GridEntityType type = grid->type; return type != GRID_TRAPDOOR && type != GRID_STAIRS && type != GRID_PRESSURE_PLATE && type != GRID_TELEPORTER; } // Whether an entity keeps the spot at a cell's center taken: a pickup, bomb or slot, or an enemy or player when the // search avoids them. static bool is_spot_taken(const Vector& center, bool isAvoidActiveEntities) { for (Entity* entity : g_game->room->entityList.updateEL) { int type = entity->type; bool isActive = type == ENTITY_PLAYER || Entity::is_enemy_type(type); bool isKept = type == ENTITY_PICKUP || type == ENTITY_BOMB || type == ENTITY_SLOT || (isAvoidActiveEntities && isActive); if (isKept && vector_length(vector_sub(entity->pos, center)) < SPOT_ENTITY_DISTANCE) return true; } return false; } // Whether a try's cell takes the pickup: trodden less than the try allows (pits up to 3000 more) and free. static bool is_cell_accepted(Room& room, int gridIndex, int pathLimit, const FreeSpotSearch& search) { int path = room.GetGridPath(gridIndex); bool isPit = search.isAllowPits && room.GetGridCollision(gridIndex) == COLLISION_PIT; return (path < pathLimit || (isPit && path < pathLimit + PIT_PATH_EXTRA)) && is_cell_free(room, gridIndex, search); } // 00813520 A free spot for a pickup near a position: tries spiral out at random angles, first only on clear cells, // then accepting more trodden ones, and fall back to the cell under the position kept off the walls. A spot near a // door, when doors are avoided, is searched again from there. // A try outside the room keeps the last cell it checked, and a spot found on the very last try falls back, as in the // original. Vector room_free_pickup_position_find(const FreeSpotSearch& search) { Room& room = *g_game->room; RNG rng = SPOT_RNG; Vector spot{}; float step = search.step; int gridIndex = -1; bool isFound = false; for (int triesLeft = SPOT_TRIES - 1; triesLeft >= 0; triesLeft--) { int pathLimit = spot_path_limit(triesLeft); if (gridIndex >= 0 && is_cell_accepted(room, gridIndex, pathLimit, search)) { isFound = triesLeft >= 1; break; } if (step > SPOT_STEP_MAX) step = 0; step += SPOT_STEP; float angle = rng.RandomFloat() * DEGREES_FULL_TURN * DEGREES_TO_RADIANS; spot = vector_make(std::cos(angle) * step + search.position.x, std::sin(angle) * step + search.position.y); Vector clamped = room.GetClampedPositionImpl(spot, 0, 0, 0, 0); if (clamped.x != spot.x || clamped.y != spot.y) continue; gridIndex = room.GetGridIndex(spot); if (gridIndex < 0 || room.GetGridPath(gridIndex) >= pathLimit) continue; spot = room.GetGridPosition(gridIndex); if (is_spot_taken(spot, search.isAvoidActiveEntities)) gridIndex = -1; } if (!isFound) { Vector clamped = room.GetClampedPositionImpl(search.position, SPOT_FALLBACK_MARGIN, SPOT_FALLBACK_MARGIN, SPOT_FALLBACK_MARGIN, SPOT_FALLBACK_MARGIN); spot = room.GetGridPosition(room.GetGridIndex(clamped)); } if (!search.isAvoidDoors) return spot; for (GridEntity_Door* door : room.doors) { if (!door) continue; Vector doorCenter = room.GetGridPosition(door->gridIndex); if (vector_length(vector_sub(doorCenter, spot)) >= DOOR_DISTANCE) continue; for (int retry = 0; retry < DOOR_RETRIES && vector_length(vector_sub(doorCenter, spot)) < DOOR_DISTANCE; retry++) spot = room_free_pickup_position_find({.position = spot, .step = DOOR_RETRY_STEP}); return spot; } return spot; } // 00813bf0, 00813c40 Destroys the grid entity on a cell, a bomb rock first made a plain rock when it is to be defused. // False for an empty cell or one that did not break. bool room_grid_destroy(const GridDestroy& destroy) { GridEntity* grid = g_game->room->GetGridEntity((uint32_t)destroy.gridIndex); if (!grid) return false; if (destroy.isDefuseBombRock && grid->type == GRID_ROCK_BOMB) grid->type = GRID_ROCK; return grid->Destroy(destroy.isImmediate, destroy.source); } // 0081e6e0 Fills a pit with a broken rock (spiked for a spiked rock that stood), unless the pit is part of a corner of // pits. False when there is no pit to fill. bool room_bridge_make(GridEntity* pit, GridEntity* rock) { if (!pit || pit->type != GRID_PIT) return false; Vector center = pit->Position(); auto isPitAt = [&](float x, float y) { GridEntity* grid = room_grid_entity_at(vector_make(center.x + x, center.y + y)); return grid && grid->type == GRID_PIT; }; bool isRowPit = isPitAt(GRID_CELL_SIZE, 0) || isPitAt(-GRID_CELL_SIZE, 0); bool isColumnPit = isPitAt(0, -GRID_CELL_SIZE) || isPitAt(0, GRID_CELL_SIZE); if (isRowPit && isColumnPit) return false; bool isRock = rock && rock->type == GRID_ROCK_SPIKED; static_cast(pit)->MakeBridge(isRock ? static_cast(rock) : nullptr, 0); return true; } // 0081e520 Room::FindFreeTilePosition: the position itself on a free cell, else the center of the nearest free cell, // taking the first one found within the distance. Vector room_free_tile_position_find(const Vector& position, float distanceThreshold) { Room& room = *g_game->room; int cell = room.GetGridIndex(position); if (room.GetGridCollision(cell) == COLLISION_NONE) return position; Vector best = room.GetGridPosition(cell); float bestDistance = FREE_TILE_FAR; for (int i = 0; i < room.gridWidth * room.gridHeight; i++) { if (i == cell || room.GetGridCollision(i) != COLLISION_NONE) continue; Vector at = room.GetGridPosition(i); float distance = (at.y - position.y) * (at.y - position.y) + (at.x - position.x) * (at.x - position.x); if (distance >= bestDistance) continue; best = at; bestDistance = distance; if (distance < distanceThreshold * distanceThreshold) break; } return best; } // 0081e930 Queues the grid entity on a cell for removal at the room's next update, leaving the cell's path at // pathTrail. A decoration stays when asked to. void Room::RemoveGridEntity(int gridIndex, int pathTrail, DecorationRemoval removal) { if ((uint32_t)gridIndex >= ROOM_GRID_CELLS || !gridEntities[gridIndex]) return; if (gridEntities[gridIndex]->type == GRID_DECORATION && removal == DECORATION_KEPT) return; gridPaths[gridIndex] = pathTrail; pendingGridRemovals.insert(gridIndex); } // 0081e980 Removes a cell's grid entity at once, unless it is a kept decoration, leaving a path trail. void Room::RemoveGridEntityImmediate(int gridIndex, int pathTrail, DecorationRemoval removal) { if ((uint32_t)gridIndex >= ROOM_GRID_CELLS || !gridEntities[gridIndex]) return; if (gridEntities[gridIndex]->type == GRID_DECORATION && removal == DECORATION_KEPT) return; gridPaths[gridIndex] = pathTrail; delete std::exchange(gridEntities[gridIndex], nullptr); }