2021-05-15 18:22:44 +02:00
/*
2021-05-16 14:39:38 +02:00
* AIGateway . cpp , part of VCMI engine
2021-05-15 18:22:44 +02:00
*
* 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"
2023-07-24 18:09:17 +02:00
# include "../../lib/ArtifactUtils.h"
2021-05-15 18:22:44 +02:00
# include "../../lib/UnlockGuard.h"
# include "../../lib/mapObjects/MapObjects.h"
2023-06-02 20:47:37 +02:00
# include "../../lib/mapObjects/ObjectTemplate.h"
2023-10-23 12:59:15 +02:00
# include "../../lib/mapObjects/CGHeroInstance.h"
2021-05-15 18:22:44 +02:00
# include "../../lib/CConfigHandler.h"
# include "../../lib/CHeroHandler.h"
2023-03-15 21:34:29 +02:00
# include "../../lib/GameSettings.h"
2023-06-23 17:02:48 +02:00
# include "../../lib/gameState/CGameState.h"
2021-05-15 18:22:44 +02:00
# include "../../lib/serializer/CTypeList.h"
# include "../../lib/serializer/BinarySerializer.h"
# include "../../lib/serializer/BinaryDeserializer.h"
2023-10-23 12:59:15 +02:00
# include "../../lib/networkPacks/PacksForClient.h"
# include "../../lib/networkPacks/PacksForClientBattle.h"
# include "../../lib/networkPacks/PacksForServer.h"
# include "../../lib/networkPacks/StackLocation.h"
2022-10-14 10:24:29 +02:00
# include "../../lib/battle/BattleStateInfoForRetreat.h"
2023-08-28 17:59:12 +02:00
# include "../../lib/battle/BattleInfo.h"
2021-05-15 18:22:44 +02:00
2021-05-16 14:39:38 +02:00
# include "AIGateway.h"
2021-05-16 13:55:47 +02:00
# include "Goals/Goals.h"
2021-05-15 18:22:44 +02:00
2022-09-26 20:01:07 +02:00
namespace NKAI
{
2021-05-15 18:22:44 +02:00
2022-04-11 08:12:41 +02:00
// our to enemy strength ratio constants
2023-06-04 15:02:02 +02:00
const float SAFE_ATTACK_CONSTANT = 1.1f ;
2022-12-08 23:20:42 +02:00
const float RETREAT_THRESHOLD = 0.3f ;
2022-12-06 14:11:52 +02:00
const double RETREAT_ABSOLUTE_THRESHOLD = 10000. ;
2021-05-15 18:22:44 +02:00
//one thread may be turn of AI and another will be handling a side effect for AI2
2023-07-31 16:00:37 +02:00
thread_local CCallback * cb = nullptr ;
thread_local AIGateway * ai = nullptr ;
2021-05-15 18:22:44 +02:00
//helper RAII to manage global ai/cb ptrs
struct SetGlobalState
{
2021-05-16 14:39:38 +02:00
SetGlobalState ( AIGateway * AI )
2021-05-15 18:22:44 +02:00
{
2023-07-31 16:00:37 +02:00
assert ( ! ai ) ;
assert ( ! cb ) ;
2021-05-15 18:22:44 +02:00
2023-07-31 16:00:37 +02:00
ai = AI ;
cb = AI - > myCb . get ( ) ;
2021-05-15 18:22:44 +02:00
}
~ SetGlobalState ( )
{
//TODO: how to handle rm? shouldn't be called after ai is destroyed, hopefully
//TODO: to ensure that, make rm unique_ptr
2023-07-31 16:00:37 +02:00
ai = nullptr ;
cb = nullptr ;
2021-05-15 18:22:44 +02:00
}
} ;
2024-01-14 16:00:32 +02:00
# define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai)
2021-05-15 18:22:44 +02:00
# define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
# define MAKING_TURN SET_GLOBAL_STATE(this)
2021-05-16 14:39:38 +02:00
AIGateway : : AIGateway ( )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
makingTurn = nullptr ;
destinationTeleport = ObjectInstanceID ( ) ;
destinationTeleportPos = int3 ( - 1 ) ;
2020-05-04 17:58:43 +02:00
nullkiller . reset ( new Nullkiller ( ) ) ;
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
AIGateway : : ~ AIGateway ( )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
finish ( ) ;
2021-05-16 13:57:15 +02:00
nullkiller . reset ( ) ;
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
void AIGateway : : availableCreaturesChanged ( const CGDwelling * town )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2022-01-25 13:19:48 +02:00
void AIGateway : : heroMoved ( const TryMoveHero & details , bool verbose )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
auto hero = cb - > getHero ( details . id ) ;
2023-06-04 15:02:02 +02:00
if ( ! hero )
validateObject ( details . id ) ; //enemy hero may have left visible area
2024-01-16 21:02:39 +02:00
const int3 from = hero ? hero - > convertToVisitablePos ( details . start ) : ( details . start - int3 ( 0 , 1 , 0 ) ) ;
2022-12-25 16:12:26 +02:00
const int3 to = hero ? hero - > convertToVisitablePos ( details . end ) : ( details . end - int3 ( 0 , 1 , 0 ) ) ;
2022-01-25 13:19:48 +02:00
const CGObjectInstance * o1 = vstd : : frontOrNull ( cb - > getVisitableObjs ( from , verbose ) ) ;
const CGObjectInstance * o2 = vstd : : frontOrNull ( cb - > getVisitableObjs ( to , verbose ) ) ;
2021-05-15 18:22:44 +02:00
if ( details . result = = TryMoveHero : : TELEPORTATION )
{
auto t1 = dynamic_cast < const CGTeleport * > ( o1 ) ;
auto t2 = dynamic_cast < const CGTeleport * > ( o2 ) ;
if ( t1 & & t2 )
{
if ( cb - > isTeleportChannelBidirectional ( t1 - > channel ) )
{
if ( o1 - > ID = = Obj : : SUBTERRANEAN_GATE & & o1 - > ID = = o2 - > ID ) // We need to only add subterranean gates in knownSubterraneanGates. Used for features not yet ported to use teleport channels
{
2020-05-04 17:58:43 +02:00
nullkiller - > memory - > addSubterraneanGate ( o1 , o2 ) ;
2021-05-15 18:22:44 +02:00
}
}
}
}
else if ( details . result = = TryMoveHero : : EMBARK & & hero )
{
//make sure AI not attempt to visit used boat
validateObject ( hero - > boat ) ;
}
else if ( details . result = = TryMoveHero : : DISEMBARK & & o1 )
{
auto boat = dynamic_cast < const CGBoat * > ( o1 ) ;
if ( boat )
addVisitableObj ( boat ) ;
}
}
2021-05-16 14:39:38 +02:00
void AIGateway : : heroInGarrisonChange ( const CGTownInstance * town )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : centerView ( int3 pos , int focusTime )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " focusTime '%i' " , focusTime ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : artifactMoved ( const ArtifactLocation & src , const ArtifactLocation & dst )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : artifactAssembled ( const ArtifactLocation & al )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2023-09-28 00:17:05 +02:00
void AIGateway : : showTavernWindow ( const CGObjectInstance * object , const CGHeroInstance * visitor , QueryID queryID )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
2023-09-28 00:17:05 +02:00
status . addQuery ( queryID , " TavernWindow " ) ;
requestActionASAP ( [ = ] ( ) { answerQuery ( queryID , 0 ) ; } ) ;
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
void AIGateway : : showThievesGuildWindow ( const CGObjectInstance * obj )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : playerBlocked ( int reason , bool start )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " reason '%i', start '%i' " , reason % start ) ;
NET_EVENT_HANDLER ;
if ( start & & reason = = PlayerBlocked : : UPCOMING_BATTLE )
status . setBattle ( UPCOMING_BATTLE ) ;
if ( reason = = PlayerBlocked : : ONGOING_MOVEMENT )
status . setMove ( start ) ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : showPuzzleMap ( )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : showShipyardDialog ( const IShipyard * obj )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : gameOver ( PlayerColor player , const EVictoryLossCheckResult & victoryLossCheckResult )
2021-05-15 18:22:44 +02:00
{
2023-06-18 12:51:11 +02:00
LOG_TRACE_PARAMS ( logAi , " victoryLossCheckResult '%s' " , victoryLossCheckResult . messageToSelf . toString ( ) ) ;
2021-05-15 18:22:44 +02:00
NET_EVENT_HANDLER ;
2023-09-04 21:21:02 +02:00
logAi - > debug ( " Player %d (%s): I heard that player %d (%s) %s. " , playerID , playerID . toString ( ) , player , player . toString ( ) , ( victoryLossCheckResult . victory ( ) ? " won " : " lost " ) ) ;
2021-05-16 13:19:44 +02:00
// some whitespace to flush stream
logAi - > debug ( std : : string ( 200 , ' ' ) ) ;
2021-05-15 18:22:44 +02:00
if ( player = = playerID )
{
if ( victoryLossCheckResult . victory ( ) )
{
2023-09-04 21:21:02 +02:00
logAi - > debug ( " AIGateway: Player %d (%s) won. I won! Incredible! " , player , player . toString ( ) ) ;
2021-05-15 18:22:44 +02:00
logAi - > debug ( " Turn nr %d " , myCb - > getDate ( ) ) ;
}
else
{
2023-09-04 21:21:02 +02:00
logAi - > debug ( " AIGateway: Player %d (%s) lost. It's me. What a disappointment! :( " , player , player . toString ( ) ) ;
2021-05-15 18:22:44 +02:00
}
2022-04-11 08:12:41 +02:00
// some whitespace to flush stream
logAi - > debug ( std : : string ( 200 , ' ' ) ) ;
2021-05-15 18:22:44 +02:00
finish ( ) ;
}
}
2021-05-16 14:39:38 +02:00
void AIGateway : : artifactPut ( const ArtifactLocation & al )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : artifactRemoved ( const ArtifactLocation & al )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : artifactDisassembled ( const ArtifactLocation & al )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : heroVisit ( const CGHeroInstance * visitor , const CGObjectInstance * visitedObj , bool start )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " start '%i'; obj '%s' " , start % ( visitedObj ? visitedObj - > getObjectName ( ) : std : : string ( " n/a " ) ) ) ;
NET_EVENT_HANDLER ;
if ( start & & visitedObj ) //we can end visit with null object, anyway
{
2020-05-04 17:58:43 +02:00
nullkiller - > memory - > markObjectVisited ( visitedObj ) ;
2024-04-14 14:23:44 +02:00
nullkiller - > objectClusterizer - > invalidate ( visitedObj - > id ) ;
2021-05-15 18:22:44 +02:00
}
status . heroVisit ( visitedObj , start ) ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : availableArtifactsChanged ( const CGBlackMarket * bm )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : heroVisitsTown ( const CGHeroInstance * hero , const CGTownInstance * town )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2023-04-16 00:48:49 +02:00
void AIGateway : : tileHidden ( const std : : unordered_set < int3 > & pos )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
2020-05-04 17:58:43 +02:00
nullkiller - > memory - > removeInvisibleObjects ( myCb . get ( ) ) ;
2021-05-15 18:22:44 +02:00
}
2023-04-16 00:48:49 +02:00
void AIGateway : : tileRevealed ( const std : : unordered_set < int3 > & pos )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
for ( int3 tile : pos )
{
for ( const CGObjectInstance * obj : myCb - > getVisitableObjs ( tile ) )
addVisitableObj ( obj ) ;
}
}
2021-05-16 14:39:38 +02:00
void AIGateway : : heroExchangeStarted ( ObjectInstanceID hero1 , ObjectInstanceID hero2 , QueryID query )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
auto firstHero = cb - > getHero ( hero1 ) ;
auto secondHero = cb - > getHero ( hero2 ) ;
2023-01-02 13:27:03 +02:00
status . addQuery ( query , boost : : str ( boost : : format ( " Exchange between heroes %s (%d) and %s (%d) " ) % firstHero - > getNameTranslated ( ) % firstHero - > tempOwner % secondHero - > getNameTranslated ( ) % secondHero - > tempOwner ) ) ;
2021-05-15 18:22:44 +02:00
requestActionASAP ( [ = ] ( )
{
auto transferFrom2to1 = [ this ] ( const CGHeroInstance * h1 , const CGHeroInstance * h2 ) - > void
{
this - > pickBestCreatures ( h1 , h2 ) ;
this - > pickBestArtifacts ( h1 , h2 ) ;
} ;
//Do not attempt army or artifacts exchange if we visited ally player
//Visits can still be useful if hero have skills like Scholar
if ( firstHero - > tempOwner ! = secondHero - > tempOwner )
{
logAi - > debug ( " Heroes owned by different players. Do not exchange army or artifacts. " ) ;
}
2021-05-16 13:38:26 +02:00
else
2021-05-15 20:27:22 +02:00
{
if ( nullkiller - > isActive ( firstHero ) )
transferFrom2to1 ( secondHero , firstHero ) ;
else
transferFrom2to1 ( firstHero , secondHero ) ;
}
2021-05-15 18:22:44 +02:00
answerQuery ( query , 0 ) ;
} ) ;
}
2023-08-19 20:43:50 +02:00
void AIGateway : : heroPrimarySkillChanged ( const CGHeroInstance * hero , PrimarySkill which , si64 val )
2021-05-15 18:22:44 +02:00
{
2023-08-19 20:43:50 +02:00
LOG_TRACE_PARAMS ( logAi , " which '%i', val '%i' " , static_cast < int > ( which ) % val ) ;
2021-05-15 18:22:44 +02:00
NET_EVENT_HANDLER ;
}
2023-10-04 16:24:19 +02:00
void AIGateway : : showRecruitmentDialog ( const CGDwelling * dwelling , const CArmedInstance * dst , int level , QueryID queryID )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " level '%i' " , level ) ;
NET_EVENT_HANDLER ;
2023-10-04 16:24:19 +02:00
status . addQuery ( queryID , " RecruitmentDialog " ) ;
2023-10-04 16:38:38 +02:00
requestActionASAP ( [ = ] ( ) {
recruitCreatures ( dwelling , dst ) ;
answerQuery ( queryID , 0 ) ;
} ) ;
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
void AIGateway : : heroMovePointsChanged ( const CGHeroInstance * hero )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : garrisonsChanged ( ObjectInstanceID id1 , ObjectInstanceID id2 )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : newObject ( const CGObjectInstance * obj )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
if ( obj - > isVisitable ( ) )
addVisitableObj ( obj ) ;
}
//to prevent AI from accessing objects that got deleted while they became invisible (Cover of Darkness, enemy hero moved etc.) below code allows AI to know deletion of objects out of sight
//see: RemoveObject::applyFirstCl, to keep AI "not cheating" do not use advantage of this and use this function just to prevent crashes
2023-09-18 21:09:55 +02:00
void AIGateway : : objectRemoved ( const CGObjectInstance * obj , const PlayerColor & initiator )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
2021-05-16 13:56:27 +02:00
if ( ! nullkiller ) // crash protection
return ;
2020-05-04 17:58:43 +02:00
nullkiller - > memory - > removeFromMemory ( obj ) ;
2024-04-14 14:23:44 +02:00
nullkiller - > objectClusterizer - > onObjectRemoved ( obj - > id ) ;
2024-03-08 14:39:16 +02:00
if ( nullkiller - > baseGraph & & nullkiller - > settings - > isObjectGraphAllowed ( ) )
{
nullkiller - > baseGraph - > removeObject ( obj ) ;
}
2021-05-15 18:22:44 +02:00
if ( obj - > ID = = Obj : : HERO & & obj - > tempOwner = = playerID )
{
lostHero ( cb - > getHero ( obj - > id ) ) ; //we can promote, since objectRemoved is called just before actual deletion
}
2023-02-28 09:07:59 +02:00
if ( obj - > ID = = Obj : : HERO & & cb - > getPlayerRelations ( obj - > tempOwner , playerID ) = = PlayerRelations : : ENEMIES )
{
nullkiller - > dangerHitMap - > reset ( ) ;
}
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
void AIGateway : : showHillFortWindow ( const CGObjectInstance * object , const CGHeroInstance * visitor )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : playerBonusChanged ( const Bonus & bonus , bool gain )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " gain '%i' " , gain ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : heroCreated ( const CGHeroInstance * h )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2023-09-04 12:03:15 +02:00
void AIGateway : : advmapSpellCast ( const CGHeroInstance * caster , SpellID spellID )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " spellID '%i " , spellID ) ;
NET_EVENT_HANDLER ;
}
2023-03-06 01:30:21 +02:00
void AIGateway : : showInfoDialog ( EInfoWindowMode type , const std : : string & text , const std : : vector < Component > & components , int soundID )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " soundID '%i' " , soundID ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : requestRealized ( PackageApplied * pa )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
if ( status . haveTurn ( ) )
{
2023-11-08 22:05:36 +02:00
if ( pa - > packType = = CTypeList : : getInstance ( ) . getTypeID < EndTurn > ( nullptr ) )
2021-05-15 18:22:44 +02:00
{
if ( pa - > result )
status . madeTurn ( ) ;
}
}
2023-11-08 22:05:36 +02:00
if ( pa - > packType = = CTypeList : : getInstance ( ) . getTypeID < QueryReply > ( nullptr ) )
2021-05-15 18:22:44 +02:00
{
status . receivedAnswerConfirmation ( pa - > requestID , pa - > result ) ;
}
}
2021-05-16 14:39:38 +02:00
void AIGateway : : receivedResource ( )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2023-09-28 00:17:05 +02:00
void AIGateway : : showUniversityWindow ( const IMarket * market , const CGHeroInstance * visitor , QueryID queryID )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
2023-09-28 00:17:05 +02:00
status . addQuery ( queryID , " UniversityWindow " ) ;
requestActionASAP ( [ = ] ( ) { answerQuery ( queryID , 0 ) ; } ) ;
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
void AIGateway : : heroManaPointsChanged ( const CGHeroInstance * hero )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : heroSecondarySkillChanged ( const CGHeroInstance * hero , int which , int val )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " which '%d', val '%d' " , which % val ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : battleResultsApplied ( )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
assert ( status . getBattle ( ) = = ENDING_BATTLE ) ;
status . setBattle ( NO_BATTLE ) ;
}
2023-07-04 19:02:41 +02:00
void AIGateway : : beforeObjectPropertyChanged ( const SetObjectProperty * sop )
{
}
2021-05-16 14:39:38 +02:00
void AIGateway : : objectPropertyChanged ( const SetObjectProperty * sop )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
if ( sop - > what = = ObjProperty : : OWNER )
{
2023-11-06 18:27:16 +02:00
auto relations = myCb - > getPlayerRelations ( playerID , sop - > identifier . as < PlayerColor > ( ) ) ;
2021-05-16 13:13:56 +02:00
auto obj = myCb - > getObj ( sop - > id , false ) ;
2021-05-16 13:56:27 +02:00
if ( ! nullkiller ) // crash protection
return ;
2021-05-16 13:13:56 +02:00
if ( obj )
2021-05-15 18:22:44 +02:00
{
2021-05-16 13:13:56 +02:00
if ( relations = = PlayerRelations : : ENEMIES )
2021-05-15 18:22:44 +02:00
{
2021-05-16 13:13:56 +02:00
//we want to visit objects owned by oppponents
2020-05-04 17:58:43 +02:00
//addVisitableObj(obj); // TODO: Remove once save compatability broken. In past owned objects were removed from this set
nullkiller - > memory - > markObjectUnvisited ( obj ) ;
2021-05-15 18:22:44 +02:00
}
2020-05-04 17:58:43 +02:00
else if ( relations = = PlayerRelations : : SAME_PLAYER & & obj - > ID = = Obj : : TOWN )
2021-05-16 13:13:56 +02:00
{
// reevaluate defence for a new town
nullkiller - > dangerHitMap - > reset ( ) ;
}
2021-05-15 18:22:44 +02:00
}
}
}
2021-05-16 14:39:38 +02:00
void AIGateway : : buildChanged ( const CGTownInstance * town , BuildingID buildingID , int what )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " what '%i' " , what ) ;
NET_EVENT_HANDLER ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : heroBonusChanged ( const CGHeroInstance * hero , const Bonus & bonus , bool gain )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " gain '%i' " , gain ) ;
NET_EVENT_HANDLER ;
}
2023-09-28 00:17:05 +02:00
void AIGateway : : showMarketWindow ( const IMarket * market , const CGHeroInstance * visitor , QueryID queryID )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
2023-09-28 00:17:05 +02:00
status . addQuery ( queryID , " MarketWindow " ) ;
requestActionASAP ( [ = ] ( ) { answerQuery ( queryID , 0 ) ; } ) ;
2021-05-15 18:22:44 +02:00
}
2023-02-21 14:38:08 +02:00
void AIGateway : : showWorldViewEx ( const std : : vector < ObjectPosInfo > & objectPositions , bool showTerrain )
2021-05-15 18:22:44 +02:00
{
//TODO: AI support for ViewXXX spell
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
}
2023-08-28 17:59:12 +02:00
std : : optional < BattleAction > AIGateway : : makeSurrenderRetreatDecision ( const BattleID & battleID , const BattleStateInfoForRetreat & battleState )
2022-10-14 10:24:29 +02:00
{
LOG_TRACE ( logAi ) ;
NET_EVENT_HANDLER ;
2022-12-06 14:11:52 +02:00
double ourStrength = battleState . getOurStrength ( ) ;
double fightRatio = ourStrength / ( double ) battleState . getEnemyStrength ( ) ;
2022-10-14 10:24:29 +02:00
2022-10-15 14:05:20 +02:00
// if we have no towns - things are already bad, so retreat is not an option.
2022-12-06 14:11:52 +02:00
if ( cb - > getTownsInfo ( ) . size ( ) & & ourStrength < RETREAT_ABSOLUTE_THRESHOLD & & fightRatio < RETREAT_THRESHOLD & & battleState . canFlee )
2022-10-14 10:24:29 +02:00
{
return BattleAction : : makeRetreat ( battleState . ourSide ) ;
}
2023-04-16 19:42:56 +02:00
return std : : nullopt ;
2022-10-14 10:24:29 +02:00
}
2022-12-07 21:50:45 +02:00
void AIGateway : : initGameInterface ( std : : shared_ptr < Environment > env , std : : shared_ptr < CCallback > CB )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE ( logAi ) ;
myCb = CB ;
cbc = CB ;
2020-05-04 17:58:43 +02:00
NET_EVENT_HANDLER ;
2023-08-30 21:07:02 +02:00
playerID = * myCb - > getPlayerID ( ) ;
2021-05-15 18:22:44 +02:00
myCb - > waitTillRealize = true ;
myCb - > unlockGsWhenWaiting = true ;
2024-03-31 17:39:00 +02:00
nullkiller - > init ( CB , this ) ;
2020-09-02 19:16:24 +02:00
2021-05-15 18:22:44 +02:00
retrieveVisitableObjs ( ) ;
}
2023-08-28 02:42:05 +02:00
void AIGateway : : yourTurn ( QueryID queryID )
2021-05-15 18:22:44 +02:00
{
2023-08-28 02:42:05 +02:00
LOG_TRACE_PARAMS ( logAi , " queryID '%i' " , queryID ) ;
2021-05-15 18:22:44 +02:00
NET_EVENT_HANDLER ;
2023-08-28 02:42:05 +02:00
status . addQuery ( queryID , " YourTurn " ) ;
requestActionASAP ( [ = ] ( ) { answerQuery ( queryID , 0 ) ; } ) ;
2021-05-15 18:22:44 +02:00
status . startedTurn ( ) ;
2022-12-07 23:36:20 +02:00
makingTurn = std : : make_unique < boost : : thread > ( & AIGateway : : makeTurn , this ) ;
2021-05-15 18:22:44 +02:00
}
2023-08-19 20:43:50 +02:00
void AIGateway : : heroGotLevel ( const CGHeroInstance * hero , PrimarySkill pskill , std : : vector < SecondarySkill > & skills , QueryID queryID )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " queryID '%i' " , queryID ) ;
NET_EVENT_HANDLER ;
2021-05-16 13:57:05 +02:00
2023-01-02 13:27:03 +02:00
status . addQuery ( queryID , boost : : str ( boost : : format ( " Hero %s got level %d " ) % hero - > getNameTranslated ( ) % hero - > level ) ) ;
2021-05-16 13:57:05 +02:00
HeroPtr hPtr = hero ;
requestActionASAP ( [ = ] ( )
{
2023-12-23 15:53:51 +02:00
int sel = 0 ;
2021-05-16 13:57:05 +02:00
if ( hPtr . validAndSet ( ) )
{
2023-12-17 10:11:05 +02:00
std : : unique_lock < std : : mutex > lockGuard ( nullkiller - > aiStateMutex ) ;
2021-05-16 13:57:26 +02:00
nullkiller - > heroManager - > update ( ) ;
2023-12-23 15:53:51 +02:00
sel = nullkiller - > heroManager - > selectBestSkill ( hPtr , skills ) ;
2021-05-16 13:57:05 +02:00
}
2023-12-23 15:53:51 +02:00
answerQuery ( queryID , sel ) ;
2021-05-16 13:57:05 +02:00
} ) ;
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
void AIGateway : : commanderGotLevel ( const CCommanderInstance * commander , std : : vector < ui32 > skills , QueryID queryID )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " queryID '%i' " , queryID ) ;
NET_EVENT_HANDLER ;
status . addQuery ( queryID , boost : : str ( boost : : format ( " Commander %s of %s got level %d " ) % commander - > name % commander - > armyObj - > nodeName ( ) % ( int ) commander - > level ) ) ;
requestActionASAP ( [ = ] ( ) { answerQuery ( queryID , 0 ) ; } ) ;
}
2024-04-17 01:08:27 +02:00
void AIGateway : : showBlockingDialog ( const std : : string & text , const std : : vector < Component > & components , QueryID askID , const int soundID , bool selection , bool cancel , bool safeToAutoaccept )
2021-05-15 18:22:44 +02:00
{
2024-04-17 01:08:27 +02:00
LOG_TRACE_PARAMS ( logAi , " text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i' " , text % askID % soundID % selection % cancel % safeToAutoaccept ) ;
2021-05-15 18:22:44 +02:00
NET_EVENT_HANDLER ;
status . addQuery ( askID , boost : : str ( boost : : format ( " Blocking dialog query with %d components - %s " )
% components . size ( ) % text ) ) ;
2021-05-16 13:39:47 +02:00
auto hero = nullkiller - > getActiveHero ( ) ;
auto target = nullkiller - > getTargetTile ( ) ;
2021-05-15 18:22:44 +02:00
2021-05-16 13:22:41 +02:00
if ( ! selection & & cancel )
{
requestActionASAP ( [ = ] ( )
{
//yes&no -> always answer yes, we are a brave AI :)
2023-02-28 09:07:59 +02:00
bool answer = true ;
2021-05-16 13:39:18 +02:00
auto objects = cb - > getVisitableObjs ( target ) ;
if ( hero . validAndSet ( ) & & target . valid ( ) & & objects . size ( ) )
2021-05-16 13:22:41 +02:00
{
2023-03-05 15:42:15 +02:00
auto topObj = objects . front ( ) - > id = = hero - > id ? objects . back ( ) : objects . front ( ) ;
auto objType = topObj - > ID ; // top object should be our hero
auto goalObjectID = nullkiller - > getTargetObject ( ) ;
2024-02-13 23:42:05 +02:00
auto danger = nullkiller - > dangerEvaluator - > evaluateDanger ( target , hero . get ( ) ) ;
auto ratio = static_cast < float > ( danger ) / hero - > getTotalStrength ( ) ;
2021-05-16 13:22:41 +02:00
2023-03-05 15:42:15 +02:00
answer = topObj - > id = = goalObjectID ; // no if we do not aim to visit this object
logAi - > trace ( " Query hook: %s(%s) by %s danger ratio %f " , target . toString ( ) , topObj - > getObjectName ( ) , hero . name , ratio ) ;
if ( cb - > getObj ( goalObjectID , false ) )
{
logAi - > trace ( " AI expected %s " , cb - > getObj ( goalObjectID , false ) - > getObjectName ( ) ) ;
}
2023-02-28 09:07:59 +02:00
if ( objType = = Obj : : BORDERGUARD | | objType = = Obj : : QUEST_GUARD )
{
answer = true ;
}
else if ( objType = = Obj : : ARTIFACT | | objType = = Obj : : RESOURCE )
{
2024-02-13 23:42:05 +02:00
bool dangerUnknown = danger = = 0 ;
2023-03-05 15:42:15 +02:00
bool dangerTooHigh = ratio > ( 1 / SAFE_ATTACK_CONSTANT ) ;
2021-05-16 13:22:41 +02:00
2023-03-05 15:42:15 +02:00
answer = ! dangerUnknown & & ! dangerTooHigh ;
2021-05-16 13:22:41 +02:00
}
}
2023-02-28 09:07:59 +02:00
answerQuery ( askID , answer ? 1 : 0 ) ;
2021-05-16 13:22:41 +02:00
} ) ;
2021-05-16 13:57:05 +02:00
2021-05-16 13:22:41 +02:00
return ;
}
2021-05-15 18:22:44 +02:00
requestActionASAP ( [ = ] ( )
{
2021-05-16 13:39:47 +02:00
int sel = 0 ;
if ( selection ) //select from multiple components -> take the last one (they're indexed [1-size])
sel = components . size ( ) ;
{
2024-01-20 23:31:57 +02:00
std : : unique_lock < std : : mutex > mxLock ( nullkiller - > aiStateMutex ) ;
2023-12-17 10:11:05 +02:00
// TODO: Find better way to understand it is Chest of Treasures
if ( hero . validAndSet ( )
& & components . size ( ) = = 2
& & components . front ( ) . type = = ComponentType : : RESOURCE
& & ( nullkiller - > heroManager - > getHeroRole ( hero ) ! = HeroRole : : MAIN
2024-04-16 23:10:15 +02:00
| | nullkiller - > buildAnalyzer - > isGoldPressureHigh ( ) ) )
2023-12-17 10:11:05 +02:00
{
2024-02-25 12:39:19 +02:00
sel = 1 ;
2023-12-17 10:11:05 +02:00
}
2021-05-16 13:39:47 +02:00
}
2021-05-15 18:22:44 +02:00
answerQuery ( askID , sel ) ;
} ) ;
}
2023-09-15 21:18:36 +02:00
void AIGateway : : showTeleportDialog ( const CGHeroInstance * hero , TeleportChannelID channel , TTeleportExitsList exits , bool impassable , QueryID askID )
2021-05-15 18:22:44 +02:00
{
NET_EVENT_HANDLER ;
2020-05-04 17:58:43 +02:00
status . addQuery ( askID , boost : : str ( boost : : format ( " Teleport dialog query with %d exits " ) % exits . size ( ) ) ) ;
2021-05-15 18:22:44 +02:00
int choosenExit = - 1 ;
if ( impassable )
{
2020-05-04 17:58:43 +02:00
nullkiller - > memory - > knownTeleportChannels [ channel ] - > passability = TeleportChannel : : IMPASSABLE ;
2021-05-15 18:22:44 +02:00
}
else if ( destinationTeleport ! = ObjectInstanceID ( ) & & destinationTeleportPos . valid ( ) )
{
auto neededExit = std : : make_pair ( destinationTeleport , destinationTeleportPos ) ;
if ( destinationTeleport ! = ObjectInstanceID ( ) & & vstd : : contains ( exits , neededExit ) )
choosenExit = vstd : : find_pos ( exits , neededExit ) ;
}
for ( auto exit : exits )
{
if ( status . channelProbing ( ) & & exit . first = = destinationTeleport )
{
choosenExit = vstd : : find_pos ( exits , exit ) ;
break ;
}
else
{
// TODO: Implement checking if visiting that teleport will uncovert any FoW
// So far this is the best option to handle decision about probing
auto obj = cb - > getObj ( exit . first , false ) ;
if ( obj = = nullptr & & ! vstd : : contains ( teleportChannelProbingList , exit . first ) )
{
if ( exit . first ! = destinationTeleport )
teleportChannelProbingList . push_back ( exit . first ) ;
}
}
}
requestActionASAP ( [ = ] ( )
{
answerQuery ( askID , choosenExit ) ;
} ) ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : showGarrisonDialog ( const CArmedInstance * up , const CGHeroInstance * down , bool removableUnits , QueryID queryID )
2021-05-15 18:22:44 +02:00
{
LOG_TRACE_PARAMS ( logAi , " removableUnits '%i', queryID '%i' " , removableUnits % queryID ) ;
NET_EVENT_HANDLER ;
2023-09-26 14:48:21 +02:00
std : : string s1 = up - > nodeName ( ) ;
std : : string s2 = down - > nodeName ( ) ;
2021-05-15 18:22:44 +02:00
status . addQuery ( queryID , boost : : str ( boost : : format ( " Garrison dialog with %s and %s " ) % s1 % s2 ) ) ;
//you can't request action from action-response thread
requestActionASAP ( [ = ] ( )
{
2023-07-02 09:28:29 +02:00
if ( removableUnits & & up - > tempOwner = = down - > tempOwner )
2023-09-26 14:48:21 +02:00
{
2021-05-15 18:22:44 +02:00
pickBestCreatures ( down , up ) ;
2023-09-26 14:48:21 +02:00
}
2021-05-15 18:22:44 +02:00
answerQuery ( queryID , 0 ) ;
} ) ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : showMapObjectSelectDialog ( QueryID askID , const Component & icon , const MetaString & title , const MetaString & description , const std : : vector < ObjectInstanceID > & objects )
2021-05-15 18:22:44 +02:00
{
NET_EVENT_HANDLER ;
status . addQuery ( askID , " Map object select query " ) ;
requestActionASAP ( [ = ] ( ) { answerQuery ( askID , selectedObject . getNum ( ) ) ; } ) ;
}
2024-01-20 20:34:51 +02:00
void AIGateway : : saveGame ( BinarySerializer & h )
2021-05-15 18:22:44 +02:00
{
NET_EVENT_HANDLER ;
2020-05-04 17:58:43 +02:00
nullkiller - > memory - > removeInvisibleObjects ( myCb . get ( ) ) ;
2021-05-15 18:22:44 +02:00
2024-01-20 20:34:51 +02:00
CAdventureAI : : saveGame ( h ) ;
serializeInternal ( h ) ;
2021-05-15 18:22:44 +02:00
}
2024-01-20 20:34:51 +02:00
void AIGateway : : loadGame ( BinaryDeserializer & h )
2021-05-15 18:22:44 +02:00
{
//NET_EVENT_HANDLER;
#if 0
//disabled due to issue 2890
registerGoals ( h ) ;
# endif // 0
2024-01-20 20:34:51 +02:00
CAdventureAI : : loadGame ( h ) ;
serializeInternal ( h ) ;
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
bool AIGateway : : makePossibleUpgrades ( const CArmedInstance * obj )
2021-05-15 18:22:44 +02:00
{
if ( ! obj )
2021-05-16 13:19:00 +02:00
return false ;
bool upgraded = false ;
2021-05-15 18:22:44 +02:00
for ( int i = 0 ; i < GameConstants : : ARMY_SIZE ; i + + )
{
if ( const CStackInstance * s = obj - > getStackPtr ( SlotID ( i ) ) )
{
UpgradeInfo ui ;
2022-12-25 14:03:43 +02:00
myCb - > fillUpgradeInfo ( obj , SlotID ( i ) , ui ) ;
2023-08-19 19:48:28 +02:00
if ( ui . oldID ! = CreatureID : : NONE & & nullkiller - > getFreeResources ( ) . canAfford ( ui . cost [ 0 ] * s - > count ) )
2021-05-15 18:22:44 +02:00
{
2021-05-16 13:19:00 +02:00
myCb - > upgradeCreature ( obj , SlotID ( i ) , ui . newID [ 0 ] ) ;
upgraded = true ;
2023-01-02 18:00:51 +02:00
logAi - > debug ( " Upgraded %d %s to %s " , s - > count , ui . oldID . toCreature ( ) - > getNamePluralTranslated ( ) , ui . newID [ 0 ] . toCreature ( ) - > getNamePluralTranslated ( ) ) ;
2021-05-15 18:22:44 +02:00
}
}
}
2021-05-16 13:19:00 +02:00
return upgraded ;
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
void AIGateway : : makeTurn ( )
2021-05-15 18:22:44 +02:00
{
MAKING_TURN ;
2023-08-19 21:35:44 +02:00
auto day = cb - > getDate ( Date : : DAY ) ;
2023-09-04 21:21:02 +02:00
logAi - > info ( " Player %d (%s) starting turn, day %d " , playerID , playerID . toString ( ) , day ) ;
2021-05-15 18:22:44 +02:00
boost : : shared_lock < boost : : shared_mutex > gsLock ( CGameState : : mutex ) ;
2021-05-16 14:39:38 +02:00
setThreadName ( " AIGateway::makeTurn " ) ;
2021-05-15 18:22:44 +02:00
2023-07-30 10:33:52 +02:00
cb - > sendMessage ( " vcmieagles " ) ;
retrieveVisitableObjs ( ) ;
2021-05-16 13:45:30 +02:00
if ( cb - > getDate ( Date : : DAY_OF_WEEK ) = = 1 )
2021-05-15 18:22:44 +02:00
{
2023-07-30 10:33:52 +02:00
for ( const CGObjectInstance * obj : nullkiller - > memory - > visitableObjs )
2021-05-15 18:22:44 +02:00
{
2024-03-31 17:39:00 +02:00
if ( isWeeklyRevisitable ( nullkiller . get ( ) , obj ) )
2021-05-15 18:22:44 +02:00
{
2020-05-04 17:58:43 +02:00
nullkiller - > memory - > markObjectUnvisited ( obj ) ;
2021-05-15 18:22:44 +02:00
}
}
}
2021-05-16 13:45:30 +02:00
2022-11-03 21:16:49 +02:00
# if NKAI_TRACE_LEVEL == 0
2021-05-15 18:22:44 +02:00
try
{
2022-11-03 21:16:49 +02:00
# endif
2019-12-15 15:47:21 +02:00
nullkiller - > makeTurn ( ) ;
2021-05-15 18:22:44 +02:00
//for debug purpose
for ( auto h : cb - > getHeroesInfo ( ) )
{
2023-06-21 19:38:26 +02:00
if ( h - > movementPointsRemaining ( ) )
2023-07-27 17:40:47 +02:00
logAi - > info ( " Hero %s has %d MP left " , h - > getNameTranslated ( ) , h - > movementPointsRemaining ( ) ) ;
2021-05-15 18:22:44 +02:00
}
2022-11-03 21:16:49 +02:00
# if NKAI_TRACE_LEVEL == 0
2021-05-15 18:22:44 +02:00
}
catch ( boost : : thread_interrupted & e )
{
2020-09-02 19:16:24 +02:00
( void ) e ;
2021-05-15 18:22:44 +02:00
logAi - > debug ( " Making turn thread has been interrupted. We'll end without calling endTurn. " ) ;
return ;
}
2022-09-06 20:14:22 +02:00
catch ( std : : exception & e )
2021-05-15 18:22:44 +02:00
{
logAi - > debug ( " Making turn thread has caught an exception: %s " , e . what ( ) ) ;
2022-09-06 20:14:22 +02:00
}
2022-11-03 21:16:49 +02:00
# endif
2021-05-15 18:22:44 +02:00
endTurn ( ) ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : performObjectInteraction ( const CGObjectInstance * obj , HeroPtr h )
2021-05-15 18:22:44 +02:00
{
2023-01-02 13:27:03 +02:00
LOG_TRACE_PARAMS ( logAi , " Hero %s and object %s at %s " , h - > getNameTranslated ( ) % obj - > getObjectName ( ) % obj - > pos . toString ( ) ) ;
2021-05-15 18:22:44 +02:00
switch ( obj - > ID )
{
case Obj : : TOWN :
if ( h - > visitedTown ) //we are inside, not just attacking
{
2021-05-16 13:09:49 +02:00
makePossibleUpgrades ( h . get ( ) ) ;
2023-12-17 10:11:05 +02:00
std : : unique_lock < std : : mutex > lockGuard ( nullkiller - > aiStateMutex ) ;
2021-05-16 14:39:38 +02:00
if ( ! h - > visitedTown - > garrisonHero | | ! nullkiller - > isHeroLocked ( h - > visitedTown - > garrisonHero ) )
2021-05-16 13:49:39 +02:00
moveCreaturesToHero ( h - > visitedTown ) ;
2021-05-16 14:39:38 +02:00
if ( nullkiller - > heroManager - > getHeroRole ( h ) = = HeroRole : : MAIN & & ! h - > hasSpellbook ( )
& & nullkiller - > getFreeGold ( ) > = GameConstants : : SPELLBOOK_GOLD_COST )
2021-05-15 18:22:44 +02:00
{
if ( h - > visitedTown - > hasBuilt ( BuildingID : : MAGES_GUILD_1 ) )
cb - > buyArtifact ( h . get ( ) , ArtifactID : : SPELLBOOK ) ;
}
}
break ;
2021-05-16 13:15:12 +02:00
case Obj : : HILL_FORT :
makePossibleUpgrades ( h . get ( ) ) ;
break ;
2021-05-15 18:22:44 +02:00
}
}
2021-05-16 14:39:38 +02:00
void AIGateway : : moveCreaturesToHero ( const CGTownInstance * t )
2021-05-15 18:22:44 +02:00
{
if ( t - > visitingHero & & t - > armedGarrison ( ) & & t - > visitingHero - > tempOwner = = t - > tempOwner )
{
2021-05-15 21:02:52 +02:00
pickBestCreatures ( t - > visitingHero , t - > getUpperArmy ( ) ) ;
2021-05-15 18:22:44 +02:00
}
}
2021-05-16 14:39:38 +02:00
void AIGateway : : pickBestCreatures ( const CArmedInstance * destinationArmy , const CArmedInstance * source )
2021-05-15 18:22:44 +02:00
{
const CArmedInstance * armies [ ] = { destinationArmy , source } ;
2021-05-16 13:56:42 +02:00
auto bestArmy = nullkiller - > armyManager - > getBestArmy ( destinationArmy , destinationArmy , source ) ;
2021-05-15 18:22:44 +02:00
2023-07-30 11:21:47 +02:00
for ( auto army : armies )
{
// move first stack at first slot if empty to avoid can not take away last creature
if ( ! army - > hasStackAtSlot ( SlotID ( 0 ) ) & & army - > stacksCount ( ) > 0 )
{
cb - > mergeOrSwapStacks (
army ,
army ,
SlotID ( 0 ) ,
army - > Slots ( ) . begin ( ) - > first ) ;
}
}
2021-05-15 18:22:44 +02:00
//foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
2021-05-16 13:56:42 +02:00
for ( SlotID i = SlotID ( 0 ) ; i . validSlot ( ) ; i . advance ( 1 ) ) //i-th strongest creature type will go to i-th slot
2021-05-15 18:22:44 +02:00
{
2021-05-16 13:56:42 +02:00
if ( i . getNum ( ) > = bestArmy . size ( ) )
{
if ( destinationArmy - > hasStackAtSlot ( i ) )
{
auto creature = destinationArmy - > getCreature ( i ) ;
auto targetSlot = source - > getSlotFor ( creature ) ;
if ( targetSlot . validSlot ( ) )
{
// remove unwanted creatures
cb - > mergeOrSwapStacks ( destinationArmy , source , i , targetSlot ) ;
}
else if ( destinationArmy - > getStack ( i ) . getPower ( ) < destinationArmy - > getArmyStrength ( ) / 100 )
{
// dismiss creatures if the amount is small
cb - > dismissCreature ( destinationArmy , i ) ;
}
}
continue ;
}
2021-05-15 20:36:50 +02:00
const CCreature * targetCreature = bestArmy [ i . getNum ( ) ] . creature ;
2021-05-15 18:22:44 +02:00
for ( auto armyPtr : armies )
{
2021-05-15 20:36:50 +02:00
for ( SlotID j = SlotID ( 0 ) ; j . validSlot ( ) ; j . advance ( 1 ) )
2021-05-15 18:22:44 +02:00
{
2021-05-15 20:36:50 +02:00
if ( armyPtr - > getCreature ( j ) = = targetCreature & & ( i ! = j | | armyPtr ! = destinationArmy ) ) //it's a searched creature not in dst SLOT
2021-05-15 18:22:44 +02:00
{
2021-05-15 20:36:50 +02:00
//can't take away last creature without split. generate a new stack with 1 creature which is weak but fast
if ( armyPtr = = source
& & source - > needsLastStack ( )
& & source - > stacksCount ( ) = = 1
& & ( ! destinationArmy - > hasStackAtSlot ( i ) | | destinationArmy - > getCreature ( i ) = = targetCreature ) )
2021-05-15 18:22:44 +02:00
{
2020-05-04 17:58:43 +02:00
auto weakest = nullkiller - > armyManager - > getWeakestCreature ( bestArmy ) ;
2021-05-15 20:36:50 +02:00
if ( weakest - > creature = = targetCreature )
{
if ( 1 = = source - > getStackCount ( j ) )
break ;
// move all except 1 of weakest creature from source to destination
cb - > splitStack (
source ,
destinationArmy ,
j ,
destinationArmy - > getSlotFor ( targetCreature ) ,
destinationArmy - > getStackCount ( i ) + source - > getStackCount ( j ) - 1 ) ;
break ;
}
else
{
// Source last stack is not weakest. Move 1 of weakest creature from destination to source
cb - > splitStack (
destinationArmy ,
source ,
destinationArmy - > getSlotFor ( weakest - > creature ) ,
source - > getFreeSlot ( ) ,
1 ) ;
2021-05-15 18:22:44 +02:00
}
}
2021-05-15 20:36:50 +02:00
cb - > mergeOrSwapStacks ( armyPtr , destinationArmy , j , i ) ;
2021-05-15 18:22:44 +02:00
}
}
}
}
//TODO - having now strongest possible army, we may want to think about arranging stacks
}
2021-05-16 14:39:38 +02:00
void AIGateway : : pickBestArtifacts ( const CGHeroInstance * h , const CGHeroInstance * other )
2021-05-15 18:22:44 +02:00
{
auto equipBest = [ ] ( const CGHeroInstance * h , const CGHeroInstance * otherh , bool giveStuffToFirstHero ) - > void
{
bool changeMade = false ;
do
{
changeMade = false ;
//we collect gear always in same order
std : : vector < ArtifactLocation > allArtifacts ;
if ( giveStuffToFirstHero )
{
for ( auto p : h - > artifactsWorn )
{
if ( p . second . artifact )
2023-10-14 21:00:39 +02:00
allArtifacts . push_back ( ArtifactLocation ( h - > id , p . first ) ) ;
2021-05-15 18:22:44 +02:00
}
}
for ( auto slot : h - > artifactsInBackpack )
2023-10-14 21:00:39 +02:00
allArtifacts . push_back ( ArtifactLocation ( h - > id , h - > getArtPos ( slot . artifact ) ) ) ;
2021-05-15 18:22:44 +02:00
if ( otherh )
{
for ( auto p : otherh - > artifactsWorn )
{
if ( p . second . artifact )
2023-10-14 21:00:39 +02:00
allArtifacts . push_back ( ArtifactLocation ( otherh - > id , p . first ) ) ;
2021-05-15 18:22:44 +02:00
}
for ( auto slot : otherh - > artifactsInBackpack )
2023-10-14 21:00:39 +02:00
allArtifacts . push_back ( ArtifactLocation ( otherh - > id , otherh - > getArtPos ( slot . artifact ) ) ) ;
2021-05-15 18:22:44 +02:00
}
//we give stuff to one hero or another, depending on giveStuffToFirstHero
const CGHeroInstance * target = nullptr ;
if ( giveStuffToFirstHero | | ! otherh )
target = h ;
else
target = otherh ;
for ( auto location : allArtifacts )
{
2023-10-14 21:00:39 +02:00
if ( location . artHolder = = target - > id & & ArtifactUtils : : isSlotEquipment ( location . slot ) )
2021-05-15 18:22:44 +02:00
continue ; //don't reequip artifact we already wear
if ( location . slot = = ArtifactPosition : : MACH4 ) // don't attempt to move catapult
continue ;
2023-10-14 21:00:39 +02:00
auto s = cb - > getHero ( location . artHolder ) - > getSlot ( location . slot ) ;
2021-05-15 18:22:44 +02:00
if ( ! s | | s - > locked ) //we can't move locks
continue ;
auto artifact = s - > artifact ;
if ( ! artifact )
continue ;
//FIXME: why are the above possible to be null?
bool emptySlotFound = false ;
2023-07-03 22:11:56 +02:00
for ( auto slot : artifact - > artType - > getPossibleSlots ( ) . at ( target - > bearerType ( ) ) )
2021-05-15 18:22:44 +02:00
{
2023-10-14 21:00:39 +02:00
if ( target - > isPositionFree ( slot ) & & artifact - > canBePutAt ( target , slot , true ) ) //combined artifacts are not always allowed to move
2021-05-15 18:22:44 +02:00
{
2023-10-14 21:00:39 +02:00
ArtifactLocation destLocation ( target - > id , slot ) ;
2021-05-15 18:22:44 +02:00
cb - > swapArtifacts ( location , destLocation ) ; //just put into empty slot
emptySlotFound = true ;
changeMade = true ;
break ;
}
}
if ( ! emptySlotFound ) //try to put that atifact in already occupied slot
{
2023-07-03 22:11:56 +02:00
for ( auto slot : artifact - > artType - > getPossibleSlots ( ) . at ( target - > bearerType ( ) ) )
2021-05-15 18:22:44 +02:00
{
auto otherSlot = target - > getSlot ( slot ) ;
if ( otherSlot & & otherSlot - > artifact ) //we need to exchange artifact for better one
{
//if that artifact is better than what we have, pick it
2023-10-14 21:00:39 +02:00
if ( compareArtifacts ( artifact , otherSlot - > artifact ) & & artifact - > canBePutAt ( target , slot , true ) ) //combined artifacts are not always allowed to move
2021-05-15 18:22:44 +02:00
{
2023-10-14 21:00:39 +02:00
ArtifactLocation destLocation ( target - > id , slot ) ;
cb - > swapArtifacts ( location , ArtifactLocation ( target - > id , target - > getArtPos ( otherSlot - > artifact ) ) ) ;
2021-05-15 18:22:44 +02:00
changeMade = true ;
break ;
}
}
}
}
if ( changeMade )
break ; //start evaluating artifacts from scratch
}
}
while ( changeMade ) ;
} ;
equipBest ( h , other , true ) ;
if ( other )
equipBest ( h , other , false ) ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : recruitCreatures ( const CGDwelling * d , const CArmedInstance * recruiter )
2021-05-15 18:22:44 +02:00
{
//now used only for visited dwellings / towns, not BuyArmy goal
for ( int i = 0 ; i < d - > creatures . size ( ) ; i + + )
{
if ( ! d - > creatures [ i ] . second . size ( ) )
continue ;
int count = d - > creatures [ i ] . first ;
CreatureID creID = d - > creatures [ i ] . second . back ( ) ;
2023-07-27 14:58:49 +02:00
if ( ! recruiter - > getSlotFor ( creID ) . validSlot ( ) )
{
2024-04-20 09:33:37 +02:00
for ( auto stack : recruiter - > Slots ( ) )
{
if ( ! stack . second - > type )
continue ;
auto duplicatingSlot = recruiter - > getSlotFor ( stack . second - > type ) ;
if ( duplicatingSlot ! = stack . first )
{
cb - > mergeStacks ( recruiter , recruiter , stack . first , duplicatingSlot ) ;
break ;
}
}
if ( ! recruiter - > getSlotFor ( creID ) . validSlot ( ) )
{
continue ;
}
2023-07-27 14:58:49 +02:00
}
2023-04-05 02:26:29 +02:00
vstd : : amin ( count , cb - > getResourceAmount ( ) / creID . toCreature ( ) - > getFullRecruitCost ( ) ) ;
2021-05-15 18:22:44 +02:00
if ( count > 0 )
cb - > recruitCreatures ( d , recruiter , creID , count , i ) ;
}
}
2023-08-28 17:59:12 +02:00
void AIGateway : : battleStart ( const BattleID & battleID , const CCreatureSet * army1 , const CCreatureSet * army2 , int3 tile , const CGHeroInstance * hero1 , const CGHeroInstance * hero2 , bool side , bool replayAllowed )
2021-05-15 18:22:44 +02:00
{
NET_EVENT_HANDLER ;
2023-08-27 00:35:38 +02:00
assert ( ! playerID . isValidPlayer ( ) | | status . getBattle ( ) = = UPCOMING_BATTLE ) ;
2021-05-15 18:22:44 +02:00
status . setBattle ( ONGOING_BATTLE ) ;
const CGObjectInstance * presumedEnemy = vstd : : backOrNull ( cb - > getVisitableObjs ( tile ) ) ; //may be nullptr in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit
2023-01-02 13:27:03 +02:00
battlename = boost : : str ( boost : : format ( " Starting battle of %s attacking %s at %s " ) % ( hero1 ? hero1 - > getNameTranslated ( ) : " a army " ) % ( presumedEnemy ? presumedEnemy - > getObjectName ( ) : " unknown enemy " ) % tile . toString ( ) ) ;
2023-08-28 17:59:12 +02:00
CAdventureAI : : battleStart ( battleID , army1 , army2 , tile , hero1 , hero2 , side , replayAllowed ) ;
2021-05-15 18:22:44 +02:00
}
2023-08-28 17:59:12 +02:00
void AIGateway : : battleEnd ( const BattleID & battleID , const BattleResult * br , QueryID queryID )
2021-05-15 18:22:44 +02:00
{
NET_EVENT_HANDLER ;
assert ( status . getBattle ( ) = = ONGOING_BATTLE ) ;
status . setBattle ( ENDING_BATTLE ) ;
2023-08-28 17:59:12 +02:00
bool won = br - > winner = = myCb - > getBattle ( battleID ) - > battleGetMySide ( ) ;
2023-09-04 21:21:02 +02:00
logAi - > debug ( " Player %d (%s): I %s the %s! " , playerID , playerID . toString ( ) , ( won ? " won " : " lost " ) , battlename ) ;
2021-05-15 18:22:44 +02:00
battlename . clear ( ) ;
2023-07-27 17:40:47 +02:00
2023-08-28 17:59:12 +02:00
CAdventureAI : : battleEnd ( battleID , br , queryID ) ;
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
void AIGateway : : waitTillFree ( )
2021-05-15 18:22:44 +02:00
{
auto unlock = vstd : : makeUnlockSharedGuard ( CGameState : : mutex ) ;
status . waitTillFree ( ) ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : retrieveVisitableObjs ( )
2021-05-15 18:22:44 +02:00
{
foreach_tile_pos ( [ & ] ( const int3 & pos )
{
for ( const CGObjectInstance * obj : myCb - > getVisitableObjs ( pos , false ) )
{
2023-07-30 10:33:52 +02:00
addVisitableObj ( obj ) ;
2021-05-15 18:22:44 +02:00
}
} ) ;
}
2021-05-16 14:39:38 +02:00
std : : vector < const CGObjectInstance * > AIGateway : : getFlaggedObjects ( ) const
2021-05-15 18:22:44 +02:00
{
std : : vector < const CGObjectInstance * > ret ;
2020-05-04 17:58:43 +02:00
for ( const CGObjectInstance * obj : nullkiller - > memory - > visitableObjs )
2021-05-15 18:22:44 +02:00
{
if ( obj - > tempOwner = = playerID )
ret . push_back ( obj ) ;
}
return ret ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : addVisitableObj ( const CGObjectInstance * obj )
2021-05-15 18:22:44 +02:00
{
if ( obj - > ID = = Obj : : EVENT )
return ;
2020-05-04 17:58:43 +02:00
nullkiller - > memory - > addVisitableObject ( obj ) ;
2021-05-16 13:13:35 +02:00
if ( obj - > ID = = Obj : : HERO & & cb - > getPlayerRelations ( obj - > tempOwner , playerID ) = = PlayerRelations : : ENEMIES )
{
2020-05-04 17:58:43 +02:00
nullkiller - > dangerHitMap - > reset ( ) ;
2021-05-15 18:22:44 +02:00
}
}
2021-05-16 14:39:38 +02:00
bool AIGateway : : moveHeroToTile ( int3 dst , HeroPtr h )
2021-05-15 18:22:44 +02:00
{
2021-05-15 21:02:57 +02:00
if ( h - > inTownGarrison & & h - > visitedTown )
2021-05-16 13:19:27 +02:00
{
2021-05-15 21:02:57 +02:00
cb - > swapGarrisonHero ( h - > visitedTown ) ;
2021-05-16 13:19:27 +02:00
moveCreaturesToHero ( h - > visitedTown ) ;
}
2021-05-15 21:02:57 +02:00
2021-05-15 18:22:44 +02:00
//TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
auto afterMovementCheck = [ & ] ( ) - > void
{
waitTillFree ( ) ; //movement may cause battle or blocking dialog
if ( ! h )
{
lostHero ( h ) ;
teleportChannelProbingList . clear ( ) ;
if ( status . channelProbing ( ) ) // if hero lost during channel probing we need to switch this mode off
status . setChannelProbing ( false ) ;
throw cannotFulfillGoalException ( " Hero was lost! " ) ;
}
} ;
2023-01-02 13:27:03 +02:00
logAi - > debug ( " Moving hero %s to tile %s " , h - > getNameTranslated ( ) , dst . toString ( ) ) ;
2021-05-15 18:22:44 +02:00
int3 startHpos = h - > visitablePos ( ) ;
bool ret = false ;
if ( startHpos = = dst )
{
//FIXME: this assertion fails also if AI moves onto defeated guarded object
2023-07-27 17:40:47 +02:00
//assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
2024-04-18 14:13:16 +02:00
cb - > moveHero ( * h , h - > convertFromVisitablePos ( dst ) , false ) ;
2021-05-15 18:22:44 +02:00
afterMovementCheck ( ) ; // TODO: is it feasible to hero get killed there if game work properly?
2020-05-04 17:58:43 +02:00
// If revisiting, teleport probing is never done, and so the entries into the list would remain unused and uncleared
teleportChannelProbingList . clear ( ) ;
2021-05-15 18:22:44 +02:00
// not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
ret = true ;
}
else
{
CGPath path ;
cb - > getPathsInfo ( h . get ( ) ) - > getPath ( path , dst ) ;
if ( path . nodes . empty ( ) )
{
2023-01-02 13:27:03 +02:00
logAi - > error ( " Hero %s cannot reach %s. " , h - > getNameTranslated ( ) , dst . toString ( ) ) ;
2021-05-16 13:38:26 +02:00
return true ;
2021-05-15 18:22:44 +02:00
}
2020-09-02 19:16:24 +02:00
int i = ( int ) path . nodes . size ( ) - 1 ;
2021-05-15 18:22:44 +02:00
auto getObj = [ & ] ( int3 coord , bool ignoreHero )
{
auto tile = cb - > getTile ( coord , false ) ;
assert ( tile ) ;
return tile - > topVisitableObj ( ignoreHero ) ;
//return cb->getTile(coord,false)->topVisitableObj(ignoreHero);
} ;
2023-06-21 14:38:57 +02:00
auto isTeleportAction = [ & ] ( EPathNodeAction action ) - > bool
2021-05-15 18:22:44 +02:00
{
2023-06-21 14:38:57 +02:00
if ( action ! = EPathNodeAction : : TELEPORT_NORMAL & & action ! = EPathNodeAction : : TELEPORT_BLOCKING_VISIT )
2021-05-15 18:22:44 +02:00
{
2023-06-21 14:38:57 +02:00
if ( action ! = EPathNodeAction : : TELEPORT_BATTLE )
2021-05-15 18:22:44 +02:00
{
return false ;
}
}
return true ;
} ;
auto getDestTeleportObj = [ & ] ( const CGObjectInstance * currentObject , const CGObjectInstance * nextObjectTop , const CGObjectInstance * nextObject ) - > const CGObjectInstance *
{
if ( CGTeleport : : isConnected ( currentObject , nextObjectTop ) )
return nextObjectTop ;
if ( nextObjectTop & & nextObjectTop - > ID = = Obj : : HERO )
{
if ( CGTeleport : : isConnected ( currentObject , nextObject ) )
return nextObject ;
}
return nullptr ;
} ;
auto doMovement = [ & ] ( int3 dst , bool transit )
{
2022-12-09 14:42:47 +02:00
cb - > moveHero ( * h , h - > convertFromVisitablePos ( dst ) , transit ) ;
2021-05-15 18:22:44 +02:00
} ;
auto doTeleportMovement = [ & ] ( ObjectInstanceID exitId , int3 exitPos )
{
destinationTeleport = exitId ;
if ( exitPos . valid ( ) )
2022-12-09 14:42:47 +02:00
destinationTeleportPos = h - > convertFromVisitablePos ( exitPos ) ;
2024-04-18 14:13:16 +02:00
cb - > moveHero ( * h , h - > pos , false ) ;
2021-05-15 18:22:44 +02:00
destinationTeleport = ObjectInstanceID ( ) ;
destinationTeleportPos = int3 ( - 1 ) ;
afterMovementCheck ( ) ;
} ;
auto doChannelProbing = [ & ] ( ) - > void
{
2022-12-07 22:51:32 +02:00
auto currentPos = h - > visitablePos ( ) ;
2021-05-15 18:22:44 +02:00
auto currentExit = getObj ( currentPos , true ) - > id ;
status . setChannelProbing ( true ) ;
for ( auto exit : teleportChannelProbingList )
doTeleportMovement ( exit , int3 ( - 1 ) ) ;
teleportChannelProbingList . clear ( ) ;
status . setChannelProbing ( false ) ;
doTeleportMovement ( currentExit , currentPos ) ;
} ;
for ( ; i > 0 ; i - - )
{
int3 currentCoord = path . nodes [ i ] . coord ;
int3 nextCoord = path . nodes [ i - 1 ] . coord ;
2022-12-07 22:51:32 +02:00
auto currentObject = getObj ( currentCoord , currentCoord = = h - > visitablePos ( ) ) ;
2021-05-15 18:22:44 +02:00
auto nextObjectTop = getObj ( nextCoord , false ) ;
auto nextObject = getObj ( nextCoord , true ) ;
auto destTeleportObj = getDestTeleportObj ( currentObject , nextObjectTop , nextObject ) ;
if ( isTeleportAction ( path . nodes [ i - 1 ] . action ) & & destTeleportObj ! = nullptr )
{
//we use special login if hero standing on teleporter it's mean we need
doTeleportMovement ( destTeleportObj - > id , nextCoord ) ;
if ( teleportChannelProbingList . size ( ) )
doChannelProbing ( ) ;
2020-05-04 17:58:43 +02:00
nullkiller - > memory - > markObjectVisited ( destTeleportObj ) ; //FIXME: Monoliths are not correctly visited
2021-05-15 18:22:44 +02:00
continue ;
}
//stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
if ( path . nodes [ i - 1 ] . turns )
{
//blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
2023-03-08 12:41:14 +02:00
return false ;
2021-05-15 18:22:44 +02:00
}
int3 endpos = path . nodes [ i - 1 ] . coord ;
if ( endpos = = h - > visitablePos ( ) )
continue ;
bool isConnected = false ;
bool isNextObjectTeleport = false ;
// Check there is node after next one; otherwise transit is pointless
if ( i - 2 > = 0 )
{
isConnected = CGTeleport : : isConnected ( nextObjectTop , getObj ( path . nodes [ i - 2 ] . coord , false ) ) ;
isNextObjectTeleport = CGTeleport : : isTeleport ( nextObjectTop ) ;
}
if ( isConnected | | isNextObjectTeleport )
{
// Hero should be able to go through object if it's allow transit
doMovement ( endpos , true ) ;
}
else if ( path . nodes [ i - 1 ] . layer = = EPathfindingLayer : : AIR )
{
doMovement ( endpos , true ) ;
}
else
{
doMovement ( endpos , false ) ;
}
afterMovementCheck ( ) ;
if ( teleportChannelProbingList . size ( ) )
doChannelProbing ( ) ;
}
2023-06-21 14:38:57 +02:00
if ( path . nodes [ 0 ] . action = = EPathNodeAction : : BLOCKING_VISIT | | path . nodes [ 0 ] . action = = EPathNodeAction : : BATTLE )
2021-05-15 18:22:44 +02:00
{
2021-05-16 13:15:03 +02:00
// when we take resource we do not reach its position. We even might not move
// also guarded town is not get visited automatically after capturing
ret = h & & i = = 0 ;
2021-05-15 18:22:44 +02:00
}
}
if ( h )
{
if ( auto visitedObject = vstd : : frontOrNull ( cb - > getVisitableObjs ( h - > visitablePos ( ) ) ) ) //we stand on something interesting
{
if ( visitedObject ! = * h )
2023-02-28 09:07:59 +02:00
{
2021-05-15 18:22:44 +02:00
performObjectInteraction ( visitedObject , h ) ;
2023-02-28 09:07:59 +02:00
ret = true ;
}
2021-05-15 18:22:44 +02:00
}
}
if ( h ) //we could have lost hero after last move
{
ret = ret | | ( dst = = h - > visitablePos ( ) ) ;
if ( startHpos = = h - > visitablePos ( ) & & ! ret ) //we didn't move and didn't reach the target
{
throw cannotFulfillGoalException ( " Invalid path found! " ) ;
}
2019-12-15 15:47:21 +02:00
2023-01-02 13:27:03 +02:00
logAi - > debug ( " Hero %s moved from %s to %s. Returning %d. " , h - > getNameTranslated ( ) , startHpos . toString ( ) , h - > visitablePos ( ) . toString ( ) , ret ) ;
2021-05-15 18:22:44 +02:00
}
return ret ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : buildStructure ( const CGTownInstance * t , BuildingID building )
2021-05-15 18:22:44 +02:00
{
2023-01-04 15:17:50 +02:00
auto name = t - > town - > buildings . at ( building ) - > getNameTranslated ( ) ;
logAi - > debug ( " Player %d will build %s in town of %s at %s " , ai - > playerID , name , t - > getNameTranslated ( ) , t - > pos . toString ( ) ) ;
2021-05-15 18:22:44 +02:00
cb - > buildBuilding ( t , building ) ; //just do this;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : tryRealize ( Goals : : DigAtTile & g )
2021-05-15 18:22:44 +02:00
{
assert ( g . hero - > visitablePos ( ) = = g . tile ) ; //surely we want to crash here?
if ( g . hero - > diggingStatus ( ) = = EDiggingStatus : : CAN_DIG )
{
2024-04-14 14:23:44 +02:00
cb - > dig ( g . hero ) ;
2021-05-15 18:22:44 +02:00
}
else
{
throw cannotFulfillGoalException ( " A hero can't dig! \n " ) ;
}
}
2021-05-16 14:39:38 +02:00
void AIGateway : : tryRealize ( Goals : : Trade & g ) //trade
2021-05-15 18:22:44 +02:00
{
2023-04-05 02:26:29 +02:00
if ( cb - > getResourceAmount ( GameResID ( g . resID ) ) > = g . value ) //goal is already fulfilled. Why we need this check, anyway?
2021-05-15 18:22:44 +02:00
throw goalFulfilledException ( sptr ( g ) ) ;
int accquiredResources = 0 ;
if ( const CGObjectInstance * obj = cb - > getObj ( ObjectInstanceID ( g . objid ) , false ) )
{
2024-02-14 12:56:37 +02:00
if ( const auto * m = dynamic_cast < const IMarket * > ( obj ) )
2021-05-15 18:22:44 +02:00
{
2019-12-15 15:47:21 +02:00
auto freeRes = cb - > getResourceAmount ( ) ; //trade only resources which are not reserved
2023-04-05 02:26:29 +02:00
for ( auto it = ResourceSet : : nziterator ( freeRes ) ; it . valid ( ) ; it + + )
2021-05-15 18:22:44 +02:00
{
auto res = it - > resType ;
2023-04-05 02:26:29 +02:00
if ( res . getNum ( ) = = g . resID ) //sell any other resource
2021-05-15 18:22:44 +02:00
continue ;
2024-01-10 00:38:54 +02:00
int toGive ;
int toGet ;
2021-05-15 18:22:44 +02:00
m - > getOffer ( res , g . resID , toGive , toGet , EMarketMode : : RESOURCE_RESOURCE ) ;
2020-09-02 19:16:24 +02:00
toGive = static_cast < int > ( toGive * ( it - > resVal / toGive ) ) ; //round down
2021-05-15 18:22:44 +02:00
//TODO trade only as much as needed
if ( toGive ) //don't try to sell 0 resources
{
2023-11-06 18:27:16 +02:00
cb - > trade ( m , EMarketMode : : RESOURCE_RESOURCE , res , GameResID ( g . resID ) , toGive ) ;
2020-09-02 19:16:24 +02:00
accquiredResources = static_cast < int > ( toGet * ( it - > resVal / toGive ) ) ;
2021-05-15 18:22:44 +02:00
logAi - > debug ( " Traded %d of %s for %d of %s at %s " , toGive , res , accquiredResources , g . resID , obj - > getObjectName ( ) ) ;
}
2023-04-05 02:26:29 +02:00
if ( cb - > getResourceAmount ( GameResID ( g . resID ) ) )
2021-05-15 18:22:44 +02:00
throw goalFulfilledException ( sptr ( g ) ) ; //we traded all we needed
}
throw cannotFulfillGoalException ( " I cannot get needed resources by trade! " ) ;
}
else
{
throw cannotFulfillGoalException ( " I don't know how to use this object to raise resources! " ) ;
}
}
else
{
throw cannotFulfillGoalException ( " No object that could be used to raise resources! " ) ;
}
}
2021-05-16 14:39:38 +02:00
void AIGateway : : endTurn ( )
2021-05-15 18:22:44 +02:00
{
2023-09-04 21:21:02 +02:00
logAi - > info ( " Player %d (%s) ends turn " , playerID , playerID . toString ( ) ) ;
2021-05-15 18:22:44 +02:00
if ( ! status . haveTurn ( ) )
{
logAi - > error ( " Not having turn at the end of turn??? " ) ;
}
2022-12-14 22:13:26 +02:00
2021-05-15 18:22:44 +02:00
logAi - > debug ( " Resources at the end of turn: %s " , cb - > getResourceAmount ( ) . toString ( ) ) ;
2022-12-14 22:13:26 +02:00
if ( cb - > getPlayerStatus ( playerID ) ! = EPlayerStatus : : INGAME )
{
logAi - > info ( " Ending turn is not needed because we already lost " ) ;
return ;
}
2021-05-15 18:22:44 +02:00
do
{
cb - > endTurn ( ) ;
}
while ( status . haveTurn ( ) ) ; //for some reasons, our request may fail -> stop requesting end of turn only after we've received a confirmation that it's over
2023-09-04 21:21:02 +02:00
logGlobal - > info ( " Player %d (%s) ended turn " , playerID , playerID . toString ( ) ) ;
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
void AIGateway : : buildArmyIn ( const CGTownInstance * t )
2021-05-15 18:22:44 +02:00
{
makePossibleUpgrades ( t - > visitingHero ) ;
makePossibleUpgrades ( t ) ;
recruitCreatures ( t , t - > getUpperArmy ( ) ) ;
moveCreaturesToHero ( t ) ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : finish ( )
2021-05-15 18:22:44 +02:00
{
2019-12-15 15:47:21 +02:00
//we want to lock to avoid multiple threads from calling makingTurn->join() at same time
boost : : lock_guard < boost : : mutex > multipleCleanupGuard ( turnInterruptionMutex ) ;
2020-09-02 19:16:24 +02:00
2021-05-15 18:22:44 +02:00
if ( makingTurn )
{
makingTurn - > interrupt ( ) ;
makingTurn - > join ( ) ;
makingTurn . reset ( ) ;
}
}
2021-05-16 14:39:38 +02:00
void AIGateway : : requestActionASAP ( std : : function < void ( ) > whatToDo )
2021-05-15 18:22:44 +02:00
{
boost : : thread newThread ( [ this , whatToDo ] ( )
{
2021-05-16 14:39:38 +02:00
setThreadName ( " AIGateway::requestActionASAP::whatToDo " ) ;
2021-05-15 18:22:44 +02:00
SET_GLOBAL_STATE ( this ) ;
boost : : shared_lock < boost : : shared_mutex > gsLock ( CGameState : : mutex ) ;
whatToDo ( ) ;
} ) ;
2023-07-31 16:00:37 +02:00
newThread . detach ( ) ;
2021-05-15 18:22:44 +02:00
}
2021-05-16 14:39:38 +02:00
void AIGateway : : lostHero ( HeroPtr h )
2021-05-15 18:22:44 +02:00
{
logAi - > debug ( " I lost my hero %s. It's best to forget and move on. " , h . name ) ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : answerQuery ( QueryID queryID , int selection )
2021-05-15 18:22:44 +02:00
{
logAi - > debug ( " I'll answer the query %d giving the choice %d " , queryID , selection ) ;
if ( queryID ! = QueryID ( - 1 ) )
{
cb - > selectionMade ( selection , queryID ) ;
}
else
{
logAi - > debug ( " Since the query ID is %d, the answer won't be sent. This is not a real query! " , queryID ) ;
//do nothing
}
}
2021-05-16 14:39:38 +02:00
void AIGateway : : requestSent ( const CPackForServer * pack , int requestID )
2021-05-15 18:22:44 +02:00
{
//BNLOG("I have sent request of type %s", typeid(*pack).name());
if ( auto reply = dynamic_cast < const QueryReply * > ( pack ) )
{
status . attemptedAnsweringQuery ( reply - > qid , requestID ) ;
}
}
2021-05-16 14:39:38 +02:00
std : : string AIGateway : : getBattleAIName ( ) const
2021-05-15 18:22:44 +02:00
{
if ( settings [ " server " ] [ " enemyAI " ] . getType ( ) = = JsonNode : : JsonType : : DATA_STRING )
return settings [ " server " ] [ " enemyAI " ] . String ( ) ;
else
return " BattleAI " ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : validateObject ( const CGObjectInstance * obj )
2021-05-15 18:22:44 +02:00
{
validateObject ( obj - > id ) ;
}
2021-05-16 14:39:38 +02:00
void AIGateway : : validateObject ( ObjectIdRef obj )
2021-05-15 18:22:44 +02:00
{
if ( ! obj )
{
2020-05-04 17:58:43 +02:00
nullkiller - > memory - > removeFromMemory ( obj ) ;
2021-05-15 18:22:44 +02:00
}
}
AIStatus : : AIStatus ( )
{
battle = NO_BATTLE ;
havingTurn = false ;
ongoingHeroMovement = false ;
ongoingChannelProbing = false ;
}
AIStatus : : ~ AIStatus ( )
{
}
void AIStatus : : setBattle ( BattleState BS )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
LOG_TRACE_PARAMS ( logAi , " battle state=%d " , ( int ) BS ) ;
battle = BS ;
cv . notify_all ( ) ;
}
BattleState AIStatus : : getBattle ( )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
return battle ;
}
void AIStatus : : addQuery ( QueryID ID , std : : string description )
{
if ( ID = = QueryID ( - 1 ) )
{
logAi - > debug ( " The \" query \" has an id %d, it'll be ignored as non-query. Description: %s " , ID , description ) ;
return ;
}
assert ( ID . getNum ( ) > = 0 ) ;
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
assert ( ! vstd : : contains ( remainingQueries , ID ) ) ;
remainingQueries [ ID ] = description ;
cv . notify_all ( ) ;
logAi - > debug ( " Adding query %d - %s. Total queries count: %d " , ID , description , remainingQueries . size ( ) ) ;
}
void AIStatus : : removeQuery ( QueryID ID )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
assert ( vstd : : contains ( remainingQueries , ID ) ) ;
std : : string description = remainingQueries [ ID ] ;
remainingQueries . erase ( ID ) ;
cv . notify_all ( ) ;
logAi - > debug ( " Removing query %d - %s. Total queries count: %d " , ID , description , remainingQueries . size ( ) ) ;
}
int AIStatus : : getQueriesCount ( )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
2020-09-02 19:16:24 +02:00
return static_cast < int > ( remainingQueries . size ( ) ) ;
2021-05-15 18:22:44 +02:00
}
void AIStatus : : startedTurn ( )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
havingTurn = true ;
cv . notify_all ( ) ;
}
void AIStatus : : madeTurn ( )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
havingTurn = false ;
cv . notify_all ( ) ;
}
void AIStatus : : waitTillFree ( )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
while ( battle ! = NO_BATTLE | | ! remainingQueries . empty ( ) | | ! objectsBeingVisited . empty ( ) | | ongoingHeroMovement )
2023-08-20 22:45:41 +02:00
cv . wait_for ( lock , boost : : chrono : : milliseconds ( 10 ) ) ;
2021-05-15 18:22:44 +02:00
}
bool AIStatus : : haveTurn ( )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
return havingTurn ;
}
void AIStatus : : attemptedAnsweringQuery ( QueryID queryID , int answerRequestID )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
assert ( vstd : : contains ( remainingQueries , queryID ) ) ;
std : : string description = remainingQueries [ queryID ] ;
logAi - > debug ( " Attempted answering query %d - %s. Request id=%d. Waiting for results... " , queryID , description , answerRequestID ) ;
requestToQueryID [ answerRequestID ] = queryID ;
}
void AIStatus : : receivedAnswerConfirmation ( int answerRequestID , int result )
{
assert ( vstd : : contains ( requestToQueryID , answerRequestID ) ) ;
QueryID query = requestToQueryID [ answerRequestID ] ;
assert ( vstd : : contains ( remainingQueries , query ) ) ;
requestToQueryID . erase ( answerRequestID ) ;
if ( result )
{
removeQuery ( query ) ;
}
else
{
logAi - > error ( " Something went really wrong, failed to answer query %d : %s " , query . getNum ( ) , remainingQueries [ query ] ) ;
//TODO safely retry
}
}
void AIStatus : : heroVisit ( const CGObjectInstance * obj , bool started )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
if ( started )
{
objectsBeingVisited . push_back ( obj ) ;
}
else
{
// There can be more than one object visited at the time (eg. hero visits Subterranean Gate
// causing visit to hero on the other side.
// However, we are guaranteed that start/end visit notification maintain stack order.
assert ( ! objectsBeingVisited . empty ( ) ) ;
objectsBeingVisited . pop_back ( ) ;
}
cv . notify_all ( ) ;
}
void AIStatus : : setMove ( bool ongoing )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
ongoingHeroMovement = ongoing ;
cv . notify_all ( ) ;
}
void AIStatus : : setChannelProbing ( bool ongoing )
{
boost : : unique_lock < boost : : mutex > lock ( mx ) ;
ongoingChannelProbing = ongoing ;
cv . notify_all ( ) ;
}
bool AIStatus : : channelProbing ( )
{
return ongoingChannelProbing ;
2022-04-25 14:13:41 +02:00
}
2022-09-26 20:01:07 +02:00
}