Skip to content

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.

fix(gameengine): ai defends its base, buys the capture upgrade

Olcay Seygan94647795d548
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 369fd8513..f82db09d9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,7 +50,7 @@ found and fixed — EA's own, not port damage.**
- Hard USA opens the way a player does. It used to start on a barracks and hold its first power plant until a second dozer existed, so its first harvest came in at the 74 second mark. It now puts down the power plant and the supply centre straight away and the barracks after them. Over 20 Hard USA against Hard China matches on Tournament Desert, seats swapped both ways, USA won 15 where it won 10. The same opening was tried on China and lost it 17 matches instead of 10, and on GLA it decided too few matches to say anything, so both keep the opening they shipped with.
- The computer no longer shoots at what it cannot see. Its units, and its base defences, used to auto-target through the fog of war - a hard exemption written into the code for computer players only. Stealth works against it now, and so does anything it has not scouted.
- 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. And it tours on purpose rather than in a circle: it goes to whichever base it has gone longest without seeing, nearest first, and it does not walk across the map to look again at something it looked at a minute ago - it stays and watches instead. Two scouts never trail each other round the same lap.
-- It takes the oil derricks instead of blowing them up. An oil derrick pays whoever owns it and costs one infantryman to walk in - and the computer used to march past the neutral ones and shell yours, which is the one thing you can do with a derrick that earns nobody anything. It now keeps a cheap infantryman doing the rounds of every derrick, refinery and hospital it has found, takes them, and when there is nothing left to take it leaves him standing on the last one instead of walking him home. And it no longer picks a capturable building as a target of its own accord: it can still be ordered to level one, and one that shoots back is still shot back at.
+- It takes the oil derricks instead of blowing them up. An oil derrick pays whoever owns it and costs one infantryman to walk in - and the computer used to march past the neutral ones and shell yours, which is the one thing you can do with a derrick that earns nobody anything. It now keeps a cheap infantryman doing the rounds of every derrick, refinery and hospital it has found, takes them, and when there is nothing left to take it leaves him standing on the last one instead of walking him home. And it no longer picks a capturable building as a target of its own accord: it can still be ordered to level one, and one that shoots back is still shot back at. That infantryman never took anything before this, though. A Ranger, a Red Guard or a Rebel can only capture once the barracks has taught him how, and the computer never paid for the lesson, so he walked up to a derrick and stood on it for the whole match. It now buys the training the first time it sends him, and keeps him at home until it is done. Replays recorded before this change play out differently.
- It steals your tanks. A hijacker costs a few hundred and walks off with whatever it touches, and no computer opponent had ever bought one: not one shipped skirmish plan asks for it. A GLA computer now keeps a thief on call as soon as one of your vehicles comes within walking distance, and sends it at the nearest one rather than the richest, because the Humvee it reaches is worth more than the Overlord it dies halfway to. Black Lotus works the same ground on the same terms: she hacks a vehicle that is already in front of her, and does not cross the map to shut one down for a few seconds.
- Nor does it know which start position you took. It used to read that straight off the lobby, for every player, from the first second. Now it works it out: each position it has not looked at is a suspect, and the odds are simply how many opponents are still unaccounted for over how many places they could be - three of you on an eight-position map is 3 in 7 for each. Every empty position its scout crosses off makes the rest likelier, 3 in 6, then 3 in 5. When the numbers meet, it stops looking: three opponents with three places left to be is not a guess, and walking over to confirm it would waste the trip. On a two-player map that is true from the start, so nothing changed there - it never wastes a second hunting for an address it can work out by subtraction. Where it has not worked you out yet, it attacks the position you are most likely to be on, and finds out on arrival.
- 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.
@@ -123,6 +123,7 @@ found and fixed — EA's own, not port damage.**
- Its aircraft are left out of it. A retreat order was what took a parked jet off the runway, so while a fight raged near the airfield the whole wing took off, flew at the base, landed, and did it again every few seconds instead of ever reaching you. Aircraft already fly home on their own when the load is spent.
- Matches finish. Two of these opponents used to fail to settle 65% of their games inside sixteen minutes; it is half that now, and they end in under seven minutes on average instead of ten.
- The retreat actually happens now, on Normal as well as Hard. The order home was handed to units that were already fighting, and the game laid it over their attack instead of replacing it, so a team told to break off carried on driving at what it was shooting, and its aggressive mood turned any walk that did start into a fight on the way. A unit that makes it home gets its mood back when it stops walking.
+- It no longer runs from a fight in its own base. Home was where the retreat went, so when you rushed a Normal or Hard computer early, every defender was outnumbered, read the fight as lost, and was ordered back to the middle of the base it was already standing in, walking and not shooting, again every second and a half. Sixteen rebels and four Scorpions sent into a Hard USA base a minute in went a full minute without losing one. A fight at home is now fought where it is. While the base is being hit the computer also keeps its attack groups at home: nothing it has gathered leaves on a wave, nothing waiting to leave gathers out on the road, and the groups guarding the base are no longer called away to join an attack. What was gathered goes once none of your units it knows of stands in its base, or half a minute after the last hit. It still has little to fight with a minute in; the opening goes on buildings first. Replays recorded before this change play out differently.
## Hard fights each unit from where it is strongest
@@ -242,6 +243,7 @@ found and fixed — EA's own, not port damage.**
- Supply trucks queued at a dock carry on after a load. Their place in the queue was written to the save and never read back, so every dock stopped letting anyone in until a thirty-second timeout sent the trucks round again.
- A cargo plane or bomber on its way off the map at save time flies on after a load. Its heading was not saved, so the first turn read as a sharp one and the plane was destroyed where it was.
- An EMP pulse, a bike being scuttled, a building's evacuation side and a horde's bonus all come back from a save as they went in.
+- A computer whose base was under attack when you saved still knows it after a load, and keeps its army at home as it would have.
- Where a supply dock's waiting spots are is the same on every machine. A dock with fewer spots in its model than in its data filled the rest from leftover memory, a different place on each computer.
- A building's toppling bursts are timed the same on every machine. They were timed off the picture's random numbers and created game objects, so two players could see different debris.
- An aircraft carrier remembers the order it was given, and each runway its own ramp.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index 09e43d8bb..08c19f332 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -508,6 +508,8 @@ protected:
UnsignedInt m_heldSince; ///< frame the first of the parked teams arrived
Bool isOutOnOrders(const Object *obj) const; ///< away from home with something to do
+ Bool isAtHome(const Coord3D *pos) const; ///< within two base radii of the base center
+ Bool isBaseUnderAttack(void) const; ///< hit lately, with a known enemy that can shoot standing at home
Real waitingPower(Team *team, AIGroup *group) const; ///< what a team has for a wave, less the members out on orders; they join the group if one is given
/** How hard this AI leans on its current enemy: its chance against him, looked at again on the
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
index cbaabe889..8b60414ba 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
@@ -4531,13 +4531,15 @@ void Player::crc( Xfer *xfer )
* 7: added Preorder flag
* 8: Save m_disabledSciences & m_hiddenSciences. jba.
* 9: The shift queue, m_orderQueue (fork).
+ * 10: The vision spies (fork).
+ * 11: m_attackedFrame, which the skirmish AI's base-under-attack test reads (fork).
*/
// ------------------------------------------------------------------------------------------------
void Player::xfer( Xfer *xfer )
{
// version
- const XferVersion currentVersion = 10;
+ const XferVersion currentVersion = 11;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -5094,6 +5096,13 @@ void Player::xfer( Xfer *xfer )
m_visionSpies[ i ].byWhom = byWhom;
}
+ // the frame this player was last hit, which the skirmish AI reads to keep a base under attack
+ // garrisoned; an older save has none and reads as never
+ if( version >= 11 )
+ xfer->xferUnsignedInt( &m_attackedFrame );
+ else
+ m_attackedFrame = 0;
+
} // end xfer
// ------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 3efad5438..d32262238 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -5996,7 +5996,37 @@ Bool AIPlayer::isOutOnOrders( const Object *obj ) const
const StateID state = obj->getAI()->getCurrentStateID();
if( state == AI_IDLE || state == AI_GUARD || state == AI_GUARD_RETALIATE || state == AI_MOVE_AND_TIGHTEN )
return FALSE;
- return sqr( obj->getPosition()->x - m_baseCenter.x ) + sqr( obj->getPosition()->y - m_baseCenter.y ) > sqr( 2.0f * m_baseRadius );
+ return !isAtHome( obj->getPosition() );
+}
+
+/** Within the reach the home guard answers to, two base radii from the base center. */
+Bool AIPlayer::isAtHome( const Coord3D *pos ) const
+{
+ return sqr( pos->x - m_baseCenter.x ) + sqr( pos->y - m_baseCenter.y ) <= sqr( 2.0f * m_baseRadius );
+}
+
+/** Something of ours was hit in the last thirty seconds and an enemy that can shoot, one this AI knows
+ * of, stands at home. The attacked frame alone is set by a hit on anything anywhere, and a tank at
+ * the enemy's base would have kept every wave at home. */
+Bool AIPlayer::isBaseUnderAttack( void ) const
+{
+ const UnsignedInt attacked = m_player->getAttackedFrame();
+ if( !m_baseCenterSet || attacked == 0 || attacked + 30 * LOGICFRAMES_PER_SECOND <= TheGameLogic->getFrame() )
+ return FALSE;
+
+ PartitionFilterAlive filterAlive;
+ PartitionFilterOnMap filterOnMap;
+ PartitionFilter *filters[] = { &filterAlive, &filterOnMap, NULL };
+ ObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( &m_baseCenter, 2.0f * m_baseRadius, FROM_CENTER_2D, filters );
+ MemoryPoolObjectHolder hold( iter );
+ for( Object *obj = iter->first(); obj; obj = iter->next() )
+ {
+ if( obj->isKindOf( KINDOF_PROJECTILE ) || m_player->getRelationship( obj->getTeam() ) != ENEMIES )
+ continue;
+ if( obj->isAbleToAttack() && observerKnowsAbout( obj, m_player->getPlayerIndex() ) )
+ return TRUE;
+ }
+ return FALSE;
}
/** What a team has to put into a wave, and those members into the group when one is given. Not the
@@ -6087,7 +6117,11 @@ Bool aiTeamAttacks( const TeamTemplateInfo *info )
//----------------------------------------------------------------------------------------------------------
Bool AIPlayer::holdTeamForWave( Team *team, const AsciiString &approach, Int pathSuffix )
{
- if( team == NULL || !isSkirmishAI() || !holdsTeamsForWaves() )
+ // a base being hit keeps what its scripts would send out, on every rung, until the fight at home is over
+ if( team == NULL || !isSkirmishAI() )
+ return FALSE;
+ const Bool underAttack = isBaseUnderAttack();
+ if( !underAttack && !holdsTeamsForWaves() )
return FALSE;
const TeamTemplateInfo *info = team->getPrototype()->getTemplateInfo();
if( info->m_isBaseDefense || info->m_isPerimeterDefense )
@@ -6109,7 +6143,7 @@ Bool AIPlayer::holdTeamForWave( Team *team, const AsciiString &approach, Int pat
}
if( freeSlot < 0 )
return FALSE; // the staging point is full, so this one goes as the script said
- if( aiReleaseWaveAt( m_pressure, waitingPower( team, NULL ), WAVE_POWER, 0, WAVE_MAX_HOLD_FRAMES ) )
+ if( !underAttack && aiReleaseWaveAt( m_pressure, waitingPower( team, NULL ), WAVE_POWER, 0, WAVE_MAX_HOLD_FRAMES ) )
return FALSE; // a wave on its own waits for nobody
m_heldUsed[ freeSlot ] = TRUE;
@@ -6141,9 +6175,10 @@ Bool AIPlayer::holdTeamForWave( Team *team, const AsciiString &approach, Int pat
break;
}
}
- // an outmatched AI gathers at home, where the wave is also the garrison
+ // an outmatched AI gathers at home, where the wave is also the garrison, and so does one whose base
+ // is being hit
Coord3D hold;
- if( getSkillProfile()->m_useInfluenceMapForAttackLane && m_pressure != AIPRESSURE_DEFEND &&
+ if( getSkillProfile()->m_useInfluenceMapForAttackLane && m_pressure != AIPRESSURE_DEFEND && !underAttack &&
forwardHoldPoint( m_heldLabel[ firstParked ], m_heldSuffix[ firstParked ], &enemyPos, &hold ) )
{
DEBUG_LOG(("AI HOLD frame %d player %d gathers at (%.0f,%.0f) on %s%d\n", TheGameLogic->getFrame(),
@@ -6345,10 +6380,18 @@ void AIPlayer::doWaves( void )
if( first < 0 )
return;
loadGunships();
+ // no wave walks out of a base that is being hit
+ if( isBaseUnderAttack() )
+ {
+ DEBUG_LOG(("AI WAVE frame %d player %d keeps %d teams at home, the base is under attack\n", TheGameLogic->getFrame(),
+ m_player->getPlayerIndex(), teams));
+ return;
+ }
const UnsignedInt heldFrames = TheGameLogic->getFrame() - m_heldSince;
// a full staging point goes whatever it adds up to: sixteen GLA teams of one man each are 3,200, and
// every team formed behind them would leave alone
- if( teams < MAX_HELD_TEAMS && !aiReleaseWaveAt( m_pressure, power, WAVE_POWER, heldFrames, WAVE_MAX_HOLD_FRAMES ) )
+ // and a rung that does not mass lets go the moment the fight at home is over
+ if( teams < MAX_HELD_TEAMS && holdsTeamsForWaves() && !aiReleaseWaveAt( m_pressure, power, WAVE_POWER, heldFrames, WAVE_MAX_HOLD_FRAMES ) )
return;
const AsciiString requested = m_heldLabel[ first ];
@@ -6551,6 +6594,10 @@ void AIPlayer::sendIdleAttackTeams( void )
{
if( !isSkirmishAI() || (m_pressure != AIPRESSURE_FINISH && !getSkillProfile()->m_massBeforeAttacking) || !m_baseCenterSet )
return;
+ // a team standing at home while the base is hit is its garrison: guarding, or idle beside a fight it
+ // will pick up, it is not called away
+ if( isBaseUnderAttack() )
+ return;
Player *enemy = getAiEnemy();
if( enemy == NULL )
return;
@@ -6826,6 +6873,12 @@ void AIPlayer::doRetreats( void )
centre.y /= count;
centre.z = TheTerrainLogic->getGroundHeight( centre.x, centre.y );
+ // A fight at home is not broken off: home is where the retreat goes. Ordered to the base
+ // centre, the defenders of an early rush stopped shooting and walked, every decision tick,
+ // while sixteen rebels took the base apart untouched for a minute.
+ if( isAtHome( &centre ) )
+ continue;
+
//
// Both sides of the exchange, measured the same way: everything of ours in this fight
// against everything of theirs in it.
@@ -7441,10 +7494,11 @@ void AIPlayer::tacticsFor( Object *obj )
if( myRange <= 0.0f )
return;
- // a hurt unit on ground it cannot win goes home, where the next wave will pick it up
+ // a hurt unit on ground it cannot win goes home, where the next wave will pick it up; one already
+ // at home has nowhere better to be and fights where it stands
const BodyModuleInterface *body = obj->getBodyModule();
const Real friendsHere = m_influence.friendAt( pos->x, pos->y );
- if( body && body->getHealth() < body->getMaxHealth() * HURT_HEALTH_SHARE && threatHere > friendsHere )
+ if( body && body->getHealth() < body->getMaxHealth() * HURT_HEALTH_SHARE && threatHere > friendsHere && !isAtHome( pos ) )
{
DEBUG_LOG(("AI TACTICS frame %d player %d pulls a hurt '%s' out, %.0f against %.0f\n", now, m_player->getPlayerIndex(),
obj->getTemplate()->getName().str(), threatHere, friendsHere));
@@ -8360,6 +8414,25 @@ void AIPlayer::doCapture( void )
// we know about but cannot reach from here is walked to first and asked again next check.
//
SpecialPowerModuleInterface *mod = capturer->findSpecialPowerModuleInterface( SPECIAL_INFANTRY_CAPTURE_BUILDING );
+
+ //
+ // The Ranger, the Red Guard and the Rebel all come out of the barracks with the capture paused
+ // until the player buys it there, and nothing bought it: the capturer walked up to a derrick and
+ // stood on it all match. Buy it (buildUpgrade waits for the money and ignores a repeat) and keep
+ // the capturer home until it is in.
+ //
+ static const AsciiString captureUpgradeName( "Upgrade_InfantryCaptureBuilding" );
+ const UpgradeTemplate *captureUpgrade = TheUpgradeCenter->findUpgrade( captureUpgradeName );
+ if( mod && captureUpgrade && mod->getPercentReady() < 1.0f && !m_player->hasUpgradeComplete( captureUpgrade ) )
+ {
+ const Bool queued = m_player->hasUpgradeInProduction( captureUpgrade );
+ buildUpgrade( captureUpgradeName );
+ if( !queued && m_player->hasUpgradeInProduction( captureUpgrade ) )
+ DEBUG_LOG(("AI player %d buys the capture upgrade for a '%s'\n", m_player->getPlayerIndex(),
+ target->getTemplate()->getName().str()));
+ return;
+ }
+
if( mod && TheActionManager->canCaptureBuilding( capturer, target, CMD_FROM_AI ) )
{
mod->doSpecialPowerAtObject( target, 0 );