1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
|
/*
* CPathfinder.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "CPathfinder.h"
#include "INodeStorage.h"
#include "PathfinderOptions.h"
#include "PathfindingRules.h"
#include "TurnInfo.h"
#include "../gameState/CGameState.h"
#include "../CPlayerState.h"
#include "../TerrainHandler.h"
#include "../mapObjects/CGHeroInstance.h"
#include "../mapObjects/CGTownInstance.h"
#include "../mapObjects/MiscObjects.h"
#include "../mapping/CMap.h"
#include "spells/CSpellHandler.h"
VCMI_LIB_NAMESPACE_BEGIN
bool CPathfinderHelper::canMoveFromNode(const PathNodeInfo & source) const
{
// we can always make the first step, even when standing on object
if(source.node->theNodeBefore == nullptr)
return true;
if (!source.nodeObject)
return true;
if (!source.isNodeObjectVisitable())
return true;
// we can always move from visitable object if hero has teleported here (e.g. went through monolith)
if (source.node->isTeleportAction())
return true;
// we can not go through teleporters since moving onto a teleport will teleport hero and may invalidate path (e.g. one-way teleport or enemy hero on other side)
if (dynamic_cast<const CGTeleport*>(source.nodeObject) != nullptr)
return false;
return true;
}
void CPathfinderHelper::calculateNeighbourTiles(NeighbourTilesVector & result, const PathNodeInfo & source) const
{
result.clear();
if (!canMoveFromNode(source))
return;
getNeighbours(
*source.tile,
source.node->coord,
result,
boost::logic::indeterminate,
source.node->layer == EPathfindingLayer::SAIL);
if(source.isNodeObjectVisitable())
{
vstd::erase_if(result, [&](const int3 & tile) -> bool
{
return !canMoveBetween(tile, source.nodeObject->visitablePos());
});
}
}
CPathfinder::CPathfinder(CGameState * _gs, std::shared_ptr<PathfinderConfig> config):
gamestate(_gs),
config(std::move(config))
{
initializeGraph();
}
void CPathfinder::push(CGPathNode * node)
{
if(node && !node->inPQ())
{
node->pq = &this->pq;
auto handle = pq.push(node);
node->pqHandle = handle;
}
}
CGPathNode * CPathfinder::topAndPop()
{
auto * node = pq.top();
pq.pop();
node->pq = nullptr;
return node;
}
void CPathfinder::calculatePaths()
{
//logGlobal->info("Calculating paths for hero %s (address %d) of player %d", hero->name, hero , hero->tempOwner);
//initial tile - set cost on 0 and add to the queue
std::vector<CGPathNode *> initialNodes = config->nodeStorage->getInitialNodes();
int counter = 0;
for(auto * initialNode : initialNodes)
{
if(!gamestate->isInTheMap(initialNode->coord)/* || !gs->map->isInTheMap(dest)*/) //check input
{
logGlobal->error("CGameState::calculatePaths: Hero outside the gs->map? How dare you...");
throw std::runtime_error("Wrong checksum");
}
source.setNode(gamestate, initialNode);
auto * hlp = config->getOrCreatePathfinderHelper(source, gamestate);
if(hlp->isHeroPatrolLocked())
continue;
pq.push(initialNode);
}
std::vector<CGPathNode *> neighbourNodes;
while(!pq.empty())
{
counter++;
auto * node = topAndPop();
source.setNode(gamestate, node);
source.node->locked = true;
int movement = source.node->moveRemains;
uint8_t turn = source.node->turns;
float cost = source.node->getCost();
auto * hlp = config->getOrCreatePathfinderHelper(source, gamestate);
hlp->updateTurnInfo(turn);
if(movement == 0)
{
hlp->updateTurnInfo(++turn);
movement = hlp->getMaxMovePoints(source.node->layer);
if(!hlp->passOneTurnLimitCheck(source))
continue;
if(turn > hlp->options.turnLimit)
continue;
}
source.isInitialPosition = source.nodeHero == hlp->hero;
source.updateInfo(hlp, gamestate);
//add accessible neighbouring nodes to the queue
for(EPathfindingLayer layer = EPathfindingLayer::LAND; layer < EPathfindingLayer::NUM_LAYERS; layer.advance(1))
{
if(!hlp->isLayerAvailable(layer))
continue;
config->nodeStorage->calculateNeighbours(neighbourNodes, source, layer, config.get(), hlp);
for(CGPathNode * neighbour : neighbourNodes)
{
if(neighbour->locked)
continue;
destination.setNode(gamestate, neighbour);
hlp = config->getOrCreatePathfinderHelper(destination, gamestate);
if(!hlp->isPatrolMovementAllowed(neighbour->coord))
continue;
/// Check transition without tile accessibility rules
if(source.node->layer != neighbour->layer && !isLayerTransitionPossible())
continue;
destination.turn = turn;
destination.movementLeft = movement;
destination.cost = cost;
destination.updateInfo(hlp, gamestate);
destination.isGuardianTile = destination.guarded && isDestinationGuardian();
for(const auto & rule : config->rules)
{
rule->process(source, destination, config.get(), hlp);
if(destination.blocked)
break;
}
if(!destination.blocked)
push(destination.node);
} //neighbours loop
}
//just add all passable teleport exits
hlp = config->getOrCreatePathfinderHelper(source, gamestate);
/// For now we disable teleports usage for patrol movement
/// VCAI not aware about patrol and may stuck while attempt to use teleport
if(hlp->patrolState == CPathfinderHelper::PATROL_RADIUS)
continue;
auto teleportationNodes = config->nodeStorage->calculateTeleportations(source, config.get(), hlp);
for(CGPathNode * teleportNode : teleportationNodes)
{
if(teleportNode->locked)
continue;
/// TODO: We may consider use invisible exits on FoW border in future
/// Useful for AI when at least one tile around exit is visible and passable
/// Objects are usually visible on FoW border anyway so it's not cheating.
///
/// For now it's disabled as it's will cause crashes in movement code.
if(teleportNode->accessible == EPathAccessibility::BLOCKED)
continue;
destination.setNode(gamestate, teleportNode);
destination.turn = turn;
destination.movementLeft = movement;
destination.cost = cost;
if(destination.isBetterWay())
{
destination.action = getTeleportDestAction();
config->nodeStorage->commit(destination, source);
if(destination.node->action == EPathNodeAction::TELEPORT_NORMAL)
push(destination.node);
}
}
} //queue loop
logAi->trace("CPathfinder finished with %s iterations", std::to_string(counter));
}
TeleporterTilesVector CPathfinderHelper::getAllowedTeleportChannelExits(const TeleportChannelID & channelID) const
{
TeleporterTilesVector allowedExits;
for(const auto & objId : getTeleportChannelExits(channelID, hero->tempOwner))
{
const auto * obj = getObj(objId);
if(dynamic_cast<const CGWhirlpool *>(obj))
{
auto pos = obj->getBlockedPos();
for(const auto & p : pos)
{
if(gs->map->getTile(p).topVisitableId() == obj->ID)
allowedExits.push_back(p);
}
}
else if(obj && CGTeleport::isExitPassable(gs, hero, obj))
allowedExits.push_back(obj->visitablePos());
}
return allowedExits;
}
TeleporterTilesVector CPathfinderHelper::getCastleGates(const PathNodeInfo & source) const
{
TeleporterTilesVector allowedExits;
for(const auto & town : getPlayerState(hero->tempOwner)->getTowns())
{
if(town->id != source.nodeObject->id && town->visitingHero == nullptr
&& town->hasBuilt(BuildingSubID::CASTLE_GATE))
{
allowedExits.push_back(town->visitablePos());
}
}
return allowedExits;
}
TeleporterTilesVector CPathfinderHelper::getTeleportExits(const PathNodeInfo & source) const
{
TeleporterTilesVector teleportationExits;
const auto * objTeleport = dynamic_cast<const CGTeleport *>(source.nodeObject);
if(isAllowedTeleportEntrance(objTeleport))
{
for(const auto & exit : getAllowedTeleportChannelExits(objTeleport->channel))
{
teleportationExits.push_back(exit);
}
}
else if(options.useCastleGate && source.nodeObject->ID == Obj::TOWN && source.objectRelations != PlayerRelations::ENEMIES)
{
auto * town = dynamic_cast<const CGTownInstance *>(source.nodeObject);
assert(town);
if (town && town->getFactionID() == FactionID::INFERNO)
{
/// TODO: Find way to reuse CPlayerSpecificInfoCallback::getTownsInfo
/// This may be handy if we allow to use teleportation to friendly towns
for(const auto & exit : getCastleGates(source))
{
teleportationExits.push_back(exit);
}
}
}
return teleportationExits;
}
bool CPathfinderHelper::isHeroPatrolLocked() const
{
return patrolState == PATROL_LOCKED;
}
bool CPathfinderHelper::isPatrolMovementAllowed(const int3 & dst) const
{
if(patrolState == PATROL_RADIUS)
{
if(!vstd::contains(patrolTiles, dst))
return false;
}
return true;
}
bool CPathfinder::isLayerTransitionPossible() const
{
ELayer destLayer = destination.node->layer;
/// No layer transition allowed when previous node action is BATTLE
if(!config->options.allowLayerTransitioningAfterBattle && source.node->action == EPathNodeAction::BATTLE)
return false;
switch(source.node->layer.toEnum())
{
case ELayer::LAND:
if(destLayer == ELayer::AIR)
{
if(!config->options.lightweightFlyingMode || source.isInitialPosition)
return true;
}
else if(destLayer == ELayer::SAIL)
{
if(destination.tile->isWater())
return true;
}
else
return true;
break;
case ELayer::SAIL:
if(destLayer == ELayer::LAND && !destination.tile->isWater())
return true;
break;
case ELayer::AIR:
if(destLayer == ELayer::LAND)
return true;
break;
case ELayer::WATER:
if(destLayer == ELayer::LAND)
return true;
break;
}
return false;
}
EPathNodeAction CPathfinder::getTeleportDestAction() const
{
EPathNodeAction action = EPathNodeAction::TELEPORT_NORMAL;
if(destination.isNodeObjectVisitable() && destination.nodeHero)
{
if(destination.heroRelations == PlayerRelations::ENEMIES)
action = EPathNodeAction::TELEPORT_BATTLE;
else
action = EPathNodeAction::TELEPORT_BLOCKING_VISIT;
}
return action;
}
bool CPathfinder::isDestinationGuardian() const
{
return gamestate->guardingCreaturePosition(destination.node->coord) == destination.node->coord;
}
void CPathfinderHelper::initializePatrol()
{
auto state = PATROL_NONE;
if(hero->patrol.patrolling && !getPlayerState(hero->tempOwner)->human)
{
if(hero->patrol.patrolRadius)
{
state = PATROL_RADIUS;
gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadius, ETileVisibility::REVEALED, std::optional<PlayerColor>(), int3::DIST_MANHATTAN);
}
else
state = PATROL_LOCKED;
}
patrolState = state;
}
void CPathfinder::initializeGraph()
{
INodeStorage * nodeStorage = config->nodeStorage.get();
nodeStorage->initialize(config->options, gamestate);
}
bool CPathfinderHelper::canMoveBetween(const int3 & a, const int3 & b) const
{
return gs->checkForVisitableDir(a, b);
}
bool CPathfinderHelper::isAllowedTeleportEntrance(const CGTeleport * obj) const
{
if(!obj || !isTeleportEntrancePassable(obj, hero->tempOwner))
return false;
const auto * whirlpool = dynamic_cast<const CGWhirlpool *>(obj);
if(whirlpool)
{
if(addTeleportWhirlpool(whirlpool))
return true;
}
else if(addTeleportTwoWay(obj) || addTeleportOneWay(obj) || addTeleportOneWayRandom(obj))
return true;
return false;
}
bool CPathfinderHelper::addTeleportTwoWay(const CGTeleport * obj) const
{
return options.useTeleportTwoWay && isTeleportChannelBidirectional(obj->channel, hero->tempOwner);
}
bool CPathfinderHelper::addTeleportOneWay(const CGTeleport * obj) const
{
if(options.useTeleportOneWay && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
{
auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
if(passableExits.size() == 1)
return true;
}
return false;
}
bool CPathfinderHelper::addTeleportOneWayRandom(const CGTeleport * obj) const
{
if(options.useTeleportOneWayRandom && isTeleportChannelUnidirectional(obj->channel, hero->tempOwner))
{
auto passableExits = CGTeleport::getPassableExits(gs, hero, getTeleportChannelExits(obj->channel, hero->tempOwner));
if(passableExits.size() > 1)
return true;
}
return false;
}
bool CPathfinderHelper::addTeleportWhirlpool(const CGWhirlpool * obj) const
{
return options.useTeleportWhirlpool && (whirlpoolProtection || options.forceUseTeleportWhirlpool) && obj;
}
int CPathfinderHelper::movementPointsAfterEmbark(int movement, int basicCost, bool disembark) const
{
return hero->movementPointsAfterEmbark(movement, basicCost, disembark, getTurnInfo());
}
bool CPathfinderHelper::passOneTurnLimitCheck(const PathNodeInfo & source) const
{
if(!options.oneTurnSpecialLayersLimit)
return true;
if(source.node->layer == EPathfindingLayer::WATER)
return false;
if(source.node->layer == EPathfindingLayer::AIR)
{
return options.originalFlyRules && source.node->accessible == EPathAccessibility::ACCESSIBLE;
}
return true;
}
int CPathfinderHelper::getGuardiansCount(int3 tile) const
{
return getGuardingCreatures(tile).size();
}
CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options):
CGameInfoCallback(gs),
turn(-1),
hero(Hero),
options(Options),
owner(Hero->tempOwner)
{
turnsInfo.reserve(16);
updateTurnInfo();
initializePatrol();
whirlpoolProtection = Hero->hasBonusOfType(BonusType::WHIRLPOOL_PROTECTION);
SpellID flySpell = SpellID::FLY;
canCastFly = Hero->canCastThisSpell(flySpell.toSpell());
SpellID waterWalk = SpellID::WATER_WALK;
canCastWaterWalk = Hero->canCastThisSpell(waterWalk.toSpell());
}
CPathfinderHelper::~CPathfinderHelper() = default;
void CPathfinderHelper::updateTurnInfo(const int Turn)
{
if(turn != Turn)
{
turn = Turn;
if(turn >= turnsInfo.size())
turnsInfo.push_back(hero->getTurnInfo(turn));
}
}
bool CPathfinderHelper::isLayerAvailable(const EPathfindingLayer & layer) const
{
switch(layer.toEnum())
{
case EPathfindingLayer::AIR:
if(!options.useFlying)
return false;
if(canCastFly && options.canUseCast)
return true;
break;
case EPathfindingLayer::WATER:
if(!options.useWaterWalking)
return false;
if(canCastWaterWalk && options.canUseCast)
return true;
break;
}
return turnsInfo[turn]->isLayerAvailable(layer);
}
const TurnInfo * CPathfinderHelper::getTurnInfo() const
{
return turnsInfo[turn].get();
}
int CPathfinderHelper::getMaxMovePoints(const EPathfindingLayer & layer) const
{
return turnsInfo[turn]->getMaxMovePoints(layer);
}
void CPathfinderHelper::getNeighbours(
const TerrainTile & sourceTile,
const int3 & srcCoord,
NeighbourTilesVector & vec,
const boost::logic::tribool & onLand,
const bool limitCoastSailing) const
{
CMap * map = gs->map;
const TerrainType * sourceTerrain = sourceTile.getTerrain();
static constexpr std::array dirs = {
int3(-1, +1, +0), int3(0, +1, +0), int3(+1, +1, +0),
int3(-1, +0, +0), /* source pos */ int3(+1, +0, +0),
int3(-1, -1, +0), int3(0, -1, +0), int3(+1, -1, +0)
};
for(const auto & dir : dirs)
{
const int3 destCoord = srcCoord + dir;
if(!map->isInTheMap(destCoord))
continue;
const TerrainTile & destTile = map->getTile(destCoord);
const TerrainType * destTerrain = destTile.getTerrain();
if(!destTerrain->isPassable())
continue;
/// Following condition let us avoid diagonal movement over coast when sailing
if(sourceTerrain->isWater() && limitCoastSailing && destTerrain->isWater() && dir.x && dir.y) //diagonal move through water
{
const int3 horizontalNeighbour = srcCoord + int3{dir.x, 0, 0};
const int3 verticalNeighbour = srcCoord + int3{0, dir.y, 0};
if(map->getTile(horizontalNeighbour).isLand() || map->getTile(verticalNeighbour).isLand())
continue;
}
if(indeterminate(onLand) || onLand == destTerrain->isLand())
{
vec.push_back(destCoord);
}
}
}
int CPathfinderHelper::getMovementCost(
const PathNodeInfo & src,
const PathNodeInfo & dst,
const int remainingMovePoints,
const bool checkLast) const
{
return getMovementCost(
src.coord,
dst.coord,
src.tile,
dst.tile,
remainingMovePoints,
checkLast,
dst.node->layer == EPathfindingLayer::SAIL,
dst.node->layer == EPathfindingLayer::WATER
);
}
int CPathfinderHelper::getMovementCost(
const int3 & src,
const int3 & dst,
const TerrainTile * ct,
const TerrainTile * dt,
const int remainingMovePoints,
const bool checkLast,
boost::logic::tribool isDstSailLayer,
boost::logic::tribool isDstWaterLayer) const
{
if(src == dst) //same tile
return 0;
const auto * ti = getTurnInfo();
if(ct == nullptr || dt == nullptr)
{
ct = hero->cb->getTile(src);
dt = hero->cb->getTile(dst);
}
bool isSailLayer;
if(indeterminate(isDstSailLayer))
isSailLayer = hero->boat && hero->boat->layer == EPathfindingLayer::SAIL && dt->isWater();
else
isSailLayer = static_cast<bool>(isDstSailLayer);
bool isWaterLayer;
if(indeterminate(isDstWaterLayer))
isWaterLayer = ((hero->boat && hero->boat->layer == EPathfindingLayer::WATER) || ti->hasWaterWalking()) && dt->isWater();
else
isWaterLayer = static_cast<bool>(isDstWaterLayer);
bool isAirLayer = (hero->boat && hero->boat->layer == EPathfindingLayer::AIR) || ti->hasFlyingMovement();
int movementCost = hero->getTileMovementCost(*dt, *ct, ti);
if(isSailLayer)
{
if(ct->hasFavorableWinds())
movementCost = static_cast<int>(movementCost * 2.0 / 3);
}
else if(isAirLayer)
vstd::amin(movementCost, GameConstants::BASE_MOVEMENT_COST + ti->getFlyingMovementValue());
else if(isWaterLayer && ti->hasWaterWalking())
movementCost = static_cast<int>(movementCost * (100.0 + ti->getWaterWalkingValue()) / 100.0);
if(src.x != dst.x && src.y != dst.y) //it's diagonal move
{
int old = movementCost;
movementCost = static_cast<int>(movementCost * M_SQRT2);
//diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
// https://heroes.thelazy.net/index.php/Movement#Diagonal_move_exception
if(movementCost > remainingMovePoints && remainingMovePoints >= old)
{
return remainingMovePoints;
}
}
//it might be the last tile - if no further move possible we take all move points
const int pointsLeft = remainingMovePoints - movementCost;
if(checkLast && pointsLeft > 0)
{
int minimalNextMoveCost = hero->getTileMovementCost(*dt, *ct, ti);
if (pointsLeft < minimalNextMoveCost)
return remainingMovePoints;
}
return movementCost;
}
VCMI_LIB_NAMESPACE_END
|