Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(gameengine): the AI breaks off a fight it is losing
Olcay Seygan1f38660925c5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4cf282dbf..a8761ae26 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,13 @@ found and fixed — EA's own, not port damage.**- It scouts. There was no such thing as scouting in the computer opponent - it never needed to look, because it could already see everything. One cheap unit now tours the enemy start positions and keeps going round for the rest of the match, replaced out of spare change when it dies. Every difficulty scouts; an opponent that never looks reads as broken, not as easy.- Nor does it read your base off the map. Where your base is, what it is worth, which supply dock to expand to and where to aim a superweapon all came off a walk of your object list, in the shroud, from the first second of the match. The computer now only counts what it can see, plus the buildings it has already found - buildings do not walk away. Before it has scouted you, all it knows is where you started, which is on the map preview anyway.+## The computer knows when to quit++- Its teams fought to the last man. The word "retreat" appeared nowhere in the opponent's code - the single most visible thing that made it look stupid.+- It now measures the fight, not the health bar: how long its force lasts against how long it needs to finish yours. A unit at a fifth of its health that still out-damages what is shooting it stays; a full-health one being melted leaves. A health percentage gets both of those backwards.+- Two levels. From Steady up, a unit that is personally finished pulls out of a fight its team is still winning. From Brutal up, the whole team breaks off when the exchange is lost. Easy never quits - that is part of what makes it easy.+- It only counts what it can see. An opponent that flinches from something it has not found is reading your unit list again.+## The computer builds against what you field- Which unit it trained next was a coin flip. It gathered the teams sharing the highest priority number in its data and picked one at random - not one line looked at what it was fighting. An opponent facing nothing but aircraft went on building tanks.diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.hindex 1cc1240ef..f4b9ade6c 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h@@ -185,7 +185,8 @@ struct AIDifficultyProfileReal m_counterCompositionWeight; ///< 0 = ignore what the enemy fields (EA's behaviour)Bool m_massBeforeAttacking;Real m_retreatTtkRatio; ///< allied time-to-kill / enemy TTK below which it pulls back- Bool m_retreatIndividualUnits;+ Bool m_retreatIndividualUnits; ///< pull a losing unit out of a fight the team is winning+ Bool m_retreatTeams; ///< ... and break off the whole team when the fight is lostBool m_useInfluenceMapForAttackLane;Bool m_focusFire;@@ -230,6 +231,15 @@ struct AITeamCapability* rather than a coin flip, and this is the half of it that has no engine in it. */Real aiCounterScore( const AIEnemyComposition &enemy, const AITeamCapability &team );+/** How the exchange is going, as the ratio of how long this force lasts to how long it needs to+ * kill what is shooting at it. Below 1 it is losing; below the rung's retreatTtkRatio it should+ * break off. This is Sins of a Solar Empire's aiRetreatThreshold, and it is the right metric+ * rather than a health percentage: a unit at 20% health that still out-damages what is shooting+ * it should stay, and a full-health one being melted should not.+ *+ * 'power' is a stand-in for damage per second - the threat value the data already carries. */+Real aiRetreatRatio( Real myHealth, Real myPower, Real enemyHealth, Real enemyPower );+class TAiData : public Snapshot{public:diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.hindex ce9edf6a8..4d2ce3ca5 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h@@ -243,6 +243,12 @@ protected:* while every strategic decision read the enemy's object list straight out of the game (see* the observer index on getPlayerStructureBounds). One cheap unit, replaced when it dies,* touring the enemy start positions: that is what turns fog back into information. */+ /** Break off a fight that is being lost. The word "retreat" did not appear anywhere in the AI:+ * teams fought to the last man, which is the single most visible thing that made it look+ * stupid. Two levels, because pulling out only whole teams still loses the units that were+ * individually finished - Sins does exactly that, and keeps losing capital ships for it. */+ virtual void doRetreats(void);+virtual void doScouting(void);Object *findScout(void); ///< a spare unit of ours that can do the touringvoid queueScout(void); ///< ... or build the cheapest one that can@@ -324,6 +330,7 @@ protected:ObjectID m_scoutID; ///< the unit currently touring the map for usInt m_scoutTimer; ///< frames until the next scouting checkInt m_scoutTarget; ///< which player's start position the scout is walking to+ Int m_retreatTimer; ///< frames until the next look at how the fights are goingBool m_readyToBuildTeam; ///< True if the team select timer has expired.Bool m_readyToBuildStructure; ///< True if the buildDelay timer has expired.diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cppindex 68f9ac6bb..fe18c5b5e 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp@@ -1011,15 +1011,15 @@ Real AI::getAdjustedVisionRangeForObject(const Object *object, Int factorsToCons** Read the columns down, not across: nothing here is money, build speed, vision or unit stats.*- * scoutS maxSc react decis cntr mass ttk indiv infl focus harv expand guard hoard */+ * scoutS maxSc react decis cntr mass ttk indiv team infl focus harv expand guard hoard */static const AIDifficultyProfile s_defaultSkillLadder[ AISKILL_COUNT ] ={- /* Easy */ { 90.0f, 1, 15.0f, 10.0f, 0.00f, FALSE, 0.00f, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, 0 },- /* Steady */ { 75.0f, 1, 10.0f, 8.0f, 0.00f, FALSE, 0.50f, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, 0 },- /* Medium */ { 60.0f, 1, 6.0f, 5.0f, 0.25f, FALSE, 0.60f, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, 10000 },- /* Hard */ { 45.0f, 2, 3.0f, 4.0f, 0.60f, FALSE, 0.70f, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, 8000 },- /* Brutal */ { 30.0f, 2, 1.0f, 2.0f, 0.85f, TRUE, 0.80f, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, 5000 },- /* Merciless */ { 25.0f, 2, 0.0f, 1.5f, 1.00f, TRUE, 0.85f, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 4000 }+ /* Easy */ { 90.0f, 1, 15.0f, 10.0f, 0.00f, FALSE, 0.00f, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, 0 },+ /* Steady */ { 75.0f, 1, 10.0f, 8.0f, 0.00f, FALSE, 0.50f, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, 0 },+ /* Medium */ { 60.0f, 1, 6.0f, 5.0f, 0.25f, FALSE, 0.60f, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, 10000 },+ /* Hard */ { 45.0f, 2, 3.0f, 4.0f, 0.60f, FALSE, 0.70f, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, 8000 },+ /* Brutal */ { 30.0f, 2, 1.0f, 2.0f, 0.85f, TRUE, 0.80f, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, 5000 },+ /* Merciless */ { 25.0f, 2, 0.0f, 1.5f, 1.00f, TRUE, 0.85f, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 4000 }};//-------------------------------------------------------------------------------------------------@@ -1034,6 +1034,32 @@ static const AIDifficultyProfile s_defaultSkillLadder[ AISKILL_COUNT ] =* Merely being able to shoot at the ground is worth a quarter share: almost every team can, so* it barely discriminates, but a team that cannot is genuinely useless against a ground army. *///-------------------------------------------------------------------------------------------------+//-------------------------------------------------------------------------------------------------+/** How the exchange is going: how long this force lasts, over how long it needs to finish what is+ * shooting at it. Above 1 it is winning.+ *+ * The two degenerate cases are the ones that matter in practice. Nothing is shooting at me: no+ * fight, never retreat, so a large number. I cannot hurt what is shooting me: no exchange to+ * win at any health, so zero. */+//-------------------------------------------------------------------------------------------------+Real aiRetreatRatio( Real myHealth, Real myPower, Real enemyHealth, Real enemyPower )+{+ const Real NOT_A_FIGHT = 1000.0f;++ if( enemyPower <= 0.0f || enemyHealth <= 0.0f )+ return NOT_A_FIGHT; // nothing that can hurt me+ if( myPower <= 0.0f || myHealth <= 0.0f )+ return 0.0f; // nothing I can do about it++ const Real howLongILast = myHealth / enemyPower;+ const Real howLongTheyLast = enemyHealth / myPower;+ if( howLongTheyLast <= 0.0f )+ return NOT_A_FIGHT;++ Real ratio = howLongILast / howLongTheyLast;+ return (ratio > NOT_A_FIGHT) ? NOT_A_FIGHT : ratio;+}+Real aiCounterScore( const AIEnemyComposition &enemy, const AITeamCapability &team ){Real score = 0.0f;@@ -1080,6 +1106,7 @@ void AI::parseSkillLevel(INI *ini, void *instance, void* /*store*/, const void*{ "MassBeforeAttacking", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_massBeforeAttacking ) },{ "RetreatTtkRatio", INI::parseReal, NULL, offsetof( AIDifficultyProfile, m_retreatTtkRatio ) },{ "RetreatIndividualUnits", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_retreatIndividualUnits ) },+ { "RetreatTeams", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_retreatTeams ) },{ "UseInfluenceMapForAttackLane", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_useInfluenceMapForAttackLane ) },{ "FocusFire", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_focusFire ) },{ "AdaptiveHarvesters", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_adaptiveHarvesters ) },diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cppindex e140e0b9e..e498860bf 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp@@ -135,6 +135,7 @@ m_curWarehouseID(INVALID_ID),m_scoutID(INVALID_ID),m_scoutTimer(1),m_scoutTarget(0),+m_retreatTimer(1),m_skillLevel(AISKILL_MERCILESS),m_role(AIROLE_AGGRESSIVE){@@ -3345,6 +3346,8 @@ void AIPlayer::update( void )doScouting(); // Keep one unit looking at the map.+ doRetreats(); // Break off the fights we are losing.+}//----------------------------------------------------------------------------------------------------------@@ -3466,6 +3469,147 @@ Bool AIPlayer::dozerInQueue( void )return false;}+//----------------------------------------------------------------------------------------------------------+/** How far around a fight to look for what is in it. Wide enough to catch the base defences and+ * the second rank shooting into it, not so wide that a skirmish at the front counts the garrison+ * at the back as part of the same exchange. */+static const Real RETREAT_ENGAGEMENT_RADIUS = 300.0f;++/** A unit's contribution to an exchange: what it can still take, and what it can still deal. The+ * threat value the data already carries stands in for damage per second - it is what+ * AI_threatScore uses for the same purpose. */+static void addToForce( const Object *obj, Real *health, Real *power )+{+ if( obj == NULL || obj->isEffectivelyDead() )+ return;++ const BodyModuleInterface *body = obj->getBodyModule();+ if( body )+ *health += body->getHealth();+ *power += INT_TO_REAL( obj->getTemplate()->getThreatValue() );+}++//----------------------------------------------------------------------------------------------------------+/** Look at every fight this AI is in and break off the ones it is losing.+ *+ * Deliberately at the player level and on the rung's decision interval rather than inside the+ * unit update: it is one partition query per engaged team every few seconds, not a judgement+ * every unit makes every frame, and it keeps the whole of "when do we quit" in one readable+ * place.+ */+//----------------------------------------------------------------------------------------------------------+void AIPlayer::doRetreats( void )+{+ const AIDifficultyProfile *profile = getSkillProfile();+ if( profile->m_retreatTtkRatio <= 0.0f )+ return; // the bottom rung does not know how to quit, on purpose++ if( --m_retreatTimer > 0 )+ return;+ m_retreatTimer = REAL_TO_INT_CEIL( profile->m_decisionIntervalSeconds * LOGICFRAMES_PER_SECOND );+ if( m_retreatTimer < 1 )+ m_retreatTimer = 1;++ if( !m_baseCenterSet )+ return; // nowhere to fall back to++ for( Player::PlayerTeamList::const_iterator t = m_player->getPlayerTeams()->begin();+ t != m_player->getPlayerTeams()->end(); ++t )+ {+ const TeamTemplateInfo *info = (*t)->getTemplateInfo();+ if( info && (info->m_isBaseDefense || info->m_isPerimeterDefense) )+ continue; // a base defence team that falls back has abandoned the thing it defends++ for( DLINK_ITERATOR<Team> iter = (*t)->iterate_TeamInstanceList(); !iter.done(); iter.advance() )+ {+ Team *team = iter.cur();+ if( team == NULL )+ continue;++ // what this team still has, and where it is+ Real myHealth = 0.0f, myPower = 0.0f, count = 0.0f;+ Coord3D centre;+ centre.zero();+ for( DLINK_ITERATOR<Object> objIter = team->iterate_TeamMemberList(); !objIter.done(); objIter.advance() )+ {+ Object *obj = objIter.cur();+ if( obj == NULL || obj->isEffectivelyDead() )+ continue;+ if( obj->isKindOf( KINDOF_STRUCTURE ) || obj->isKindOf( KINDOF_IMMOBILE ) ||+ obj->isKindOf( KINDOF_PROJECTILE ) || obj->getAI() == NULL )+ continue;+ addToForce( obj, &myHealth, &myPower );+ centre.x += obj->getPosition()->x;+ centre.y += obj->getPosition()->y;+ count += 1.0f;+ }+ if( count < 1.0f )+ continue;+ centre.x /= count;+ centre.y /= count;+ centre.z = TheTerrainLogic->getGroundHeight( centre.x, centre.y );++ // ... and what is shooting at it+ Real enemyHealth = 0.0f, enemyPower = 0.0f;+ {+ PartitionFilterPlayerAffiliation filterEnemies( m_player, ALLOW_ENEMIES, true );+ PartitionFilterAlive filterAlive;+ PartitionFilterOnMap filterOnMap;+ PartitionFilter *filters[] = { &filterEnemies, &filterAlive, &filterOnMap, 0 };++ MemoryPoolObjectHolder hold;+ SimpleObjectIterator *nearby = ThePartitionManager->iterateObjectsInRange(+ ¢re, RETREAT_ENGAGEMENT_RADIUS, FROM_CENTER_2D, filters );+ hold.hold( nearby );+ for( Object *e = nearby->first(); e; e = nearby->next() )+ {+ if( e->isKindOf( KINDOF_PROJECTILE ) )+ continue;+ // only what it can see: an AI that pulls back from something it has not found+ // is reading the object list again (A2)+ if( !observerKnowsAbout( e, m_player->getPlayerIndex() ) )+ continue;+ addToForce( e, &enemyHealth, &enemyPower );+ }+ }++ if( enemyPower <= 0.0f )+ continue; // not in a fight++ const Real ratio = aiRetreatRatio( myHealth, myPower, enemyHealth, enemyPower );+ if( ratio >= profile->m_retreatTtkRatio )+ continue; // holding, or winning++ //+ // Losing. The whole team goes home if this rung knows how; otherwise the members that+ // are personally finished go, which saves the units that would otherwise die inside a+ // fight the team as a whole is still winning.+ //+ for( DLINK_ITERATOR<Object> objIter = team->iterate_TeamMemberList(); !objIter.done(); objIter.advance() )+ {+ Object *obj = objIter.cur();+ if( obj == NULL || obj->isEffectivelyDead() || obj->getAI() == NULL )+ continue;+ if( obj->isKindOf( KINDOF_STRUCTURE ) || obj->isKindOf( KINDOF_IMMOBILE ) )+ continue;++ if( !profile->m_retreatTeams )+ {+ if( !profile->m_retreatIndividualUnits )+ continue;+ // this one's own exchange, against the same enemy force+ Real oneHealth = 0.0f, onePower = 0.0f;+ addToForce( obj, &oneHealth, &onePower );+ if( aiRetreatRatio( oneHealth, onePower, enemyHealth, enemyPower ) >= profile->m_retreatTtkRatio )+ continue;+ }++ obj->getAI()->aiMoveToPosition( &m_baseCenter, CMD_FROM_AI );+ }+ }+ }+}+//----------------------------------------------------------------------------------------------------------/** How often the scout is looked at. It only ever gets an order when it has arrived, so this is a* check, not a repath. */@@ -4027,6 +4171,8 @@ void AIPlayer::xfer( Xfer *xfer )xfer->xferInt( &m_scoutTimer );xfer->xferInt( &m_scoutTarget );}+ if( version >= 3 )+ xfer->xferInt( &m_retreatTimer );// the ladder rung and the role, which are rolled once and must come back the same wayif( version >= 3 )diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex c27e76a95..b204fbbc8 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -5815,6 +5815,7 @@ TEST(the_difficulty_ladder_climbs_in_every_direction_it_should)// capabilities only ever switch on as you climb, never off againCHECK( upper.m_massBeforeAttacking >= lower.m_massBeforeAttacking );CHECK( upper.m_retreatIndividualUnits >= lower.m_retreatIndividualUnits );+ CHECK( upper.m_retreatTeams >= lower.m_retreatTeams );CHECK( upper.m_useInfluenceMapForAttackLane >= lower.m_useInfluenceMapForAttackLane );CHECK( upper.m_focusFire >= lower.m_focusFire );CHECK( upper.m_adaptiveHarvesters >= lower.m_adaptiveHarvesters );@@ -5888,3 +5889,44 @@ TEST(counter_score_answers_what_the_enemy_actually_fields)CHECK( aiCounterScore( mixed, everything ) <= 1.0f );CHECK( aiCounterScore( mixed, everything ) > aiCounterScore( mixed, generic ) );}+++/** C1's arithmetic: the ratio of how long a force lasts to how long it needs to finish what is+ shooting at it. The word "retreat" did not appear anywhere in the AI before this - teams fought+ to the last man - and the metric is deliberately not a health percentage: Sins of a Solar+ Empire's aiRetreatThreshold is a time-to-kill ratio for the reason the third case below shows. */+TEST(retreat_ratio_measures_the_exchange_not_the_health_bar)+{+ // even fight: both sides need the same time to finish the other+ CHECK_NEAR( 1.0f, aiRetreatRatio( 100.0f, 10.0f, 100.0f, 10.0f ), 0.0001f );++ // twice their damage for the same health: they die in half the time I do+ CHECK( aiRetreatRatio( 100.0f, 20.0f, 100.0f, 10.0f ) > 1.0f );+ CHECK( aiRetreatRatio( 100.0f, 5.0f, 100.0f, 10.0f ) < 1.0f );++ // the case a health percentage gets wrong, and the reason for the metric: a unit at a fifth of+ // its health that still out-damages what is shooting it is winning and should stay+ CHECK( aiRetreatRatio( 20.0f, 100.0f, 500.0f, 1.0f ) > 1.0f );+ // ... and a full-health one being melted is losing and should not+ CHECK( aiRetreatRatio( 1000.0f, 1.0f, 10.0f, 500.0f ) < 1.0f );++ // nothing shooting at me is not a fight, at any health+ CHECK( aiRetreatRatio( 1.0f, 1.0f, 0.0f, 0.0f ) > 100.0f );+ CHECK( aiRetreatRatio( 1.0f, 1.0f, 100.0f, 0.0f ) > 100.0f );++ // nothing I can do about it: leave, whatever my health+ CHECK_NEAR( 0.0f, aiRetreatRatio( 10000.0f, 0.0f, 10.0f, 10.0f ), 0.0001f );++ // already dead is not a fight to stay in either+ CHECK_NEAR( 0.0f, aiRetreatRatio( 0.0f, 10.0f, 10.0f, 10.0f ), 0.0001f );++ // and the ladder's thresholds mean what they say: at Brutal's 0.8 a force that lasts three+ // quarters as long as the one it is fighting breaks off, and one that lasts as long does not+ TAiData data;+ const Real brutal = data.m_skill[ AISKILL_BRUTAL ].m_retreatTtkRatio;+ CHECK( aiRetreatRatio( 75.0f, 10.0f, 100.0f, 10.0f ) < brutal );+ CHECK( aiRetreatRatio( 100.0f, 10.0f, 100.0f, 10.0f ) >= brutal );++ // the bottom rung has no threshold at all: it never quits, which is what makes it Easy+ CHECK_EQ( 0.0f, data.m_skill[ AISKILL_EASY ].m_retreatTtkRatio );+}