Files
isaac-port/src/path_finder.cpp
T

903 lines
40 KiB
C++

#include "path_finder.h"
#include "boss_ai.h"
#include "game.h"
#include "grid_entity.h"
#include "npc_ai.h"
#include "npc_basement.h"
#include "room.h"
#include "room_grid.h"
#include <algorithm>
#include <cmath>
#include <queue>
static_assert(PATH_GRID_CELLS == ROOM_GRID_CELLS);
constexpr int PATH_ENEMY_TYPE_LAST = 999;
// How an owner wanders: to a free spot 40 away, pushed at half its speed, until within 3 of it, against a wall, or
// (one time in ten) once slower than about 0.3. A friendly one paths to its target instead.
constexpr float WANDER_STEP = 40;
constexpr float WANDER_PUSH = 0.5f;
constexpr float WANDER_ARRIVED = 3;
constexpr float WANDER_STALL_SPEED_SQUARED = 0.1f;
constexpr int WANDER_GIVE_UP_ODDS = 10;
constexpr float WANDER_FRIENDLY_SPEED = 0.5f;
// How an owner wanders along the axes: up to 10 tries a call at a run of up to 11 cells (1 to 4 while it flees) that
// ends before a cell felt over 300 (998 on the last try, 800 while fleeing). A cell marked 999 is never a spot.
constexpr int AXIS_ATTEMPTS = 10;
constexpr uint32_t AXIS_RUN_CELLS = 12;
constexpr int AXIS_BLOCKING_PATH = 300;
constexpr int AXIS_LAST_TRY_BLOCKING_PATH = 998;
constexpr int AXIS_FLEE_BLOCKING_PATH = 800;
constexpr int AXIS_AVOIDED_PATH = 999;
constexpr int AXIS_SIDE_OPEN_PATH = 200;
constexpr uint32_t AXIS_SIDE_ODDS = 10;
constexpr uint32_t AXIS_SHORT_ODDS = 10;
constexpr uint32_t AXIS_TURN_BACK_ODDS = 5;
constexpr float AXIS_FLEE_AWAY_DOT = 0.95f;
constexpr float AXIS_ARRIVED = 5;
constexpr float AXIS_STALL_SPEED = 0.6f;
constexpr int AXIS_STALL_CHECKS = 10;
constexpr int AXIS_HAZARD_PATH = 700;
constexpr float AXIS_HAZARD_SPEED = 3;
constexpr int AXIS_HAZARD_CHECKS = 2;
constexpr float AXIS_FOLLOW_NEAR_SQUARED = 1600;
constexpr float AXIS_FOLLOW_FRICTION = 0.8f;
// How an owner evades: within 250 of its target (170 when the target cannot walk to it) it keeps fleeing for three
// checks of every 14 frames, pushing away at 1.5 and trying up to 7 random cells 30 to 480 past a point 30 away
// (fewer as the evasion widens toward 20) that lie farther from the target than it by 100 and a third of their reach.
constexpr int EVADE_CHECK_FRAMES = 14;
constexpr int EVADE_FORGET_FRAMES = 30;
constexpr int EVADE_RECHECK_FRAMES = 10;
constexpr int EVADE_COUNTDOWN = 3;
constexpr float EVADE_RANGE_SEEN = 250;
constexpr float EVADE_RANGE_HIDDEN = 170;
constexpr float EVADE_WIDE = 20;
constexpr float EVADE_WIDEN = 0.35f;
constexpr float EVADE_DECAY = 0.9f;
constexpr float EVADE_DIAGONAL = 0.25f;
constexpr float EVADE_PUSH = 1.5f;
constexpr float EVADE_BASE_REACH = 30;
constexpr float EVADE_ATTEMPTS = 7;
constexpr float EVADE_ATTEMPT_SHARE = 0.3f;
constexpr float EVADE_REVISIT_REFUND = 0.7f;
constexpr float EVADE_REACH_MIN = 30;
constexpr float EVADE_REACH_RANGE = 450;
constexpr float EVADE_REACH_SHARE = 3;
constexpr float EVADE_FLATTEN = 0.5f;
constexpr float EVADE_MARGIN = 100;
constexpr float EVADE_BAR_STEP = 10;
constexpr float EVADE_GRID_TOP = 120;
constexpr float EVADE_SPOT_RANGE_SQUARED = 40000;
constexpr float EVADE_PATH_SPEED = 1.079f;
// The grid paths a cell's cost means: a pit band and a blocked band some grid collisions ignore, the highest cost a
// path still crosses, and what a rock crusher pays to walk through rocks and through hazards.
constexpr int GRID_PATH_IMPASSABLE = 950;
constexpr int GRID_PATH_SOLID_CELL = 1000;
constexpr int GRID_PATH_POOP_CELL = 1500;
constexpr int GRID_PATH_SLOWING_MAX = 949;
constexpr int CRUSH_COST_EASY = 1;
constexpr int CRUSH_COST_DANGEROUS = 800;
// A body wider than a cell paths with its collision points, and one an odd number of cells wide shifts by about half.
constexpr float LARGE_BODY_PERIOD = 80;
constexpr float ODD_BODY_SHIFT = 19.96f;
// How the cell its owner counts itself in lags behind: 10 a tick, 50 while walking straight, refilled to 20 / speed.
constexpr int CELL_DELAY_TICK = 10;
constexpr int CELL_DELAY_DIRECT_TICK = 50;
constexpr float CELL_DELAY = 20;
constexpr float CELL_DELAY_SPEED_MIN = 0.2f;
// Every 10 to 19 ticks the cost map is flooded again, each step costing 1, or 7 into a cell with a cost.
constexpr int REPATH_MIN = 10;
constexpr int REPATH_RANGE = 10;
constexpr int STEP_COST = 1;
constexpr int STEP_COST_ROUGH = 7;
// How often it looks ahead for slowing cells and for a clear line, and how far straight walking reaches.
constexpr int SLOW_PROBE_FRAMES = 3;
constexpr float SLOWDOWN = 0.7f;
constexpr int LINE_CHECK_FRAMES = 10;
constexpr float DIRECT_RANGE_NEAR = 70;
constexpr float DIRECT_RANGE_FAR = 750;
// The steering: no target brakes, an arrival brakes harder, else a push of a tenth of the distance up to 2.
constexpr float FRICTION_IDLE = 0.85f;
constexpr float FRICTION_ARRIVED = 0.5f;
constexpr float FRICTION_MOVING = 0.7f;
constexpr float ARRIVE_DISTANCE = 1;
constexpr float PUSH_PER_DISTANCE = 0.1f;
constexpr float PUSH_MAX = 2;
// The cells left of, above, right of and below a cell, each -1 off the grid.
static std::array<int, PATH_DIRECTION_COUNT> grid_neighbors_get(Room& room, int gridIndex)
{
int column = gridIndex % room.gridWidth;
int row = gridIndex / room.gridWidth;
return {room.GetGridIndexByTile(column - 1, row), room.GetGridIndexByTile(column, row - 1),
room.GetGridIndexByTile(column + 1, row), room.GetGridIndexByTile(column, row + 1)};
}
// 004cdd30 Raises a cell's path marker (its cost below the thousands) to marker, never past the impassable ones.
bool room_grid_path_mark(Room& room, int gridIndex, int marker)
{
if ((uint32_t)gridIndex >= ROOM_GRID_CELLS || marker > GRID_PATH_IMPASSABLE) return false;
int& path = room.gridPaths[gridIndex];
if (path % (int)GRID_PATH_BAND < marker) path = path - path % (int)GRID_PATH_BAND + marker;
return true;
}
// 007e3260 Forgets every path, target and evasion, and its grid cell.
void PathFinder::Reset()
{
gridIndex = -1;
gridIndexDelay = 0;
moveCountdown = 0;
hasDirectPath = false;
isPathFound = false;
gridPathTarget = {};
evadeMovementCountdown = 0;
evadeBar = 0;
evadeDistance = 0;
visitedGridIndices.clear();
direction = PATH_DIRECTION_NONE;
directionTimer = 0;
lastMoveFrame = -1;
canCrushRocks = false;
movementTarget = {};
moveDirection = {};
}
// 007e6fa0 Forgets the spot it wanders to.
void PathFinder::ResetMovementTarget()
{
movementTarget = {};
moveDirection = {};
}
// 007e6ff0 Notes the grid cell its owner stands in, or -1 outside the grid.
void PathFinder::UpdateGridIndex()
{
gridIndex = g_game->room->GetGridIndex(entity->pos);
}
// 007e3340 Whether its owner paths as the players' side: charmed, the Blood Puppy, after a baited target, or an
// enemy under a player's control or forced onto a target.
bool PathFinder::is_entity_friendly()
{
if (!entity) return false;
if (entity->HasEntityFlags(FLAG_CHARM) || entity->type == ENTITY_BLOOD_PUPPY) return true;
if (entity->target && entity->target->HasEntityFlags(FLAG_BAITED)) return true;
if (entity->type < ENTITY_FIRST_ENEMY || entity->type > PATH_ENEMY_TYPE_LAST) return false;
Entity_NPC* npc = static_cast<Entity_NPC*>(entity);
return npc->controllerID != -1 || npc->forcedTarget;
}
// 007e7fb0 A grid path as its owner's grid collision feels it: flying over pits drops the pit band, walking on the
// ground keeps all, and anything else drops both the blocked and the pit bands.
int PathFinder::grid_path_felt(uint32_t gridPath)
{
if (!entity || entity->entityGridCollisionClass == GRIDCOLL_GROUND) return (int)gridPath;
if (entity->entityGridCollisionClass == GRIDCOLL_NOPITS)
return (int)(gridPath - GRID_PATH_PIT < GRID_PATH_BAND ? gridPath - GRID_PATH_PIT : gridPath);
uint32_t felt = gridPath - GRID_PATH_BAND < GRID_PATH_BAND ? gridPath - GRID_PATH_BAND : gridPath;
return (int)(felt - GRID_PATH_PIT < GRID_PATH_BAND ? felt - GRID_PATH_PIT : felt);
}
// Whether a target's cell is worth remembering: one that is not solid, or for a rock crusher a grid entity that is
// neither easy nor dangerous to crush.
bool PathFinder::is_target_kept(Room& room, int targetIndex)
{
if (!canCrushRocks) return targetIndex >= 0 && room.GetGridPath(targetIndex) < GRID_PATH_SOLID;
GridEntity* grid = room.GetGridEntity(targetIndex);
return grid && !grid->IsEasyCrushableOrWalkable() && !grid->IsDangerousCrushableOrWalkable();
}
// The cost map: the room's grid paths, or for a large body each cell's cost under the first half of its collision
// points (the most blocked of them, a rock crusher paying less for rocks and hazards).
void PathFinder::grid_costs_fill(Room& room, const Vector& offset, bool isLarge)
{
if (!isLarge)
{
gridCosts = room.gridPaths;
return;
}
std::vector<Vector> offsets{offset};
for (const Vector& point : entity->collisionPoints) offsets.push_back(vector_add(offset, point));
gridCosts.fill(0);
for (int cell = 0; cell < room.gridWidth * room.gridHeight; cell++)
{
Vector center = room.GetGridPosition(cell);
for (size_t i = 0; i < offsets.size() / 2; i++)
{
int covered = room.GetGridIndex(vector_add(center, offsets[i]));
int path = room.GetGridPath(covered);
int cost = path;
GridEntity* grid = canCrushRocks ? room.GetGridEntity(covered) : nullptr;
if (grid)
{
if (grid->IsEasyCrushableOrWalkable()) cost = CRUSH_COST_EASY;
if (grid->IsDangerousCrushableOrWalkable()) cost = CRUSH_COST_DANGEROUS;
cost = std::min(cost, path);
}
if (i == 0 || (path > gridCosts[cell] && path > GRID_PATH_FREED)) gridCosts[cell] = cost;
}
}
}
// A large body aiming at a cell it cannot fit into aims at the cheapest cell its collision points reach from there.
// The original reads its countdown as the cost of a point off the grid. Such points are skipped here.
int PathFinder::large_target_get(Room& room, const Vector& position, int targetIndex)
{
if (targetIndex < 0 || gridCosts[targetIndex] <= GRID_PATH_FREED) return targetIndex;
if (room.GetGridPath(targetIndex) > GRID_PATH_FREED) return targetIndex;
Vector center = room.GetGridPosition(room.GetGridIndex(position));
int best = gridCosts[targetIndex];
for (size_t i = 0; i < entity->collisionPoints.size() / 2; i++)
{
int cell = room.GetGridIndex(vector_sub(center, entity->collisionPoints[i]));
if (cell < 0 || gridCosts[cell] >= best) continue;
best = gridCosts[cell];
targetIndex = cell;
}
return targetIndex;
}
// (007e4860, 007e85a0) Floods the cost map from the target, cheapest first, marking each reached cell with its
// negated cost until it reaches its own cell or half the room's cells in cost.
void PathFinder::grid_costs_flood(Room& room, int targetIndex, bool isFriendly)
{
auto isCostlier = [](const PathNode& first, const PathNode& second) {
return first.cost > second.cost;
};
std::priority_queue<PathNode, std::vector<PathNode>, decltype(isCostlier)> open(isCostlier);
open.push({targetIndex, 0});
isPathFound = false;
while (!open.empty() && !isPathFound)
{
PathNode node = open.top();
if (node.cost >= room.gridWidth * room.gridHeight / 2) break;
open.pop();
for (int next : grid_neighbors_get(room, node.gridIndex))
{
if (next < 0 || gridCosts[next] < 0 || gridCosts[next] >= GRID_PATH_IMPASSABLE) continue;
int cost = node.cost + (gridCosts[next] > 0 && !isFriendly ? STEP_COST_ROUGH : STEP_COST);
gridCosts[next] = -cost;
if (next == gridIndex) isPathFound = true;
open.push({next, cost});
}
}
}
// The neighbour of its cell the flood reached cheapest, or its own cell. A crawlspace ladder above is never taken.
int PathFinder::path_next_get(Room& room)
{
std::array<int, PATH_DIRECTION_COUNT> neighbors = grid_neighbors_get(room, gridIndex);
int next = gridIndex;
int best = -GRID_PATH_SOLID;
for (int direction = 0; direction < PATH_DIRECTION_COUNT; direction++)
{
int cell = neighbors[direction];
GridEntity* grid = room.GetGridEntity(cell);
bool isLadder = room.roomType == ROOM_DUNGEON && direction == PATH_DIRECTION_UP && grid &&
grid->type == GRID_GRAVITY;
if (isLadder || cell < 0 || gridCosts[cell] >= 0 || gridCosts[cell] <= best) continue;
best = gridCosts[cell];
next = cell;
}
return next;
}
// Pushes its owner from where it stands toward the spot, braking when there is none or it has arrived.
void PathFinder::path_steer(const Vector& moveTarget, const Vector& from, float speed)
{
if (vector_is_zero(moveTarget))
{
entity->friction *= FRICTION_IDLE;
return;
}
Vector delta = vector_sub(moveTarget, from);
float distance = vector_length(delta);
if (distance <= ARRIVE_DISTANCE)
{
entity->friction *= FRICTION_ARRIVED;
return;
}
float push = std::min(distance * PUSH_PER_DISTANCE, PUSH_MAX) * speed;
entity->friction *= FRICTION_MOVING;
entity->AddVelocity_divided(vector_make(delta.x / distance * push, delta.y / distance * push), false);
}
// 007e33c0 Steers its owner toward position: straight at it when the line is clear and near enough, else down the
// cost map it floods from the target every 10 to 19 ticks. A controlled enemy moves by its player's input instead.
// A versus match's player never paths, so only enemies are tested for a controller.
void PathFinder::FindGridPath(const Vector& position, float speed, int pathMarker, DirectPathMode mode)
{
bool isEnemy = entity->type >= ENTITY_FIRST_ENEMY && entity->type <= PATH_ENEMY_TYPE_LAST;
if (isEnemy && static_cast<Entity_NPC*>(entity)->controllerID != -1)
{
SimulatePlayerMovement(static_cast<Entity_NPC*>(entity)->GetControllerInput(0), 1);
UpdateGridIndex();
hasDirectPath = true;
return;
}
if (entity->HasEntityFlags(FLAG_CONFUSION) && !entity->HasEntityFlags(FLAG_CHARM))
{
MoveRandomly(STATUS_IGNORED);
Vector heading = vector_normalized(entity->velocity);
entity->velocity = {};
entity->AddVelocity_divided(vector_scale(heading, speed), false);
}
Vector body = vector_scale(entity->sizeMulti, entity->size * 2);
bool isLarge = body.x > GRID_CELL_SIZE || body.y > GRID_CELL_SIZE;
bool isFamiliar = entity->type == ENTITY_FAMILIAR && pathMarker <= 0;
bool isFriendly = is_entity_friendly() || pathMarker < 0;
Vector offset{};
if (std::fmod(body.x, LARGE_BODY_PERIOD) > GRID_CELL_SIZE) offset.x = ODD_BODY_SHIFT;
if (std::fmod(body.y, LARGE_BODY_PERIOD) > GRID_CELL_SIZE) offset.y = ODD_BODY_SHIFT;
Vector from = vector_sub(entity->pos, offset);
Room& room = *g_game->room;
int targetIndex = room.GetGridIndex(position);
if (is_target_kept(room, targetIndex)) gridPathTarget = position;
else if (!vector_is_zero(gridPathTarget)) targetIndex = room.GetGridIndex(gridPathTarget);
int ticks = entity->update_ticks_get();
int ownIndex = room.GetGridIndex(from);
Vector ownCenter = room.GetGridPosition(ownIndex);
if (ownIndex != gridIndex && (gridIndexDelay -= ticks * CELL_DELAY_TICK) < 0)
{
gridIndex = ownIndex;
gridIndexDelay = (int)(CELL_DELAY / std::max(speed, CELL_DELAY_SPEED_MIN));
}
float slowdown = 1;
if (!isFamiliar)
{
if (entity->IsFrame(SLOW_PROBE_FRAMES, 1))
{
Vector ahead = vector_add(vector_scale(vector_normalized(entity->velocity), GRID_CELL_SIZE), from);
int felt = grid_path_felt(room.GetGridPath(room.GetGridIndex(ahead)));
if ((uint32_t)(felt - 1) < GRID_PATH_SLOWING_MAX) slowdown = SLOWDOWN;
}
if (pathMarker >= 0 && room.GetGridPath(gridIndex) < GRID_PATH_IMPASSABLE)
room_grid_path_mark(room, gridIndex, pathMarker);
}
if (entity->IsFrame(LINE_CHECK_FRAMES, entity->index))
{
Vector targetCenter = room.GetGridPosition(room.GetGridIndex(position));
int threshold = isFriendly || isFamiliar ? GRID_PATH_FREED : 0;
if (entity->entityGridCollisionClass == GRIDCOLL_WALLS) hasDirectPath = true;
else if (canCrushRocks)
reconstruction_missing("Room::CheckLine 007f0df0: the rocks a rock crusher sees through");
else hasDirectPath = room_check_line(ownCenter, targetCenter, LINE_MODE_GROUND, threshold);
}
float directRange = mode == DIRECT_PATH_FAR ? DIRECT_RANGE_FAR : DIRECT_RANGE_NEAR;
if (isLarge && mode == DIRECT_PATH_NEAR)
directRange += std::max(entity->size * entity->sizeMulti.x, entity->size * entity->sizeMulti.y);
Vector moveTarget{};
if ((hasDirectPath && vector_length(vector_sub(position, entity->pos)) < directRange) || gridIndex == targetIndex)
{
moveTarget = vector_sub(position, offset);
moveCountdown -= ticks * CELL_DELAY_TICK;
gridIndexDelay -= ticks * CELL_DELAY_DIRECT_TICK;
}
else
{
if (room.GetGridPath(gridIndex) == GRID_PATH_SOLID || moveCountdown > 0) moveCountdown -= ticks;
else
{
moveCountdown = (int)(Random() % REPATH_RANGE) + REPATH_MIN;
grid_costs_fill(room, offset, isLarge);
if (isLarge) targetIndex = large_target_get(room, position, targetIndex);
grid_costs_flood(room, targetIndex, isFriendly);
}
if (isPathFound) moveTarget = room.GetGridPosition(path_next_get(room));
}
path_steer(moveTarget, from, slowdown * speed);
}
// Whether the owner's periodic checks run this frame: every period frames by its index, not while paused or
// interpolating.
static bool is_evade_check_frame(Entity& entity, int period)
{
if (entity.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused()) return false;
return ((int)entity.index + g_game->frameCount) % period == 0;
}
// One try at a spot to flee to: a random cell within 30 to 480 of base, not tried this half second, free and in
// walking reach. It is taken while the target cannot walk to the owner (or the evasion is wide) and it lies far
// enough from the target. Each taken spot raises the bar for the next.
static void evade_spot_try(PathFinder& finder, const Vector& targetPos, const Vector& base, float distance,
float& attempt)
{
Entity* entity = finder.entity;
Room& room = *g_game->room;
float reach = random_unit() * EVADE_REACH_RANGE + EVADE_REACH_MIN;
float angle = random_unit() * RANDOM_HALF_TURN;
angle += angle;
Vector spot = vector_make(std::cos(angle) * reach + base.x, std::sin(angle) * EVADE_FLATTEN * reach + base.y);
int column = (int)((spot.x - GRID_CELL_SIZE) / GRID_CELL_SIZE + 0.5f);
int row = (int)((spot.y - EVADE_GRID_TOP) / GRID_CELL_SIZE + 0.5f);
bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight;
int cell = isInside ? room.gridWidth * row + column : -1;
if (!finder.visitedGridIndices.insert(cell).second)
{
attempt -= EVADE_REVISIT_REFUND;
return;
}
Vector center = vector_make((float)(cell % room.gridWidth) * GRID_CELL_SIZE + GRID_CELL_SIZE,
(float)(cell / room.gridWidth) * GRID_CELL_SIZE + EVADE_GRID_TOP);
if (room_grid_collision_at(center) != 0 || !room_check_line(entity->pos, center, LINE_MODE_CELL, 0)) return;
if (room_check_line(targetPos, entity->pos, LINE_MODE_CELL, 0) && finder.evadeDistance < EVADE_WIDE)
{
finder.evadeDistance += EVADE_WIDEN;
return;
}
float bar = reach / EVADE_REACH_SHARE + distance + EVADE_MARGIN + finder.evadeDistance;
bar -= finder.evadeBar;
if (bar <= vector_length(vector_sub(targetPos, center)))
{
finder.movementTarget = center;
if (finder.evadeDistance < EVADE_WIDE) finder.evadeDistance *= 0.5f;
}
finder.evadeBar += EVADE_BAR_STEP;
}
// 007e4940 Flees targetPos: within 250 of it (170 out of its walking sight) it keeps evading for 3 more checks of
// every 14 frames, pushing away and seeking a cell to run to that lies well away from the target, and it wanders
// once the evasion runs out. A friendly owner paths to its target instead. evadeBar lowers the bar each candidate
// spot must clear.
void PathFinder::EvadeTarget(const Vector& targetPos, StatusMode mode)
{
if (mode == STATUS_OBEYED && is_entity_friendly())
{
FindGridPath(static_cast<Entity_NPC*>(entity)->GetPlayerTarget()->pos, EVADE_PATH_SPEED, 0, DIRECT_PATH_FAR);
return;
}
Vector delta = vector_sub(targetPos, entity->pos);
float distance = vector_length(delta);
evadeDistance = std::min(evadeDistance, EVADE_WIDE);
if (is_evade_check_frame(*entity, EVADE_CHECK_FRAMES))
{
float range = room_check_line(entity->pos, targetPos, LINE_MODE_CELL, 0) ? EVADE_RANGE_SEEN : EVADE_RANGE_HIDDEN;
if (distance >= range) evadeMovementCountdown -= entity->update_ticks_get();
else
{
if (evadeMovementCountdown < 1) movementTarget = {};
evadeMovementCountdown = EVADE_COUNTDOWN;
}
}
if (is_evade_check_frame(*entity, EVADE_FORGET_FRAMES)) visitedGridIndices.clear();
if (evadeMovementCountdown < 1)
{
evadeBar = 0;
evadeDistance *= EVADE_DECAY;
MoveRandomly(STATUS_IGNORED);
entity->friction *= EVADE_DECAY;
return;
}
if (vector_is_zero(movementTarget) || evadeDistance > EVADE_WIDE)
{
Vector away = distance > 0 ? vector_make(delta.x / -distance, delta.y / -distance) : Vector{};
if (std::abs(std::abs(away.x) - std::abs(away.y)) < EVADE_DIAGONAL)
{
if ((Random() & 1) == 0) away.x *= 0.5f;
else away.y *= 0.5f;
}
if (entity->friction != 0)
{
entity->velocity.x += away.x * EVADE_PUSH * entity->speedMultiplier / entity->friction;
entity->velocity.y += away.y * EVADE_PUSH * entity->speedMultiplier / entity->friction;
}
Vector base = vector_add(entity->pos, vector_scale(away, EVADE_BASE_REACH));
for (float attempt = 0; attempt < EVADE_ATTEMPTS - evadeDistance * EVADE_ATTEMPT_SHARE; attempt += 1)
evade_spot_try(*this, targetPos, base, distance, attempt);
}
if (vector_is_zero(movementTarget)) return;
if (is_evade_check_frame(*entity, EVADE_RECHECK_FRAMES))
{
bool isDropped = room_check_line(targetPos, movementTarget, LINE_MODE_CELL, 0) && evadeDistance < EVADE_WIDE;
Vector fromTarget = vector_sub(targetPos, movementTarget);
isDropped = isDropped || vector_length_squared(fromTarget) < EVADE_SPOT_RANGE_SQUARED ||
std::abs(fromTarget.x) < EVADE_WIDE || std::abs(fromTarget.y) < EVADE_WIDE;
if (isDropped) movementTarget = {};
}
if (!vector_is_zero(movementTarget)) FindGridPath(movementTarget, EVADE_PATH_SPEED, 0, DIRECT_PATH_FAR);
}
// 007e6300 Wanders: picks a free spot 40 away when it has none and drifts toward it, dropping it once there, against a
// wall, or now and then once stalled. Unless told to ignore its status, a friendly owner paths to its target and a
// feared or shrunk one flees instead. Whether it finished a wander (or did something else).
bool PathFinder::MoveRandomly(StatusMode mode)
{
if (entity->minecart) return true;
if (mode == STATUS_OBEYED && is_entity_friendly())
{
FindGridPath(static_cast<Entity_NPC*>(entity)->CalcTargetPosition(0), WANDER_FRIENDLY_SPEED, 0, DIRECT_PATH_FAR);
return true;
}
if (mode == STATUS_OBEYED && entity->HasEntityFlags(FLAG_FEAR | FLAG_SHRINK))
{
EvadeTarget(static_cast<Entity_NPC*>(entity)->GetPlayerTarget()->pos, STATUS_OBEYED);
return true;
}
if (vector_is_zero(movementTarget))
{
float angle = random_unit() * RANDOM_HALF_TURN;
angle += angle;
Vector spot = vector_make(std::cos(angle) * WANDER_STEP + entity->pos.x,
std::sin(angle) * WANDER_STEP + entity->pos.y);
if (room_grid_collision_at(spot) == 0) movementTarget = spot;
}
if (vector_is_zero(movementTarget)) return false;
Vector delta = vector_sub(movementTarget, entity->pos);
float distance = vector_length(delta);
bool isStalled = vector_length_squared(entity->velocity) < WANDER_STALL_SPEED_SQUARED;
if (distance < WANDER_ARRIVED || entity->isCollidesWithGrid || (isStalled && Random() % WANDER_GIVE_UP_ODDS == 0))
{
movementTarget = {};
return true;
}
if (distance > 0 && entity->friction != 0)
{
entity->velocity.x += delta.x / distance * WANDER_PUSH * entity->speedMultiplier / entity->friction;
entity->velocity.y += delta.y / distance * WANDER_PUSH * entity->speedMultiplier / entity->friction;
}
return false;
}
// A run of cells straight from the owner in a direction: how far it reaches before a cell it would not cross (none past
// the room's box), and none when both cells beside its end are blocked, unless one time in ten.
static int axis_run_get(PathFinder& finder, int direction, int attemptsLeft)
{
Entity* entity = finder.entity;
Room& room = *g_game->room;
int cells = (int)(Random() % AXIS_RUN_CELLS);
bool isFleeing = entity->HasEntityFlags(FLAG_FEAR | FLAG_SHRINK);
if (isFleeing) cells = (int)(Random() & 3) + 1;
Vector axis = vector_from_direction(direction);
Vector end = vector_add(entity->pos, vector_scale(axis, (float)cells * GRID_CELL_SIZE));
bool isInside = end.x <= room.bottomRightPos.x && end.x >= room.topLeftPos.x && end.y <= room.bottomRightPos.y &&
end.y >= room.topLeftPos.y;
if (!isInside || vector_is_zero(end)) return 0;
for (int step = 1; step < cells; step++)
{
Vector cell = vector_add(entity->pos, vector_scale(axis, (float)step * GRID_CELL_SIZE));
int path = finder.grid_path_felt(room.GetGridPath(room.GetGridIndex(cell)));
bool isBlocked = path > AXIS_BLOCKING_PATH && (attemptsLeft > 0 || path > AXIS_LAST_TRY_BLOCKING_PATH) &&
(!isFleeing || path > AXIS_FLEE_BLOCKING_PATH);
if (!isBlocked) continue;
cells = step - 1;
break;
}
end = vector_add(entity->pos, vector_scale(axis, (float)cells * GRID_CELL_SIZE));
bool isOpen = false;
for (int side : {direction + 3, direction + 1})
{
Vector step = vector_scale(vector_from_direction(side % PATH_DIRECTION_COUNT), GRID_CELL_SIZE);
Vector beside = vector_add(end, step);
isOpen = isOpen || finder.grid_path_felt(room.GetGridPath(room.GetGridIndex(beside))) < AXIS_SIDE_OPEN_PATH;
}
return isOpen || Random() % AXIS_SIDE_ODDS == 0 ? cells : 0;
}
// The direction of the longest run, looked over from a random start. A fleeing NPC takes the longest run away from its
// target, else across it. best is the run's length.
static int axis_direction_pick(PathFinder& finder, const std::array<int, PATH_DIRECTION_COUNT>& runs, int& best)
{
Entity* entity = finder.entity;
auto* npc = dynamic_cast<Entity_NPC*>(entity);
int chosen = PATH_DIRECTION_NONE;
int start = (int)(Random() & 3);
auto longest_take = [&](int direction) {
if (runs[direction] <= best) return;
best = runs[direction];
chosen = direction;
};
if (npc && entity->HasEntityFlags(FLAG_FEAR | FLAG_SHRINK))
{
Vector toward = vector_sub(npc->GetPlayerTarget()->pos, entity->pos);
for (int i = start; i < start + PATH_DIRECTION_COUNT; i++)
if (vector_dot(toward, vector_from_direction(i & 3)) <= 0) longest_take(i & 3);
int across = std::abs(toward.y) <= std::abs(toward.x) ? PATH_DIRECTION_UP : PATH_DIRECTION_LEFT;
if (best == 0)
for (int direction = across; direction < PATH_DIRECTION_COUNT; direction += 2) longest_take(direction);
if (best != 0) return chosen;
}
for (int i = start; i < start + PATH_DIRECTION_COUNT; i++) longest_take(i & 3);
return chosen;
}
// One try at a run to wander: the longest, though one under two cells only one time in ten and a turn back only one
// time in five (a fleeing NPC takes either, but no run within 0.95 of straight at its target). Its end cell becomes
// the spot to reach unless marked avoided or not free, and the owner stops across the run's axis.
static void axis_run_try(PathFinder& finder, int attemptsLeft)
{
Entity* entity = finder.entity;
Room& room = *g_game->room;
std::array<int, PATH_DIRECTION_COUNT> runs{};
for (int direction = 0; direction < PATH_DIRECTION_COUNT; direction++)
runs[direction] = axis_run_get(finder, direction, attemptsLeft);
int best = 0;
int chosen = axis_direction_pick(finder, runs, best);
bool isFleeing = entity->HasEntityFlags(FLAG_FEAR | FLAG_SHRINK);
if (best < 2 && Random() % AXIS_SHORT_ODDS != 0 && !isFleeing) chosen = PATH_DIRECTION_NONE;
bool isTaken = std::abs(finder.direction - chosen) != 2 || Random() % AXIS_TURN_BACK_ODDS == 0 || isFleeing;
finder.directionTimer = 0;
if (!isTaken || chosen < 0) return;
Vector axis = vector_from_direction(chosen);
if (isFleeing)
{
Vector toward = vector_sub(static_cast<Entity_NPC*>(entity)->GetPlayerTarget()->pos, entity->pos);
if (vector_dot(vector_normalized(toward), axis) > AXIS_FLEE_AWAY_DOT) return;
}
Vector end = vector_add(entity->pos, vector_scale(axis, (float)best * GRID_CELL_SIZE));
Vector center = room.GetGridPosition(room.GetGridIndex(end));
int cell = room.GetGridIndex(center);
if (room.GetGridPath(cell) == AXIS_AVOIDED_PATH) return;
finder.direction = chosen;
auto collision = (GridCollision)room.GetGridCollision(cell);
bool isFree = collision == COLLISION_NONE ||
(entity->entityGridCollisionClass == GRIDCOLL_WALLS && collision != COLLISION_WALL);
if (!isFree) return;
finder.movementTarget = center;
if (std::abs(axis.x) <= std::abs(axis.y)) entity->velocity.x = 0;
else entity->velocity.y = 0;
}
// Drives toward the spot to reach, kept in the room's box. It drops the spot after a skipped frame, once within 5,
// once slower than 0.6 for over 10 checks, or once heading at over 3 into a cell it feels over 700 for over 2 checks.
static void axis_steer(PathFinder& finder, float speed, int elapsed)
{
Entity* entity = finder.entity;
Room& room = *g_game->room;
Vector& target = finder.movementTarget;
if (elapsed > 1)
{
target = {};
return;
}
target.x = std::min(std::max(target.x, room.topLeftPos.x), room.bottomRightPos.x);
target.y = std::min(std::max(target.y, room.topLeftPos.y), room.bottomRightPos.y);
Vector away = vector_sub(vector_add(entity->pos, entity->velocity), target);
if (vector_length(away) < AXIS_ARRIVED) target = {};
else if (vector_length(entity->velocity) < AXIS_STALL_SPEED && ++finder.directionTimer > AXIS_STALL_CHECKS)
target = {};
away = vector_normalized(away);
if (entity->friction != 0)
{
entity->velocity.y += entity->speedMultiplier * -away.y * speed / entity->friction;
entity->velocity.x += entity->speedMultiplier * -away.x * speed / entity->friction;
}
Vector ahead = vector_add(entity->pos, vector_scale(vector_normalized(entity->velocity), GRID_CELL_SIZE));
int felt = finder.grid_path_felt(room.GetGridPath(room.GetGridIndex(ahead)));
if (felt > AXIS_HAZARD_PATH && vector_length(entity->velocity) > AXIS_HAZARD_SPEED &&
++finder.directionTimer > AXIS_HAZARD_CHECKS)
target = {};
}
// 007e5340 Wanders along the axes: up to 10 tries a call at a run of cells left, up, right or down to a free cell,
// then drives there at speed. A friendly owner paths to its target instead, sliding along the axis it leans on most,
// and holds still near a player it follows.
void PathFinder::MoveRandomlyAxisAligned(float speed, StatusMode mode)
{
if (entity->minecart) return;
if (mode == STATUS_OBEYED && is_entity_friendly())
{
auto* npc = static_cast<Entity_NPC*>(entity);
Vector target = npc->CalcTargetPosition(0);
bool isNear = npc->HasEntityFlags(FLAG_FRIENDLY) && npc->GetPlayerTarget()->type == ENTITY_PLAYER &&
vector_length_squared(vector_sub(npc->pos, target)) < AXIS_FOLLOW_NEAR_SQUARED;
if (isNear)
{
npc->friction *= AXIS_FOLLOW_FRICTION;
return;
}
FindGridPath(npc->CalcTargetPosition(0), speed, 0, DIRECT_PATH_FAR);
npc->velocity = vector_scale(vector_cardinal(npc->velocity), vector_length(npc->velocity));
return;
}
int elapsed = g_game->frameCount - lastMoveFrame;
lastMoveFrame = g_game->frameCount;
for (int attempts = AXIS_ATTEMPTS; vector_is_zero(movementTarget) && attempts > 0; attempts--)
axis_run_try(*this, attempts - 1);
if (!vector_is_zero(movementTarget)) axis_steer(*this, speed, elapsed);
}
// How a boss wanders: pushed at half its speed along its heading, veering one time in 30, turning back off walls every
// 5 frames, and trying up to 5 new headings while the cell 10 ahead is blocked.
constexpr float BOSS_WANDER_PUSH = 0.5f;
constexpr uint32_t BOSS_WANDER_TURN_ODDS = 30;
constexpr int BOSS_WANDER_BOUNCE_FRAMES = 5;
constexpr int BOSS_WANDER_TRIES = 5;
constexpr float BOSS_WANDER_LOOKAHEAD = 10;
// 007e6650 Wanders like a boss along moveDirection. Stuck inside a wall it now and then heads for a free spot instead.
// Unless told to ignore its status, a friendly owner paths to its target and a feared or shrunk one flees.
void PathFinder::MoveRandomlyBoss(StatusMode mode)
{
if (entity->minecart) return;
if (mode == STATUS_OBEYED && is_entity_friendly())
return FindGridPath(static_cast<Entity_NPC*>(entity)->CalcTargetPosition(0), WANDER_FRIENDLY_SPEED, 0,
DIRECT_PATH_FAR);
if (mode == STATUS_OBEYED && entity->HasEntityFlags(FLAG_FEAR | FLAG_SHRINK))
return EvadeTarget(static_cast<Entity_NPC*>(entity)->GetPlayerTarget()->pos, STATUS_OBEYED);
if (vector_is_zero(moveDirection)) moveDirection = random_direction();
npc_push(*entity, vector_scale(moveDirection, BOSS_WANDER_PUSH));
Room& room = *g_game->room;
if (room_grid_collision_at(entity->pos) != 0)
{
if (Random() % BOSS_WANDER_TURN_ODDS != 0) return;
Vector spot = room_free_pickup_position_find({.position = entity->pos});
moveDirection = vector_normalized(vector_sub(spot, entity->pos));
return;
}
if (Random() % BOSS_WANDER_TURN_ODDS == 0)
moveDirection = vector_normalized(vector_add(moveDirection, random_direction()));
if (entity->isCollidesWithGrid && entity->IsFrame(BOSS_WANDER_BOUNCE_FRAMES, 0))
moveDirection = vector_scale(moveDirection, -1);
for (int triesLeft = BOSS_WANDER_TRIES; triesLeft > 0; triesLeft--)
{
Vector ahead = vector_add(entity->pos, vector_scale(moveDirection, BOSS_WANDER_LOOKAHEAD));
if (room.GetGridCollision(room.GetGridIndex(ahead)) == 0) return;
moveDirection = vector_normalized(vector_sub(random_direction(), moveDirection));
entity->velocity = {};
}
}
// 007e6b90
void PathFinder::update_chase_movement()
{
reconstruction_missing("PathFinder::update_chase_movement 007e6b90");
}
// 007e7070 Whether the owner can walk to a position: a flood from its cell over the walkable cells (and poop, when
// asked) reaches the owner's cell within half the room's cells. An owner standing in a solid cell cannot.
bool PathFinder::HasPathToPos(const Vector& position, bool isIgnorePoop)
{
Room& room = *g_game->room;
int start = room.GetGridIndex(entity->pos);
if (start >= 0 && room.gridPaths[start] == GRID_PATH_SOLID_CELL) return false;
std::array<int, PATH_GRID_CELLS> costs = room.gridPaths;
std::queue<PathNode> open;
open.push({room.GetGridIndex(position), 0});
while (!open.empty())
{
PathNode node = open.front();
if (node.cost >= room.gridWidth * room.gridHeight / 2) return false;
open.pop();
for (int next : grid_neighbors_get(room, node.gridIndex))
{
if (next < 0) continue;
bool isWalkable = costs[next] >= 0 && costs[next] < GRID_PATH_IMPASSABLE;
if (!isWalkable && !(isIgnorePoop && costs[next] == GRID_PATH_POOP_CELL)) continue;
costs[next] = -(node.cost + 1);
if (next == start) return true;
open.push({next, node.cost + 1});
}
}
return false;
}
// 007e8010 Moves its owner as a player walks with that input, in two half steps: the input (capped at 1, without its
// vertical part for a falling grounded owner) scales with speed into the move direction and the way it faces, the
// velocity across it fades, it accelerates up to speed * 4.41 and is damped, more slowly while the slippery countdown
// lasts. A falling grounded owner keeps falling instead of being damped vertically.
void PathFinder::SimulatePlayerMovement(const Vector& input, float speed)
{
constexpr int SLIPPERY_COUNTDOWN = 60;
constexpr float INPUT_SPEED_SHARE = 0.25f;
constexpr float FALL_PULL = 0.225f;
constexpr float MAX_SPEED_PER_SPEED = 4.41f;
constexpr float PUSH_DRY = -0.2f;
constexpr float PUSH_SLIPPERY = 0.5f;
constexpr float DRAG_DRY = 0.775f;
constexpr float DRAG_SLIPPERY = 0.96f;
constexpr float KEEP_DRY = 0.8f;
constexpr float ACCEL_BASE = 3;
constexpr float ACCEL_SCALE = 0.4f;
constexpr float ACCEL_SLIPPERY_SHARE = 0.25f;
auto lerp = [](float from, float to, float t) {
return from + (to - from) * t;
};
bool isFalling = entity->HasEntityFlags(FLAG_APPLY_GRAVITY) && entity->entityGridCollisionClass == GRIDCOLL_GROUND;
Vector walk = vector_make(input.x, isFalling ? 0 : input.y);
float length = vector_length(walk);
if (length > 1 && length > 0) walk = vector_make(input.x * (1 / length), walk.y * (1 / length));
float scale = speed * INPUT_SPEED_SHARE + (1 - INPUT_SPEED_SHARE);
moveDirection = vector_make(scale * walk.x, scale * walk.y);
if (std::fabs(moveDirection.x) > std::fabs(moveDirection.y))
direction = moveDirection.x >= 0 ? PATH_DIRECTION_RIGHT : PATH_DIRECTION_LEFT;
else if (moveDirection.y < 0) direction = PATH_DIRECTION_UP;
else direction = moveDirection.y > 0 ? PATH_DIRECTION_DOWN : PATH_DIRECTION_NONE;
if (entity->HasEntityFlags(FLAG_SLIPPERY_PHYSICS)) moveCountdown = SLIPPERY_COUNTDOWN;
else moveCountdown = std::max(moveCountdown - 1, 0);
float slippery = entity->HasEntityFlags(FLAG_SLOW) ? 0 : (float)moveCountdown / SLIPPERY_COUNTDOWN;
float pushShare = lerp(PUSH_DRY, PUSH_SLIPPERY, slippery);
float damping = std::sqrt(lerp(DRAG_DRY, DRAG_SLIPPERY, slippery));
float maxSpeed = speed * MAX_SPEED_PER_SPEED;
Vector half = vector_scale(entity->velocity, 0.5f);
for (int step = 0; step < 2; step++)
{
bool isMoving = moveDirection.x != 0 || moveDirection.y != 0;
if (isMoving && !isFalling)
{
float along = half.y * moveDirection.y + half.x * moveDirection.x;
Vector kept = vector_make(along * moveDirection.x, along * moveDirection.y);
float keep = std::sqrt(lerp(KEEP_DRY, 1, slippery));
half = vector_make((half.x - kept.x) * keep + kept.x, (half.y - kept.y) * keep + kept.y);
}
Vector before = half;
float push = pushShare * (half.y * moveDirection.y + half.x * moveDirection.x);
float accel = ((push > 0 ? push : 0) / speed + ACCEL_BASE) * ACCEL_SCALE;
accel = (accel * ACCEL_SLIPPERY_SHARE - accel) * slippery + accel;
half = vector_make(half.x + moveDirection.x * 0.5f * accel, half.y + moveDirection.y * 0.5f * accel);
float lengthSquared = half.x * half.x + half.y * half.y;
if (slippery > 0 && lengthSquared > maxSpeed * maxSpeed)
{
float moved = std::sqrt(lengthSquared);
if (moved > 0) half = vector_scale(half, vector_length(before) / moved);
}
half.x *= damping;
half.y = isFalling ? half.y + FALL_PULL : half.y * damping;
}
entity->velocity = vector_make(half.x + half.x, half.y + half.y);
}