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 chooses which enemy to fight on more than distance
Olcay Seyganc6045da7f84b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d9ed8e41a..aadfbaad2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,10 +1,10 @@-# Command and Conquer: Generals: Zero Hour: Reborn+# Command and Conquer: Generals: Zero Hour: RebornEA released the 2003 source for preservation. It did not compile, did not run, and nobody had touchedthe bugs inside it in twenty-two years. This build compiles, runs and plays.**119 changes. ~580 engine source files ported. 14 automated test suites. Around 60 original bugs-found and fixed — EA's own, not port damage.**+found and fixed — EA's own, not port damage.**---@@ -29,6 +29,10 @@ 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 picks its fights+- Which enemy it goes after was the nearest one and nothing else, plus a rule with its sign the wrong way round: an opponent who had lost his units or his production had his distance treated as half the map, so the computer ignored the one it was about to beat. That is what dragged matches out.+- It now weighs distance, whether the target is crippled - an opportunity, not a distraction - and how much of what it can see that player is worth. Only a genuinely finished enemy is skipped.+- It still refuses to gang up with another computer opponent on one victim, and still gently prefers whoever is already shooting at it.## 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.@@ -148,10 +152,10 @@ found and fixed — EA's own, not port damage.**- The building on your cursor shows where its units will come out.- An ordered building stands as a see-through plan until a worker starts it.- Click a plan, or press Stop, to cancel it and take the money back.-- Cancelling a plan is silent — nothing was built, so nothing explodes.+- Cancelling a plan is silent — nothing was built, so nothing explodes.- Ground your units have walked stays buildable after they leave it.- A plan opens no fog of its own, and your opponent never sees it.-- Your units walk straight over a plan — nothing solid is there until the builder starts work.+- Your units walk straight over a plan — nothing solid is there until the builder starts work.- The plan turns solid the instant the first work goes in, so no building goes up inside its own ghost.- The builder starts work from where it reaches the site instead of shuffling into place first.- Dozers and workers walk through anything still going up, so they never shut themselves in behind@@ -346,7 +350,7 @@ found and fixed — EA's own, not port damage.**- Audio is real, through the audio library the retail game ships with.- The videos play: the intro, the sizzle reel, the mission briefings, the general portraits.- About 5,600 graphics calls are translated to a modern path, none of them touched.-- No disc, no registry keys, no retail installer — a normal install works.+- No disc, no registry keys, no retail installer — a normal install works.- The 1.04 patch content is reachable again.---@@ -360,7 +364,7 @@ found and fixed — EA's own, not port damage.**- Its sight is yours from the first frame, and clicking any of it hands you the base itself.- Shift-Ctrl-T does the same to any opponent, a computer one included, and walks around the table.- Headless, a 23-minute skirmish plays out in 38 seconds, identically every run.-- It plays itself over a network too — two copies, one real connection.+- It plays itself over a network too — two copies, one real connection.- That found every multiplayer replay falsely accusing itself of desync since 2003.- Every fix was proved by putting the bug back and watching the test fail.- No debugger here: a crash symboliser, a sampling profiler, probes in live matches.@@ -378,7 +382,7 @@ found and fixed — EA's own, not port damage.**## Not there yet-- Random maps generate and can be played — a number picks the map and the match starts on it —+- Random maps generate and can be played — a number picks the map and the match starts on it —but there is still no menu entry and no reroll button.- Online and LAN play are untested.- You need to own the game; no game data ships here.diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.hindex b27b9569e..d5bd423c4 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h@@ -253,6 +253,21 @@ Real aiRetreatRatio( Real myHealth, Real myPower, Real enemyHealth, Real enemyPoBool aiShouldMass( Real waitingThreat, Real enemyVisibleThreat, Real massFraction,Bool timeExpired, Bool baseUnderAttack );+/** How attractive an enemy player is to go after, as a cost - lower is better, and it is a squared+ * distance with the other terms folded into it so the units stay comparable.+ *+ * EA's version was distance and nothing else, plus one rule that had the sign wrong: an enemy+ * who had lost his units or his production had his distance set to half the map, which reads as+ * "ignore the crippled one". Finishing off the weak one is usually the right move, and refusing+ * to is what drags matches out.+ *+ * Sins of a Solar Empire has the identical bug, in its own community's words: its AI "is much+ * more likely to send its fleet to a well-defended planet roughly 5 map units away than an+ * ill-defended planet 25 map units away". Two independently written RTS AIs converging on the+ * same mistake is decent evidence that distance-dominated target selection is the wrong default. */+Real aiEnemyCost( Real distSqr, Bool crippled, Bool alreadyTargetedByAnotherAI,+ Bool isAttackingMe, Real economyShare );+class TAiData : public Snapshot{public:diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.hindex 454786e05..258088455 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h@@ -267,6 +267,7 @@ protected:virtual Object *findDozer(const Coord3D *pos);virtual void queueDozer(void);void computeEnemyComposition( AIEnemyComposition *out ); ///< what this AI can see the enemy fielding+ Real visibleEstateValue( Int playerNdx ); ///< what this AI can see that player is worth, in build costvirtual Bool selectTeamToBuild( void ); ///< determine the next team to buildvirtual Bool selectTeamToReinforce( Int minPriority ); ///< determine the next team to reinforcevirtual Bool startTraining( WorkOrder *order, Bool busyOK, AsciiString teamName); ///< find a production building that can handle the order, and start buildingdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cppindex cb93389fb..8faa08df4 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp@@ -1076,6 +1076,31 @@ Bool aiShouldMass( Real waitingThreat, Real enemyVisibleThreat, Real massFractioreturn waitingThreat < massFraction * enemyVisibleThreat;}+//-------------------------------------------------------------------------------------------------+Real aiEnemyCost( Real distSqr, Bool crippled, Bool alreadyTargetedByAnotherAI,+ Bool isAttackingMe, Real economyShare )+{+ Real cost = distSqr;++ // A crippled enemy is an opportunity, not a distraction. EA multiplied his distance up; this+ // pulls it down. Only a genuinely finished one is skipped, and that is the caller's test.+ if( crippled )+ cost *= 0.4f;++ // The bigger his economy, the more of the match is decided by hitting him.+ if( economyShare < 0.0f ) economyShare = 0.0f;+ if( economyShare > 1.0f ) economyShare = 1.0f;+ cost *= (1.0f - 0.3f * economyShare);++ // EA's two flat terms, kept: do not gang up, and gently prefer whoever is already on me.+ if( alreadyTargetedByAnotherAI )+ cost += 500.0f * 500.0f;+ if( isAttackingMe )+ cost -= 25.0f * 25.0f;++ return (cost < 0.0f) ? 0.0f : cost;+}+Real aiCounterScore( const AIEnemyComposition &enemy, const AITeamCapability &team ){Real score = 0.0f;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cppindex 22279921f..6fe397dc3 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp@@ -1899,6 +1899,41 @@ void AIPlayer::computeEnemyComposition( AIEnemyComposition *out )out->m_stealth = stealth / total;}+//-------------------------------------------------------------------------------------------------+/** What this AI can see another player is worth, priced in build cost - his army and his base.+ * Fog-aware, so an enemy nobody has scouted is worth nothing to attack rather than everything. */+//-------------------------------------------------------------------------------------------------+Real AIPlayer::visibleEstateValue( Int playerNdx )+{+ Player *p = ThePlayerList->getNthPlayer( playerNdx );+ if( p == NULL )+ return 0.0f;++ const Int me = m_player->getPlayerIndex();+ Real value = 0.0f;++ for( Player::PlayerTeamList::const_iterator t = p->getPlayerTeams()->begin();+ t != p->getPlayerTeams()->end(); ++t )+ {+ for( DLINK_ITERATOR<Team> iter = (*t)->iterate_TeamInstanceList(); !iter.done(); iter.advance() )+ {+ Team *team = iter.cur();+ if( team == NULL )+ continue;+ for( DLINK_ITERATOR<Object> objIter = team->iterate_TeamMemberList(); !objIter.done(); objIter.advance() )+ {+ Object *obj = objIter.cur();+ if( obj == NULL || obj->isEffectivelyDead() || obj->isKindOf( KINDOF_PROJECTILE ) )+ continue;+ if( !observerKnowsAbout( obj, me ) )+ continue;+ value += INT_TO_REAL( obj->getTemplate()->calcCostToBuild( p ) );+ }+ }+ }+ return value;+}+Bool AIPlayer::selectTeamToBuild( void ){diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cppindex e957d8449..f7edc1309 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp@@ -486,7 +486,20 @@ void AISkirmishPlayer::acquireEnemy(void)if (!inBadShape) return;}- // look for the closest enemy.+ //+ // How much of what this AI can see belongs to each candidate, so a fat enemy outweighs a thin+ // one at the same distance. Gathered first because each player's share is of the total.+ //+ Real estate[ MAX_PLAYER_COUNT ];+ Real estateTotal = 0.0f;+ {+ for (Int e = 0; e < ThePlayerList->getPlayerCount() && e < MAX_PLAYER_COUNT; e++) {+ estate[e] = visibleEstateValue(e);+ estateTotal += estate[e];+ }+ }++ // look for the best enemy to go after.Int i;for (i=0; i<ThePlayerList->getPlayerCount(); i++) {Player *curPlayer = ThePlayerList->getNthPlayer(i);@@ -503,27 +516,26 @@ void AISkirmishPlayer::acquireEnemy(void)enemyPos.y = bounds.lo.y + bounds.height()/2;Real curDistSqr = sqr(enemyPos.x-m_baseCenter.x) + sqr(enemyPos.y-m_baseCenter.y);- //Fudge for in bad shape. If an enemy is crippled, concentrate on the other ones.- if (inBadShape) {- curDistSqr = HUGE_DIST*HUGE_DIST*0.5f;- }- // See if other ai's are attacking this target.- // We don't want the ai's to gang up on one enemy.+ //+ // The two flags EA folded straight into the distance, gathered rather than applied:+ // aiEnemyCost decides what each is worth, and its test says what that is. The "in bad+ // shape" rule went with them, with its sign corrected - EA set a crippled enemy's+ // distance to half the map, which reads as "ignore the one you are about to beat".+ //+ Bool alreadyTargeted = FALSE;+ Bool attackingMe = FALSE;Int k;for (k=0; k<ThePlayerList->getPlayerCount(); k++) {if (k==i) continue; // don't count self.Player *somePlayer = ThePlayerList->getNthPlayer(k);- if (somePlayer->isSkirmishAIPlayer() && (somePlayer->getCurrentEnemy()==curPlayer)) {- // Some ai is already targeting this guy. Add a distance penalty.- curDistSqr += (500*500);- }- if (somePlayer->isSkirmishAIPlayer() && (somePlayer->getCurrentEnemy()==m_player)) {- // he is attacking me. So I will (gently) prefer to attack him.- curDistSqr -= (25*25);- if (curDistSqr<0) curDistSqr = 0;- }+ if (!somePlayer->isSkirmishAIPlayer()) continue;+ if (somePlayer->getCurrentEnemy()==curPlayer) alreadyTargeted = TRUE;+ if (somePlayer->getCurrentEnemy()==m_player) attackingMe = TRUE;}+ const Real share = (estateTotal > 0.0f && i < MAX_PLAYER_COUNT) ? (estate[i] / estateTotal) : 0.0f;+ curDistSqr = aiEnemyCost( curDistSqr, inBadShape, alreadyTargeted, attackingMe, share );+// Ai enemy - will take if we don't get a better offer.if (curDistSqr<bestDistanceSqr) {bestEnemy = curPlayer;diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex f2d203cfd..6f287242f 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -1,4 +1,4 @@-/*+/** GameEngine boot coverage: the Phase 3 checkpoint.** Linking gameengine.lib proves nothing on its own, so this brings up the@@ -5968,3 +5968,47 @@ TEST(massing_waits_for_a_force_but_never_waits_for_ever)CHECK( data.m_skill[ AISKILL_BRUTAL ].m_massBeforeAttacking );CHECK( data.m_skill[ AISKILL_MERCILESS ].m_massBeforeAttacking );}+++/** B2: which enemy to go after. EA's answer was the nearest one, plus a rule with the sign the+ wrong way round - an enemy who had lost his units or his production had his distance set to half+ the map, which is "ignore the one you are about to beat" and is what drags matches out. */+TEST(enemy_choice_prefers_the_weak_the_rich_and_the_near)+{+ const Real CLOSE_BY = 100.0f * 100.0f;+ const Real FAR_OFF = 300.0f * 300.0f;++ // all else equal, the near one+ CHECK( aiEnemyCost( CLOSE_BY, FALSE, FALSE, FALSE, 0.0f ) <+ aiEnemyCost( FAR_OFF, FALSE, FALSE, FALSE, 0.0f ) );++ // a crippled enemy is an opportunity, not a distraction: this is the sign EA had backwards+ CHECK( aiEnemyCost( CLOSE_BY, TRUE, FALSE, FALSE, 0.0f ) <+ aiEnemyCost( CLOSE_BY, FALSE, FALSE, FALSE, 0.0f ) );++ // and it is worth walking past a healthy neighbour to finish him+ CHECK( aiEnemyCost( FAR_OFF, TRUE, FALSE, FALSE, 0.0f ) <+ aiEnemyCost( FAR_OFF, FALSE, FALSE, FALSE, 0.0f ) );++ // the fatter of two enemies at the same distance is the one that decides the match+ CHECK( aiEnemyCost( CLOSE_BY, FALSE, FALSE, FALSE, 1.0f ) <+ aiEnemyCost( CLOSE_BY, FALSE, FALSE, FALSE, 0.0f ) );++ // EA's two flat terms are kept: do not gang up, and gently prefer whoever is already on you+ CHECK( aiEnemyCost( CLOSE_BY, FALSE, TRUE, FALSE, 0.0f ) >+ aiEnemyCost( CLOSE_BY, FALSE, FALSE, FALSE, 0.0f ) );+ CHECK( aiEnemyCost( CLOSE_BY, FALSE, FALSE, TRUE, 0.0f ) <+ aiEnemyCost( CLOSE_BY, FALSE, FALSE, FALSE, 0.0f ) );++ // the gang-up penalty is the big one: it should outweigh being shot at+ CHECK( aiEnemyCost( CLOSE_BY, FALSE, TRUE, TRUE, 0.0f ) >+ aiEnemyCost( CLOSE_BY, FALSE, FALSE, FALSE, 0.0f ) );++ // never negative, whatever the bonuses add up to+ CHECK( aiEnemyCost( 0.0f, TRUE, FALSE, TRUE, 1.0f ) >= 0.0f );++ // an economy share outside 0..1 cannot flip the cost the wrong way+ CHECK( aiEnemyCost( CLOSE_BY, FALSE, FALSE, FALSE, 5.0f ) > 0.0f );+ CHECK( aiEnemyCost( CLOSE_BY, FALSE, FALSE, FALSE, -5.0f ) <=+ aiEnemyCost( CLOSE_BY, FALSE, FALSE, FALSE, 0.0f ) );+}