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 retreats to a safe point and rejoins the fight

Olcay Seygan0cdf9945e354
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 32f922110..cef0e2741 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -139,6 +139,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.
+- A beaten team stops running once it is out of range. It used to break off a fight at your front door and walk the whole map back to its base at full health, where nothing repaired it, then stand there until a script or the next wave remembered it. Now it falls back just past the reach of the guns it was losing to, waits, and goes straight back in as soon as that fight turns: your units leave or die, or enough of its own arrive. If the fight still looks lost half a minute later, it goes home and joins the next wave. A team only walks home first when your guns cover the whole road. In 32 Hard against Hard matches on Twilight Flame, 2,748 of 2,756 retreats stopped short of home, and the side doing it lost 92 units a match where it had lost 96, for the same number of kills; that difference is inside the noise of 32 matches. Replays recorded before this change play out differently.
- 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. And it spends on the fight. A minute in, its opening has gone on buildings: a Hard USA had two soldiers and 8,000 in the bank when that rush arrived. Now a base under attack trains fighters from every factory that has room, each one picked against whatever of yours it has the least answer to yet, so sixteen rebels and four Scorpions get Rangers as well as Missile Defenders. It stops buying income buildings and extra factories until the fight is over, puts a gun up between the middle of its base and your units when it finds the room, and sends what it has at home at you once there is enough of it to matter; a handful sent out by twos only feeds you. Over four matches the USA left 36 of those 64 rebels alive where it had left 49. China and GLA already train at the pace their barracks allow, and came out about where they were. Replays recorded before this change play out differently.
## Hard fights each unit from where it is strongest
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
index cf9845d8a..9dbb677c2 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
@@ -285,6 +285,16 @@ Real aiMatchupScore( Real myFramesToKill, Real theirFramesToKill, Real myCost, R
* '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 );
+/** Where a force losing a fight stops: the first spot on its line home that none of the fight's
+ * guns reach (x, y, reach triples), plus one step. FALSE and home when there is none short of it. */
+Bool aiRetreatFallbackPoint( Real fromX, Real fromY, Real homeX, Real homeY, Real step,
+ const Real *guns, Int gunCount, Real *outX, Real *outY );
+
+/** A force holding where it fell back to: stay, go back to the fight it left, or give up and go home. */
+enum AIFallbackDecision { AIFALLBACK_HOLD, AIFALLBACK_RESUME, AIFALLBACK_GO_HOME };
+AIFallbackDecision aiRetreatHoldDecision( Bool arrived, UnsignedInt heldFrames, Real ratioThere, Real resumeRatio,
+ UnsignedInt minHold, UnsignedInt maxHold );
+
/** Hold a finished team at the rally point instead of sending it?
*
* A string of small waves is free veterancy for whoever is on the other end: EA's AI sent every
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index d1b410574..36dab3f81 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -553,11 +553,18 @@ protected:
Int savedAttitude; ///< its mood before a step calmed it, AI_INVALID when it has its own
UnsignedInt lastKiteFrame; ///< last time it stepped back from something it outranges, 0 for never
UnsignedInt lastSeenFrame; ///< a unit not looked at for a while has died or left, and its row goes
+ Bool fallingBack; ///< pulled out of a lost fight to a safe spot, and goes back once it is safe
+ Coord3D fallbackFrom; ///< the fight it was pulled out of
+ UnsignedInt fallbackFrame; ///< when it was pulled out
};
std::vector<TacticalStep> m_tactics;
TacticalStep *findTacticalStep(ObjectID unit);
TacticalStep *tacticalStepFor(ObjectID unit); ///< ... making the row if there is none
void leaveTacticsAlone(ObjectID unit);
+ Bool isFallingBack(ObjectID unit); ///< holding at a safe spot after a lost fight, for doRetreats to send back
+ void measureFight(const Coord3D *centre, Team *team, Real *myHealth, Real *myPower,
+ Real *enemyHealth, Real *enemyPower, std::vector<Real> *enemyGuns);
+ void doFallback(Team *team);
void stepCalmly(Object *obj, TacticalStep *step, const Coord3D *spot); ///< a move the unit's mood cannot turn into an attack move
void restoreMood(Object *obj, TacticalStep *step);
Bool pickTacticalSpot(const Object *obj, const Coord3D *from, const Coord3D *awayFrom, Real distance,
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
index 2c3fc7e53..4372880b2 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
@@ -1131,6 +1131,62 @@ Real aiRetreatRatio( Real myHealth, Real myPower, Real enemyHealth, Real enemyPo
return (ratio > NOT_A_FIGHT) ? NOT_A_FIGHT : ratio;
}
+static Bool gunsReach( Real x, Real y, const Real *guns, Int gunCount )
+{
+ for( Int g = 0; g < gunCount; ++g )
+ {
+ const Real gx = x - guns[ 3 * g ];
+ const Real gy = y - guns[ 3 * g + 1 ];
+ if( gx * gx + gy * gy <= guns[ 3 * g + 2 ] * guns[ 3 * g + 2 ] )
+ return TRUE;
+ }
+ return FALSE;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Where a force that is losing stops falling back: walking from (fromX, fromY) towards home in
+ * steps, the first spot no gun in guns[] reaches with one more step of clear ground past it, and
+ * that next step is where it stands, so the edge of a reach is never the place. guns holds x, y
+ * and reach for each of gunCount guns. FALSE, with home in the answer, when the line never leaves
+ * their reach before it gets home. */
+//-------------------------------------------------------------------------------------------------
+Bool aiRetreatFallbackPoint( Real fromX, Real fromY, Real homeX, Real homeY, Real step,
+ const Real *guns, Int gunCount, Real *outX, Real *outY )
+{
+ *outX = homeX;
+ *outY = homeY;
+ const Real dx = homeX - fromX;
+ const Real dy = homeY - fromY;
+ const Real homeDist = (Real)sqrt( dx * dx + dy * dy );
+ for( Real along = step; along + step < homeDist; along += step )
+ {
+ const Real x = fromX + dx * (along + step) / homeDist;
+ const Real y = fromY + dy * (along + step) / homeDist;
+ if( gunsReach( fromX + dx * along / homeDist, fromY + dy * along / homeDist, guns, gunCount ) ||
+ gunsReach( x, y, guns, gunCount ) )
+ continue;
+ *outX = x;
+ *outY = y;
+ return TRUE;
+ }
+ return FALSE;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** What a force that fell back does next. It holds until it has stopped and minHold has passed;
+ * then it goes back the moment the fight it left no longer reads as lost (ratioThere at or over
+ * resumeRatio, which an empty fight always is), and gives up and goes home at maxHold. */
+//-------------------------------------------------------------------------------------------------
+AIFallbackDecision aiRetreatHoldDecision( Bool arrived, UnsignedInt heldFrames, Real ratioThere, Real resumeRatio,
+ UnsignedInt minHold, UnsignedInt maxHold )
+{
+ if( heldFrames < minHold || (!arrived && heldFrames < maxHold) )
+ return AIFALLBACK_HOLD;
+ if( ratioThere >= resumeRatio )
+ return AIFALLBACK_RESUME;
+ return heldFrames >= maxHold ? AIFALLBACK_GO_HOME : AIFALLBACK_HOLD;
+}
+
//-------------------------------------------------------------------------------------------------
/** What a spot is still worth to aim a superweapon at, after one already aimed near it.
*
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 129cb71b3..7b5436bc1 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -6864,7 +6864,7 @@ void AIPlayer::sendIdleAttackTeams( void )
{
Object *obj = m.cur();
if( obj->isEffectivelyDead() || obj->getAI() == NULL || obj->isContained() || obj->isKindOf( KINDOF_IMMOBILE ) ||
- isOutOnOrders( obj ) )
+ isOutOnOrders( obj ) || isFallingBack( obj->getID() ) )
continue;
++members;
const StateID state = obj->getAI()->getCurrentStateID();
@@ -6936,8 +6936,9 @@ void AIPlayer::sendIdleUnitsHunting( void )
for( DLINK_ITERATOR<Object> m = team->iterate_TeamMemberList(); !m.done(); m.advance() )
{
Object *obj = m.cur();
+ // one holding after a lost fight is idle on purpose; doRetreats sends it back when it is safe
if( obj->isEffectivelyDead() || obj->getAI() == NULL || obj->isContained() || obj->isKindOf( KINDOF_IMMOBILE ) ||
- !leavesToFinish( obj ) )
+ !leavesToFinish( obj ) || isFallingBack( obj->getID() ) )
continue;
const StateID state = obj->getAI()->getCurrentStateID();
const Bool atHome = sqr( obj->getPosition()->x - m_baseCenter.x ) + sqr( obj->getPosition()->y - m_baseCenter.y ) <= reachSqr;
@@ -7001,6 +7002,8 @@ void AIPlayer::sendWaveThroughTunnels( AIGroup *wave, const Coord3D *center, Way
* at the back as part of the same exchange. */
static const Real RETREAT_ENGAGEMENT_RADIUS = 300.0f;
+static Real groundAttackRange( const Object *obj );
+
/** 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. */
@@ -7106,59 +7109,19 @@ void AIPlayer::doRetreats( void )
centre.y /= count;
centre.z = TheTerrainLogic->getGroundHeight( centre.x, centre.y );
+ // the members holding back from an earlier fight: back to it, or home
+ doFallback( team );
+
// 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.
- //
- // Not this team against everything of theirs. An AI team is one to three units, and the
- // first cut of this compared one such team with every enemy within three hundred feet -
- // so a team of two tanks read a battle it was part of as 2,600 against 29,400, decided
- // it was losing by a hundred to one and walked home. Every team did, every few seconds,
- // for the whole match: twenty measured matches ended with zero kills on both sides.
- //
Real myHealth = 0.0f, myPower = 0.0f;
Real enemyHealth = 0.0f, enemyPower = 0.0f;
- {
- PartitionFilterAlive filterAlive;
- PartitionFilterOnMap filterOnMap;
- PartitionFilter *filters[] = { &filterAlive, &filterOnMap, 0 };
-
- MemoryPoolObjectHolder hold;
- SimpleObjectIterator *nearby = ThePartitionManager->iterateObjectsInRange(
- &centre, 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 the field battle. Base defences shoot, but they are what an attack goes
- // *through* - counting them makes every approach to a defended base read as a
- // lost fight, and the AI never attacks anything again. Picking a way in past
- // them is the influence map's job (B4), not the retreat's.
- //
- if( e->isKindOf( KINDOF_STRUCTURE ) || e->isKindOf( KINDOF_IMMOBILE ) )
- continue;
-
- if( e->getControllingPlayer() == m_player )
- {
- addToForce( e, &myHealth, &myPower );
- }
- else if( m_player->getRelationship( e->getTeam() ) == ENEMIES )
- {
- // 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() ) )
- addToForce( e, &enemyHealth, &enemyPower );
- }
- }
- }
+ std::vector<Real> enemyGuns;
+ measureFight( &centre, NULL, &myHealth, &myPower, &enemyHealth, &enemyPower, &enemyGuns );
if( enemyPower <= 0.0f )
continue; // not in a fight
@@ -7168,18 +7131,32 @@ void AIPlayer::doRetreats( void )
continue; // holding, or winning
//
- // Losing. The whole team goes home if this rung knows how; otherwise the members that
+ // Losing. The whole team falls back 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. Through the tunnels, when there is one
- // near the fight and one near home.
+ // fight the team as a whole is still winning.
//
+ // Back to the first ground on the way home that none of the guns in this fight reach, not
+ // to the base. Sent home, a team that broke off a fight at the enemy's gate walked the
+ // whole map back, healed nothing (nothing at home repairs a unit the walk delivers to the
+ // base centre), and then stood there until a script or the next wave called it up. From
+ // the safe spot it goes back once the fight turns (doFallback). Only when there is no
+ // such ground short of home does it go home, through the tunnels when there is one near the
+ // fight and one near home.
+ //
+ Coord3D fallback = m_baseCenter;
+ const Bool shortOfHome = !measuringWithoutTactics() &&
+ aiRetreatFallbackPoint( centre.x, centre.y, m_baseCenter.x, m_baseCenter.y, INFLUENCE_CELL_SIZE,
+ enemyGuns.empty() ? NULL : &enemyGuns[ 0 ], (Int)enemyGuns.size() / 3, &fallback.x, &fallback.y );
+ if( shortOfHome )
+ fallback.z = TheTerrainLogic->getGroundHeight( fallback.x, fallback.y );
const Real homeX = m_baseCenter.x - centre.x;
const Real homeY = m_baseCenter.y - centre.y;
- Object *homeTunnel = m_player->getTunnelSystem()->findTunnelShortcut( &centre, &m_baseCenter,
+ Object *homeTunnel = shortOfHome ? NULL : m_player->getTunnelSystem()->findTunnelShortcut( &centre, &m_baseCenter,
(Real)sqrt( homeX * homeX + homeY * homeY ) );
if( homeTunnel )
DEBUG_LOG(("AI RETREAT frame %d player %d falls back through tunnel %d\n", TheGameLogic->getFrame(),
m_player->getPlayerIndex(), homeTunnel->getID()));
+ Int ordered = 0;
for( DLINK_ITERATOR<Object> objIter = team->iterate_TeamMemberList(); !objIter.done(); objIter.advance() )
{
Object *obj = objIter.cur();
@@ -7206,19 +7183,181 @@ void AIPlayer::doRetreats( void )
const TacticalStep *kiting = findTacticalStep( obj->getID() );
if( kiting && kiting->lastKiteFrame != 0 && TheGameLogic->getFrame() - kiting->lastKiteFrame < KITE_KEEPS_FIGHT_FRAMES )
continue;
+ ++ordered;
if( homeTunnel != NULL && obj->getAI()->takeTunnelTrip( homeTunnel, &m_baseCenter, TUNNEL_TRIP_MOVE, CMD_FROM_AI ) )
leaveTacticsAlone( obj->getID() );
else if( measuringWithoutTactics() )
obj->getAI()->aiMoveToPosition( &m_baseCenter, CMD_FROM_AI );
else
{
- // the walk home taken calm and as an order, on every rung: a CMD_FROM_AI move to a unit
+ // the walk back taken calm and as an order, on every rung: a CMD_FROM_AI move to a unit
// that is fighting is laid under its attack, and an aggressive mood turns the walk back
// into a fight, so the retreat never happened
leaveTacticsAlone( obj->getID() );
- stepCalmly( obj, tacticalStepFor( obj->getID() ), &m_baseCenter );
+ TacticalStep *step = tacticalStepFor( obj->getID() );
+ step->fallingBack = shortOfHome;
+ step->fallbackFrom = centre;
+ step->fallbackFrame = TheGameLogic->getFrame();
+ stepCalmly( obj, step, &fallback );
}
}
+ if( ordered > 0 )
+ DEBUG_LOG(("AI RETREAT frame %d player %d '%s' pulls %d units out at %.2f, %s (%.0f,%.0f)\n", TheGameLogic->getFrame(),
+ m_player->getPlayerIndex(), team->getName().str(), ordered, ratio, shortOfHome ? "falls back to" : "goes home to",
+ fallback.x, fallback.y));
+ }
+ }
+}
+
+/** A unit pulled out of a lost fight to a safe spot, and not yet sent back or home. */
+Bool AIPlayer::isFallingBack( ObjectID unit )
+{
+ const TacticalStep *step = findTacticalStep( unit );
+ return step != NULL && step->fallingBack;
+}
+
+//----------------------------------------------------------------------------------------------------------
+/** Both sides of the exchange around centre, measured the same way: everything of ours in the fight
+ * against everything of theirs in it. With a team, all of that team counts on our side wherever it
+ * stands, which is how a team holding at its safe spot weighs the fight it would go back to. With
+ * enemyGuns, every known enemy gun in reach of the ground (base defences too) is added as x, y, reach.
+ *
+ * Not one team against everything of theirs. An AI team is one to three units, and the first cut of
+ * the retreat compared one such team with every enemy within three hundred feet - so a team of two
+ * tanks read a battle it was part of as 2,600 against 29,400, decided it was losing by a hundred to
+ * one and walked home. Every team did, every few seconds, for the whole match: twenty measured
+ * matches ended with zero kills on both sides. */
+//----------------------------------------------------------------------------------------------------------
+void AIPlayer::measureFight( const Coord3D *centre, Team *team, Real *myHealth, Real *myPower,
+ Real *enemyHealth, Real *enemyPower, std::vector<Real> *enemyGuns )
+{
+ PartitionFilterAlive filterAlive;
+ PartitionFilterOnMap filterOnMap;
+ PartitionFilter *filters[] = { &filterAlive, &filterOnMap, 0 };
+
+ MemoryPoolObjectHolder hold;
+ SimpleObjectIterator *nearby = ThePartitionManager->iterateObjectsInRange(
+ centre, 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 the field battle. Base defences shoot, but they are what an attack goes *through* -
+ // counting them makes every approach to a defended base read as a lost fight, and the AI never
+ // attacks anything again. Picking a way in past them is the influence map's job (B4), not the
+ // retreat's. Where it stops falling back is another matter: a tower's reach is no place to wait.
+ //
+ const Bool fixed = e->isKindOf( KINDOF_STRUCTURE ) || e->isKindOf( KINDOF_IMMOBILE );
+
+ if( e->getControllingPlayer() == m_player )
+ {
+ if( !fixed && (team == NULL || e->getTeam() != team) )
+ addToForce( e, myHealth, myPower );
+ }
+ else if( m_player->getRelationship( e->getTeam() ) == ENEMIES )
+ {
+ // 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;
+ if( !fixed )
+ addToForce( e, enemyHealth, enemyPower );
+ const Real reach = enemyGuns ? groundAttackRange( e ) : 0.0f;
+ if( reach > 0.0f )
+ {
+ enemyGuns->push_back( e->getPosition()->x );
+ enemyGuns->push_back( e->getPosition()->y );
+ enemyGuns->push_back( reach );
+ }
+ }
+ }
+
+ if( team == NULL )
+ return;
+ for( DLINK_ITERATOR<Object> objIter = team->iterate_TeamMemberList(); !objIter.done(); objIter.advance() )
+ {
+ Object *obj = objIter.cur();
+ if( !obj->isKindOf( KINDOF_PROJECTILE ) && !obj->isKindOf( KINDOF_STRUCTURE ) && !obj->isKindOf( KINDOF_IMMOBILE ) )
+ addToForce( obj, myHealth, myPower );
+ }
+}
+
+/** How long a team that fell back holds before it may go back, at the least and at the most; and how
+ * well the fight it left has to read before it does, which is even. Breaking off is decided at the
+ * rung's own ratio, well under even, so a team does not turn round on the same reading it ran from. */
+static const UnsignedInt FALLBACK_MIN_HOLD_FRAMES = 5 * LOGICFRAMES_PER_SECOND;
+static const UnsignedInt FALLBACK_MAX_HOLD_FRAMES = 30 * LOGICFRAMES_PER_SECOND;
+static const Real FALLBACK_RESUME_RATIO = 1.0f;
+
+//----------------------------------------------------------------------------------------------------------
+/** The members of this team holding at a safe spot after a lost fight. Once they have stopped, they go
+ * back to the fight they left when it no longer reads as lost - the enemy gone or dead, or enough of
+ * ours there now - attack-moving to it, which picks up the fight or whatever is beyond it. A fight
+ * that still reads as lost after FALLBACK_MAX_HOLD_FRAMES sends them home, where the next wave takes
+ * them along. */
+//----------------------------------------------------------------------------------------------------------
+void AIPlayer::doFallback( Team *team )
+{
+ const UnsignedInt now = TheGameLogic->getFrame();
+ Bool holding = FALSE;
+ Bool arrived = TRUE;
+ Coord3D from;
+ UnsignedInt since = now;
+ for( DLINK_ITERATOR<Object> objIter = team->iterate_TeamMemberList(); !objIter.done(); objIter.advance() )
+ {
+ Object *obj = objIter.cur();
+ const TacticalStep *step = findTacticalStep( obj->getID() );
+ if( step == NULL || !step->fallingBack || obj->isEffectivelyDead() )
+ continue;
+ if( !holding || step->fallbackFrame > since )
+ {
+ from = step->fallbackFrom; // the latest fight any of them left
+ since = step->fallbackFrame;
+ }
+ holding = TRUE;
+ if( obj->getAI() && obj->getAI()->isMoving() )
+ arrived = FALSE;
+ }
+ if( !holding )
+ return;
+
+ Real myHealth = 0.0f, myPower = 0.0f;
+ Real enemyHealth = 0.0f, enemyPower = 0.0f;
+ measureFight( &from, team, &myHealth, &myPower, &enemyHealth, &enemyPower, NULL );
+ const Real ratio = aiRetreatRatio( myHealth, myPower, enemyHealth, enemyPower );
+ const AIFallbackDecision what = aiRetreatHoldDecision( arrived, now - since, ratio, FALLBACK_RESUME_RATIO,
+ FALLBACK_MIN_HOLD_FRAMES, FALLBACK_MAX_HOLD_FRAMES );
+ if( what == AIFALLBACK_HOLD )
+ return;
+
+ DEBUG_LOG(("AI RETREAT frame %d player %d '%s' %s after %d s, the fight at (%.0f,%.0f) reads %.2f\n", now,
+ m_player->getPlayerIndex(), team->getName().str(), what == AIFALLBACK_RESUME ? "goes back" : "gives up and goes home",
+ (now - since) / LOGICFRAMES_PER_SECOND, from.x, from.y, ratio));
+ for( DLINK_ITERATOR<Object> objIter = team->iterate_TeamMemberList(); !objIter.done(); objIter.advance() )
+ {
+ Object *obj = objIter.cur();
+ TacticalStep *step = findTacticalStep( obj->getID() );
+ if( step == NULL || !step->fallingBack )
+ continue;
+ step->fallingBack = FALSE;
+ if( obj->isEffectivelyDead() || obj->getAI() == NULL )
+ continue;
+ // One that is already on its way somewhere was given that by its script, the home guard or a
+ // step of its own, and carries on with it. One with no gun has no fight to go back to: a
+ // Dozer pulled out of a fight was walked back into it.
+ if( obj->getAI()->isMoving() || (what == AIFALLBACK_RESUME && aiCombatPower( obj ) <= 0.0f) )
+ restoreMood( obj, step );
+ else if( what == AIFALLBACK_RESUME )
+ {
+ restoreMood( obj, step );
+ obj->getAI()->aiAttackMoveToPosition( &from, NO_MAX_SHOTS_LIMIT, CMD_FROM_AI );
+ }
+ else
+ {
+ leaveTacticsAlone( obj->getID() );
+ stepCalmly( obj, step, &m_baseCenter );
}
}
}
@@ -7370,6 +7509,9 @@ AIPlayer::TacticalStep *AIPlayer::tacticalStepFor( ObjectID unit )
step.rejoin = FALSE;
step.savedAttitude = AI_INVALID;
step.lastKiteFrame = 0;
+ step.fallingBack = FALSE;
+ step.fallbackFrom.zero();
+ step.fallbackFrame = 0;
m_tactics.push_back( step );
return &m_tactics.back();
}
@@ -7522,8 +7664,10 @@ void AIPlayer::doTactics( void )
Object *unit = TheGameLogic->findObjectByID( m_tactics[ i ].unit );
const TacticalStep &row = m_tactics[ i ];
// with the tactics running a row goes when the unit has not been looked at for a while; without
- // them the only rows are walks home from a retreat, which end when the walk does
+ // them the only rows are walks home from a retreat, which end when the walk does. One holding
+ // after a retreat is doFallback's until it sends it back or home.
const Bool done = (unit == NULL || unit->isEffectivelyDead()) ? TRUE :
+ row.fallingBack ? FALSE :
tactics ? now - row.lastSeenFrame > TACTICAL_ROW_EXPIRY_FRAMES :
now >= row.leaveAloneUntil && (unit->getAI() == NULL || !unit->getAI()->isMoving() || now >= row.leaveAloneUntil + WALK_HOME_MAX_FRAMES);
if( done )
@@ -7675,8 +7819,9 @@ void AIPlayer::tacticsFor( Object *obj )
if( now < step->leaveAloneUntil )
return;
// home from a lost fight: its own mood again once the walk is over, and not before, or the mood turns
- // what is left of the walk into an attack move
- if( step->resumeFrame == 0 && (!ai->isMoving() || now >= step->leaveAloneUntil + WALK_HOME_MAX_FRAMES) )
+ // what is left of the walk into an attack move. One holding at a safe spot stays calm until it is sent
+ // back, or its mood walks it into the fight it was pulled out of.
+ if( step->resumeFrame == 0 && !step->fallingBack && (!ai->isMoving() || now >= step->leaveAloneUntil + WALK_HOME_MAX_FRAMES) )
restoreMood( obj, step );
// a step under way ends when it gets there or runs out of time, and the unit goes back to work:
@@ -9311,7 +9456,7 @@ void AIPlayer::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 12; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker 9: tactical steps 10: the ferry and dropped riders 11: the outward placement ring 12: the pressure level
+ XferVersion currentVersion = 13; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker 9: tactical steps 10: the ferry and dropped riders 11: the outward placement ring 12: the pressure level 13: falling back
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -9550,6 +9695,19 @@ void AIPlayer::xfer( Xfer *xfer )
xfer->xferBool( &step.rejoin );
xfer->xferInt( &step.savedAttitude );
xfer->xferUnsignedInt( &step.lastKiteFrame );
+ // a unit holding after a lost fight, so a loaded game still sends it back
+ if( version >= 13 )
+ {
+ xfer->xferBool( &step.fallingBack );
+ xfer->xferCoord3D( &step.fallbackFrom );
+ xfer->xferUnsignedInt( &step.fallbackFrame );
+ }
+ else
+ {
+ step.fallingBack = FALSE;
+ step.fallbackFrom.zero();
+ step.fallbackFrame = 0;
+ }
}
}
// the capturer's helicopter, and the riders a helicopter is putting down at a fight
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index eb556fa0b..388d129bb 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -10104,6 +10104,66 @@ TEST(the_retreat_never_orders_an_aircraft_home)
}
+/** AI.cpp: a team that loses a fight stops at the first ground on its way home that none of the
+ fight's guns reach, a step past it, rather than walking the whole map back to its base. */
+TEST(a_losing_team_falls_back_out_of_reach_not_home)
+{
+ Real x = 0.0f, y = 0.0f;
+
+ // home is 2000 east; one gun at the fight reaching 150: covered up to 150, first clear sample at
+ // 180, one 60 step past it
+ const Real oneGun[] = { 0.0f, 0.0f, 150.0f };
+ CHECK( aiRetreatFallbackPoint( 0.0f, 0.0f, 2000.0f, 0.0f, 60.0f, oneGun, 1, &x, &y ) );
+ CHECK_NEAR( 240.0f, x, 0.01f );
+ CHECK_NEAR( 0.0f, y, 0.01f );
+
+ // a second gun further down the road home (200..600 covered) pushes the stop past its reach too:
+ // the gap at 180 is clear, but the step past it is not, and a stop inside a reach is no stop
+ const Real twoGuns[] = { 0.0f, 0.0f, 150.0f, 400.0f, 0.0f, 200.0f };
+ CHECK( aiRetreatFallbackPoint( 0.0f, 0.0f, 2000.0f, 0.0f, 60.0f, twoGuns, 2, &x, &y ) );
+ CHECK_NEAR( 720.0f, x, 0.01f );
+
+ // any direction: home to the south-west
+ CHECK( aiRetreatFallbackPoint( 1000.0f, 1000.0f, 0.0f, 1000.0f, 60.0f, NULL, 0, &x, &y ) );
+ CHECK_NEAR( 880.0f, x, 0.01f );
+ CHECK_NEAR( 1000.0f, y, 0.01f );
+
+ // guns covering the whole road: home, and FALSE says so
+ const Real bigGun[] = { 0.0f, 0.0f, 5000.0f };
+ CHECK( !aiRetreatFallbackPoint( 0.0f, 0.0f, 2000.0f, 0.0f, 60.0f, bigGun, 1, &x, &y ) );
+ CHECK_NEAR( 2000.0f, x, 0.01f );
+
+ // a fight on the doorstep: no room short of home either
+ CHECK( !aiRetreatFallbackPoint( 0.0f, 0.0f, 100.0f, 0.0f, 60.0f, NULL, 0, &x, &y ) );
+ CHECK_NEAR( 100.0f, x, 0.01f );
+}
+
+
+/** AI.cpp: what a team holding at its safe spot does next. */
+TEST(a_fallen_back_team_goes_back_once_the_fight_turns)
+{
+ const UnsignedInt MIN = 150, MAX = 900;
+
+ // too soon, or still walking: hold, however the fight reads
+ CHECK_EQ( (Int)AIFALLBACK_HOLD, (Int)aiRetreatHoldDecision( TRUE, 100, 1000.0f, 1.0f, MIN, MAX ) );
+ CHECK_EQ( (Int)AIFALLBACK_HOLD, (Int)aiRetreatHoldDecision( FALSE, 400, 1000.0f, 1.0f, MIN, MAX ) );
+
+ // stopped, and the fight it left is empty or won: back to it
+ CHECK_EQ( (Int)AIFALLBACK_RESUME, (Int)aiRetreatHoldDecision( TRUE, 200, 1000.0f, 1.0f, MIN, MAX ) );
+ CHECK_EQ( (Int)AIFALLBACK_RESUME, (Int)aiRetreatHoldDecision( TRUE, 200, 1.2f, 1.0f, MIN, MAX ) );
+
+ // still lost, or only as good as the reading it ran from: keep holding, not a yo-yo
+ CHECK_EQ( (Int)AIFALLBACK_HOLD, (Int)aiRetreatHoldDecision( TRUE, 200, 0.4f, 1.0f, MIN, MAX ) );
+ CHECK_EQ( (Int)AIFALLBACK_HOLD, (Int)aiRetreatHoldDecision( TRUE, 200, 0.9f, 1.0f, MIN, MAX ) );
+
+ // still lost at the limit: home, where the next wave picks it up
+ CHECK_EQ( (Int)AIFALLBACK_GO_HOME, (Int)aiRetreatHoldDecision( TRUE, MAX, 0.4f, 1.0f, MIN, MAX ) );
+ // ... and a team stuck walking is decided at the limit too, not held forever
+ CHECK_EQ( (Int)AIFALLBACK_GO_HOME, (Int)aiRetreatHoldDecision( FALSE, MAX, 0.4f, 1.0f, MIN, MAX ) );
+ CHECK_EQ( (Int)AIFALLBACK_RESUME, (Int)aiRetreatHoldDecision( FALSE, MAX, 1000.0f, 1.0f, MIN, MAX ) );
+}
+
+
/** The second half of scouting: once every enemy has been placed there is nothing left to search for,
and the job becomes keeping the picture of their bases current. That is the stalest one per step
walked, recomputed at every arrival - which is what stopped the scout walking a blind lap of the