mirror of
https://github.com/vcmi/vcmi.git
synced 2025-09-16 09:26:28 +02:00
Merge pull request #2585 from vcmi/battle-damage-cache
Battle damage cache
This commit is contained in:
@@ -18,17 +18,98 @@ uint64_t averageDmg(const DamageRange & range)
|
||||
return (range.min + range.max) / 2;
|
||||
}
|
||||
|
||||
void DamageCache::cacheDamage(const battle::Unit * attacker, const battle::Unit * defender, std::shared_ptr<CBattleInfoCallback> hb)
|
||||
{
|
||||
auto damage = averageDmg(hb->battleEstimateDamage(attacker, defender, 0).damage);
|
||||
|
||||
damageCache[attacker->unitId()][defender->unitId()] = static_cast<float>(damage) / attacker->getCount();
|
||||
}
|
||||
|
||||
|
||||
void DamageCache::buildDamageCache(std::shared_ptr<HypotheticBattle> hb, int side)
|
||||
{
|
||||
auto stacks = hb->battleGetUnitsIf([=](const battle::Unit * u) -> bool
|
||||
{
|
||||
return true;
|
||||
});
|
||||
|
||||
std::vector<const battle::Unit *> ourUnits, enemyUnits;
|
||||
|
||||
for(auto stack : stacks)
|
||||
{
|
||||
if(stack->unitSide() == side)
|
||||
ourUnits.push_back(stack);
|
||||
else
|
||||
enemyUnits.push_back(stack);
|
||||
}
|
||||
|
||||
for(auto ourUnit : ourUnits)
|
||||
{
|
||||
if(!ourUnit->alive())
|
||||
continue;
|
||||
|
||||
for(auto enemyUnit : enemyUnits)
|
||||
{
|
||||
if(enemyUnit->alive())
|
||||
{
|
||||
cacheDamage(ourUnit, enemyUnit, hb);
|
||||
cacheDamage(enemyUnit, ourUnit, hb);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int64_t DamageCache::getDamage(const battle::Unit * attacker, const battle::Unit * defender, std::shared_ptr<CBattleInfoCallback> hb)
|
||||
{
|
||||
auto damage = damageCache[attacker->unitId()][defender->unitId()] * attacker->getCount();
|
||||
|
||||
if(damage == 0)
|
||||
{
|
||||
cacheDamage(attacker, defender, hb);
|
||||
|
||||
damage = damageCache[attacker->unitId()][defender->unitId()] * attacker->getCount();
|
||||
}
|
||||
|
||||
return static_cast<int64_t>(damage);
|
||||
}
|
||||
|
||||
int64_t DamageCache::getOriginalDamage(const battle::Unit * attacker, const battle::Unit * defender, std::shared_ptr<CBattleInfoCallback> hb)
|
||||
{
|
||||
if(parent)
|
||||
{
|
||||
auto attackerDamageMap = parent->damageCache.find(attacker->unitId());
|
||||
|
||||
if(attackerDamageMap != parent->damageCache.end())
|
||||
{
|
||||
auto targetDamage = attackerDamageMap->second.find(defender->unitId());
|
||||
|
||||
if(targetDamage != attackerDamageMap->second.end())
|
||||
{
|
||||
return static_cast<int64_t>(targetDamage->second * attacker->getCount());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return getDamage(attacker, defender, hb);
|
||||
}
|
||||
|
||||
AttackPossibility::AttackPossibility(BattleHex from, BattleHex dest, const BattleAttackInfo & attack)
|
||||
: from(from), dest(dest), attack(attack)
|
||||
{
|
||||
}
|
||||
|
||||
int64_t AttackPossibility::damageDiff() const
|
||||
float AttackPossibility::damageDiff() const
|
||||
{
|
||||
return defenderDamageReduce - attackerDamageReduce - collateralDamageReduce + shootersBlockedDmg;
|
||||
}
|
||||
|
||||
int64_t AttackPossibility::attackValue() const
|
||||
float AttackPossibility::damageDiff(float positiveEffectMultiplier, float negativeEffectMultiplier) const
|
||||
{
|
||||
return positiveEffectMultiplier * (defenderDamageReduce + shootersBlockedDmg)
|
||||
- negativeEffectMultiplier * (attackerDamageReduce + collateralDamageReduce);
|
||||
}
|
||||
|
||||
float AttackPossibility::attackValue() const
|
||||
{
|
||||
return damageDiff();
|
||||
}
|
||||
@@ -38,25 +119,28 @@ int64_t AttackPossibility::attackValue() const
|
||||
/// Half bounty for kill, half for making damage equal to enemy health
|
||||
/// Bounty - the killed creature average damage calculated against attacker
|
||||
/// </summary>
|
||||
int64_t AttackPossibility::calculateDamageReduce(
|
||||
float AttackPossibility::calculateDamageReduce(
|
||||
const battle::Unit * attacker,
|
||||
const battle::Unit * defender,
|
||||
uint64_t damageDealt,
|
||||
const CBattleInfoCallback & cb)
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<CBattleInfoCallback> state)
|
||||
{
|
||||
const float HEALTH_BOUNTY = 0.5;
|
||||
const float KILL_BOUNTY = 1.0 - HEALTH_BOUNTY;
|
||||
|
||||
vstd::amin(damageDealt, defender->getAvailableHealth());
|
||||
|
||||
// FIXME: provide distance info for Jousting bonus
|
||||
auto attackerUnitForMeasurement = attacker;
|
||||
|
||||
if(attackerUnitForMeasurement->isTurret())
|
||||
if(!attackerUnitForMeasurement || attackerUnitForMeasurement->isTurret())
|
||||
{
|
||||
auto ourUnits = cb.battleGetUnitsIf([&](const battle::Unit * u) -> bool
|
||||
auto ourUnits = state->battleGetUnitsIf([&](const battle::Unit * u) -> bool
|
||||
{
|
||||
return u->unitSide() == attacker->unitSide() && !u->isTurret();
|
||||
return u->unitSide() != defender->unitSide()
|
||||
&& !u->isTurret()
|
||||
&& u->creatureId() != CreatureID::CATAPULT
|
||||
&& u->creatureId() != CreatureID::BALLISTA
|
||||
&& u->creatureId() != CreatureID::FIRST_AID_TENT
|
||||
&& u->getCount();
|
||||
});
|
||||
|
||||
if(ourUnits.empty())
|
||||
@@ -65,15 +149,28 @@ int64_t AttackPossibility::calculateDamageReduce(
|
||||
attackerUnitForMeasurement = ourUnits.front();
|
||||
}
|
||||
|
||||
auto enemyDamageBeforeAttack = cb.battleEstimateDamage(defender, attackerUnitForMeasurement, 0);
|
||||
auto enemiesKilled = damageDealt / defender->getMaxHealth() + (damageDealt % defender->getMaxHealth() >= defender->getFirstHPleft() ? 1 : 0);
|
||||
auto enemyDamage = averageDmg(enemyDamageBeforeAttack.damage);
|
||||
auto damagePerEnemy = enemyDamage / (double)defender->getCount();
|
||||
auto maxHealth = defender->getMaxHealth();
|
||||
auto availableHealth = defender->getFirstHPleft() + ((defender->getCount() - 1) * maxHealth);
|
||||
|
||||
return (int64_t)(damagePerEnemy * (enemiesKilled * KILL_BOUNTY + damageDealt * HEALTH_BOUNTY / (double)defender->getMaxHealth()));
|
||||
vstd::amin(damageDealt, availableHealth);
|
||||
|
||||
auto enemyDamageBeforeAttack = damageCache.getOriginalDamage(defender, attackerUnitForMeasurement, state);
|
||||
auto enemiesKilled = damageDealt / maxHealth + (damageDealt % maxHealth >= defender->getFirstHPleft() ? 1 : 0);
|
||||
auto damagePerEnemy = enemyDamageBeforeAttack / (double)defender->getCount();
|
||||
|
||||
// lets use cached maxHealth here instead of getAvailableHealth
|
||||
auto firstUnitHpLeft = (availableHealth - damageDealt) % maxHealth;
|
||||
auto firstUnitHealthRatio = firstUnitHpLeft == 0 ? 1 : static_cast<float>(firstUnitHpLeft) / maxHealth;
|
||||
auto firstUnitKillValue = (1 - firstUnitHealthRatio) * (1 - firstUnitHealthRatio);
|
||||
|
||||
return damagePerEnemy * (enemiesKilled + firstUnitKillValue * HEALTH_BOUNTY);
|
||||
}
|
||||
|
||||
int64_t AttackPossibility::evaluateBlockedShootersDmg(const BattleAttackInfo & attackInfo, BattleHex hex, const HypotheticBattle & state)
|
||||
int64_t AttackPossibility::evaluateBlockedShootersDmg(
|
||||
const BattleAttackInfo & attackInfo,
|
||||
BattleHex hex,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<CBattleInfoCallback> state)
|
||||
{
|
||||
int64_t res = 0;
|
||||
|
||||
@@ -84,10 +181,10 @@ int64_t AttackPossibility::evaluateBlockedShootersDmg(const BattleAttackInfo & a
|
||||
auto hexes = attacker->getSurroundingHexes(hex);
|
||||
for(BattleHex tile : hexes)
|
||||
{
|
||||
auto st = state.battleGetUnitByPos(tile, true);
|
||||
if(!st || !state.battleMatchOwner(st, attacker))
|
||||
auto st = state->battleGetUnitByPos(tile, true);
|
||||
if(!st || !state->battleMatchOwner(st, attacker))
|
||||
continue;
|
||||
if(!state.battleCanShoot(st))
|
||||
if(!state->battleCanShoot(st))
|
||||
continue;
|
||||
|
||||
// FIXME: provide distance info for Jousting bonus
|
||||
@@ -97,8 +194,8 @@ int64_t AttackPossibility::evaluateBlockedShootersDmg(const BattleAttackInfo & a
|
||||
BattleAttackInfo meleeAttackInfo(st, attacker, 0, false);
|
||||
meleeAttackInfo.defenderPos = hex;
|
||||
|
||||
auto rangeDmg = state.battleEstimateDamage(rangeAttackInfo);
|
||||
auto meleeDmg = state.battleEstimateDamage(meleeAttackInfo);
|
||||
auto rangeDmg = state->battleEstimateDamage(rangeAttackInfo);
|
||||
auto meleeDmg = state->battleEstimateDamage(meleeAttackInfo);
|
||||
|
||||
int64_t gain = averageDmg(rangeDmg.damage) - averageDmg(meleeDmg.damage) + 1;
|
||||
res += gain;
|
||||
@@ -107,13 +204,17 @@ int64_t AttackPossibility::evaluateBlockedShootersDmg(const BattleAttackInfo & a
|
||||
return res;
|
||||
}
|
||||
|
||||
AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo & attackInfo, BattleHex hex, const HypotheticBattle & state)
|
||||
AttackPossibility AttackPossibility::evaluate(
|
||||
const BattleAttackInfo & attackInfo,
|
||||
BattleHex hex,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<CBattleInfoCallback> state)
|
||||
{
|
||||
auto attacker = attackInfo.attacker;
|
||||
auto defender = attackInfo.defender;
|
||||
const std::string cachingStringBlocksRetaliation = "type_BLOCKS_RETALIATION";
|
||||
static const auto selectorBlocksRetaliation = Selector::type()(BonusType::BLOCKS_RETALIATION);
|
||||
const auto attackerSide = state.playerToSide(state.battleGetOwner(attacker));
|
||||
const auto attackerSide = state->playerToSide(state->battleGetOwner(attacker));
|
||||
const bool counterAttacksBlocked = attacker->hasBonus(selectorBlocksRetaliation, cachingStringBlocksRetaliation);
|
||||
|
||||
AttackPossibility bestAp(hex, BattleHex::INVALID, attackInfo);
|
||||
@@ -141,9 +242,9 @@ AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo & attackInf
|
||||
std::vector<const battle::Unit*> units;
|
||||
|
||||
if (attackInfo.shooting)
|
||||
units = state.getAttackedBattleUnits(attacker, defHex, true, BattleHex::INVALID);
|
||||
units = state->getAttackedBattleUnits(attacker, defHex, true, BattleHex::INVALID);
|
||||
else
|
||||
units = state.getAttackedBattleUnits(attacker, defHex, false, hex);
|
||||
units = state->getAttackedBattleUnits(attacker, defHex, false, hex);
|
||||
|
||||
// ensure the defender is also affected
|
||||
bool addDefender = true;
|
||||
@@ -169,10 +270,11 @@ AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo & attackInf
|
||||
|
||||
for(int i = 0; i < totalAttacks; i++)
|
||||
{
|
||||
int64_t damageDealt, damageReceived, defenderDamageReduce, attackerDamageReduce;
|
||||
int64_t damageDealt, damageReceived;
|
||||
float defenderDamageReduce, attackerDamageReduce;
|
||||
|
||||
DamageEstimation retaliation;
|
||||
auto attackDmg = state.battleEstimateDamage(ap.attack, &retaliation);
|
||||
auto attackDmg = state->battleEstimateDamage(ap.attack, &retaliation);
|
||||
|
||||
vstd::amin(attackDmg.damage.min, defenderState->getAvailableHealth());
|
||||
vstd::amin(attackDmg.damage.max, defenderState->getAvailableHealth());
|
||||
@@ -181,7 +283,7 @@ AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo & attackInf
|
||||
vstd::amin(retaliation.damage.max, ap.attackerState->getAvailableHealth());
|
||||
|
||||
damageDealt = averageDmg(attackDmg.damage);
|
||||
defenderDamageReduce = calculateDamageReduce(attacker, defender, damageDealt, state);
|
||||
defenderDamageReduce = calculateDamageReduce(attacker, defender, damageDealt, damageCache, state);
|
||||
ap.attackerState->afterAttack(attackInfo.shooting, false);
|
||||
|
||||
//FIXME: use ranged retaliation
|
||||
@@ -191,11 +293,11 @@ AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo & attackInf
|
||||
if (!attackInfo.shooting && defenderState->ableToRetaliate() && !counterAttacksBlocked)
|
||||
{
|
||||
damageReceived = averageDmg(retaliation.damage);
|
||||
attackerDamageReduce = calculateDamageReduce(defender, attacker, damageReceived, state);
|
||||
attackerDamageReduce = calculateDamageReduce(defender, attacker, damageReceived, damageCache, state);
|
||||
defenderState->afterAttack(attackInfo.shooting, true);
|
||||
}
|
||||
|
||||
bool isEnemy = state.battleMatchOwner(attacker, u);
|
||||
bool isEnemy = state->battleMatchOwner(attacker, u);
|
||||
|
||||
// this includes enemy units as well as attacker units under enemy's mind control
|
||||
if(isEnemy)
|
||||
@@ -225,7 +327,7 @@ AttackPossibility AttackPossibility::evaluate(const BattleAttackInfo & attackInf
|
||||
}
|
||||
|
||||
// check how much damage we gain from blocking enemy shooters on this hex
|
||||
bestAp.shootersBlockedDmg = evaluateBlockedShootersDmg(attackInfo, hex, state);
|
||||
bestAp.shootersBlockedDmg = evaluateBlockedShootersDmg(attackInfo, hex, damageCache, state);
|
||||
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace("BattleAI best AP: %s -> %s at %d from %d, affects %d units: d:%lld a:%lld c:%lld s:%lld",
|
||||
|
@@ -15,6 +15,22 @@
|
||||
|
||||
#define BATTLE_TRACE_LEVEL 0
|
||||
|
||||
class DamageCache
|
||||
{
|
||||
private:
|
||||
std::unordered_map<uint32_t, std::unordered_map<uint32_t, float>> damageCache;
|
||||
DamageCache * parent;
|
||||
|
||||
public:
|
||||
DamageCache() : parent(nullptr) {}
|
||||
DamageCache(DamageCache * parent) : parent(parent) {}
|
||||
|
||||
void cacheDamage(const battle::Unit * attacker, const battle::Unit * defender, std::shared_ptr<CBattleInfoCallback> hb);
|
||||
int64_t getDamage(const battle::Unit * attacker, const battle::Unit * defender, std::shared_ptr<CBattleInfoCallback> hb);
|
||||
int64_t getOriginalDamage(const battle::Unit * attacker, const battle::Unit * defender, std::shared_ptr<CBattleInfoCallback> hb);
|
||||
void buildDamageCache(std::shared_ptr<HypotheticBattle> hb, int side);
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Evaluate attack value of one particular attack taking into account various effects like
|
||||
/// retaliation, 2-hex breath, collateral damage, shooters blocked damage
|
||||
@@ -30,24 +46,34 @@ public:
|
||||
|
||||
std::vector<std::shared_ptr<battle::CUnitState>> affectedUnits;
|
||||
|
||||
int64_t defenderDamageReduce = 0;
|
||||
int64_t attackerDamageReduce = 0; //usually by counter-attack
|
||||
int64_t collateralDamageReduce = 0; // friendly fire (usually by two-hex attacks)
|
||||
float defenderDamageReduce = 0;
|
||||
float attackerDamageReduce = 0; //usually by counter-attack
|
||||
float collateralDamageReduce = 0; // friendly fire (usually by two-hex attacks)
|
||||
int64_t shootersBlockedDmg = 0;
|
||||
|
||||
AttackPossibility(BattleHex from, BattleHex dest, const BattleAttackInfo & attack_);
|
||||
|
||||
int64_t damageDiff() const;
|
||||
int64_t attackValue() const;
|
||||
float damageDiff() const;
|
||||
float attackValue() const;
|
||||
float damageDiff(float positiveEffectMultiplier, float negativeEffectMultiplier) const;
|
||||
|
||||
static AttackPossibility evaluate(const BattleAttackInfo & attackInfo, BattleHex hex, const HypotheticBattle & state);
|
||||
static AttackPossibility evaluate(
|
||||
const BattleAttackInfo & attackInfo,
|
||||
BattleHex hex,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<CBattleInfoCallback> state);
|
||||
|
||||
static int64_t calculateDamageReduce(
|
||||
static float calculateDamageReduce(
|
||||
const battle::Unit * attacker,
|
||||
const battle::Unit * defender,
|
||||
uint64_t damageDealt,
|
||||
const CBattleInfoCallback & cb);
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<CBattleInfoCallback> cb);
|
||||
|
||||
private:
|
||||
static int64_t evaluateBlockedShootersDmg(const BattleAttackInfo & attackInfo, BattleHex hex, const HypotheticBattle & state);
|
||||
static int64_t evaluateBlockedShootersDmg(
|
||||
const BattleAttackInfo & attackInfo,
|
||||
BattleHex hex,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<CBattleInfoCallback> state);
|
||||
};
|
||||
|
@@ -9,10 +9,12 @@
|
||||
*/
|
||||
#include "StdInc.h"
|
||||
#include "BattleAI.h"
|
||||
#include "BattleEvaluator.h"
|
||||
#include "BattleExchangeVariant.h"
|
||||
|
||||
#include "StackWithBonuses.h"
|
||||
#include "EnemyInfo.h"
|
||||
#include "tbb/parallel_for.h"
|
||||
#include "../../lib/CStopWatch.h"
|
||||
#include "../../lib/CThreadHelper.h"
|
||||
#include "../../lib/mapObjects/CGTownInstance.h"
|
||||
@@ -28,42 +30,6 @@
|
||||
#define LOGL(text) print(text)
|
||||
#define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
|
||||
|
||||
enum class SpellTypes
|
||||
{
|
||||
ADVENTURE, BATTLE, OTHER
|
||||
};
|
||||
|
||||
SpellTypes spellType(const CSpell * spell)
|
||||
{
|
||||
if(!spell->isCombat() || spell->isCreatureAbility())
|
||||
return SpellTypes::OTHER;
|
||||
|
||||
if(spell->isOffensive() || spell->hasEffects() || spell->hasBattleEffects())
|
||||
return SpellTypes::BATTLE;
|
||||
|
||||
return SpellTypes::OTHER;
|
||||
}
|
||||
|
||||
std::vector<BattleHex> CBattleAI::getBrokenWallMoatHexes() const
|
||||
{
|
||||
std::vector<BattleHex> result;
|
||||
|
||||
for(EWallPart wallPart : { EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL })
|
||||
{
|
||||
auto state = cb->battleGetWallState(wallPart);
|
||||
|
||||
if(state != EWallState::DESTROYED)
|
||||
continue;
|
||||
|
||||
auto wallHex = cb->wallPartToBattleHex((EWallPart)wallPart);
|
||||
auto moatHex = wallHex.cloneInDirection(BattleHex::LEFT);
|
||||
|
||||
result.push_back(moatHex);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
CBattleAI::CBattleAI()
|
||||
: side(-1),
|
||||
wasWaitingForRealize(false),
|
||||
@@ -110,162 +76,43 @@ BattleAction CBattleAI::useHealingTent(const CStack *stack)
|
||||
return BattleAction::makeHeal(stack, woundHpToStack.rbegin()->second); //last element of the woundHpToStack is the most wounded stack
|
||||
}
|
||||
|
||||
std::optional<PossibleSpellcast> CBattleAI::findBestCreatureSpell(const CStack *stack)
|
||||
{
|
||||
//TODO: faerie dragon type spell should be selected by server
|
||||
SpellID creatureSpellToCast = cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), stack, CBattleInfoCallback::RANDOM_AIMED);
|
||||
if(stack->hasBonusOfType(BonusType::SPELLCASTER) && stack->canCast() && creatureSpellToCast != SpellID::NONE)
|
||||
{
|
||||
const CSpell * spell = creatureSpellToCast.toSpell();
|
||||
|
||||
if(spell->canBeCast(getCbc().get(), spells::Mode::CREATURE_ACTIVE, stack))
|
||||
{
|
||||
std::vector<PossibleSpellcast> possibleCasts;
|
||||
spells::BattleCast temp(getCbc().get(), stack, spells::Mode::CREATURE_ACTIVE, spell);
|
||||
for(auto & target : temp.findPotentialTargets())
|
||||
{
|
||||
PossibleSpellcast ps;
|
||||
ps.dest = target;
|
||||
ps.spell = spell;
|
||||
evaluateCreatureSpellcast(stack, ps);
|
||||
possibleCasts.push_back(ps);
|
||||
}
|
||||
|
||||
std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; });
|
||||
if(!possibleCasts.empty() && possibleCasts.front().value > 0)
|
||||
{
|
||||
return possibleCasts.front();
|
||||
}
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
BattleAction CBattleAI::selectStackAction(const CStack * stack)
|
||||
{
|
||||
//evaluate casting spell for spellcasting stack
|
||||
std::optional<PossibleSpellcast> bestSpellcast = findBestCreatureSpell(stack);
|
||||
|
||||
HypotheticBattle hb(env.get(), cb);
|
||||
|
||||
PotentialTargets targets(stack, hb);
|
||||
BattleExchangeEvaluator scoreEvaluator(cb, env);
|
||||
auto moveTarget = scoreEvaluator.findMoveTowardsUnreachable(stack, targets, hb);
|
||||
|
||||
int64_t score = EvaluationResult::INEFFECTIVE_SCORE;
|
||||
|
||||
|
||||
if(targets.possibleAttacks.empty() && bestSpellcast.has_value())
|
||||
{
|
||||
movesSkippedByDefense = 0;
|
||||
return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
|
||||
}
|
||||
|
||||
if(!targets.possibleAttacks.empty())
|
||||
{
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace("Evaluating attack for %s", stack->getDescription());
|
||||
#endif
|
||||
|
||||
auto evaluationResult = scoreEvaluator.findBestTarget(stack, targets, hb);
|
||||
auto & bestAttack = evaluationResult.bestAttack;
|
||||
|
||||
//TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc.
|
||||
if(bestSpellcast.has_value() && bestSpellcast->value > bestAttack.damageDiff())
|
||||
{
|
||||
// return because spellcast value is damage dealt and score is dps reduce
|
||||
movesSkippedByDefense = 0;
|
||||
return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
|
||||
}
|
||||
|
||||
if(evaluationResult.score > score)
|
||||
{
|
||||
score = evaluationResult.score;
|
||||
|
||||
logAi->debug("BattleAI: %s -> %s x %d, from %d curpos %d dist %d speed %d: +%lld -%lld = %lld",
|
||||
bestAttack.attackerState->unitType()->getJsonKey(),
|
||||
bestAttack.affectedUnits[0]->unitType()->getJsonKey(),
|
||||
(int)bestAttack.affectedUnits[0]->getCount(),
|
||||
(int)bestAttack.from,
|
||||
(int)bestAttack.attack.attacker->getPosition().hex,
|
||||
bestAttack.attack.chargeDistance,
|
||||
bestAttack.attack.attacker->speed(0, true),
|
||||
bestAttack.defenderDamageReduce,
|
||||
bestAttack.attackerDamageReduce, bestAttack.attackValue()
|
||||
);
|
||||
|
||||
if (moveTarget.score <= score)
|
||||
{
|
||||
if(evaluationResult.wait)
|
||||
{
|
||||
return BattleAction::makeWait(stack);
|
||||
}
|
||||
else if(bestAttack.attack.shooting)
|
||||
{
|
||||
movesSkippedByDefense = 0;
|
||||
return BattleAction::makeShotAttack(stack, bestAttack.attack.defender);
|
||||
}
|
||||
else
|
||||
{
|
||||
movesSkippedByDefense = 0;
|
||||
return BattleAction::makeMeleeAttack(stack, bestAttack.attack.defender->getPosition(), bestAttack.from);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
|
||||
if(moveTarget.score > score)
|
||||
{
|
||||
score = moveTarget.score;
|
||||
|
||||
if(stack->waited())
|
||||
{
|
||||
return goTowardsNearest(stack, moveTarget.positions);
|
||||
}
|
||||
else
|
||||
{
|
||||
return BattleAction::makeWait(stack);
|
||||
}
|
||||
}
|
||||
|
||||
if(score <= EvaluationResult::INEFFECTIVE_SCORE
|
||||
&& !stack->hasBonusOfType(BonusType::FLYING)
|
||||
&& stack->unitSide() == BattleSide::ATTACKER
|
||||
&& cb->battleGetSiegeLevel() >= CGTownInstance::CITADEL)
|
||||
{
|
||||
auto brokenWallMoat = getBrokenWallMoatHexes();
|
||||
|
||||
if(brokenWallMoat.size())
|
||||
{
|
||||
movesSkippedByDefense = 0;
|
||||
|
||||
if(stack->doubleWide() && vstd::contains(brokenWallMoat, stack->getPosition()))
|
||||
return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT));
|
||||
else
|
||||
return goTowardsNearest(stack, brokenWallMoat);
|
||||
}
|
||||
}
|
||||
|
||||
return BattleAction::makeDefend(stack);
|
||||
}
|
||||
|
||||
void CBattleAI::yourTacticPhase(int distance)
|
||||
{
|
||||
cb->battleMakeTacticAction(BattleAction::makeEndOFTacticPhase(cb->battleGetTacticsSide()));
|
||||
}
|
||||
|
||||
uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
|
||||
float getStrengthRatio(std::shared_ptr<CBattleCallback> cb, int side)
|
||||
{
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
auto stacks = cb->battleGetAllStacks();
|
||||
auto our = 0, enemy = 0;
|
||||
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
|
||||
for(auto stack : stacks)
|
||||
{
|
||||
auto creature = stack->creatureId().toCreature();
|
||||
|
||||
if(!creature)
|
||||
continue;
|
||||
|
||||
if(stack->unitSide() == side)
|
||||
our += stack->getCount() * creature->getAIValue();
|
||||
else
|
||||
enemy += stack->getCount() * creature->getAIValue();
|
||||
}
|
||||
|
||||
return enemy == 0 ? 1.0f : static_cast<float>(our) / enemy;
|
||||
}
|
||||
|
||||
void CBattleAI::activeStack( const CStack * stack )
|
||||
void CBattleAI::activeStack(const CStack * stack )
|
||||
{
|
||||
LOG_TRACE_PARAMS(logAi, "stack: %s", stack->nodeName());
|
||||
|
||||
auto timeElapsed = [](std::chrono::time_point<std::chrono::high_resolution_clock> start) -> uint64_t
|
||||
{
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
|
||||
};
|
||||
|
||||
BattleAction result = BattleAction::makeDefend(stack);
|
||||
setCbc(cb); //TODO: make solid sure that AIs always use their callbacks (need to take care of event handlers too)
|
||||
|
||||
@@ -284,8 +131,23 @@ void CBattleAI::activeStack( const CStack * stack )
|
||||
return;
|
||||
}
|
||||
|
||||
if (attemptCastingSpell())
|
||||
return;
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace("Build evaluator and targets");
|
||||
#endif
|
||||
|
||||
BattleEvaluator evaluator(env, cb, stack, playerID, side, getStrengthRatio(cb, side));
|
||||
|
||||
result = evaluator.selectStackAction(stack);
|
||||
|
||||
if(!skipCastUntilNextBattle && evaluator.canCastSpell())
|
||||
{
|
||||
auto spelCasted = evaluator.attemptCastingSpell(stack);
|
||||
|
||||
if(spelCasted)
|
||||
return;
|
||||
|
||||
skipCastUntilNextBattle = true;
|
||||
}
|
||||
|
||||
logAi->trace("Spellcast attempt completed in %lld", timeElapsed(start));
|
||||
|
||||
@@ -294,8 +156,6 @@ void CBattleAI::activeStack( const CStack * stack )
|
||||
cb->battleMakeUnitAction(*action);
|
||||
return;
|
||||
}
|
||||
|
||||
result = selectStackAction(stack);
|
||||
}
|
||||
catch(boost::thread_interrupted &)
|
||||
{
|
||||
@@ -320,106 +180,6 @@ void CBattleAI::activeStack( const CStack * stack )
|
||||
cb->battleMakeUnitAction(result);
|
||||
}
|
||||
|
||||
BattleAction CBattleAI::goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes) const
|
||||
{
|
||||
auto reachability = cb->getReachability(stack);
|
||||
auto avHexes = cb->battleGetAvailableHexes(reachability, stack, false);
|
||||
|
||||
if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
|
||||
{
|
||||
return BattleAction::makeDefend(stack);
|
||||
}
|
||||
|
||||
std::sort(hexes.begin(), hexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
|
||||
{
|
||||
return reachability.distances[h1] < reachability.distances[h2];
|
||||
});
|
||||
|
||||
for(auto hex : hexes)
|
||||
{
|
||||
if(vstd::contains(avHexes, hex))
|
||||
{
|
||||
return BattleAction::makeMove(stack, hex);
|
||||
}
|
||||
|
||||
if(stack->coversPos(hex))
|
||||
{
|
||||
logAi->warn("Warning: already standing on neighbouring tile!");
|
||||
//We shouldn't even be here...
|
||||
return BattleAction::makeDefend(stack);
|
||||
}
|
||||
}
|
||||
|
||||
BattleHex bestNeighbor = hexes.front();
|
||||
|
||||
if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
|
||||
{
|
||||
return BattleAction::makeDefend(stack);
|
||||
}
|
||||
|
||||
BattleExchangeEvaluator scoreEvaluator(cb, env);
|
||||
HypotheticBattle hb(env.get(), cb);
|
||||
|
||||
scoreEvaluator.updateReachabilityMap(hb);
|
||||
|
||||
if(stack->hasBonusOfType(BonusType::FLYING))
|
||||
{
|
||||
std::set<BattleHex> obstacleHexes;
|
||||
|
||||
auto insertAffected = [](const CObstacleInstance & spellObst, std::set<BattleHex> obstacleHexes) {
|
||||
auto affectedHexes = spellObst.getAffectedTiles();
|
||||
obstacleHexes.insert(affectedHexes.cbegin(), affectedHexes.cend());
|
||||
};
|
||||
|
||||
const auto & obstacles = hb.battleGetAllObstacles();
|
||||
|
||||
for (const auto & obst: obstacles) {
|
||||
|
||||
if(obst->triggersEffects())
|
||||
{
|
||||
auto triggerAbility = VLC->spells()->getById(obst->getTrigger());
|
||||
auto triggerIsNegative = triggerAbility->isNegative() || triggerAbility->isDamage();
|
||||
|
||||
if(triggerIsNegative)
|
||||
insertAffected(*obst, obstacleHexes);
|
||||
}
|
||||
}
|
||||
// Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
|
||||
// We just check all available hexes and pick the one closest to the target.
|
||||
auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
|
||||
{
|
||||
const int NEGATIVE_OBSTACLE_PENALTY = 100; // avoid landing on negative obstacle (moat, fire wall, etc)
|
||||
const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
|
||||
|
||||
auto distance = BattleHex::getDistance(bestNeighbor, hex);
|
||||
|
||||
if(vstd::contains(obstacleHexes, hex))
|
||||
distance += NEGATIVE_OBSTACLE_PENALTY;
|
||||
|
||||
return scoreEvaluator.checkPositionBlocksOurStacks(hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
|
||||
});
|
||||
|
||||
return BattleAction::makeMove(stack, *nearestAvailableHex);
|
||||
}
|
||||
else
|
||||
{
|
||||
BattleHex currentDest = bestNeighbor;
|
||||
while(1)
|
||||
{
|
||||
if(!currentDest.isValid())
|
||||
{
|
||||
return BattleAction::makeDefend(stack);
|
||||
}
|
||||
|
||||
if(vstd::contains(avHexes, currentDest)
|
||||
&& !scoreEvaluator.checkPositionBlocksOurStacks(hb, stack, currentDest))
|
||||
return BattleAction::makeMove(stack, currentDest);
|
||||
|
||||
currentDest = reachability.predecessors[currentDest];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BattleAction CBattleAI::useCatapult(const CStack * stack)
|
||||
{
|
||||
BattleAction attack;
|
||||
@@ -468,380 +228,12 @@ BattleAction CBattleAI::useCatapult(const CStack * stack)
|
||||
return attack;
|
||||
}
|
||||
|
||||
bool CBattleAI::attemptCastingSpell()
|
||||
{
|
||||
auto hero = cb->battleGetMyHero();
|
||||
if(!hero)
|
||||
return false;
|
||||
|
||||
if(cb->battleCanCastSpell(hero, spells::Mode::HERO) != ESpellCastProblem::OK)
|
||||
return false;
|
||||
|
||||
LOGL("Casting spells sounds like fun. Let's see...");
|
||||
//Get all spells we can cast
|
||||
std::vector<const CSpell*> possibleSpells;
|
||||
vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [hero, this](const CSpell *s) -> bool
|
||||
{
|
||||
return s->canBeCast(cb.get(), spells::Mode::HERO, hero);
|
||||
});
|
||||
LOGFL("I can cast %d spells.", possibleSpells.size());
|
||||
|
||||
vstd::erase_if(possibleSpells, [](const CSpell *s)
|
||||
{
|
||||
return spellType(s) != SpellTypes::BATTLE;
|
||||
});
|
||||
|
||||
LOGFL("I know how %d of them works.", possibleSpells.size());
|
||||
|
||||
//Get possible spell-target pairs
|
||||
std::vector<PossibleSpellcast> possibleCasts;
|
||||
for(auto spell : possibleSpells)
|
||||
{
|
||||
spells::BattleCast temp(cb.get(), hero, spells::Mode::HERO, spell);
|
||||
|
||||
if(!spell->isDamage() && spell->getTargetType() == spells::AimType::LOCATION)
|
||||
continue;
|
||||
|
||||
const bool FAST = true;
|
||||
|
||||
for(auto & target : temp.findPotentialTargets(FAST))
|
||||
{
|
||||
PossibleSpellcast ps;
|
||||
ps.dest = target;
|
||||
ps.spell = spell;
|
||||
possibleCasts.push_back(ps);
|
||||
}
|
||||
}
|
||||
LOGFL("Found %d spell-target combinations.", possibleCasts.size());
|
||||
if(possibleCasts.empty())
|
||||
return false;
|
||||
|
||||
using ValueMap = PossibleSpellcast::ValueMap;
|
||||
|
||||
auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, HypotheticBattle & state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
|
||||
{
|
||||
bool firstRound = true;
|
||||
bool enemyHadTurn = false;
|
||||
size_t ourTurnSpan = 0;
|
||||
|
||||
bool stop = false;
|
||||
|
||||
for(auto & round : queue)
|
||||
{
|
||||
if(!firstRound)
|
||||
state.nextRound(0);//todo: set actual value?
|
||||
for(auto unit : round)
|
||||
{
|
||||
if(!vstd::contains(values, unit->unitId()))
|
||||
values[unit->unitId()] = 0;
|
||||
|
||||
if(!unit->alive())
|
||||
continue;
|
||||
|
||||
if(state.battleGetOwner(unit) != playerID)
|
||||
{
|
||||
enemyHadTurn = true;
|
||||
|
||||
if(!firstRound || state.battleCastSpells(unit->unitSide()) == 0)
|
||||
{
|
||||
//enemy could counter our spell at this point
|
||||
//anyway, we do not know what enemy will do
|
||||
//just stop evaluation
|
||||
stop = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if(!enemyHadTurn)
|
||||
{
|
||||
ourTurnSpan++;
|
||||
}
|
||||
|
||||
state.nextTurn(unit->unitId());
|
||||
|
||||
PotentialTargets pt(unit, state);
|
||||
|
||||
if(!pt.possibleAttacks.empty())
|
||||
{
|
||||
AttackPossibility ap = pt.bestAction();
|
||||
|
||||
auto swb = state.getForUpdate(unit->unitId());
|
||||
*swb = *ap.attackerState;
|
||||
|
||||
if(ap.defenderDamageReduce > 0)
|
||||
swb->removeUnitBonus(Bonus::UntilAttack);
|
||||
if(ap.attackerDamageReduce > 0)
|
||||
swb->removeUnitBonus(Bonus::UntilBeingAttacked);
|
||||
|
||||
for(auto affected : ap.affectedUnits)
|
||||
{
|
||||
swb = state.getForUpdate(affected->unitId());
|
||||
*swb = *affected;
|
||||
|
||||
if(ap.defenderDamageReduce > 0)
|
||||
swb->removeUnitBonus(Bonus::UntilBeingAttacked);
|
||||
if(ap.attackerDamageReduce > 0 && ap.attack.defender->unitId() == affected->unitId())
|
||||
swb->removeUnitBonus(Bonus::UntilAttack);
|
||||
}
|
||||
}
|
||||
|
||||
auto bav = pt.bestActionValue();
|
||||
|
||||
//best action is from effective owner`s point if view, we need to convert to our point if view
|
||||
if(state.battleGetOwner(unit) != playerID)
|
||||
bav = -bav;
|
||||
values[unit->unitId()] += bav;
|
||||
}
|
||||
|
||||
firstRound = false;
|
||||
|
||||
if(stop)
|
||||
break;
|
||||
}
|
||||
|
||||
if(enemyHadTurnOut)
|
||||
*enemyHadTurnOut = enemyHadTurn;
|
||||
|
||||
return ourTurnSpan >= minTurnSpan;
|
||||
};
|
||||
|
||||
ValueMap valueOfStack;
|
||||
ValueMap healthOfStack;
|
||||
|
||||
TStacks all = cb->battleGetAllStacks(false);
|
||||
|
||||
size_t ourRemainingTurns = 0;
|
||||
|
||||
for(auto unit : all)
|
||||
{
|
||||
healthOfStack[unit->unitId()] = unit->getAvailableHealth();
|
||||
valueOfStack[unit->unitId()] = 0;
|
||||
|
||||
if(cb->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
|
||||
ourRemainingTurns++;
|
||||
}
|
||||
|
||||
LOGFL("I have %d turns left in this round", ourRemainingTurns);
|
||||
|
||||
const bool castNow = ourRemainingTurns <= 1;
|
||||
|
||||
if(castNow)
|
||||
print("I should try to cast a spell now");
|
||||
else
|
||||
print("I could wait better moment to cast a spell");
|
||||
|
||||
auto amount = all.size();
|
||||
|
||||
std::vector<battle::Units> turnOrder;
|
||||
|
||||
cb->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
|
||||
|
||||
{
|
||||
bool enemyHadTurn = false;
|
||||
|
||||
HypotheticBattle state(env.get(), cb);
|
||||
|
||||
evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
|
||||
|
||||
if(!enemyHadTurn)
|
||||
{
|
||||
auto battleIsFinishedOpt = state.battleIsFinished();
|
||||
|
||||
if(battleIsFinishedOpt)
|
||||
{
|
||||
print("No need to cast a spell. Battle will finish soon.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ScriptsCache
|
||||
{
|
||||
//todo: re-implement scripts context cache
|
||||
};
|
||||
|
||||
auto evaluateSpellcast = [&] (PossibleSpellcast * ps, std::shared_ptr<ScriptsCache>)
|
||||
{
|
||||
HypotheticBattle state(env.get(), cb);
|
||||
|
||||
spells::BattleCast cast(&state, hero, spells::Mode::HERO, ps->spell);
|
||||
cast.castEval(state.getServerCallback(), ps->dest);
|
||||
ValueMap newHealthOfStack;
|
||||
ValueMap newValueOfStack;
|
||||
|
||||
size_t ourUnits = 0;
|
||||
|
||||
std::set<uint32_t> unitIds;
|
||||
|
||||
state.battleGetUnitsIf([&](const battle::Unit * u)->bool
|
||||
{
|
||||
if(!u->isGhost() && !u->isTurret())
|
||||
unitIds.insert(u->unitId());
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
for(auto unitId : unitIds)
|
||||
{
|
||||
auto localUnit = state.battleGetUnitByID(unitId);
|
||||
|
||||
newHealthOfStack[unitId] = localUnit->getAvailableHealth();
|
||||
newValueOfStack[unitId] = 0;
|
||||
|
||||
if(state.battleGetOwner(localUnit) == playerID && localUnit->alive() && localUnit->willMove())
|
||||
ourUnits++;
|
||||
}
|
||||
|
||||
size_t minTurnSpan = ourUnits/3; //todo: tweak this
|
||||
|
||||
std::vector<battle::Units> newTurnOrder;
|
||||
|
||||
state.battleGetTurnOrder(newTurnOrder, amount, 2);
|
||||
|
||||
const bool turnSpanOK = evaluateQueue(newValueOfStack, newTurnOrder, state, minTurnSpan, nullptr);
|
||||
|
||||
if(turnSpanOK || castNow)
|
||||
{
|
||||
int64_t totalGain = 0;
|
||||
|
||||
for(auto unitId : unitIds)
|
||||
{
|
||||
auto localUnit = state.battleGetUnitByID(unitId);
|
||||
|
||||
auto newValue = getValOr(newValueOfStack, unitId, 0);
|
||||
auto oldValue = getValOr(valueOfStack, unitId, 0);
|
||||
|
||||
auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
|
||||
|
||||
if(localUnit->unitOwner() != playerID)
|
||||
healthDiff = -healthDiff;
|
||||
|
||||
if(healthDiff < 0)
|
||||
{
|
||||
ps->value = -1;
|
||||
return; //do not damage own units at all
|
||||
}
|
||||
|
||||
totalGain += (newValue - oldValue + healthDiff);
|
||||
}
|
||||
|
||||
ps->value = totalGain;
|
||||
}
|
||||
else
|
||||
{
|
||||
ps->value = -1;
|
||||
}
|
||||
};
|
||||
|
||||
using EvalRunner = ThreadPool<ScriptsCache>;
|
||||
|
||||
EvalRunner::Tasks tasks;
|
||||
|
||||
for(PossibleSpellcast & psc : possibleCasts)
|
||||
tasks.push_back(std::bind(evaluateSpellcast, &psc, _1));
|
||||
|
||||
uint32_t threadCount = boost::thread::hardware_concurrency();
|
||||
|
||||
if(threadCount == 0)
|
||||
{
|
||||
logGlobal->warn("No information of CPU cores available");
|
||||
threadCount = 1;
|
||||
}
|
||||
|
||||
CStopWatch timer;
|
||||
|
||||
std::vector<std::shared_ptr<ScriptsCache>> scriptsPool;
|
||||
|
||||
for(uint32_t idx = 0; idx < threadCount; idx++)
|
||||
{
|
||||
scriptsPool.emplace_back();
|
||||
}
|
||||
|
||||
EvalRunner runner(&tasks, scriptsPool);
|
||||
runner.run();
|
||||
|
||||
LOGFL("Evaluation took %d ms", timer.getDiff());
|
||||
|
||||
auto pscValue = [](const PossibleSpellcast &ps) -> int64_t
|
||||
{
|
||||
return ps.value;
|
||||
};
|
||||
auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
|
||||
|
||||
if(castToPerform.value > 0)
|
||||
{
|
||||
LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->getNameTranslated() % castToPerform.value);
|
||||
BattleAction spellcast;
|
||||
spellcast.actionType = EActionType::HERO_SPELL;
|
||||
spellcast.spell = castToPerform.spell->getId();
|
||||
spellcast.setTarget(castToPerform.dest);
|
||||
spellcast.side = side;
|
||||
spellcast.stackNumber = (!side) ? -1 : -2;
|
||||
cb->battleMakeSpellAction(spellcast);
|
||||
movesSkippedByDefense = 0;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->getNameTranslated() % castToPerform.value);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
//Below method works only for offensive spells
|
||||
void CBattleAI::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
|
||||
{
|
||||
using ValueMap = PossibleSpellcast::ValueMap;
|
||||
|
||||
RNGStub rngStub;
|
||||
HypotheticBattle state(env.get(), cb);
|
||||
TStacks all = cb->battleGetAllStacks(false);
|
||||
|
||||
ValueMap healthOfStack;
|
||||
ValueMap newHealthOfStack;
|
||||
|
||||
for(auto unit : all)
|
||||
{
|
||||
healthOfStack[unit->unitId()] = unit->getAvailableHealth();
|
||||
}
|
||||
|
||||
spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
|
||||
cast.castEval(state.getServerCallback(), ps.dest);
|
||||
|
||||
for(auto unit : all)
|
||||
{
|
||||
auto unitId = unit->unitId();
|
||||
auto localUnit = state.battleGetUnitByID(unitId);
|
||||
newHealthOfStack[unitId] = localUnit->getAvailableHealth();
|
||||
}
|
||||
|
||||
int64_t totalGain = 0;
|
||||
|
||||
for(auto unit : all)
|
||||
{
|
||||
auto unitId = unit->unitId();
|
||||
auto localUnit = state.battleGetUnitByID(unitId);
|
||||
|
||||
auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
|
||||
|
||||
if(localUnit->unitOwner() != getCbc()->getPlayerID())
|
||||
healthDiff = -healthDiff;
|
||||
|
||||
if(healthDiff < 0)
|
||||
{
|
||||
ps.value = -1;
|
||||
return; //do not damage own units at all
|
||||
}
|
||||
|
||||
totalGain += healthDiff;
|
||||
}
|
||||
|
||||
ps.value = totalGain;
|
||||
}
|
||||
|
||||
void CBattleAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool Side, bool replayAllowed)
|
||||
{
|
||||
LOG_TRACE(logAi);
|
||||
side = Side;
|
||||
|
||||
skipCastUntilNextBattle = false;
|
||||
}
|
||||
|
||||
void CBattleAI::print(const std::string &text) const
|
||||
|
@@ -62,15 +62,13 @@ class CBattleAI : public CBattleGameInterface
|
||||
bool wasWaitingForRealize;
|
||||
bool wasUnlockingGs;
|
||||
int movesSkippedByDefense;
|
||||
bool skipCastUntilNextBattle;
|
||||
|
||||
public:
|
||||
CBattleAI();
|
||||
~CBattleAI();
|
||||
|
||||
void initBattleInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CBattleCallback> CB) override;
|
||||
bool attemptCastingSpell();
|
||||
|
||||
void evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps); //for offensive damaging spells only
|
||||
|
||||
void activeStack(const CStack * stack) override; //called when it's turn of that stack
|
||||
void yourTacticPhase(int distance) override;
|
||||
@@ -80,8 +78,6 @@ public:
|
||||
void print(const std::string &text) const;
|
||||
BattleAction useCatapult(const CStack *stack);
|
||||
BattleAction useHealingTent(const CStack *stack);
|
||||
BattleAction selectStackAction(const CStack * stack);
|
||||
std::optional<PossibleSpellcast> findBestCreatureSpell(const CStack *stack);
|
||||
|
||||
void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool Side, bool replayAllowed) override;
|
||||
//void actionFinished(const BattleAction &action) override;//occurs AFTER every action taken by any stack or by the hero
|
||||
@@ -98,8 +94,4 @@ public:
|
||||
//void battleTriggerEffect(const BattleTriggerEffect & bte) override;
|
||||
//void battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side) override; //called by engine when battle starts; side=0 - left, side=1 - right
|
||||
//void battleCatapultAttacked(const CatapultAttack & ca) override; //called when catapult makes an attack
|
||||
|
||||
private:
|
||||
BattleAction goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes) const;
|
||||
std::vector<BattleHex> getBrokenWallMoatHexes() const;
|
||||
};
|
||||
|
710
AI/BattleAI/BattleEvaluator.cpp
Normal file
710
AI/BattleAI/BattleEvaluator.cpp
Normal file
@@ -0,0 +1,710 @@
|
||||
/*
|
||||
* BattleAI.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 "BattleEvaluator.h"
|
||||
#include "BattleExchangeVariant.h"
|
||||
|
||||
#include "StackWithBonuses.h"
|
||||
#include "EnemyInfo.h"
|
||||
#include "tbb/parallel_for.h"
|
||||
#include "../../lib/CStopWatch.h"
|
||||
#include "../../lib/CThreadHelper.h"
|
||||
#include "../../lib/mapObjects/CGTownInstance.h"
|
||||
#include "../../lib/spells/CSpellHandler.h"
|
||||
#include "../../lib/spells/ISpellMechanics.h"
|
||||
#include "../../lib/battle/BattleStateInfoForRetreat.h"
|
||||
#include "../../lib/battle/CObstacleInstance.h"
|
||||
#include "../../lib/battle/BattleAction.h"
|
||||
|
||||
// TODO: remove
|
||||
// Eventually only IBattleInfoCallback and battle::Unit should be used,
|
||||
// CUnitState should be private and CStack should be removed completely
|
||||
#include "../../lib/CStack.h"
|
||||
|
||||
#define LOGL(text) print(text)
|
||||
#define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl))
|
||||
|
||||
enum class SpellTypes
|
||||
{
|
||||
ADVENTURE, BATTLE, OTHER
|
||||
};
|
||||
|
||||
SpellTypes spellType(const CSpell * spell)
|
||||
{
|
||||
if(!spell->isCombat() || spell->isCreatureAbility())
|
||||
return SpellTypes::OTHER;
|
||||
|
||||
if(spell->isOffensive() || spell->hasEffects() || spell->hasBattleEffects())
|
||||
return SpellTypes::BATTLE;
|
||||
|
||||
return SpellTypes::OTHER;
|
||||
}
|
||||
|
||||
std::vector<BattleHex> BattleEvaluator::getBrokenWallMoatHexes() const
|
||||
{
|
||||
std::vector<BattleHex> result;
|
||||
|
||||
for(EWallPart wallPart : { EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL })
|
||||
{
|
||||
auto state = cb->battleGetWallState(wallPart);
|
||||
|
||||
if(state != EWallState::DESTROYED)
|
||||
continue;
|
||||
|
||||
auto wallHex = cb->wallPartToBattleHex((EWallPart)wallPart);
|
||||
auto moatHex = wallHex.cloneInDirection(BattleHex::LEFT);
|
||||
|
||||
result.push_back(moatHex);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<PossibleSpellcast> BattleEvaluator::findBestCreatureSpell(const CStack *stack)
|
||||
{
|
||||
//TODO: faerie dragon type spell should be selected by server
|
||||
SpellID creatureSpellToCast = cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), stack, CBattleInfoCallback::RANDOM_AIMED);
|
||||
if(stack->hasBonusOfType(BonusType::SPELLCASTER) && stack->canCast() && creatureSpellToCast != SpellID::NONE)
|
||||
{
|
||||
const CSpell * spell = creatureSpellToCast.toSpell();
|
||||
|
||||
if(spell->canBeCast(getCbc().get(), spells::Mode::CREATURE_ACTIVE, stack))
|
||||
{
|
||||
std::vector<PossibleSpellcast> possibleCasts;
|
||||
spells::BattleCast temp(getCbc().get(), stack, spells::Mode::CREATURE_ACTIVE, spell);
|
||||
for(auto & target : temp.findPotentialTargets())
|
||||
{
|
||||
PossibleSpellcast ps;
|
||||
ps.dest = target;
|
||||
ps.spell = spell;
|
||||
evaluateCreatureSpellcast(stack, ps);
|
||||
possibleCasts.push_back(ps);
|
||||
}
|
||||
|
||||
std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; });
|
||||
if(!possibleCasts.empty() && possibleCasts.front().value > 0)
|
||||
{
|
||||
return possibleCasts.front();
|
||||
}
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
BattleAction BattleEvaluator::selectStackAction(const CStack * stack)
|
||||
{
|
||||
#if BATTLE_TRACE_LEVEL >= 1
|
||||
logAi->trace("Select stack action");
|
||||
#endif
|
||||
//evaluate casting spell for spellcasting stack
|
||||
std::optional<PossibleSpellcast> bestSpellcast = findBestCreatureSpell(stack);
|
||||
|
||||
auto moveTarget = scoreEvaluator.findMoveTowardsUnreachable(stack, *targets, damageCache, hb);
|
||||
float score = EvaluationResult::INEFFECTIVE_SCORE;
|
||||
|
||||
if(targets->possibleAttacks.empty() && bestSpellcast.has_value())
|
||||
{
|
||||
activeActionMade = true;
|
||||
return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
|
||||
}
|
||||
|
||||
if(!targets->possibleAttacks.empty())
|
||||
{
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace("Evaluating attack for %s", stack->getDescription());
|
||||
#endif
|
||||
|
||||
auto evaluationResult = scoreEvaluator.findBestTarget(stack, *targets, damageCache, hb);
|
||||
auto & bestAttack = evaluationResult.bestAttack;
|
||||
|
||||
cachedAttack = bestAttack;
|
||||
cachedScore = evaluationResult.score;
|
||||
|
||||
//TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc.
|
||||
if(bestSpellcast.has_value() && bestSpellcast->value > bestAttack.damageDiff())
|
||||
{
|
||||
// return because spellcast value is damage dealt and score is dps reduce
|
||||
activeActionMade = true;
|
||||
return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id);
|
||||
}
|
||||
|
||||
if(evaluationResult.score > score)
|
||||
{
|
||||
score = evaluationResult.score;
|
||||
|
||||
logAi->debug("BattleAI: %s -> %s x %d, from %d curpos %d dist %d speed %d: +%2f -%2f = %2f",
|
||||
bestAttack.attackerState->unitType()->getJsonKey(),
|
||||
bestAttack.affectedUnits[0]->unitType()->getJsonKey(),
|
||||
(int)bestAttack.affectedUnits[0]->getCount(),
|
||||
(int)bestAttack.from,
|
||||
(int)bestAttack.attack.attacker->getPosition().hex,
|
||||
bestAttack.attack.chargeDistance,
|
||||
bestAttack.attack.attacker->speed(0, true),
|
||||
bestAttack.defenderDamageReduce,
|
||||
bestAttack.attackerDamageReduce,
|
||||
bestAttack.attackValue()
|
||||
);
|
||||
|
||||
if (moveTarget.scorePerTurn <= score)
|
||||
{
|
||||
if(evaluationResult.wait)
|
||||
{
|
||||
return BattleAction::makeWait(stack);
|
||||
}
|
||||
else if(bestAttack.attack.shooting)
|
||||
{
|
||||
activeActionMade = true;
|
||||
return BattleAction::makeShotAttack(stack, bestAttack.attack.defender);
|
||||
}
|
||||
else
|
||||
{
|
||||
if(bestAttack.collateralDamageReduce
|
||||
&& bestAttack.collateralDamageReduce >= bestAttack.defenderDamageReduce / 2
|
||||
&& score < 0)
|
||||
{
|
||||
return BattleAction::makeDefend(stack);
|
||||
}
|
||||
else
|
||||
{
|
||||
activeActionMade = true;
|
||||
return BattleAction::makeMeleeAttack(stack, bestAttack.attack.defender->getPosition(), bestAttack.from);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//ThreatMap threatsToUs(stack); // These lines may be usefull but they are't used in the code.
|
||||
if(moveTarget.scorePerTurn > score)
|
||||
{
|
||||
score = moveTarget.score;
|
||||
cachedAttack = moveTarget.cachedAttack;
|
||||
cachedScore = score;
|
||||
|
||||
if(stack->waited())
|
||||
{
|
||||
return goTowardsNearest(stack, moveTarget.positions);
|
||||
}
|
||||
else
|
||||
{
|
||||
return BattleAction::makeWait(stack);
|
||||
}
|
||||
}
|
||||
|
||||
if(score <= EvaluationResult::INEFFECTIVE_SCORE
|
||||
&& !stack->hasBonusOfType(BonusType::FLYING)
|
||||
&& stack->unitSide() == BattleSide::ATTACKER
|
||||
&& cb->battleGetSiegeLevel() >= CGTownInstance::CITADEL)
|
||||
{
|
||||
auto brokenWallMoat = getBrokenWallMoatHexes();
|
||||
|
||||
if(brokenWallMoat.size())
|
||||
{
|
||||
activeActionMade = true;
|
||||
|
||||
if(stack->doubleWide() && vstd::contains(brokenWallMoat, stack->getPosition()))
|
||||
return BattleAction::makeMove(stack, stack->getPosition().cloneInDirection(BattleHex::RIGHT));
|
||||
else
|
||||
return goTowardsNearest(stack, brokenWallMoat);
|
||||
}
|
||||
}
|
||||
|
||||
return BattleAction::makeDefend(stack);
|
||||
}
|
||||
|
||||
uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
|
||||
{
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
|
||||
}
|
||||
|
||||
BattleAction BattleEvaluator::goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes)
|
||||
{
|
||||
auto reachability = cb->getReachability(stack);
|
||||
auto avHexes = cb->battleGetAvailableHexes(reachability, stack, false);
|
||||
|
||||
if(!avHexes.size() || !hexes.size()) //we are blocked or dest is blocked
|
||||
{
|
||||
return BattleAction::makeDefend(stack);
|
||||
}
|
||||
|
||||
std::sort(hexes.begin(), hexes.end(), [&](BattleHex h1, BattleHex h2) -> bool
|
||||
{
|
||||
return reachability.distances[h1] < reachability.distances[h2];
|
||||
});
|
||||
|
||||
for(auto hex : hexes)
|
||||
{
|
||||
if(vstd::contains(avHexes, hex))
|
||||
{
|
||||
return BattleAction::makeMove(stack, hex);
|
||||
}
|
||||
|
||||
if(stack->coversPos(hex))
|
||||
{
|
||||
logAi->warn("Warning: already standing on neighbouring tile!");
|
||||
//We shouldn't even be here...
|
||||
return BattleAction::makeDefend(stack);
|
||||
}
|
||||
}
|
||||
|
||||
BattleHex bestNeighbor = hexes.front();
|
||||
|
||||
if(reachability.distances[bestNeighbor] > GameConstants::BFIELD_SIZE)
|
||||
{
|
||||
return BattleAction::makeDefend(stack);
|
||||
}
|
||||
|
||||
scoreEvaluator.updateReachabilityMap(hb);
|
||||
|
||||
if(stack->hasBonusOfType(BonusType::FLYING))
|
||||
{
|
||||
std::set<BattleHex> obstacleHexes;
|
||||
|
||||
auto insertAffected = [](const CObstacleInstance & spellObst, std::set<BattleHex> obstacleHexes) {
|
||||
auto affectedHexes = spellObst.getAffectedTiles();
|
||||
obstacleHexes.insert(affectedHexes.cbegin(), affectedHexes.cend());
|
||||
};
|
||||
|
||||
const auto & obstacles = hb->battleGetAllObstacles();
|
||||
|
||||
for (const auto & obst: obstacles) {
|
||||
|
||||
if(obst->triggersEffects())
|
||||
{
|
||||
auto triggerAbility = VLC->spells()->getById(obst->getTrigger());
|
||||
auto triggerIsNegative = triggerAbility->isNegative() || triggerAbility->isDamage();
|
||||
|
||||
if(triggerIsNegative)
|
||||
insertAffected(*obst, obstacleHexes);
|
||||
}
|
||||
}
|
||||
// Flying stack doesn't go hex by hex, so we can't backtrack using predecessors.
|
||||
// We just check all available hexes and pick the one closest to the target.
|
||||
auto nearestAvailableHex = vstd::minElementByFun(avHexes, [&](BattleHex hex) -> int
|
||||
{
|
||||
const int NEGATIVE_OBSTACLE_PENALTY = 100; // avoid landing on negative obstacle (moat, fire wall, etc)
|
||||
const int BLOCKED_STACK_PENALTY = 100; // avoid landing on moat
|
||||
|
||||
auto distance = BattleHex::getDistance(bestNeighbor, hex);
|
||||
|
||||
if(vstd::contains(obstacleHexes, hex))
|
||||
distance += NEGATIVE_OBSTACLE_PENALTY;
|
||||
|
||||
return scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, hex) ? BLOCKED_STACK_PENALTY + distance : distance;
|
||||
});
|
||||
|
||||
return BattleAction::makeMove(stack, *nearestAvailableHex);
|
||||
}
|
||||
else
|
||||
{
|
||||
BattleHex currentDest = bestNeighbor;
|
||||
while(1)
|
||||
{
|
||||
if(!currentDest.isValid())
|
||||
{
|
||||
return BattleAction::makeDefend(stack);
|
||||
}
|
||||
|
||||
if(vstd::contains(avHexes, currentDest)
|
||||
&& !scoreEvaluator.checkPositionBlocksOurStacks(*hb, stack, currentDest))
|
||||
return BattleAction::makeMove(stack, currentDest);
|
||||
|
||||
currentDest = reachability.predecessors[currentDest];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool BattleEvaluator::canCastSpell()
|
||||
{
|
||||
auto hero = cb->battleGetMyHero();
|
||||
if(!hero)
|
||||
return false;
|
||||
|
||||
return cb->battleCanCastSpell(hero, spells::Mode::HERO) == ESpellCastProblem::OK;
|
||||
}
|
||||
|
||||
bool BattleEvaluator::attemptCastingSpell(const CStack * activeStack)
|
||||
{
|
||||
auto hero = cb->battleGetMyHero();
|
||||
if(!hero)
|
||||
return false;
|
||||
|
||||
LOGL("Casting spells sounds like fun. Let's see...");
|
||||
//Get all spells we can cast
|
||||
std::vector<const CSpell*> possibleSpells;
|
||||
vstd::copy_if(VLC->spellh->objects, std::back_inserter(possibleSpells), [hero, this](const CSpell *s) -> bool
|
||||
{
|
||||
return s->canBeCast(cb.get(), spells::Mode::HERO, hero);
|
||||
});
|
||||
LOGFL("I can cast %d spells.", possibleSpells.size());
|
||||
|
||||
vstd::erase_if(possibleSpells, [](const CSpell *s)
|
||||
{
|
||||
return spellType(s) != SpellTypes::BATTLE || s->getTargetType() == spells::AimType::LOCATION;
|
||||
});
|
||||
|
||||
LOGFL("I know how %d of them works.", possibleSpells.size());
|
||||
|
||||
//Get possible spell-target pairs
|
||||
std::vector<PossibleSpellcast> possibleCasts;
|
||||
for(auto spell : possibleSpells)
|
||||
{
|
||||
spells::BattleCast temp(cb.get(), hero, spells::Mode::HERO, spell);
|
||||
|
||||
if(spell->getTargetType() == spells::AimType::LOCATION)
|
||||
continue;
|
||||
|
||||
const bool FAST = true;
|
||||
|
||||
for(auto & target : temp.findPotentialTargets(FAST))
|
||||
{
|
||||
PossibleSpellcast ps;
|
||||
ps.dest = target;
|
||||
ps.spell = spell;
|
||||
possibleCasts.push_back(ps);
|
||||
}
|
||||
}
|
||||
LOGFL("Found %d spell-target combinations.", possibleCasts.size());
|
||||
if(possibleCasts.empty())
|
||||
return false;
|
||||
|
||||
using ValueMap = PossibleSpellcast::ValueMap;
|
||||
|
||||
auto evaluateQueue = [&](ValueMap & values, const std::vector<battle::Units> & queue, std::shared_ptr<HypotheticBattle> state, size_t minTurnSpan, bool * enemyHadTurnOut) -> bool
|
||||
{
|
||||
bool firstRound = true;
|
||||
bool enemyHadTurn = false;
|
||||
size_t ourTurnSpan = 0;
|
||||
|
||||
bool stop = false;
|
||||
|
||||
for(auto & round : queue)
|
||||
{
|
||||
if(!firstRound)
|
||||
state->nextRound(0);//todo: set actual value?
|
||||
for(auto unit : round)
|
||||
{
|
||||
if(!vstd::contains(values, unit->unitId()))
|
||||
values[unit->unitId()] = 0;
|
||||
|
||||
if(!unit->alive())
|
||||
continue;
|
||||
|
||||
if(state->battleGetOwner(unit) != playerID)
|
||||
{
|
||||
enemyHadTurn = true;
|
||||
|
||||
if(!firstRound || state->battleCastSpells(unit->unitSide()) == 0)
|
||||
{
|
||||
//enemy could counter our spell at this point
|
||||
//anyway, we do not know what enemy will do
|
||||
//just stop evaluation
|
||||
stop = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if(!enemyHadTurn)
|
||||
{
|
||||
ourTurnSpan++;
|
||||
}
|
||||
|
||||
state->nextTurn(unit->unitId());
|
||||
|
||||
PotentialTargets pt(unit, damageCache, state);
|
||||
|
||||
if(!pt.possibleAttacks.empty())
|
||||
{
|
||||
AttackPossibility ap = pt.bestAction();
|
||||
|
||||
auto swb = state->getForUpdate(unit->unitId());
|
||||
*swb = *ap.attackerState;
|
||||
|
||||
if(ap.defenderDamageReduce > 0)
|
||||
swb->removeUnitBonus(Bonus::UntilAttack);
|
||||
if(ap.attackerDamageReduce > 0)
|
||||
swb->removeUnitBonus(Bonus::UntilBeingAttacked);
|
||||
|
||||
for(auto affected : ap.affectedUnits)
|
||||
{
|
||||
swb = state->getForUpdate(affected->unitId());
|
||||
*swb = *affected;
|
||||
|
||||
if(ap.defenderDamageReduce > 0)
|
||||
swb->removeUnitBonus(Bonus::UntilBeingAttacked);
|
||||
if(ap.attackerDamageReduce > 0 && ap.attack.defender->unitId() == affected->unitId())
|
||||
swb->removeUnitBonus(Bonus::UntilAttack);
|
||||
}
|
||||
}
|
||||
|
||||
auto bav = pt.bestActionValue();
|
||||
|
||||
//best action is from effective owner`s point if view, we need to convert to our point if view
|
||||
if(state->battleGetOwner(unit) != playerID)
|
||||
bav = -bav;
|
||||
values[unit->unitId()] += bav;
|
||||
}
|
||||
|
||||
firstRound = false;
|
||||
|
||||
if(stop)
|
||||
break;
|
||||
}
|
||||
|
||||
if(enemyHadTurnOut)
|
||||
*enemyHadTurnOut = enemyHadTurn;
|
||||
|
||||
return ourTurnSpan >= minTurnSpan;
|
||||
};
|
||||
|
||||
ValueMap valueOfStack;
|
||||
ValueMap healthOfStack;
|
||||
|
||||
TStacks all = cb->battleGetAllStacks(false);
|
||||
|
||||
size_t ourRemainingTurns = 0;
|
||||
|
||||
for(auto unit : all)
|
||||
{
|
||||
healthOfStack[unit->unitId()] = unit->getAvailableHealth();
|
||||
valueOfStack[unit->unitId()] = 0;
|
||||
|
||||
if(cb->battleGetOwner(unit) == playerID && unit->canMove() && !unit->moved())
|
||||
ourRemainingTurns++;
|
||||
}
|
||||
|
||||
LOGFL("I have %d turns left in this round", ourRemainingTurns);
|
||||
|
||||
const bool castNow = ourRemainingTurns <= 1;
|
||||
|
||||
if(castNow)
|
||||
print("I should try to cast a spell now");
|
||||
else
|
||||
print("I could wait better moment to cast a spell");
|
||||
|
||||
auto amount = all.size();
|
||||
|
||||
std::vector<battle::Units> turnOrder;
|
||||
|
||||
cb->battleGetTurnOrder(turnOrder, amount, 2); //no more than 1 turn after current, each unit at least once
|
||||
|
||||
{
|
||||
bool enemyHadTurn = false;
|
||||
|
||||
auto state = std::make_shared<HypotheticBattle>(env.get(), cb);
|
||||
|
||||
evaluateQueue(valueOfStack, turnOrder, state, 0, &enemyHadTurn);
|
||||
|
||||
if(!enemyHadTurn)
|
||||
{
|
||||
auto battleIsFinishedOpt = state->battleIsFinished();
|
||||
|
||||
if(battleIsFinishedOpt)
|
||||
{
|
||||
print("No need to cast a spell. Battle will finish soon.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CStopWatch timer;
|
||||
|
||||
#if BATTLE_TRACE_LEVEL >= 1
|
||||
tbb::blocked_range<size_t> r(0, possibleCasts.size());
|
||||
#else
|
||||
tbb::parallel_for(tbb::blocked_range<size_t>(0, possibleCasts.size()), [&](const tbb::blocked_range<size_t> & r)
|
||||
{
|
||||
#endif
|
||||
for(auto i = r.begin(); i != r.end(); i++)
|
||||
{
|
||||
auto & ps = possibleCasts[i];
|
||||
|
||||
#if BATTLE_TRACE_LEVEL >= 1
|
||||
logAi->trace("Evaluating %s", ps.spell->getNameTranslated());
|
||||
#endif
|
||||
|
||||
auto state = std::make_shared<HypotheticBattle>(env.get(), cb);
|
||||
|
||||
spells::BattleCast cast(state.get(), hero, spells::Mode::HERO, ps.spell);
|
||||
cast.castEval(state->getServerCallback(), ps.dest);
|
||||
|
||||
auto allUnits = state->battleGetUnitsIf([](const battle::Unit * u) -> bool { return true; });
|
||||
|
||||
auto needFullEval = vstd::contains_if(allUnits, [&](const battle::Unit * u) -> bool
|
||||
{
|
||||
auto original = cb->battleGetUnitByID(u->unitId());
|
||||
return !original || u->speed() != original->speed();
|
||||
});
|
||||
|
||||
DamageCache safeCopy = damageCache;
|
||||
DamageCache innerCache(&safeCopy);
|
||||
innerCache.buildDamageCache(state, side);
|
||||
|
||||
if(needFullEval || !cachedAttack)
|
||||
{
|
||||
#if BATTLE_TRACE_LEVEL >= 1
|
||||
logAi->trace("Full evaluation is started due to stack speed affected.");
|
||||
#endif
|
||||
|
||||
PotentialTargets innerTargets(activeStack, innerCache, state);
|
||||
BattleExchangeEvaluator innerEvaluator(state, env, strengthRatio);
|
||||
|
||||
if(!innerTargets.possibleAttacks.empty())
|
||||
{
|
||||
innerEvaluator.updateReachabilityMap(state);
|
||||
|
||||
auto newStackAction = innerEvaluator.findBestTarget(activeStack, innerTargets, innerCache, state);
|
||||
|
||||
ps.value = newStackAction.score;
|
||||
}
|
||||
else
|
||||
{
|
||||
ps.value = 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ps.value = scoreEvaluator.calculateExchange(*cachedAttack, *targets, innerCache, state);
|
||||
}
|
||||
|
||||
for(auto unit : allUnits)
|
||||
{
|
||||
auto newHealth = unit->getAvailableHealth();
|
||||
auto oldHealth = healthOfStack[unit->unitId()];
|
||||
|
||||
if(oldHealth != newHealth)
|
||||
{
|
||||
auto damage = std::abs(oldHealth - newHealth);
|
||||
auto originalDefender = cb->battleGetUnitByID(unit->unitId());
|
||||
|
||||
auto dpsReduce = AttackPossibility::calculateDamageReduce(
|
||||
nullptr,
|
||||
originalDefender && originalDefender->alive() ? originalDefender : unit,
|
||||
damage,
|
||||
innerCache,
|
||||
state);
|
||||
|
||||
auto ourUnit = unit->unitSide() == side ? 1 : -1;
|
||||
auto goodEffect = newHealth > oldHealth ? 1 : -1;
|
||||
|
||||
if(ourUnit * goodEffect == 1)
|
||||
{
|
||||
if(ourUnit && goodEffect && (unit->isClone() || unit->isGhost() || !unit->unitSlot().validSlot()))
|
||||
continue;
|
||||
|
||||
ps.value += dpsReduce * scoreEvaluator.getPositiveEffectMultiplier();
|
||||
}
|
||||
else
|
||||
ps.value -= dpsReduce * scoreEvaluator.getNegativeEffectMultiplier();
|
||||
|
||||
#if BATTLE_TRACE_LEVEL >= 1
|
||||
logAi->trace(
|
||||
"Spell affects %s (%d), dps: %2f",
|
||||
unit->creatureId().toCreature()->getNameSingularTranslated(),
|
||||
unit->getCount(),
|
||||
dpsReduce);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#if BATTLE_TRACE_LEVEL >= 1
|
||||
logAi->trace("Total score: %2f", ps.value);
|
||||
#endif
|
||||
}
|
||||
#if BATTLE_TRACE_LEVEL == 0
|
||||
});
|
||||
#endif
|
||||
|
||||
LOGFL("Evaluation took %d ms", timer.getDiff());
|
||||
|
||||
auto pscValue = [](const PossibleSpellcast &ps) -> float
|
||||
{
|
||||
return ps.value;
|
||||
};
|
||||
auto castToPerform = *vstd::maxElementByFun(possibleCasts, pscValue);
|
||||
|
||||
if(castToPerform.value > cachedScore)
|
||||
{
|
||||
LOGFL("Best spell is %s (value %d). Will cast.", castToPerform.spell->getNameTranslated() % castToPerform.value);
|
||||
BattleAction spellcast;
|
||||
spellcast.actionType = EActionType::HERO_SPELL;
|
||||
spellcast.spell = castToPerform.spell->id;
|
||||
spellcast.setTarget(castToPerform.dest);
|
||||
spellcast.side = side;
|
||||
spellcast.stackNumber = (!side) ? -1 : -2;
|
||||
cb->battleMakeSpellAction(spellcast);
|
||||
activeActionMade = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
LOGFL("Best spell is %s. But it is actually useless (value %d).", castToPerform.spell->getNameTranslated() % castToPerform.value);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//Below method works only for offensive spells
|
||||
void BattleEvaluator::evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps)
|
||||
{
|
||||
using ValueMap = PossibleSpellcast::ValueMap;
|
||||
|
||||
RNGStub rngStub;
|
||||
HypotheticBattle state(env.get(), cb);
|
||||
TStacks all = cb->battleGetAllStacks(false);
|
||||
|
||||
ValueMap healthOfStack;
|
||||
ValueMap newHealthOfStack;
|
||||
|
||||
for(auto unit : all)
|
||||
{
|
||||
healthOfStack[unit->unitId()] = unit->getAvailableHealth();
|
||||
}
|
||||
|
||||
spells::BattleCast cast(&state, stack, spells::Mode::CREATURE_ACTIVE, ps.spell);
|
||||
cast.castEval(state.getServerCallback(), ps.dest);
|
||||
|
||||
for(auto unit : all)
|
||||
{
|
||||
auto unitId = unit->unitId();
|
||||
auto localUnit = state.battleGetUnitByID(unitId);
|
||||
newHealthOfStack[unitId] = localUnit->getAvailableHealth();
|
||||
}
|
||||
|
||||
int64_t totalGain = 0;
|
||||
|
||||
for(auto unit : all)
|
||||
{
|
||||
auto unitId = unit->unitId();
|
||||
auto localUnit = state.battleGetUnitByID(unitId);
|
||||
|
||||
auto healthDiff = newHealthOfStack[unitId] - healthOfStack[unitId];
|
||||
|
||||
if(localUnit->unitOwner() != getCbc()->getPlayerID())
|
||||
healthDiff = -healthDiff;
|
||||
|
||||
if(healthDiff < 0)
|
||||
{
|
||||
ps.value = -1;
|
||||
return; //do not damage own units at all
|
||||
}
|
||||
|
||||
totalGain += healthDiff;
|
||||
}
|
||||
|
||||
ps.value = totalGain;
|
||||
}
|
||||
|
||||
void BattleEvaluator::print(const std::string & text) const
|
||||
{
|
||||
logAi->trace("%s Battle AI[%p]: %s", playerID.getStr(), this, text);
|
||||
}
|
||||
|
||||
|
||||
|
80
AI/BattleAI/BattleEvaluator.h
Normal file
80
AI/BattleAI/BattleEvaluator.h
Normal file
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* BattleEvaluator.h, 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
|
||||
*
|
||||
*/
|
||||
#pragma once
|
||||
#include "../../lib/AI_Base.h"
|
||||
#include "../../lib/battle/ReachabilityInfo.h"
|
||||
#include "PossibleSpellcast.h"
|
||||
#include "PotentialTargets.h"
|
||||
#include "BattleExchangeVariant.h"
|
||||
|
||||
VCMI_LIB_NAMESPACE_BEGIN
|
||||
|
||||
class CSpell;
|
||||
|
||||
VCMI_LIB_NAMESPACE_END
|
||||
|
||||
class EnemyInfo;
|
||||
|
||||
class BattleEvaluator
|
||||
{
|
||||
std::unique_ptr<PotentialTargets> targets;
|
||||
std::shared_ptr<HypotheticBattle> hb;
|
||||
BattleExchangeEvaluator scoreEvaluator;
|
||||
std::shared_ptr<CBattleCallback> cb;
|
||||
std::shared_ptr<Environment> env;
|
||||
bool activeActionMade = false;
|
||||
std::optional<AttackPossibility> cachedAttack;
|
||||
PlayerColor playerID;
|
||||
int side;
|
||||
float cachedScore;
|
||||
DamageCache damageCache;
|
||||
float strengthRatio;
|
||||
|
||||
public:
|
||||
BattleAction selectStackAction(const CStack * stack);
|
||||
bool attemptCastingSpell(const CStack * stack);
|
||||
bool canCastSpell();
|
||||
std::optional<PossibleSpellcast> findBestCreatureSpell(const CStack * stack);
|
||||
BattleAction goTowardsNearest(const CStack * stack, std::vector<BattleHex> hexes);
|
||||
std::vector<BattleHex> getBrokenWallMoatHexes() const;
|
||||
void evaluateCreatureSpellcast(const CStack * stack, PossibleSpellcast & ps); //for offensive damaging spells only
|
||||
void print(const std::string & text) const;
|
||||
|
||||
BattleEvaluator(
|
||||
std::shared_ptr<Environment> env,
|
||||
std::shared_ptr<CBattleCallback> cb,
|
||||
const battle::Unit * activeStack,
|
||||
PlayerColor playerID,
|
||||
int side,
|
||||
float strengthRatio)
|
||||
:scoreEvaluator(cb, env, strengthRatio), cachedAttack(), playerID(playerID), side(side), env(env), cb(cb), strengthRatio(strengthRatio)
|
||||
{
|
||||
hb = std::make_shared<HypotheticBattle>(env.get(), cb);
|
||||
damageCache.buildDamageCache(hb, side);
|
||||
|
||||
targets = std::make_unique<PotentialTargets>(activeStack, damageCache, hb);
|
||||
cachedScore = EvaluationResult::INEFFECTIVE_SCORE;
|
||||
}
|
||||
|
||||
BattleEvaluator(
|
||||
std::shared_ptr<Environment> env,
|
||||
std::shared_ptr<CBattleCallback> cb,
|
||||
std::shared_ptr<HypotheticBattle> hb,
|
||||
DamageCache & damageCache,
|
||||
const battle::Unit * activeStack,
|
||||
PlayerColor playerID,
|
||||
int side,
|
||||
float strengthRatio)
|
||||
:scoreEvaluator(cb, env, strengthRatio), cachedAttack(), playerID(playerID), side(side), env(env), cb(cb), hb(hb), damageCache(damageCache), strengthRatio(strengthRatio)
|
||||
{
|
||||
targets = std::make_unique<PotentialTargets>(activeStack, damageCache, hb);
|
||||
cachedScore = EvaluationResult::INEFFECTIVE_SCORE;
|
||||
}
|
||||
};
|
@@ -18,75 +18,135 @@ AttackerValue::AttackerValue()
|
||||
}
|
||||
|
||||
MoveTarget::MoveTarget()
|
||||
: positions()
|
||||
: positions(), cachedAttack()
|
||||
{
|
||||
score = EvaluationResult::INEFFECTIVE_SCORE;
|
||||
scorePerTurn = EvaluationResult::INEFFECTIVE_SCORE;
|
||||
turnsToRich = 1;
|
||||
}
|
||||
|
||||
int64_t BattleExchangeVariant::trackAttack(const AttackPossibility & ap, HypotheticBattle & state)
|
||||
float BattleExchangeVariant::trackAttack(
|
||||
const AttackPossibility & ap,
|
||||
std::shared_ptr<HypotheticBattle> hb,
|
||||
DamageCache & damageCache)
|
||||
{
|
||||
auto attacker = hb->getForUpdate(ap.attack.attacker->unitId());
|
||||
|
||||
const std::string cachingStringBlocksRetaliation = "type_BLOCKS_RETALIATION";
|
||||
static const auto selectorBlocksRetaliation = Selector::type()(BonusType::BLOCKS_RETALIATION);
|
||||
const bool counterAttacksBlocked = attacker->hasBonus(selectorBlocksRetaliation, cachingStringBlocksRetaliation);
|
||||
|
||||
float attackValue = 0;
|
||||
auto affectedUnits = ap.affectedUnits;
|
||||
|
||||
affectedUnits.push_back(ap.attackerState);
|
||||
|
||||
for(auto affectedUnit : affectedUnits)
|
||||
{
|
||||
auto unitToUpdate = state.getForUpdate(affectedUnit->unitId());
|
||||
auto unitToUpdate = hb->getForUpdate(affectedUnit->unitId());
|
||||
|
||||
unitToUpdate->health = affectedUnit->health;
|
||||
unitToUpdate->shots = affectedUnit->shots;
|
||||
unitToUpdate->counterAttacks = affectedUnit->counterAttacks;
|
||||
unitToUpdate->movedThisRound = affectedUnit->movedThisRound;
|
||||
}
|
||||
if(unitToUpdate->unitSide() == attacker->unitSide())
|
||||
{
|
||||
if(unitToUpdate->unitId() == attacker->unitId())
|
||||
{
|
||||
auto defender = hb->getForUpdate(ap.attack.defender->unitId());
|
||||
|
||||
auto attackValue = ap.attackValue();
|
||||
if(!defender->alive() || counterAttacksBlocked || ap.attack.shooting || !defender->ableToRetaliate())
|
||||
continue;
|
||||
|
||||
dpsScore += attackValue;
|
||||
auto retaliationDamage = damageCache.getDamage(defender.get(), unitToUpdate.get(), hb);
|
||||
auto attackerDamageReduce = AttackPossibility::calculateDamageReduce(defender.get(), unitToUpdate.get(), retaliationDamage, damageCache, hb);
|
||||
|
||||
attackValue -= attackerDamageReduce;
|
||||
dpsScore -= attackerDamageReduce * negativeEffectMultiplier;
|
||||
attackerValue[unitToUpdate->unitId()].isRetalitated = true;
|
||||
|
||||
unitToUpdate->damage(retaliationDamage);
|
||||
defender->afterAttack(false, true);
|
||||
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace(
|
||||
"%s -> %s, ap attack, %s, dps: %lld, score: %lld",
|
||||
ap.attack.attacker->getDescription(),
|
||||
ap.attack.defender->getDescription(),
|
||||
ap.attack.shooting ? "shot" : "mellee",
|
||||
ap.damageDealt,
|
||||
attackValue);
|
||||
logAi->trace(
|
||||
"%s -> %s, ap retalitation, %s, dps: %2f, score: %2f",
|
||||
defender->getDescription(),
|
||||
unitToUpdate->getDescription(),
|
||||
ap.attack.shooting ? "shot" : "mellee",
|
||||
retaliationDamage,
|
||||
attackerDamageReduce);
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
auto collateralDamage = damageCache.getDamage(attacker.get(), unitToUpdate.get(), hb);
|
||||
auto collateralDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), unitToUpdate.get(), collateralDamage, damageCache, hb);
|
||||
|
||||
attackValue -= collateralDamageReduce;
|
||||
dpsScore -= collateralDamageReduce * negativeEffectMultiplier;
|
||||
|
||||
unitToUpdate->damage(collateralDamage);
|
||||
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace(
|
||||
"%s -> %s, ap collateral, %s, dps: %2f, score: %2f",
|
||||
attacker->getDescription(),
|
||||
unitToUpdate->getDescription(),
|
||||
ap.attack.shooting ? "shot" : "mellee",
|
||||
collateralDamage,
|
||||
collateralDamageReduce);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int64_t attackDamage = damageCache.getDamage(attacker.get(), unitToUpdate.get(), hb);
|
||||
float defenderDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), unitToUpdate.get(), attackDamage, damageCache, hb);
|
||||
|
||||
attackValue += defenderDamageReduce;
|
||||
dpsScore += defenderDamageReduce * positiveEffectMultiplier;
|
||||
attackerValue[attacker->unitId()].value += defenderDamageReduce;
|
||||
|
||||
unitToUpdate->damage(attackDamage);
|
||||
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace(
|
||||
"%s -> %s, ap attack, %s, dps: %2f, score: %2f",
|
||||
attacker->getDescription(),
|
||||
unitToUpdate->getDescription(),
|
||||
ap.attack.shooting ? "shot" : "mellee",
|
||||
attackDamage,
|
||||
defenderDamageReduce);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
attackValue += ap.shootersBlockedDmg;
|
||||
dpsScore += ap.shootersBlockedDmg * positiveEffectMultiplier;
|
||||
attacker->afterAttack(ap.attack.shooting, false);
|
||||
|
||||
return attackValue;
|
||||
}
|
||||
|
||||
int64_t BattleExchangeVariant::trackAttack(
|
||||
float BattleExchangeVariant::trackAttack(
|
||||
std::shared_ptr<StackWithBonuses> attacker,
|
||||
std::shared_ptr<StackWithBonuses> defender,
|
||||
bool shooting,
|
||||
bool isOurAttack,
|
||||
const CBattleInfoCallback & cb,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<HypotheticBattle> hb,
|
||||
bool evaluateOnly)
|
||||
{
|
||||
const std::string cachingStringBlocksRetaliation = "type_BLOCKS_RETALIATION";
|
||||
static const auto selectorBlocksRetaliation = Selector::type()(BonusType::BLOCKS_RETALIATION);
|
||||
const bool counterAttacksBlocked = attacker->hasBonus(selectorBlocksRetaliation, cachingStringBlocksRetaliation);
|
||||
|
||||
DamageEstimation retaliation;
|
||||
// FIXME: provide distance info for Jousting bonus
|
||||
BattleAttackInfo bai(attacker.get(), defender.get(), 0, shooting);
|
||||
|
||||
if(shooting)
|
||||
{
|
||||
bai.attackerPos.setXY(8, 5);
|
||||
}
|
||||
|
||||
auto attack = cb.battleEstimateDamage(bai, &retaliation);
|
||||
int64_t attackDamage = (attack.damage.min + attack.damage.max) / 2;
|
||||
int64_t defenderDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), defender.get(), attackDamage, cb);
|
||||
int64_t attackerDamageReduce = 0;
|
||||
int64_t attackDamage = damageCache.getDamage(attacker.get(), defender.get(), hb);
|
||||
float defenderDamageReduce = AttackPossibility::calculateDamageReduce(attacker.get(), defender.get(), attackDamage, damageCache, hb);
|
||||
float attackerDamageReduce = 0;
|
||||
|
||||
if(!evaluateOnly)
|
||||
{
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace(
|
||||
"%s -> %s, normal attack, %s, dps: %lld, %lld",
|
||||
"%s -> %s, normal attack, %s, dps: %lld, %2f",
|
||||
attacker->getDescription(),
|
||||
defender->getDescription(),
|
||||
shooting ? "shot" : "mellee",
|
||||
@@ -96,49 +156,43 @@ int64_t BattleExchangeVariant::trackAttack(
|
||||
|
||||
if(isOurAttack)
|
||||
{
|
||||
dpsScore += defenderDamageReduce;
|
||||
dpsScore += defenderDamageReduce * positiveEffectMultiplier;
|
||||
attackerValue[attacker->unitId()].value += defenderDamageReduce;
|
||||
}
|
||||
else
|
||||
dpsScore -= defenderDamageReduce;
|
||||
dpsScore -= defenderDamageReduce * negativeEffectMultiplier;
|
||||
|
||||
defender->damage(attackDamage);
|
||||
attacker->afterAttack(shooting, false);
|
||||
}
|
||||
|
||||
if(defender->alive() && defender->ableToRetaliate() && !counterAttacksBlocked && !shooting)
|
||||
if(!evaluateOnly && defender->alive() && defender->ableToRetaliate() && !counterAttacksBlocked && !shooting)
|
||||
{
|
||||
if(retaliation.damage.max != 0)
|
||||
{
|
||||
auto retaliationDamage = (retaliation.damage.min + retaliation.damage.max) / 2;
|
||||
attackerDamageReduce = AttackPossibility::calculateDamageReduce(defender.get(), attacker.get(), retaliationDamage, cb);
|
||||
auto retaliationDamage = damageCache.getDamage(defender.get(), attacker.get(), hb);
|
||||
attackerDamageReduce = AttackPossibility::calculateDamageReduce(defender.get(), attacker.get(), retaliationDamage, damageCache, hb);
|
||||
|
||||
if(!evaluateOnly)
|
||||
{
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace(
|
||||
"%s -> %s, retaliation, dps: %lld, %lld",
|
||||
defender->getDescription(),
|
||||
attacker->getDescription(),
|
||||
retaliationDamage,
|
||||
attackerDamageReduce);
|
||||
logAi->trace(
|
||||
"%s -> %s, retaliation, dps: %lld, %2f",
|
||||
defender->getDescription(),
|
||||
attacker->getDescription(),
|
||||
retaliationDamage,
|
||||
attackerDamageReduce);
|
||||
#endif
|
||||
|
||||
if(isOurAttack)
|
||||
{
|
||||
dpsScore -= attackerDamageReduce;
|
||||
attackerValue[attacker->unitId()].isRetalitated = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
dpsScore += attackerDamageReduce;
|
||||
attackerValue[defender->unitId()].value += attackerDamageReduce;
|
||||
}
|
||||
|
||||
attacker->damage(retaliationDamage);
|
||||
defender->afterAttack(false, true);
|
||||
}
|
||||
if(isOurAttack)
|
||||
{
|
||||
dpsScore -= attackerDamageReduce * negativeEffectMultiplier;
|
||||
attackerValue[attacker->unitId()].isRetalitated = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
dpsScore += attackerDamageReduce * positiveEffectMultiplier;
|
||||
attackerValue[defender->unitId()].value += attackerDamageReduce;
|
||||
}
|
||||
|
||||
attacker->damage(retaliationDamage);
|
||||
defender->afterAttack(false, true);
|
||||
}
|
||||
|
||||
auto score = defenderDamageReduce - attackerDamageReduce;
|
||||
@@ -146,44 +200,37 @@ int64_t BattleExchangeVariant::trackAttack(
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
if(!score)
|
||||
{
|
||||
logAi->trace("Attack has zero score d:%lld a:%lld", defenderDamageReduce, attackerDamageReduce);
|
||||
logAi->trace("Attack has zero score d:%2f a:%2f", defenderDamageReduce, attackerDamageReduce);
|
||||
}
|
||||
#endif
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
EvaluationResult BattleExchangeEvaluator::findBestTarget(const battle::Unit * activeStack, PotentialTargets & targets, HypotheticBattle & hb)
|
||||
EvaluationResult BattleExchangeEvaluator::findBestTarget(
|
||||
const battle::Unit * activeStack,
|
||||
PotentialTargets & targets,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<HypotheticBattle> hb)
|
||||
{
|
||||
EvaluationResult result(targets.bestAction());
|
||||
|
||||
updateReachabilityMap(hb);
|
||||
|
||||
for(auto & ap : targets.possibleAttacks)
|
||||
{
|
||||
int64_t score = calculateExchange(ap, targets, hb);
|
||||
|
||||
if(score > result.score)
|
||||
{
|
||||
result.score = score;
|
||||
result.bestAttack = ap;
|
||||
}
|
||||
}
|
||||
|
||||
if(!activeStack->waited())
|
||||
{
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace("Evaluating waited attack for %s", activeStack->getDescription());
|
||||
#endif
|
||||
|
||||
hb.getForUpdate(activeStack->unitId())->waiting = true;
|
||||
hb.getForUpdate(activeStack->unitId())->waitedThisTurn = true;
|
||||
auto hbWaited = std::make_shared<HypotheticBattle>(env.get(), hb);
|
||||
|
||||
updateReachabilityMap(hb);
|
||||
hbWaited->getForUpdate(activeStack->unitId())->waiting = true;
|
||||
hbWaited->getForUpdate(activeStack->unitId())->waitedThisTurn = true;
|
||||
|
||||
updateReachabilityMap(hbWaited);
|
||||
|
||||
for(auto & ap : targets.possibleAttacks)
|
||||
{
|
||||
int64_t score = calculateExchange(ap, targets, hb);
|
||||
float score = calculateExchange(ap, targets, damageCache, hbWaited);
|
||||
|
||||
if(score > result.score)
|
||||
{
|
||||
@@ -194,13 +241,35 @@ EvaluationResult BattleExchangeEvaluator::findBestTarget(const battle::Unit * ac
|
||||
}
|
||||
}
|
||||
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace("Evaluating normal attack for %s", activeStack->getDescription());
|
||||
#endif
|
||||
|
||||
updateReachabilityMap(hb);
|
||||
|
||||
for(auto & ap : targets.possibleAttacks)
|
||||
{
|
||||
float score = calculateExchange(ap, targets, damageCache, hb);
|
||||
|
||||
if(score >= result.score)
|
||||
{
|
||||
result.score = score;
|
||||
result.bestAttack = ap;
|
||||
result.wait = false;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
MoveTarget BattleExchangeEvaluator::findMoveTowardsUnreachable(const battle::Unit * activeStack, PotentialTargets & targets, HypotheticBattle & hb)
|
||||
MoveTarget BattleExchangeEvaluator::findMoveTowardsUnreachable(
|
||||
const battle::Unit * activeStack,
|
||||
PotentialTargets & targets,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<HypotheticBattle> hb)
|
||||
{
|
||||
MoveTarget result;
|
||||
BattleExchangeVariant ev;
|
||||
BattleExchangeVariant ev(getPositiveEffectMultiplier(), getNegativeEffectMultiplier());
|
||||
|
||||
if(targets.unreachableEnemies.empty())
|
||||
return result;
|
||||
@@ -237,16 +306,20 @@ MoveTarget BattleExchangeEvaluator::findMoveTowardsUnreachable(const battle::Uni
|
||||
{
|
||||
// FIXME: provide distance info for Jousting bonus
|
||||
auto bai = BattleAttackInfo(activeStack, closestStack, 0, cb->battleCanShoot(activeStack));
|
||||
auto attack = AttackPossibility::evaluate(bai, hex, hb);
|
||||
auto attack = AttackPossibility::evaluate(bai, hex, damageCache, hb);
|
||||
|
||||
attack.shootersBlockedDmg = 0; // we do not want to count on it, it is not for sure
|
||||
|
||||
auto score = calculateExchange(attack, targets, hb) / turnsToRich;
|
||||
auto score = calculateExchange(attack, targets, damageCache, hb);
|
||||
auto scorePerTurn = score / turnsToRich;
|
||||
|
||||
if(result.score < score)
|
||||
if(result.scorePerTurn < scorePerTurn)
|
||||
{
|
||||
result.scorePerTurn = scorePerTurn;
|
||||
result.score = score;
|
||||
result.positions = closestStack->getAttackableHexes(activeStack);
|
||||
result.cachedAttack = attack;
|
||||
result.turnsToRich = turnsToRich;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -287,7 +360,7 @@ std::vector<const battle::Unit *> BattleExchangeEvaluator::getAdjacentUnits(cons
|
||||
std::vector<const battle::Unit *> BattleExchangeEvaluator::getExchangeUnits(
|
||||
const AttackPossibility & ap,
|
||||
PotentialTargets & targets,
|
||||
HypotheticBattle & hb)
|
||||
std::shared_ptr<HypotheticBattle> hb)
|
||||
{
|
||||
auto hexes = ap.attack.defender->getHexes();
|
||||
|
||||
@@ -308,7 +381,7 @@ std::vector<const battle::Unit *> BattleExchangeEvaluator::getExchangeUnits(
|
||||
{
|
||||
for(auto adjacentUnit : getAdjacentUnits(unit))
|
||||
{
|
||||
auto unitWithBonuses = hb.battleGetUnitByID(adjacentUnit->unitId());
|
||||
auto unitWithBonuses = hb->battleGetUnitByID(adjacentUnit->unitId());
|
||||
|
||||
if(vstd::contains(targets.unreachableEnemies, adjacentUnit)
|
||||
&& !vstd::contains(allReachableUnits, unitWithBonuses))
|
||||
@@ -343,16 +416,22 @@ std::vector<const battle::Unit *> BattleExchangeEvaluator::getExchangeUnits(
|
||||
}
|
||||
}
|
||||
|
||||
vstd::erase_if(exchangeUnits, [&](const battle::Unit * u) -> bool
|
||||
{
|
||||
return !hb->battleGetUnitByID(u->unitId())->alive();
|
||||
});
|
||||
|
||||
return exchangeUnits;
|
||||
}
|
||||
|
||||
int64_t BattleExchangeEvaluator::calculateExchange(
|
||||
float BattleExchangeEvaluator::calculateExchange(
|
||||
const AttackPossibility & ap,
|
||||
PotentialTargets & targets,
|
||||
HypotheticBattle & hb)
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<HypotheticBattle> hb)
|
||||
{
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace("Battle exchange at %lld", ap.attack.shooting ? ap.dest : ap.from);
|
||||
logAi->trace("Battle exchange at %d", ap.attack.shooting ? ap.dest.hex : ap.from.hex);
|
||||
#endif
|
||||
|
||||
if(cb->battleGetMySide() == BattlePerspective::LEFT_SIDE
|
||||
@@ -365,7 +444,8 @@ int64_t BattleExchangeEvaluator::calculateExchange(
|
||||
std::vector<const battle::Unit *> ourStacks;
|
||||
std::vector<const battle::Unit *> enemyStacks;
|
||||
|
||||
enemyStacks.push_back(ap.attack.defender);
|
||||
if(hb->battleGetUnitByID(ap.attack.defender->unitId())->alive())
|
||||
enemyStacks.push_back(ap.attack.defender);
|
||||
|
||||
std::vector<const battle::Unit *> exchangeUnits = getExchangeUnits(ap, targets, hb);
|
||||
|
||||
@@ -374,8 +454,23 @@ int64_t BattleExchangeEvaluator::calculateExchange(
|
||||
return 0;
|
||||
}
|
||||
|
||||
HypotheticBattle exchangeBattle(env.get(), cb);
|
||||
BattleExchangeVariant v;
|
||||
auto exchangeBattle = std::make_shared<HypotheticBattle>(env.get(), hb);
|
||||
BattleExchangeVariant v(getPositiveEffectMultiplier(), getNegativeEffectMultiplier());
|
||||
|
||||
for(auto unit : exchangeUnits)
|
||||
{
|
||||
if(unit->isTurret())
|
||||
continue;
|
||||
|
||||
bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, unit, true);
|
||||
auto & attackerQueue = isOur ? ourStacks : enemyStacks;
|
||||
|
||||
if(exchangeBattle->getForUpdate(unit->unitId())->alive() && !vstd::contains(attackerQueue, unit))
|
||||
{
|
||||
attackerQueue.push_back(unit);
|
||||
}
|
||||
}
|
||||
|
||||
auto melleeAttackers = ourStacks;
|
||||
|
||||
vstd::removeDuplicates(melleeAttackers);
|
||||
@@ -384,30 +479,15 @@ int64_t BattleExchangeEvaluator::calculateExchange(
|
||||
return !cb->battleCanShoot(u);
|
||||
});
|
||||
|
||||
for(auto unit : exchangeUnits)
|
||||
{
|
||||
if(unit->isTurret())
|
||||
continue;
|
||||
|
||||
bool isOur = cb->battleMatchOwner(ap.attack.attacker, unit, true);
|
||||
auto & attackerQueue = isOur ? ourStacks : enemyStacks;
|
||||
|
||||
|
||||
if(!vstd::contains(attackerQueue, unit))
|
||||
{
|
||||
attackerQueue.push_back(unit);
|
||||
}
|
||||
}
|
||||
|
||||
bool canUseAp = true;
|
||||
|
||||
for(auto activeUnit : exchangeUnits)
|
||||
{
|
||||
bool isOur = cb->battleMatchOwner(ap.attack.attacker, activeUnit, true);
|
||||
bool isOur = exchangeBattle->battleMatchOwner(ap.attack.attacker, activeUnit, true);
|
||||
battle::Units & attackerQueue = isOur ? ourStacks : enemyStacks;
|
||||
battle::Units & oppositeQueue = isOur ? enemyStacks : ourStacks;
|
||||
|
||||
auto attacker = exchangeBattle.getForUpdate(activeUnit->unitId());
|
||||
auto attacker = exchangeBattle->getForUpdate(activeUnit->unitId());
|
||||
|
||||
if(!attacker->alive())
|
||||
{
|
||||
@@ -420,21 +500,22 @@ int64_t BattleExchangeEvaluator::calculateExchange(
|
||||
|
||||
auto targetUnit = ap.attack.defender;
|
||||
|
||||
if(!isOur || !exchangeBattle.getForUpdate(targetUnit->unitId())->alive())
|
||||
if(!isOur || !exchangeBattle->battleGetUnitByID(targetUnit->unitId())->alive())
|
||||
{
|
||||
auto estimateAttack = [&](const battle::Unit * u) -> int64_t
|
||||
auto estimateAttack = [&](const battle::Unit * u) -> float
|
||||
{
|
||||
auto stackWithBonuses = exchangeBattle.getForUpdate(u->unitId());
|
||||
auto stackWithBonuses = exchangeBattle->getForUpdate(u->unitId());
|
||||
auto score = v.trackAttack(
|
||||
attacker,
|
||||
stackWithBonuses,
|
||||
exchangeBattle.battleCanShoot(stackWithBonuses.get()),
|
||||
exchangeBattle->battleCanShoot(stackWithBonuses.get()),
|
||||
isOur,
|
||||
*cb,
|
||||
damageCache,
|
||||
hb,
|
||||
true);
|
||||
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace("Best target selector %s->%s score = %lld", attacker->getDescription(), u->getDescription(), score);
|
||||
logAi->trace("Best target selector %s->%s score = %2f", attacker->getDescription(), u->getDescription(), score);
|
||||
#endif
|
||||
|
||||
return score;
|
||||
@@ -446,9 +527,12 @@ int64_t BattleExchangeEvaluator::calculateExchange(
|
||||
}
|
||||
else
|
||||
{
|
||||
auto reachable = exchangeBattle.battleGetUnitsIf([&](const battle::Unit * u) -> bool
|
||||
auto reachable = exchangeBattle->battleGetUnitsIf([&](const battle::Unit * u) -> bool
|
||||
{
|
||||
if(!u->alive() || u->unitSide() == attacker->unitSide())
|
||||
if(u->unitSide() == attacker->unitSide())
|
||||
return false;
|
||||
|
||||
if(!exchangeBattle->getForUpdate(u->unitId())->alive())
|
||||
return false;
|
||||
|
||||
return vstd::contains_if(reachabilityMap[u->getPosition()], [&](const battle::Unit * other) -> bool
|
||||
@@ -472,19 +556,20 @@ int64_t BattleExchangeEvaluator::calculateExchange(
|
||||
}
|
||||
}
|
||||
|
||||
auto defender = exchangeBattle.getForUpdate(targetUnit->unitId());
|
||||
auto shooting = cb->battleCanShoot(attacker.get());
|
||||
auto defender = exchangeBattle->getForUpdate(targetUnit->unitId());
|
||||
auto shooting = exchangeBattle->battleCanShoot(attacker.get());
|
||||
const int totalAttacks = attacker->getTotalAttacks(shooting);
|
||||
|
||||
if(canUseAp && activeUnit == ap.attack.attacker && targetUnit == ap.attack.defender)
|
||||
if(canUseAp && activeUnit->unitId() == ap.attack.attacker->unitId()
|
||||
&& targetUnit->unitId() == ap.attack.defender->unitId())
|
||||
{
|
||||
v.trackAttack(ap, exchangeBattle);
|
||||
v.trackAttack(ap, exchangeBattle, damageCache);
|
||||
}
|
||||
else
|
||||
{
|
||||
for(int i = 0; i < totalAttacks; i++)
|
||||
{
|
||||
v.trackAttack(attacker, defender, shooting, isOur, exchangeBattle);
|
||||
v.trackAttack(attacker, defender, shooting, isOur, damageCache, exchangeBattle);
|
||||
|
||||
if(!attacker->alive() || !defender->alive())
|
||||
break;
|
||||
@@ -495,12 +580,12 @@ int64_t BattleExchangeEvaluator::calculateExchange(
|
||||
|
||||
vstd::erase_if(attackerQueue, [&](const battle::Unit * u) -> bool
|
||||
{
|
||||
return !exchangeBattle.getForUpdate(u->unitId())->alive();
|
||||
return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
|
||||
});
|
||||
|
||||
vstd::erase_if(oppositeQueue, [&](const battle::Unit * u) -> bool
|
||||
{
|
||||
return !exchangeBattle.getForUpdate(u->unitId())->alive();
|
||||
return !exchangeBattle->battleGetUnitByID(u->unitId())->alive();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -509,7 +594,7 @@ int64_t BattleExchangeEvaluator::calculateExchange(
|
||||
v.adjustPositions(melleeAttackers, ap, reachabilityMap);
|
||||
|
||||
#if BATTLE_TRACE_LEVEL>=1
|
||||
logAi->trace("Exchange score: %lld", v.getScore());
|
||||
logAi->trace("Exchange score: %2f", v.getScore());
|
||||
#endif
|
||||
|
||||
return v.getScore();
|
||||
@@ -539,7 +624,7 @@ void BattleExchangeVariant::adjustPositions(
|
||||
vstd::erase_if_present(hexes, ap.attack.attacker->occupiedHex(ap.attack.attackerPos));
|
||||
}
|
||||
|
||||
int64_t notRealizedDamage = 0;
|
||||
float notRealizedDamage = 0;
|
||||
|
||||
for(auto unit : attackers)
|
||||
{
|
||||
@@ -555,7 +640,7 @@ void BattleExchangeVariant::adjustPositions(
|
||||
continue;
|
||||
}
|
||||
|
||||
auto desiredPosition = vstd::minElementByFun(hexes, [&](BattleHex h) -> int64_t
|
||||
auto desiredPosition = vstd::minElementByFun(hexes, [&](BattleHex h) -> float
|
||||
{
|
||||
auto score = vstd::contains(reachabilityMap[h], unit)
|
||||
? reachabilityMap[h].size()
|
||||
@@ -581,13 +666,13 @@ void BattleExchangeVariant::adjustPositions(
|
||||
}
|
||||
}
|
||||
|
||||
void BattleExchangeEvaluator::updateReachabilityMap(HypotheticBattle & hb)
|
||||
void BattleExchangeEvaluator::updateReachabilityMap( std::shared_ptr<HypotheticBattle> hb)
|
||||
{
|
||||
const int TURN_DEPTH = 2;
|
||||
|
||||
turnOrder.clear();
|
||||
|
||||
hb.battleGetTurnOrder(turnOrder, std::numeric_limits<int>::max(), TURN_DEPTH);
|
||||
hb->battleGetTurnOrder(turnOrder, std::numeric_limits<int>::max(), TURN_DEPTH);
|
||||
reachabilityMap.clear();
|
||||
|
||||
for(int turn = 0; turn < turnOrder.size(); turn++)
|
||||
|
@@ -16,7 +16,7 @@
|
||||
|
||||
struct AttackerValue
|
||||
{
|
||||
int64_t value;
|
||||
float value;
|
||||
bool isRetalitated;
|
||||
BattleHex position;
|
||||
|
||||
@@ -25,20 +25,23 @@ struct AttackerValue
|
||||
|
||||
struct MoveTarget
|
||||
{
|
||||
int64_t score;
|
||||
float score;
|
||||
float scorePerTurn;
|
||||
std::vector<BattleHex> positions;
|
||||
std::optional<AttackPossibility> cachedAttack;
|
||||
uint8_t turnsToRich;
|
||||
|
||||
MoveTarget();
|
||||
};
|
||||
|
||||
struct EvaluationResult
|
||||
{
|
||||
static const int64_t INEFFECTIVE_SCORE = -1000000;
|
||||
static const int64_t INEFFECTIVE_SCORE = -10000;
|
||||
|
||||
AttackPossibility bestAttack;
|
||||
MoveTarget bestMove;
|
||||
bool wait;
|
||||
int64_t score;
|
||||
float score;
|
||||
bool defend;
|
||||
|
||||
EvaluationResult(const AttackPossibility & ap)
|
||||
@@ -56,19 +59,24 @@ struct EvaluationResult
|
||||
class BattleExchangeVariant
|
||||
{
|
||||
public:
|
||||
BattleExchangeVariant(): dpsScore(0) {}
|
||||
BattleExchangeVariant(float positiveEffectMultiplier, float negativeEffectMultiplier)
|
||||
: dpsScore(0), positiveEffectMultiplier(positiveEffectMultiplier), negativeEffectMultiplier(negativeEffectMultiplier) {}
|
||||
|
||||
int64_t trackAttack(const AttackPossibility & ap, HypotheticBattle & state);
|
||||
float trackAttack(
|
||||
const AttackPossibility & ap,
|
||||
std::shared_ptr<HypotheticBattle> hb,
|
||||
DamageCache & damageCache);
|
||||
|
||||
int64_t trackAttack(
|
||||
float trackAttack(
|
||||
std::shared_ptr<StackWithBonuses> attacker,
|
||||
std::shared_ptr<StackWithBonuses> defender,
|
||||
bool shooting,
|
||||
bool isOurAttack,
|
||||
const CBattleInfoCallback & cb,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<HypotheticBattle> hb,
|
||||
bool evaluateOnly = false);
|
||||
|
||||
int64_t getScore() const { return dpsScore; }
|
||||
float getScore() const { return dpsScore; }
|
||||
|
||||
void adjustPositions(
|
||||
std::vector<const battle::Unit *> attackers,
|
||||
@@ -76,7 +84,9 @@ public:
|
||||
std::map<BattleHex, battle::Units> & reachabilityMap);
|
||||
|
||||
private:
|
||||
int64_t dpsScore;
|
||||
float positiveEffectMultiplier;
|
||||
float negativeEffectMultiplier;
|
||||
float dpsScore;
|
||||
std::map<uint32_t, AttackerValue> attackerValue;
|
||||
};
|
||||
|
||||
@@ -87,15 +97,40 @@ private:
|
||||
std::shared_ptr<Environment> env;
|
||||
std::map<BattleHex, std::vector<const battle::Unit *>> reachabilityMap;
|
||||
std::vector<battle::Units> turnOrder;
|
||||
float negativeEffectMultiplier;
|
||||
|
||||
public:
|
||||
BattleExchangeEvaluator(std::shared_ptr<CBattleInfoCallback> cb, std::shared_ptr<Environment> env): cb(cb), env(env) {}
|
||||
BattleExchangeEvaluator(
|
||||
std::shared_ptr<CBattleInfoCallback> cb,
|
||||
std::shared_ptr<Environment> env,
|
||||
float strengthRatio): cb(cb), env(env) {
|
||||
negativeEffectMultiplier = strengthRatio;
|
||||
}
|
||||
|
||||
EvaluationResult findBestTarget(const battle::Unit * activeStack, PotentialTargets & targets, HypotheticBattle & hb);
|
||||
int64_t calculateExchange(const AttackPossibility & ap, PotentialTargets & targets, HypotheticBattle & hb);
|
||||
void updateReachabilityMap(HypotheticBattle & hb);
|
||||
std::vector<const battle::Unit *> getExchangeUnits(const AttackPossibility & ap, PotentialTargets & targets, HypotheticBattle & hb);
|
||||
EvaluationResult findBestTarget(
|
||||
const battle::Unit * activeStack,
|
||||
PotentialTargets & targets,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<HypotheticBattle> hb);
|
||||
|
||||
float calculateExchange(
|
||||
const AttackPossibility & ap,
|
||||
PotentialTargets & targets,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<HypotheticBattle> hb);
|
||||
|
||||
void updateReachabilityMap(std::shared_ptr<HypotheticBattle> hb);
|
||||
std::vector<const battle::Unit *> getExchangeUnits(const AttackPossibility & ap, PotentialTargets & targets, std::shared_ptr<HypotheticBattle> hb);
|
||||
bool checkPositionBlocksOurStacks(HypotheticBattle & hb, const battle::Unit * unit, BattleHex position);
|
||||
MoveTarget findMoveTowardsUnreachable(const battle::Unit * activeStack, PotentialTargets & targets, HypotheticBattle & hb);
|
||||
|
||||
MoveTarget findMoveTowardsUnreachable(
|
||||
const battle::Unit * activeStack,
|
||||
PotentialTargets & targets,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<HypotheticBattle> hb);
|
||||
|
||||
std::vector<const battle::Unit *> getAdjacentUnits(const battle::Unit * unit);
|
||||
|
||||
float getPositiveEffectMultiplier() { return 1; }
|
||||
float getNegativeEffectMultiplier() { return negativeEffectMultiplier; }
|
||||
};
|
@@ -1,6 +1,7 @@
|
||||
set(battleAI_SRCS
|
||||
AttackPossibility.cpp
|
||||
BattleAI.cpp
|
||||
BattleEvaluator.cpp
|
||||
common.cpp
|
||||
EnemyInfo.cpp
|
||||
PossibleSpellcast.cpp
|
||||
@@ -15,6 +16,7 @@ set(battleAI_HEADERS
|
||||
|
||||
AttackPossibility.h
|
||||
BattleAI.h
|
||||
BattleEvaluator.h
|
||||
common.h
|
||||
EnemyInfo.h
|
||||
PotentialTargets.h
|
||||
@@ -37,7 +39,11 @@ else()
|
||||
endif()
|
||||
|
||||
target_include_directories(BattleAI PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(BattleAI PRIVATE ${VCMI_LIB_TARGET})
|
||||
target_link_libraries(BattleAI PRIVATE ${VCMI_LIB_TARGET} TBB::tbb)
|
||||
|
||||
vcmi_set_output_dir(BattleAI "AI")
|
||||
enable_pch(BattleAI)
|
||||
|
||||
if(APPLE_IOS AND NOT USING_CONAN)
|
||||
install(IMPORTED_RUNTIME_ARTIFACTS TBB::tbb LIBRARY DESTINATION ${LIB_DIR}) # CMake 3.21+
|
||||
endif()
|
||||
|
@@ -27,7 +27,7 @@ public:
|
||||
|
||||
const CSpell * spell;
|
||||
spells::Target dest;
|
||||
int64_t value;
|
||||
float value;
|
||||
|
||||
PossibleSpellcast();
|
||||
virtual ~PossibleSpellcast();
|
||||
|
@@ -11,11 +11,14 @@
|
||||
#include "PotentialTargets.h"
|
||||
#include "../../lib/CStack.h"//todo: remove
|
||||
|
||||
PotentialTargets::PotentialTargets(const battle::Unit * attacker, const HypotheticBattle & state)
|
||||
PotentialTargets::PotentialTargets(
|
||||
const battle::Unit * attacker,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<HypotheticBattle> state)
|
||||
{
|
||||
auto attackerInfo = state.battleGetUnitByID(attacker->unitId());
|
||||
auto reachability = state.getReachability(attackerInfo);
|
||||
auto avHexes = state.battleGetAvailableHexes(reachability, attackerInfo, false);
|
||||
auto attackerInfo = state->battleGetUnitByID(attacker->unitId());
|
||||
auto reachability = state->getReachability(attackerInfo);
|
||||
auto avHexes = state->battleGetAvailableHexes(reachability, attackerInfo, false);
|
||||
|
||||
//FIXME: this should part of battleGetAvailableHexes
|
||||
bool forceTarget = false;
|
||||
@@ -25,7 +28,7 @@ PotentialTargets::PotentialTargets(const battle::Unit * attacker, const Hypothet
|
||||
if(attackerInfo->hasBonusOfType(BonusType::ATTACKS_NEAREST_CREATURE))
|
||||
{
|
||||
forceTarget = true;
|
||||
auto nearest = state.getNearestStack(attackerInfo);
|
||||
auto nearest = state->getNearestStack(attackerInfo);
|
||||
|
||||
if(nearest.first != nullptr)
|
||||
{
|
||||
@@ -34,14 +37,14 @@ PotentialTargets::PotentialTargets(const battle::Unit * attacker, const Hypothet
|
||||
}
|
||||
}
|
||||
|
||||
auto aliveUnits = state.battleGetUnitsIf([=](const battle::Unit * unit)
|
||||
auto aliveUnits = state->battleGetUnitsIf([=](const battle::Unit * unit)
|
||||
{
|
||||
return unit->isValidTarget() && unit->unitId() != attackerInfo->unitId();
|
||||
});
|
||||
|
||||
for(auto defender : aliveUnits)
|
||||
{
|
||||
if(!forceTarget && !state.battleMatchOwner(attackerInfo, defender))
|
||||
if(!forceTarget && !state->battleMatchOwner(attackerInfo, defender))
|
||||
continue;
|
||||
|
||||
auto GenerateAttackInfo = [&](bool shooting, BattleHex hex) -> AttackPossibility
|
||||
@@ -49,7 +52,7 @@ PotentialTargets::PotentialTargets(const battle::Unit * attacker, const Hypothet
|
||||
int distance = hex.isValid() ? reachability.distances[hex] : 0;
|
||||
auto bai = BattleAttackInfo(attackerInfo, defender, distance, shooting);
|
||||
|
||||
return AttackPossibility::evaluate(bai, hex, state);
|
||||
return AttackPossibility::evaluate(bai, hex, damageCache, state);
|
||||
};
|
||||
|
||||
if(forceTarget)
|
||||
@@ -59,7 +62,7 @@ PotentialTargets::PotentialTargets(const battle::Unit * attacker, const Hypothet
|
||||
else
|
||||
unreachableEnemies.push_back(defender);
|
||||
}
|
||||
else if(state.battleCanShoot(attackerInfo, defender->getPosition()))
|
||||
else if(state->battleCanShoot(attackerInfo, defender->getPosition()))
|
||||
{
|
||||
possibleAttacks.push_back(GenerateAttackInfo(true, BattleHex::INVALID));
|
||||
}
|
||||
|
@@ -17,7 +17,10 @@ public:
|
||||
std::vector<const battle::Unit *> unreachableEnemies;
|
||||
|
||||
PotentialTargets(){};
|
||||
PotentialTargets(const battle::Unit * attacker, const HypotheticBattle & state);
|
||||
PotentialTargets(
|
||||
const battle::Unit * attacker,
|
||||
DamageCache & damageCache,
|
||||
std::shared_ptr<HypotheticBattle> hb);
|
||||
|
||||
const AttackPossibility & bestAction() const;
|
||||
int64_t bestActionValue() const;
|
||||
|
@@ -45,13 +45,32 @@ StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle:
|
||||
id(Stack->unitId()),
|
||||
side(Stack->unitSide()),
|
||||
player(Stack->unitOwner()),
|
||||
slot(Stack->unitSlot())
|
||||
slot(Stack->unitSlot()),
|
||||
treeVersionLocal(0)
|
||||
{
|
||||
localInit(Owner);
|
||||
|
||||
battle::CUnitState::operator=(*Stack);
|
||||
}
|
||||
|
||||
StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle::Unit * Stack)
|
||||
: battle::CUnitState(),
|
||||
origBearer(Stack->getBonusBearer()),
|
||||
owner(Owner),
|
||||
type(Stack->unitType()),
|
||||
baseAmount(Stack->unitBaseAmount()),
|
||||
id(Stack->unitId()),
|
||||
side(Stack->unitSide()),
|
||||
player(Stack->unitOwner()),
|
||||
slot(Stack->unitSlot()),
|
||||
treeVersionLocal(0)
|
||||
{
|
||||
localInit(Owner);
|
||||
|
||||
auto state = Stack->acquireState();
|
||||
battle::CUnitState::operator=(*state);
|
||||
}
|
||||
|
||||
StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle::UnitInfo & info)
|
||||
: battle::CUnitState(),
|
||||
origBearer(nullptr),
|
||||
@@ -59,7 +78,8 @@ StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle:
|
||||
baseAmount(info.count),
|
||||
id(info.id),
|
||||
side(info.side),
|
||||
slot(SlotID::SUMMONED_SLOT_PLACEHOLDER)
|
||||
slot(SlotID::SUMMONED_SLOT_PLACEHOLDER),
|
||||
treeVersionLocal(0)
|
||||
{
|
||||
type = info.type.toCreature();
|
||||
origBearer = type;
|
||||
@@ -124,7 +144,7 @@ TConstBonusListPtr StackWithBonuses::getAllBonuses(const CSelector & selector, c
|
||||
|
||||
for(const Bonus & bonus : bonusesToUpdate)
|
||||
{
|
||||
if(selector(&bonus) && (!limit || !limit(&bonus)))
|
||||
if(selector(&bonus) && (!limit || limit(&bonus)))
|
||||
{
|
||||
if(ret->getFirst(Selector::source(BonusSource::SPELL_EFFECT, bonus.sid).And(Selector::typeSubtype(bonus.type, bonus.subtype))))
|
||||
{
|
||||
@@ -150,12 +170,18 @@ TConstBonusListPtr StackWithBonuses::getAllBonuses(const CSelector & selector, c
|
||||
|
||||
int64_t StackWithBonuses::getTreeVersion() const
|
||||
{
|
||||
return owner->getTreeVersion();
|
||||
auto result = owner->getTreeVersion();
|
||||
|
||||
if(bonusesToAdd.empty() && bonusesToUpdate.empty() && bonusesToRemove.empty())
|
||||
return result;
|
||||
else
|
||||
return result + treeVersionLocal;
|
||||
}
|
||||
|
||||
void StackWithBonuses::addUnitBonus(const std::vector<Bonus> & bonus)
|
||||
{
|
||||
vstd::concatenate(bonusesToAdd, bonus);
|
||||
treeVersionLocal++;
|
||||
}
|
||||
|
||||
void StackWithBonuses::updateUnitBonus(const std::vector<Bonus> & bonus)
|
||||
@@ -163,6 +189,7 @@ void StackWithBonuses::updateUnitBonus(const std::vector<Bonus> & bonus)
|
||||
//TODO: optimize, actualize to last value
|
||||
|
||||
vstd::concatenate(bonusesToUpdate, bonus);
|
||||
treeVersionLocal++;
|
||||
}
|
||||
|
||||
void StackWithBonuses::removeUnitBonus(const std::vector<Bonus> & bonus)
|
||||
@@ -197,6 +224,8 @@ void StackWithBonuses::removeUnitBonus(const CSelector & selector)
|
||||
|
||||
vstd::erase_if(bonusesToAdd, [&](const Bonus & b){return selector(&b);});
|
||||
vstd::erase_if(bonusesToUpdate, [&](const Bonus & b){return selector(&b);});
|
||||
|
||||
treeVersionLocal++;
|
||||
}
|
||||
|
||||
std::string StackWithBonuses::getDescription() const
|
||||
@@ -256,7 +285,7 @@ std::shared_ptr<StackWithBonuses> HypotheticBattle::getForUpdate(uint32_t id)
|
||||
|
||||
if(iter == stackStates.end())
|
||||
{
|
||||
const CStack * s = subject->battleGetStackByID(id, false);
|
||||
const battle::Unit * s = subject->battleGetUnitByID(id);
|
||||
|
||||
auto ret = std::make_shared<StackWithBonuses>(this, s);
|
||||
stackStates[id] = ret;
|
||||
|
@@ -47,9 +47,12 @@ public:
|
||||
std::vector<Bonus> bonusesToAdd;
|
||||
std::vector<Bonus> bonusesToUpdate;
|
||||
std::set<std::shared_ptr<Bonus>> bonusesToRemove;
|
||||
int treeVersionLocal;
|
||||
|
||||
StackWithBonuses(const HypotheticBattle * Owner, const battle::CUnitState * Stack);
|
||||
|
||||
StackWithBonuses(const HypotheticBattle * Owner, const battle::Unit * Stack);
|
||||
|
||||
StackWithBonuses(const HypotheticBattle * Owner, const battle::UnitInfo & info);
|
||||
|
||||
virtual ~StackWithBonuses();
|
||||
|
@@ -138,8 +138,8 @@ void Nullkiller::updateAiState(int pass, bool fast)
|
||||
{
|
||||
memory->removeInvisibleObjects(cb.get());
|
||||
|
||||
dangerHitMap->calculateTileOwners();
|
||||
dangerHitMap->updateHitMap();
|
||||
dangerHitMap->calculateTileOwners();
|
||||
|
||||
boost::this_thread::interruption_point();
|
||||
|
||||
|
Reference in New Issue
Block a user