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): make the skirmish AI spend, spread and attack together
Olcay Seygan840f80802e84
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4b26fda7f..4ab675c4a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -60,6 +60,10 @@ found and fixed — EA's own, not port damage.**## The computer spends its money- It no longer sits on a pile of cash. Past a level that depends on the difficulty, the more money it has the faster it builds - twice the pile, half the wait, and it stops at four times. It is spending sooner, not building faster: the rate itself is untouched.+- A full bank buys a bigger army. Late in a match the computer's plan allows one of each attack group, so once they were all on the map it only replaced its losses and banked the rest: a Hard USA sat on 117,000 on Twilight Flame. Now every 8,000 in the bank on Hard allows one more copy of each attack group, up to four of them.+- Hard builds past its plan. When every war factory, barracks or airfield it owns is busy it puts down another, beside its newest expansion so the army comes out nearer the fighting. When production keeps up it buys income instead, supply drop zones and black markets, as many as the bank pays for. China trains hackers from any idle barracks with no cap, and a hacker left standing still is put to work.+- Hard picks its road into your base. Of the three approaches it takes the one with the fewest guns it has seen along it, and keeps to the one its plan named until it has scouted something. Aiming at your money instead was tried first and walked it straight past your army.+- Hard sends its attack groups out together. A group too small to be a wave on its own waits on the near side of its base until about seven tanks' worth has gathered, or a minute and a half has passed, and then everything waiting leaves on one road at the pace of its slowest unit. A lone artillery piece or a single bomb truck used to drive across the map by itself, and nearly a third of Hard's units died with barely anyone of their own nearby.- It puts more harvesters on a supply centre with more piles around it, instead of the same three numbers everywhere.## The computer picks its fights@@ -81,7 +85,7 @@ found and fixed — EA's own, not port damage.**## 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.-- Now the priority is the start of a score, not the whole of it. What it can *see* you fielding weights the choice: air pushes anti-air up, stealth pushes detectors up, armour pushes anti-tank up. Its own data decides what counts as the answer to what, so a mod's units are read correctly too.+- Now the priority is the start of a score, not the whole of it. What it can *see* you fielding weights the choice, and the weighing is the game's own arithmetic: for every unit it could build and every unit it sees you with, how many shots each needs to kill the other through its armour, how long it waits between them, and what each one costs. A Crusader shell does a tenth of its damage to a rifleman, so your Rebels get Gattlings and your Overlords get Tank Hunters, not whatever the script listed first. Stealth still pushes detectors up. It reads the same unit data the game fights with, so a mod's units are weighed correctly too.- How much that weighs depends on the level, from nothing at all on Easy - which is what the game always did - to fully on Hard.- Anti-air was the computer's oldest hole. It is closed.diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.hindex 7aa27ee8a..5c21613af 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h@@ -526,6 +526,12 @@ public:/// Have the ai check for bridges.virtual Bool checkBridges(Object *unit, Waypoint *way);+ /// The skirmish approach this player's team should take: the script's choice, unless the AI reads the map.+ AsciiString chooseApproachLabel(const Coord3D *from, const AsciiString &requested, Int pathSuffix);++ /// TRUE when the AI parks this team to go out with the rest of its wave instead of on its own.+ Bool holdTeamForWave(Team *team, const AsciiString &approach, Int pathSuffix);+/// Get the center of the ai's base.virtual Bool getAiBaseCenter(Coord3D *pos);diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.hindex 8a32a0e21..001ccf467 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h@@ -48,6 +48,7 @@ class Path;class Pathfinder;class Player;class PolygonTrigger;+class ThingTemplate;class UpgradeTemplate;class WeaponTemplate;@@ -202,6 +203,7 @@ struct AIDifficultyProfileBool m_selfTriggeredExpansion;Bool m_defendExpansions;Int m_cashHoardThreshold; ///< above this, spend faster; 0 = never hurry+ Bool m_economyBuildings; ///< past the hoard, buy production and income the build list never had};//-------------------------------------------------------------------------------------------------@@ -220,19 +222,25 @@ struct AIEnemyCompositionm_totalThreat(0.0f) {}};+//-------------------------------------------------------------------------------------------------+/** One kind of enemy unit the AI can see, and how much of the visible army it makes up. */+//-------------------------------------------------------------------------------------------------+struct AIVisibleEnemy+{+ const ThingTemplate *m_template;+ Real m_weight; ///< summed combat power of every visible unit of this kind+ Real m_cost; ///< what one of them cost its owner+};+//-------------------------------------------------------------------------------------------------/** What a team can answer, read off the unit templates it is built from. *///-------------------------------------------------------------------------------------------------struct AITeamCapability{- Bool m_hitsAir;- Bool m_hitsGround;+ Real m_answer; ///< 0..1: how its units fare against the visible enemy army, money for moneyBool m_detectsStealth;- Bool m_prefersVehicles; ///< carries a weapon declared PreferredAgainst a vehicle: anti-tank- Bool m_prefersInfantry; ///< ... or against infantry: splash, flame, machine gun- AITeamCapability() : m_hitsAir(FALSE), m_hitsGround(FALSE), m_detectsStealth(FALSE),- m_prefersVehicles(FALSE), m_prefersInfantry(FALSE) {}+ AITeamCapability() : m_answer(0.0f), m_detectsStealth(FALSE) {}};/** How well this team answers what the enemy is fielding, 0 (answers none of it) to 1 (answers all@@ -240,6 +248,31 @@ 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 one weapon works on one target, in the numbers that decide how long the target lasts. */+//-------------------------------------------------------------------------------------------------+struct AIShotPattern+{+ Real m_damagePerShot; ///< after the target's armour; 0 cannot hurt it+ Real m_delayFrames; ///< between two shots of one clip+ Int m_clipSize; ///< 0 never reloads+ Real m_reloadFrames; ///< between the shot that empties a clip and the next one+ Real m_openingFrames; ///< once, before the first shot++ AIShotPattern() : m_damagePerShot(0.0f), m_delayFrames(0.0f), m_clipSize(0), m_reloadFrames(0.0f),+ m_openingFrames(0.0f) {}+};++const Real AI_CANNOT_KILL = -1.0f;++/** Frames until a weapon firing this pattern kills a target with this much health, or+ * AI_CANNOT_KILL when it does no damage to it. */+Real aiFramesToKill( Real targetHealth, const AIShotPattern &shots );++/** One pairing as 0..1, money for money: 0.5 an even trade, 1 when my side kills sixteen times+ * faster for its price (or cannot be hurt back), 0 when it cannot hurt the other side. */+Real aiMatchupScore( Real myFramesToKill, Real theirFramesToKill, Real myCost, Real theirCost );+/** 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@@ -320,6 +353,23 @@ Real aiEnemyCost( Real distSqr, Bool crippled, Bool alreadyTargetedByAnotherAI,* decision to spend faster, not a production multiplier, and D10 draws that line. */Int aiHoardAdjustedDelay( Int frames, Int money, Int hoardAt );+/** How many copies of one team a skirmish AI may field. The skirmish scripts cap the army by+ * their roster: late in a match every attack team left to build allows one copy, so the AI+ * replaces its losses and banks the rest. Every two thresholds of cash allows one more copy of+ * the teams the script already permits, up to three more. A team the data never allows stays+ * at zero, and no threshold leaves EA's limit alone. */+Int aiHoardAllowedTeamInstances( Int maxInstances, Int money, Int hoardAt );++/** Which approach a team takes: the lane with the least known enemy firepower along it. A negative+ * entry is a lane this map does not have. A tie, or nothing known anywhere, keeps the lane the+ * script asked for, so an AI that has not scouted plays exactly as the script wrote it. */+Int aiLeastDefendedLane( const Real *laneFirepower, Int laneCount, Int requestedLane );++/** Whether the attack teams parked at the staging point go now: when what is parked adds up to a wave,+ * or the oldest has waited long enough. The threshold is this AI's own force, never a fraction of+ * the enemy's, because two AIs each waiting to outnumber the other never move. */+Bool aiReleaseWave( Real heldPower, Real wavePower, UnsignedInt heldFrames, UnsignedInt maxHoldFrames );+class TAiData : public Snapshot{public:diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.hindex e6d78e581..4d1d12b31 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h@@ -217,6 +217,12 @@ public: // AIPlayer interface, may be overridden by AISkirmishPlayer. jba.virtual Bool isSkirmishAI(void) {return false;}virtual Player *getAiEnemy(void) {return NULL;} ///< Solo AI attacks based on scripting. Only skirmish auto-acquires an enemy at this point. jba.virtual Bool checkBridges(Object *unit, Waypoint *way) {return false;}+ /** Center, Flank or Backdoor: the approach with the least enemy firepower this AI knows about.+ * The script's own label when the rung does not read the map, or the label is not one of the three. */+ AsciiString chooseApproachLabel(const Coord3D *from, const AsciiString &requested, Int pathSuffix);+ /** C2: park an attack team that is not a wave on its own until the rest of the wave is in hand.+ * TRUE when it is parked, and the caller's own order must not go out. */+ Bool holdTeamForWave(Team *team, const AsciiString &approach, Int pathSuffix);virtual void repairStructure(ObjectID structure);virtual void selectSkillset(Int skillset);@@ -301,6 +307,14 @@ protected:void queueCapturer(void); ///< ... or build the cheapest thing that can take onevoid queueSupportUnit(const ThingTemplate *tmpl, const char *what); ///< one cheap unit, outside the team system+ /** Past the hoard, buy what the build list never had: another production building beside the last+ * expansion when every one of a kind is busy, another income building when production keeps up,+ * and money units (China's hackers) from any factory standing idle. */+ virtual void doEconomy(void);+ void buyMoneyUnit(void);+ Bool placeNear(const ThingTemplate *tmpl, const Coord3D *center, Real innerRadius); ///< a legal, safe spot on a ring round center, queued for a dozer+ Real knownFirepowerAlongPath(Waypoint *way); ///< what this AI has seen that can shoot, along an approach+virtual void doBaseBuilding(void);virtual void checkReadyTeams(void);virtual void checkQueuedTeams(void);@@ -308,7 +322,7 @@ protected:virtual void doUpgradesAndSkills(void);virtual Object *findDozer(const Coord3D *pos);virtual void queueDozer(void);- void computeEnemyComposition( AIEnemyComposition *out ); ///< what this AI can see the enemy fielding+ void computeEnemyComposition( AIEnemyComposition *out, std::vector<AIVisibleEnemy> *army = NULL ); ///< what this AI can see the enemy fielding, and optionally which unitsReal 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 reinforce@@ -428,6 +442,15 @@ protected:ObjectID m_attackedSupplyCenter;ObjectID m_curWarehouseID;++ /** C2: attack teams parked at the staging point, waiting to go out together. */+ virtual void doWaves(void);+ enum { MAX_HELD_TEAMS = 16 };+ Bool m_heldUsed[ MAX_HELD_TEAMS ];+ UnsignedInt m_heldTeam[ MAX_HELD_TEAMS ]; ///< TeamID; Team.h is not included here+ AsciiString m_heldLabel[ MAX_HELD_TEAMS ]; ///< the approach the script asked for+ Int m_heldSuffix[ MAX_HELD_TEAMS ]; ///< the enemy start index its path name ends in+ UnsignedInt m_heldSince; ///< frame the first of the parked teams arrived};#endif // _AI_PLAYER_H_diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.hindex 5ffabd9a7..8dd103d6a 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h@@ -437,6 +437,8 @@ public:inline WeaponPrefireType getPrefireType() const { return m_prefireType; }inline Bool getAutoReloadsClip() const { return m_reloadType == AUTO_RELOAD; }inline Int getClipSize() const { return m_clipSize; }+ inline Int getMinDelayBetweenShots() const { return m_minDelayBetweenShots; } ///< frames; unlike getDelayBetweenShots, draws no random number+ inline Int getMaxDelayBetweenShots() const { return m_maxDelayBetweenShots; }inline Int getContinuousFireOneShotsNeeded() const { return m_continuousFireOneShotsNeeded; }inline Int getContinuousFireTwoShotsNeeded() const { return m_continuousFireTwoShotsNeeded; }inline UnsignedInt getContinuousFireCoastFrames() const { return m_continuousFireCoastFrames; }diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cppindex df8da5813..9f9b23a9d 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp@@ -1593,7 +1593,19 @@ GameDifficulty Player::getPlayerDifficulty(void) const//-------------------------------------------------------------------------------------------------Bool Player::checkBridges(Object *unit, Waypoint *way){- return m_ai?m_ai->checkBridges(unit, way):false;+ return m_ai?m_ai->checkBridges(unit, way):false;+}++//-------------------------------------------------------------------------------------------------+AsciiString Player::chooseApproachLabel(const Coord3D *from, const AsciiString &requested, Int pathSuffix)+{+ return m_ai ? m_ai->chooseApproachLabel(from, requested, pathSuffix) : requested;+}++//-------------------------------------------------------------------------------------------------+Bool Player::holdTeamForWave(Team *team, const AsciiString &approach, Int pathSuffix)+{+ return m_ai ? m_ai->holdTeamForWave(team, approach, pathSuffix) : FALSE;}//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cppindex c20149b2f..bc65bc1e5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp@@ -1056,35 +1056,20 @@ Real AI::getAdjustedVisionRangeForObject(const Object *object, Int factorsToCons* than 0.85 did. These are the "clearly losing" numbers, and at 0.5 retreat is worth about a* win in twenty over having none.*- * - useInfluenceMapForAttackLane is FALSE everywhere, deliberately. It works - it aims at the- * enemy's most valuable visible cell instead of the middle of his base - and measured against- * itself it does not pay: with one rung copied onto the other so the lane was the only- * difference, and both seats played, it went 7-9 over 32 matches, and the side using it took- * twice the losses for half the kills. Aiming at the money means walking past the army. The- * roadmap's actual proposal is to come in where the *defence density* is lowest, which is the- * threat map rather than the cash map; getMostValuableVisibleLocation and- * influenceMapAttackGoal are kept for that attempt.+ * - useInfluenceMapForAttackLane was FALSE everywhere after its first cut aimed at the enemy's+ * most valuable visible cell: 7-9 over 32 matches against itself, twice the losses for half+ * the kills, because aiming at the money means walking past the army. It is on at the top+ * again for the roadmap's actual proposal, AIPlayer::chooseApproachLabel: of Center, Flank and+ * Backdoor, the approach with the least firepower this AI has seen along it.*- * scoutS maxSc react decis cntr mass ttk indiv team infl focus save harv expand guard hoard */+ * scoutS maxSc react decis cntr mass ttk indiv team infl focus save harv expand guard hoard econ */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, FALSE, FALSE, 0 },- /* Medium */ { 60.0f, 1, 6.0f, 5.0f, 0.25f, FALSE, 0.35f, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, 10000 },- /* Brutal */ { 25.0f, 2, 0.0f, 1.5f, 1.00f, TRUE, 0.50f, TRUE, TRUE, FALSE, 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, FALSE, 0, FALSE },+ /* Medium */ { 60.0f, 1, 6.0f, 5.0f, 0.25f, FALSE, 0.35f, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, 10000, FALSE },+ /* Brutal */ { 25.0f, 2, 0.0f, 1.5f, 1.00f, TRUE, 0.50f, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 4000, TRUE }};-//--------------------------------------------------------------------------------------------------/** How well a team answers what the enemy is fielding.- *- * Anti-air and stealth detection carry their enemy's whole share, because a team that cannot- * touch what it is walking into is worth nothing against it - AA is the AI's classic hole and- * stealth became a real threat to it the moment its units stopped shooting through fog. A- * weapon declared PreferredAgainst something is the data's own statement that it is the answer to- * it, so that is what "anti-tank" and "anti-infantry" mean here rather than a hand-kept list.- *- * 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.@@ -1218,26 +1203,114 @@ Int aiHoardAdjustedDelay( Int frames, Int money, Int hoardAt )return (out < 1) ? 1 : out;}-Real aiCounterScore( const AIEnemyComposition &enemy, const AITeamCapability &team )+//-------------------------------------------------------------------------------------------------+Int aiHoardAllowedTeamInstances( Int maxInstances, Int money, Int hoardAt ){- Real score = 0.0f;+ const Int MAX_EXTRA_INSTANCES = 3;++ if( hoardAt <= 0 || maxInstances <= 0 )+ return maxInstances;++ Int extra = money / (2 * hoardAt);+ if( extra > MAX_EXTRA_INSTANCES )+ extra = MAX_EXTRA_INSTANCES;+ return maxInstances + extra;+}- if( team.m_hitsAir )- score += enemy.m_air;+//-------------------------------------------------------------------------------------------------+Int aiLeastDefendedLane( const Real *laneFirepower, Int laneCount, Int requestedLane )+{+ Int quietest = -1;+ for( Int i = 0; i < laneCount; ++i )+ {+ if( laneFirepower[ i ] < 0.0f )+ continue;+ if( quietest < 0 || laneFirepower[ i ] < laneFirepower[ quietest ] )+ quietest = i;+ }+ if( quietest < 0 )+ return requestedLane;++ const Bool requestedExists = requestedLane >= 0 && requestedLane < laneCount && laneFirepower[ requestedLane ] >= 0.0f;+ if( requestedExists && laneFirepower[ requestedLane ] <= laneFirepower[ quietest ] )+ return requestedLane;+ return quietest;+}++//-------------------------------------------------------------------------------------------------+Bool aiReleaseWave( Real heldPower, Real wavePower, UnsignedInt heldFrames, UnsignedInt maxHoldFrames )+{+ if( heldPower <= 0.0f )+ return FALSE; // nothing parked that can fight, nothing to send+ return heldPower >= wavePower || heldFrames >= maxHoldFrames;+}++//-------------------------------------------------------------------------------------------------+/** How well a team answers what the enemy is fielding.+ *+ * m_answer carries the matchups: how the team's own units fare, weapon against armour, against+ * every kind of unit it can see. EA's data says a Crusader shell does a tenth of its damage to a+ * rifleman, and that is the kind of fact a KindOf flag could never tell the AI. Stealth detection+ * keeps a term of its own, because no firepower answers a unit nobody can target. */+//-------------------------------------------------------------------------------------------------+Real aiCounterScore( const AIEnemyComposition &enemy, const AITeamCapability &team )+{+ Real score = team.m_answer;if( team.m_detectsStealth )score += enemy.m_stealth;- if( team.m_prefersVehicles )- score += enemy.m_armour;- if( team.m_prefersInfantry )- score += enemy.m_infantry;- if( team.m_hitsGround )- score += 0.25f * (enemy.m_armour + enemy.m_infantry);if( score < 0.0f ) score = 0.0f;if( score > 1.0f ) score = 1.0f;return score;}+//-------------------------------------------------------------------------------------------------+/** Frames until one weapon puts one target down. The first shot pays one delay and every later+ * shot pays the wait before it - the reload when the shot before it emptied the clip. Paying a+ * delay for the first shot is what keeps two one-shot kills from both reading as instant. */+//-------------------------------------------------------------------------------------------------+Real aiFramesToKill( Real targetHealth, const AIShotPattern &shots )+{+ const Real OVERKILL_TOLERANCE = 0.0001f; // 480 health at 60 a shot is eight shots, not nine++ if( shots.m_damagePerShot <= 0.0f || targetHealth <= 0.0f )+ return AI_CANNOT_KILL;++ Int shotsNeeded = (Int)ceilf( targetHealth / shots.m_damagePerShot - OVERKILL_TOLERANCE );+ if( shotsNeeded < 1 )+ shotsNeeded = 1;+ const Int reloads = (shots.m_clipSize > 0) ? (shotsNeeded - 1) / shots.m_clipSize : 0;+ const Real firstShot = (shots.m_delayFrames > 1.0f) ? shots.m_delayFrames : 1.0f;++ return shots.m_openingFrames + firstShot+ + INT_TO_REAL( shotsNeeded - 1 - reloads ) * shots.m_delayFrames+ + INT_TO_REAL( reloads ) * shots.m_reloadFrames;+}++//-------------------------------------------------------------------------------------------------+/** One pairing, money for money. On a log scale, so twice as good and half as good sit the same+ * distance either side of an even trade, and the two directions of one pairing always sum to 1. */+//-------------------------------------------------------------------------------------------------+Real aiMatchupScore( Real myFramesToKill, Real theirFramesToKill, Real myCost, Real theirCost )+{+ const Real SATURATING_DOUBLINGS = 4.0f; // sixteen times better is as good as it gets++ if( myFramesToKill < 0.0f )+ return 0.0f; // nothing I can do about it, whatever it can do to me+ if( theirFramesToKill < 0.0f )+ return 1.0f; // it cannot touch me and I can kill it++ Real advantage = theirFramesToKill / myFramesToKill;+ if( myCost > 0.0f && theirCost > 0.0f )+ advantage *= theirCost / myCost; // twice the price has to kill twice as fast to break even++ const Real doublings = (Real)( log( advantage ) / log( 2.0 ) );+ Real score = 0.5f + 0.5f * doublings / SATURATING_DOUBLINGS;+ if( score < 0.0f ) score = 0.0f;+ if( score > 1.0f ) score = 1.0f;+ return score;+}+//-------------------------------------------------------------------------------------------------const AIDifficultyProfile *AI::getDifficultyProfile( AISkillLevel level ) const{@@ -1272,6 +1345,7 @@ void AI::parseSkillLevel(INI *ini, void *instance, void* /*store*/, const void*{ "SelfTriggeredExpansion", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_selfTriggeredExpansion ) },{ "DefendExpansions", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_defendExpansions ) },{ "CashHoardThreshold", INI::parseInt, NULL, offsetof( AIDifficultyProfile, m_cashHoardThreshold ) },+ { "EconomyBuildings", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_economyBuildings ) },{ NULL, NULL, NULL, 0 }};diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cppindex b372f49f2..2c797a2db 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp@@ -51,7 +51,11 @@#include "GameLogic/SidesList.h"#include "GameLogic/AI.h"#include "GameLogic/AIPathfind.h"-#include "GameLogic/Weapon.h" // the anti-masks B1 reads off a team's weapons+#include "GameLogic/Weapon.h" // the weapons B1 weighs a team's units by+#include "GameLogic/WeaponSet.h"+#include "GameLogic/Armor.h" // ... the armour they land on+#include "GameLogic/ArmorSet.h"+#include "GameLogic/Module/ActiveBody.h" // ... and the health behind it#include "GameLogic/TerrainLogic.h"#include "GameLogic/Module/AIUpdate.h"#include "GameLogic/Module/DozerAIUpdate.h"@@ -277,6 +281,14 @@ m_role(AIROLE_AGGRESSIVE)m_capturerID = INVALID_ID;m_captureTimer = 1;+ for( Int held = 0; held < MAX_HELD_TEAMS; ++held )+ {+ m_heldUsed[ held ] = FALSE;+ m_heldTeam[ held ] = 0;+ m_heldSuffix[ held ] = 0;+ }+ m_heldSince = 0;+m_frameLastBuildingBuilt = TheGameLogic->getFrame();p->setCanBuildUnits(false); // turn off ai production by default.@@ -2013,66 +2025,187 @@ Bool AIPlayer::selectTeamToReinforce( Int minPriority )/** Determine the next team to build. Return true if one was selected. */// ------------------------------------------------------------------------------------------------//--------------------------------------------------------------------------------------------------/** What one unit template can answer. Read off its weapons: what they are allowed to shoot at,- * and what the data says they are the preferred answer to. */+/** The health a unit template is built with. Every body module that can be hurt keeps it in+ * ActiveBodyModuleData; the one that cannot, InactiveBody, is not on the list and answers zero. *///--------------------------------------------------------------------------------------------------static void addTemplateCapability( const ThingTemplate *tmpl, AITeamCapability *cap )+static Real templateMaxHealth( const ThingTemplate *tmpl ){- if( tmpl == NULL )- return;+ static const char *BODIES_WITH_HEALTH[] =+ { "ActiveBody", "StructureBody", "HiveStructureBody", "UndeadBody", "HighlanderBody", "ImmortalBody", NULL };- //- // "Can it see stealth" is not a KindOf - it is a module the data hangs on the unit, so ask the- // template's module list by name. That is the same question the game itself answers when it- // builds the object, one INI edit away from being right for a mod's own detector.- //const ModuleInfo &modules = tmpl->getBehaviorModuleInfo();for( Int m = 0; m < modules.getCount(); ++m ){- if( modules.getNthName( m ).compareNoCase( "StealthDetectorUpdate" ) == 0 )+ for( const char **body = BODIES_WITH_HEALTH; *body != NULL; ++body ){- cap->m_detectsStealth = TRUE;- break;+ if( modules.getNthName( m ).compareNoCase( *body ) == 0 )+ return static_cast<const ActiveBodyModuleData *>( modules.getNthData( m ) )->m_maxHealth;}}+ return 0.0f;+}++// ponytail: an aircraft that empties its clip flies home to rearm; a flat twenty seconds stands in+// for the trip, until a measured sortie replaces it+static const Real AI_SORTIE_FRAMES = 20.0f * LOGICFRAMES_PER_SECOND;++//-------------------------------------------------------------------------------------------------+/** How one weapon works on one target, as the numbers aiFramesToKill needs. FALSE when the weapon+ * may not aim at it at all. Read off the unconditioned sets - no upgrades, no veterancy - which is+ * the unit the build menu offers. */+//-------------------------------------------------------------------------------------------------+static Bool shotPatternAgainst( const WeaponTemplate *weapon, const ThingTemplate *target, Real targetHealth, AIShotPattern *out )+{+ const Int aimNeeded = target->isKindOf( KINDOF_AIRCRAFT ) ? WEAPON_ANTI_AIRBORNE_VEHICLE : WEAPON_ANTI_GROUND;+ if( (weapon->getAntiMask() & aimNeeded) == 0 )+ return FALSE;- const WeaponTemplateSetVector &sets = tmpl->getWeaponTemplateSets();- for( WeaponTemplateSetVector::const_iterator it = sets.begin(); it != sets.end(); ++it )+ //+ // A gattling spins up: its own WeaponBonus block makes it fire faster once it has kept firing.+ // An exchange lasts that long, so it is read at the fastest step the weapon has.+ //+ WeaponBonus bonus;+ if( weapon->getExtraBonus() != NULL ){- for( Int slot = 0; slot < WEAPONSLOT_COUNT; ++slot )- {- const WeaponTemplate *w = it->getNth( (WeaponSlotType)slot );- if( w == NULL )- continue;+ WeaponBonusConditionFlags spunUp = 0;+ if( weapon->getContinuousFireTwoShotsNeeded() != INT_MAX )+ spunUp = 1 << WEAPONBONUSCONDITION_CONTINUOUS_FIRE_FAST;+ else if( weapon->getContinuousFireOneShotsNeeded() != INT_MAX )+ spunUp = 1 << WEAPONBONUSCONDITION_CONTINUOUS_FIRE_MEAN;+ weapon->getExtraBonus()->appendBonuses( spunUp, bonus );+ }++ const ArmorTemplateSet *armorSet = target->findArmorTemplateSet( ArmorSetFlags() );+ const Armor armor = TheArmorStore->makeArmor( armorSet ? armorSet->getArmorTemplate() : NULL );+ const DamageType type = weapon->getDamageType();++ if( type == DAMAGE_KILLPILOT )+ out->m_damagePerShot = target->isKindOf( KINDOF_VEHICLE ) ? armor.adjustDamage( type, targetHealth ) : 0.0f; // the vehicle leaves the fight in one hit+ else if( type == DAMAGE_HEALING || !IsHealthDamagingDamage( type ) )+ out->m_damagePerShot = 0.0f;+ else+ out->m_damagePerShot = armor.adjustDamage( type, weapon->getPrimaryDamage( bonus ) );++ const Real rateOfFire = bonus.getField( WeaponBonus::RATE_OF_FIRE );+ const Real preAttack = INT_TO_REAL( weapon->getPreAttackDelay( bonus ) );+ out->m_delayFrames = INT_TO_REAL( weapon->getMinDelayBetweenShots() + weapon->getMaxDelayBetweenShots() ) * 0.5f / rateOfFire;+ out->m_clipSize = weapon->getClipSize();+ out->m_reloadFrames = INT_TO_REAL( weapon->getClipReloadTime( bonus ) );+ if( weapon->getReloadType() == RETURN_TO_BASE_TO_RELOAD )+ out->m_reloadFrames += AI_SORTIE_FRAMES;++ switch( weapon->getPrefireType() )+ {+ case PREFIRE_PER_SHOT:+ out->m_delayFrames += preAttack;+ out->m_reloadFrames += preAttack;+ break;+ case PREFIRE_PER_CLIP:+ out->m_openingFrames = preAttack;+ out->m_reloadFrames += preAttack;+ break;+ case PREFIRE_PER_ATTACK:+ out->m_openingFrames = preAttack;+ break;+ }+ return TRUE;+}++//-------------------------------------------------------------------------------------------------+/** Frames one unit template needs to kill another, with the best weapon it carries against it. */+//-------------------------------------------------------------------------------------------------+static Real templateFramesToKill( const ThingTemplate *attacker, const ThingTemplate *target )+{+ if( attacker->getWeaponTemplateSets().empty() )+ return AI_CANNOT_KILL; // a dozer, a supply truck: the data gives it nothing to shoot with++ const Real health = templateMaxHealth( target );+ const WeaponTemplateSet *set = attacker->findWeaponTemplateSet( WeaponSetFlags() );+ Real best = AI_CANNOT_KILL;+ for( Int slot = 0; slot < WEAPONSLOT_COUNT; ++slot )+ {+ const WeaponTemplate *weapon = set->getNth( (WeaponSlotType)slot );+ AIShotPattern shots;+ if( weapon == NULL || !shotPatternAgainst( weapon, target, health, &shots ) )+ continue;- const Int anti = w->getAntiMask();- if( anti & (WEAPON_ANTI_AIRBORNE_VEHICLE | WEAPON_ANTI_AIRBORNE_INFANTRY) )- cap->m_hitsAir = TRUE;- if( anti & WEAPON_ANTI_GROUND )- cap->m_hitsGround = TRUE;-- const KindOfMaskType &preferred = it->getNthPreferredAgainstMask( (WeaponSlotType)slot );- if( preferred.test( KINDOF_VEHICLE ) )- cap->m_prefersVehicles = TRUE;- if( preferred.test( KINDOF_INFANTRY ) )- cap->m_prefersInfantry = TRUE;+ const Real frames = aiFramesToKill( health, shots );+ if( frames >= 0.0f && (best < 0.0f || frames < best) )+ best = frames;+ }+ return best;+}++//-------------------------------------------------------------------------------------------------+/** Count one visible enemy unit into the army: one entry per kind of unit, in the order first seen. */+//-------------------------------------------------------------------------------------------------+static void addToVisibleArmy( std::vector<AIVisibleEnemy> *army, const ThingTemplate *tmpl, const Player *owner, Real weight )+{+ for( std::vector<AIVisibleEnemy>::iterator kind = army->begin(); kind != army->end(); ++kind )+ {+ if( kind->m_template == tmpl )+ {+ kind->m_weight += weight;+ return;}}++ AIVisibleEnemy kind;+ kind.m_template = tmpl;+ kind.m_weight = weight;+ kind.m_cost = INT_TO_REAL( tmpl->calcCostToBuild( owner ) );+ army->push_back( kind );}//--------------------------------------------------------------------------------------------------/** What a team prototype can answer, over every unit it is built from. */+/** What a team prototype can answer, over every unit it is built from: each of its units against+ * each kind of enemy unit in sight, both ways round, weighted by how much of the visible army that+ * kind is and by how many of the unit the team fields. *///--------------------------------------------------------------------------------------------------static AITeamCapability teamCapability( const TeamPrototype *proto )+static AITeamCapability teamCapability( const TeamPrototype *proto, const Player *owner, const std::vector<AIVisibleEnemy> &army ){AITeamCapability cap;const TeamTemplateInfo *info = proto ? proto->getTemplateInfo() : NULL;if( info == NULL )return cap;+ Real answered = 0.0f;+ Real weighed = 0.0f;for( Int i = 0; i < info->m_numUnitsInfo; ++i )- addTemplateCapability( TheThingFactory->findTemplate( info->m_unitsInfo[ i ].unitThingName, FALSE ), &cap );+ {+ const ThingTemplate *tmpl = TheThingFactory->findTemplate( info->m_unitsInfo[ i ].unitThingName, FALSE );+ if( tmpl == NULL )+ continue; // a map's team naming a unit this game does not have++ //+ // "Can it see stealth" is not a KindOf - it is a module the data hangs on the unit, so ask the+ // template's module list by name. That is the same question the game itself answers when it+ // builds the object, one INI edit away from being right for a mod's own detector.+ //+ const ModuleInfo &modules = tmpl->getBehaviorModuleInfo();+ for( Int m = 0; m < modules.getCount(); ++m )+ {+ if( modules.getNthName( m ).compareNoCase( "StealthDetectorUpdate" ) == 0 )+ {+ cap.m_detectsStealth = TRUE;+ break;+ }+ }++ const Int minUnits = info->m_unitsInfo[ i ].minUnits;+ const Real fielded = INT_TO_REAL( minUnits > 1 ? minUnits : 1 );+ const Real myCost = INT_TO_REAL( tmpl->calcCostToBuild( owner ) );+ for( std::vector<AIVisibleEnemy>::const_iterator enemy = army.begin(); enemy != army.end(); ++enemy )+ {+ const Real score = aiMatchupScore( templateFramesToKill( tmpl, enemy->m_template ),+ templateFramesToKill( enemy->m_template, tmpl ), myCost, enemy->m_cost );+ answered += fielded * enemy->m_weight * score;+ weighed += fielded * enemy->m_weight;+ }+ }+ if( weighed > 0.0f )+ cap.m_answer = answered / weighed;return cap;}@@ -2081,7 +2214,7 @@ static AITeamCapability teamCapability( const TeamPrototype *proto )* counts for more than a rifleman. Fog-aware by construction - it asks observerKnowsAbout of* every object, which is what makes B1 A2's first customer. *///--------------------------------------------------------------------------------------------------void AIPlayer::computeEnemyComposition( AIEnemyComposition *out )+void AIPlayer::computeEnemyComposition( AIEnemyComposition *out, std::vector<AIVisibleEnemy> *army ){Real air = 0.0f, armour = 0.0f, infantry = 0.0f, stealth = 0.0f, total = 0.0f;const Int me = m_player->getPlayerIndex();@@ -2117,6 +2250,8 @@ void AIPlayer::computeEnemyComposition( AIEnemyComposition *out )continue;total += threat;+ if( army != NULL )+ addToVisibleArmy( army, obj->getTemplate(), p, threat );if( obj->isKindOf( KINDOF_AIRCRAFT ) ) air += threat;if( obj->isKindOf( KINDOF_VEHICLE ) ) armour += threat;if( obj->isKindOf( KINDOF_INFANTRY ) ) infantry += threat;@@ -2226,8 +2361,9 @@ Bool AIPlayer::selectTeamToBuild( void )//const AIDifficultyProfile *profile = getSkillProfile();AIEnemyComposition enemy;+ std::vector<AIVisibleEnemy> army;if (profile->m_counterCompositionWeight > 0.0f)- computeEnemyComposition( &enemy );+ computeEnemyComposition( &enemy, &army );// what a perfect counter, and the role preference, are worth in units of production priorityconst Real COUNTER_SPAN = 20.0f;@@ -2244,7 +2380,7 @@ Bool AIPlayer::selectTeamToBuild( void )Real score = INT_TO_REAL( info->m_productionPriority );score += profile->m_counterCompositionWeight * COUNTER_SPAN *- aiCounterScore( enemy, teamCapability( *t ) );+ aiCounterScore( enemy, teamCapability( *t, m_player, army ) );if( (m_role == AIROLE_DEFENSIVE) == (isDefenceTeam != FALSE) )score += ROLE_SPAN;@@ -2284,7 +2420,12 @@ Bool AIPlayer::selectTeamToBuild( void )teamStr.concat("' has no Home Position (or Origin).");TheScriptEngine->AppendDebugMessage(teamStr, false);}- // Build it at low priority, as we have selected it automagically.+ // one line per decision, so a batch can show what the AI answered with and not just who won+ DEBUG_LOG(("AI COUNTER frame %d player %d builds '%s' score %.2f counter %.2f against %d visible kinds, %.0f threat\n",+ TheGameLogic->getFrame(), m_player->getPlayerIndex(), teamProto->getName().str(), bestScore,+ aiCounterScore( enemy, teamCapability( teamProto, m_player, army ) ), (Int)army.size(), enemy.m_totalThreat));++ // Build it at low priority, as we have selected it automagically.buildSpecificAITeam(teamProto, false);m_readyToBuildTeam = false;m_teamTimer = computeTeamDelay();@@ -3759,9 +3900,9 @@ void AIPlayer::doUpgradesAndSkills( void )Pathfinder already break theirs down: per job, plus whichever single player cost the most.Reset once per logic frame by AI::update. */enum { AIP_BASE, AIP_READY, AIP_QUEUED, AIP_TEAM, AIP_UPGRADE,- AIP_BRIDGE, AIP_SCOUT, AIP_RETREAT, AIP_EXPAND, AIP_CAPTURE, AIP_PHASE_COUNT };+ AIP_BRIDGE, AIP_SCOUT, AIP_RETREAT, AIP_EXPAND, AIP_CAPTURE, AIP_ECONOMY, AIP_WAVE, AIP_PHASE_COUNT };static const char *theAIPhaseName[ AIP_PHASE_COUNT ] =- { "base", "ready", "queued", "team", "upg", "bridge", "scout", "retreat", "expand", "capture" };+ { "base", "ready", "queued", "team", "upg", "bridge", "scout", "retreat", "expand", "capture", "economy", "wave" };static Real theAIPhaseMS[ AIP_PHASE_COUNT ];static Real theAIWorstPlayerMS = 0.0f;static Int theAIWorstPlayer = -1;@@ -3834,6 +3975,8 @@ void AIPlayer::update( void )AI_PHASE( AIP_RETREAT, doRetreats() ); // Break off the fights we are losing.AI_PHASE( AIP_EXPAND, doExpansion() ); // Go and take the money that is lying around.AI_PHASE( AIP_CAPTURE, doCapture() ); // ... and the money that is standing around.+ AI_PHASE( AIP_ECONOMY, doEconomy() ); // ... and the money sitting in the bank.+ AI_PHASE( AIP_WAVE, doWaves() ); // Send the parked attack teams out together.#ifdef DEBUG_LOGGINGInt64 playerEnd;@@ -4047,6 +4190,443 @@ void AIPlayer::doExpansion( void )}}+//----------------------------------------------------------------------------------------------------------+/** How often the economy is looked at. No timer: the frame and the player's slot decide it, so there+ * is nothing to save and every machine lands on the same frame. */+static const Int ECONOMY_CHECK_RATE = 10 * LOGICFRAMES_PER_SECOND;++/** Tries on each ring when looking for somewhere to put a purchase down. Every try is a legality+ * check that costs about a millisecond, so this bounds the spike rather than the search. */+static const Int PLACEMENT_ANGLES = 12;+static const Int PLACEMENT_RINGS = 2;++/** How far either side of a waypoint an approach counts the guns along it. */+static const Real APPROACH_WATCH_RADIUS = 250.0f;++/** Longest approach walked, in waypoints; a path that loops would otherwise never end. */+static const Int APPROACH_MAX_WAYPOINTS = 64;++/** Something of this kind the builder can make right now, off the builder's own buttons, so the+ * answer is right for every faction and general without a table of names. */+static const ThingTemplate *buildableOfKind( Object *builder, GUICommandType commandType, KindOfType kind )+{+ const CommandSet *commandSet = TheControlBar->findCommandSet( builder->getCommandSetString() );+ if( commandSet == NULL )+ return NULL;++ for( Int i = 0; i < MAX_COMMANDS_PER_SET; ++i )+ {+ const CommandButton *button = commandSet->getCommandButton( i );+ if( button == NULL || button->getCommandType() != commandType )+ continue;+ const ThingTemplate *tmpl = button->getThingTemplate();+ if( tmpl && tmpl->isKindOf( kind ) && TheBuildAssistant->canMakeUnit( builder, tmpl ) == CANMAKE_OK )+ return tmpl;+ }+ return NULL;+}++/** Every finished production building of this kind has something in its queue. One still going up+ * counts as spare: it is the answer already on its way. */+static Bool everyFactoryBusy( Player *player, KindOfType kind )+{+ Int factories = 0;+ for( BuildListInfo *info = player->getBuildList(); info; info = info->getNext() )+ {+ Object *factory = TheGameLogic->findObjectByID( info->getObjectID() );+ if( factory == NULL || factory->getControllingPlayer() != player || !factory->isKindOf( kind ) )+ continue;+ if( factory->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )+ return FALSE;+ ProductionUpdateInterface *pu = factory->getProductionUpdateInterface();+ if( pu == NULL )+ continue;+ if( pu->getProductionCount() == 0 )+ return FALSE;+ ++factories;+ }+ return factories > 0;+}++/** A hacker standing about is income nobody switched on. */+static void putToHacking( Object *obj, void * )+{+ if( !obj->isKindOf( KINDOF_MONEY_HACKER ) || obj->isContained() || obj->isEffectivelyDead() )+ return;+ AIUpdateInterface *ai = obj->getAI();+ if( ai && ai->isIdle() )+ ai->aiHackInternet( CMD_FROM_AI );+}++/** The first dozer this player owns, busy or not. */+static void findAnyDozer( Object *obj, void *userData )+{+ Object **dozer = (Object **)userData;+ if( *dozer == NULL && obj->isKindOf( KINDOF_DOZER ) && !obj->isEffectivelyDead() )+ *dozer = obj;+}++/** A purchase of this kind is already on the build list and waiting for a dozer. Asked per template+ * rather than for the whole list: the script's own plan keeps seven to twenty priority entries+ * waiting through most of a match, and a global "wait for the last one" never let anything through. */+static Bool priorityBuildPending( Player *player, const ThingTemplate *tmpl )+{+ for( BuildListInfo *info = player->getBuildList(); info; info = info->getNext() )+ {+ if( info->isPriorityBuild() && info->isBuildable() && info->getObjectID() == INVALID_ID &&+ info->getTemplateName() == tmpl->getName() )+ return TRUE;+ }+ return FALSE;+}++//----------------------------------------------------------------------------------------------------------+/** A bank of a hundred thousand is an army and an economy that were never bought. The skirmish build+ * list is a fixed plan - two war factories and a barracks - and the scripts never add to it, so+ * once the plan stood the money had nowhere to go.+ *+ * Three things the plan cannot buy. Another production building when every one of a kind is busy,+ * put down beside the last expansion so the army comes out nearer the fighting. Another income+ * building - a supply drop zone, a black market - when production is keeping up; neither has a+ * limit. And hackers from any factory standing idle, because China's income building takes one+ * copy and a hacker earns wherever it stands.+ */+//----------------------------------------------------------------------------------------------------------+void AIPlayer::doEconomy( void )+{+ const AIDifficultyProfile *profile = getSkillProfile();+ if( !profile->m_economyBuildings )+ return;+ const Int phase = computeUpdatePhase( m_player->getPlayerIndex(), ECONOMY_CHECK_RATE );+ if( (TheGameLogic->getFrame() + phase) % ECONOMY_CHECK_RATE != 0 )+ return;++ m_player->iterateObjects( putToHacking, NULL );++ // a hacker pays for itself in about four minutes, so it only waits for the hoard threshold ...+ if( m_player->getMoney()->countMoney() <= profile->m_cashHoardThreshold )+ return;+ buyMoneyUnit();++ // ... and buildings for twice it, so the opening build order is not what pays for them+ if( m_player->getMoney()->countMoney() <= 2 * profile->m_cashHoardThreshold )+ return;++ if( !m_player->getCanBuildBase() || !m_baseCenterSet )+ return;++ // any dozer will do to read the buttons from: an idle one is what builds it, and that is later+ Object *dozer = NULL;+ m_player->iterateObjects( findAnyDozer, &dozer );+ if( dozer == NULL )+ return;++ const Int PRODUCTION_KINDS = 3;+ static const KindOfType PRODUCTION[ PRODUCTION_KINDS ] = { KINDOF_FS_WARFACTORY, KINDOF_FS_BARRACKS, KINDOF_FS_AIRFIELD };+ for( Int i = 0; i < PRODUCTION_KINDS; ++i )+ {+ if( !everyFactoryBusy( m_player, PRODUCTION[ i ] ) )+ continue;+ const ThingTemplate *tmpl = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, PRODUCTION[ i ] );+ if( tmpl == NULL || priorityBuildPending( m_player, tmpl ) )+ continue;++ const Object *warehouse = TheGameLogic->findObjectByID( m_curWarehouseID );+ if( warehouse && placeNear( tmpl, warehouse->getPosition(),+ warehouse->getGeometryInfo().getBoundingCircleRadius() + SUPPLY_CENTER_CLOSE_DIST*0.5f ) )+ return;+ if( placeNear( tmpl, &m_baseCenter, m_baseRadius ) )+ return;+ }++ const Int INCOME_KINDS = 2;+ static const KindOfType INCOME[ INCOME_KINDS ] = { KINDOF_FS_SUPPLY_DROPZONE, KINDOF_FS_BLACK_MARKET };+ for( Int i = 0; i < INCOME_KINDS; ++i )+ {+ const ThingTemplate *tmpl = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, INCOME[ i ] );+ if( tmpl && !priorityBuildPending( m_player, tmpl ) && placeNear( tmpl, &m_baseCenter, m_baseRadius ) )+ return;+ }+}++//----------------------------------------------------------------------------------------------------------+/** A money unit from the first factory that trains one and has at most one thing in its queue. An+ * idle-only rule measured as two hackers in a whole match, because a barracks feeding the army is+ * never idle; one slot behind the army's unit is a delay the army does not notice. */+//----------------------------------------------------------------------------------------------------------+void AIPlayer::buyMoneyUnit( void )+{+ const Int MAX_QUEUED_AHEAD = 1;+ for( BuildListInfo *info = m_player->getBuildList(); info; info = info->getNext() )+ {+ Object *factory = TheGameLogic->findObjectByID( info->getObjectID() );+ if( factory == NULL || factory->getControllingPlayer() != m_player || factory->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )+ continue;+ ProductionUpdateInterface *pu = factory->getProductionUpdateInterface();+ if( pu == NULL || pu->getProductionCount() > MAX_QUEUED_AHEAD )+ continue;+ const ThingTemplate *moneyUnit = buildableOfKind( factory, GUI_COMMAND_UNIT_BUILD, KINDOF_MONEY_HACKER );+ if( moneyUnit && pu->queueCreateUnit( moneyUnit, pu->requestUniqueUnitID() ) )+ {+ DEBUG_LOG(("AI ECONOMY frame %d player %d trains '%s', %d in the bank\n", TheGameLogic->getFrame(),+ m_player->getPlayerIndex(), moneyUnit->getName().str(), m_player->getMoney()->countMoney()));+ return;+ }+ }+}++//----------------------------------------------------------------------------------------------------------+/** Walk rings round center until a spot is legal and safe, and hand it to the dozers as a priority+ * build. ponytail: a fixed dozen angles on two rings, so a crowded spot can miss room that a wider+ * search would find; the next check tries again with whatever has changed. */+//----------------------------------------------------------------------------------------------------------+Bool AIPlayer::placeNear( const ThingTemplate *tmpl, const Coord3D *center, Real innerRadius )+{+ const Real structureRadius = tmpl->getTemplateGeometryInfo().getBoundingCircleRadius();+ const Real placeAngle = tmpl->getPlacementViewAngle();++ for( Int ring = 0; ring < PLACEMENT_RINGS; ++ring )+ {+ const Real distance = innerRadius + structureRadius * (2 * ring + 1);+ for( Int step = 0; step < PLACEMENT_ANGLES; ++step )+ {+ const Real angle = 2.0f * PI * step / PLACEMENT_ANGLES;+ Coord3D pos = *center;+ pos.x += distance * Cos( angle );+ pos.y += distance * Sin( angle );+ pos.z = 0;++ const Bool legal = TheBuildAssistant->isLocationLegalToBuild( &pos, tmpl, placeAngle,+ BuildAssistant::CLEAR_PATH | BuildAssistant::TERRAIN_RESTRICTIONS | BuildAssistant::NO_OBJECT_OVERLAP,+ NULL, m_player ) == LBC_OK;+ TheTerrainVisual->removeAllBibs(); // isLocationLegalToBuild adds bib feedback+ if( legal && isLocationSafe( &pos, tmpl ) )+ {+ DEBUG_LOG(("AI ECONOMY frame %d player %d builds '%s' at (%.0f,%.0f), %d in the bank\n", TheGameLogic->getFrame(),+ m_player->getPlayerIndex(), tmpl->getName().str(), pos.x, pos.y, m_player->getMoney()->countMoney()));+ m_player->addToPriorityBuildList( tmpl->getName(), &pos, placeAngle );+ return TRUE;+ }+ }+ }+ return FALSE;+}++//----------------------------------------------------------------------------------------------------------+/** B4, second attempt. The first aimed at the enemy's most valuable cell, which is his money, and+ * walked past his army: 7-9, twice the losses. The roadmap asked for the approach where the defence+ * is thinnest, and the engine's threat layer cannot say where that is - it is built from+ * ThingTemplate::ThreatValue, which the shipped data never sets, so every cell reads zero. So the+ * guns are counted off the objects themselves, the same weighing the retreat and the counter score+ * use, and only what this AI has seen: a defence it has never scouted does not steer it. */+//----------------------------------------------------------------------------------------------------------+AsciiString AIPlayer::chooseApproachLabel( const Coord3D *from, const AsciiString &requested, Int pathSuffix )+{+ if( !getSkillProfile()->m_useInfluenceMapForAttackLane || from == NULL )+ return requested;++ const Int LANE_COUNT = 3;+ static const char *LANES[ LANE_COUNT ] = { SKIRMISH_CENTER, SKIRMISH_FLANK, SKIRMISH_BACKDOOR };++ Int requestedLane = -1;+ for( Int i = 0; i < LANE_COUNT; ++i )+ {+ if( requested.compareNoCase( LANES[ i ] ) == 0 )+ requestedLane = i;+ }+ if( requestedLane < 0 )+ return requested; // "Special" and whatever a map names for itself stay the script's business++ Real firepower[ LANE_COUNT ];+ for( Int i = 0; i < LANE_COUNT; ++i )+ {+ AsciiString label;+ label.format( "%s%d", LANES[ i ], pathSuffix );+ Waypoint *way = TheTerrainLogic->getClosestWaypointOnPath( from, label );+ firepower[ i ] = (way == NULL) ? -1.0f : knownFirepowerAlongPath( way );+ }++ const Int lane = aiLeastDefendedLane( firepower, LANE_COUNT, requestedLane );+ if( lane != requestedLane )+ DEBUG_LOG(("AI LANE frame %d player %d takes %s (%.0f) instead of %s (%.0f)\n", TheGameLogic->getFrame(),+ m_player->getPlayerIndex(), LANES[ lane ], firepower[ lane ], LANES[ requestedLane ], firepower[ requestedLane ]));+ return AsciiString( LANES[ lane ] );+}++//----------------------------------------------------------------------------------------------------------+Real AIPlayer::knownFirepowerAlongPath( Waypoint *way )+{+ PartitionFilterPlayerAffiliation enemies( m_player, ALLOW_ENEMIES, true );+ PartitionFilterAlive alive;+ PartitionFilter *filters[] = { &enemies, &alive, NULL };++ Real firepower = 0.0f;+ for( Int step = 0; way != NULL && step < APPROACH_MAX_WAYPOINTS; ++step )+ {+ ObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( way->getLocation(), APPROACH_WATCH_RADIUS,+ FROM_BOUNDINGSPHERE_2D, filters );+ MemoryPoolObjectHolder hold( iter );+ for( Object *obj = iter->first(); obj; obj = iter->next() )+ {+ if( observerKnowsAbout( obj, m_player->getPlayerIndex() ) )+ firepower += aiCombatPower( obj );+ }+ way = (way->getNumLinks() > 0) ? way->getLink( 0 ) : NULL;+ }+ return firepower;+}++//----------------------------------------------------------------------------------------------------------+/** A wave worth sending: about what seven main battle tanks cost, in the build-cost currency+ * aiCombatPower counts in. */+static const Real WAVE_POWER = 6000.0f;++/** The longest a parked team waits for the rest of its wave. */+static const UnsignedInt WAVE_MAX_HOLD_FRAMES = 90 * LOGICFRAMES_PER_SECOND;++/** How often the parked teams are looked at. */+static const Int WAVE_CHECK_RATE = 2 * LOGICFRAMES_PER_SECOND;++static Real teamPower( Team *team )+{+ Real power = 0.0f;+ for( DLINK_ITERATOR<Object> iter = team->iterate_TeamMemberList(); !iter.done(); iter.advance() )+ {+ Object *obj = iter.cur();+ if( obj && !obj->isEffectivelyDead() )+ power += aiCombatPower( obj );+ }+ return power;+}++//----------------------------------------------------------------------------------------------------------+/** C2, second attempt. Teams went out as they came off the line - a lone artillery piece, a single bomb+ * truck, one helicopter - and three brutal matches on Winter Wolf counted 29% of the AI's units dying+ * with two or fewer of their own combat units within 300 feet.+ *+ * The first attempt held finished teams in the ready queue, and a team in the queue still counts as an+ * instance, so production stopped behind it. This one lets the team activate and catches its attack+ * order instead: the team drives to a staging point on the enemy's side of the base and waits there,+ * production carries on, and doWaves sends everything parked out together.+ */+//----------------------------------------------------------------------------------------------------------+Bool AIPlayer::holdTeamForWave( Team *team, const AsciiString &approach, Int pathSuffix )+{+ if( team == NULL || !isSkirmishAI() || !getSkillProfile()->m_massBeforeAttacking )+ return FALSE;+ const TeamTemplateInfo *info = team->getPrototype()->getTemplateInfo();+ if( info->m_isBaseDefense || info->m_isPerimeterDefense )+ return FALSE;++ Int freeSlot = -1;+ Bool anyParked = FALSE;+ for( Int i = 0; i < MAX_HELD_TEAMS; ++i )+ {+ if( !m_heldUsed[ i ] )+ {+ if( freeSlot < 0 )+ freeSlot = i;+ continue;+ }+ if( m_heldTeam[ i ] == team->getID() )+ return TRUE; // already parked; the script asking again changes nothing+ anyParked = TRUE;+ }+ if( freeSlot < 0 )+ return FALSE; // the staging point is full, so this one goes as the script said+ if( teamPower( team ) >= WAVE_POWER )+ return FALSE; // a wave on its own waits for nobody++ m_heldUsed[ freeSlot ] = TRUE;+ m_heldTeam[ freeSlot ] = team->getID();+ m_heldLabel[ freeSlot ] = approach;+ m_heldSuffix[ freeSlot ] = pathSuffix;+ if( !anyParked )+ m_heldSince = TheGameLogic->getFrame();++ Coord3D staging = m_baseCenter;+ Player *enemy = getAiEnemy();+ Coord3D enemyPos;+ if( enemy && enemyStartGuess( enemy->getPlayerIndex(), &enemyPos ) )+ {+ Coord2D toward;+ toward.x = enemyPos.x - m_baseCenter.x;+ toward.y = enemyPos.y - m_baseCenter.y;+ toward.normalize();+ staging.x += toward.x * m_baseRadius;+ staging.y += toward.y * m_baseRadius;+ }+ AIGroup *group = TheAI->createGroup();+ team->getTeamAsAIGroup( group );+ group->groupTightenToPosition( &staging, FALSE, CMD_FROM_AI );+ return TRUE;+}++//----------------------------------------------------------------------------------------------------------+/** Send the parked teams once they add up to a wave or have waited long enough. They go as one group+ * down one approach at the pace of the slowest, so what gathered together arrives together. */+//----------------------------------------------------------------------------------------------------------+void AIPlayer::doWaves( void )+{+ if( (TheGameLogic->getFrame() + computeUpdatePhase( m_player->getPlayerIndex(), WAVE_CHECK_RATE )) % WAVE_CHECK_RATE != 0 )+ return;++ Real power = 0.0f;+ Int first = -1;+ Int teams = 0;+ for( Int i = 0; i < MAX_HELD_TEAMS; ++i )+ {+ if( !m_heldUsed[ i ] )+ continue;+ Team *team = TheTeamFactory->findTeamByID( m_heldTeam[ i ] );+ if( team == NULL || !team->hasAnyUnits() )+ {+ m_heldUsed[ i ] = FALSE;+ continue;+ }+ power += teamPower( team );+ if( first < 0 )+ first = i;+ ++teams;+ }+ if( first < 0 )+ return;+ const UnsignedInt heldFrames = TheGameLogic->getFrame() - m_heldSince;+ if( !aiReleaseWave( power, WAVE_POWER, heldFrames, WAVE_MAX_HOLD_FRAMES ) )+ return;++ const AsciiString requested = m_heldLabel[ first ];+ const Int pathSuffix = m_heldSuffix[ first ];++ AIGroup *wave = TheAI->createGroup();+ for( Int i = 0; i < MAX_HELD_TEAMS; ++i )+ {+ if( !m_heldUsed[ i ] )+ continue;+ m_heldUsed[ i ] = FALSE;+ Team *team = TheTeamFactory->findTeamByID( m_heldTeam[ i ] );+ if( team == NULL )+ continue;+ for( DLINK_ITERATOR<Object> iter = team->iterate_TeamMemberList(); !iter.done(); iter.advance() )+ {+ Object *obj = iter.cur();+ if( obj && !obj->isEffectivelyDead() && obj->getAI() )+ wave->add( obj );+ }+ }++ Coord3D center;+ wave->getCenter( ¢er );+ const AsciiString approach = chooseApproachLabel( ¢er, requested, pathSuffix );+ AsciiString pathLabel;+ pathLabel.format( "%s%d", approach.str(), pathSuffix );+ Waypoint *way = TheTerrainLogic->getClosestWaypointOnPath( ¢er, pathLabel );+ DEBUG_LOG(("AI WAVE frame %d player %d sends %d teams, %d units, %.0f power, after %d s, down %s\n", TheGameLogic->getFrame(),+ m_player->getPlayerIndex(), teams, wave->getCount(), power, heldFrames / LOGICFRAMES_PER_SECOND, pathLabel.str()));+ if( way )+ wave->groupFollowWaypointPathAsTeam( way, CMD_FROM_AI );+}+//----------------------------------------------------------------------------------------------------------/** 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@@ -5214,7 +5794,7 @@ void AIPlayer::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 5; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer+ XferVersion currentVersion = 6; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked wavesXferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );@@ -5401,6 +5981,18 @@ void AIPlayer::xfer( Xfer *xfer )xfer->xferObjectID( &m_capturerID );xfer->xferInt( &m_captureTimer );}+ // the attack teams parked at the staging point, so a loaded game sends the same wave+ if( version >= 6 )+ {+ for( Int held = 0; held < MAX_HELD_TEAMS; ++held )+ {+ xfer->xferBool( &m_heldUsed[ held ] );+ xfer->xferUnsignedInt( &m_heldTeam[ held ] );+ xfer->xferAsciiString( &m_heldLabel[ held ] );+ xfer->xferInt( &m_heldSuffix[ held ] );+ }+ xfer->xferUnsignedInt( &m_heldSince );+ }// the ladder rung and the role, which are rolled once and must come back the same wayif( version >= 3 )diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cppindex 45d1846a5..599bd6f5f 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp@@ -366,8 +366,14 @@ Bool AISkirmishPlayer::isAGoodIdeaToBuildTeam( TeamPrototype *proto )if (!proto->evaluateProductionCondition()) {return false;}- // check build limit- if (proto->countTeamInstances() >= proto->getTemplateInfo()->m_maxInstances){+ // check build limit, which a hoard raises for attack teams; defence teams keep the data's+ const TeamTemplateInfo *info = proto->getTemplateInfo();+ Int allowedInstances = info->m_maxInstances;+ if (!info->m_isBaseDefense && !info->m_isPerimeterDefense) {+ allowedInstances = aiHoardAllowedTeamInstances( allowedInstances, m_player->getMoney()->countMoney(),+ getSkillProfile()->m_cashHoardThreshold );+ }+ if (proto->countTeamInstances() >= allowedInstances){if (TheGlobalData->m_debugAI) {AsciiString str;str.format("Team %s not chosen - %d already exist.", proto->getName().str(), proto->countTeamInstances());diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cppindex 72cdb6c6e..eb2195a15 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp@@ -1712,7 +1712,10 @@ void ScriptActions::doTeamFollowSkirmishApproachPath(const AsciiString& teamNameInt mpNdx = enemyPlayer->getMpStartIndex()+1;AsciiString pathLabel;- pathLabel.format("%s%d", waypointPathLabel.str(), mpNdx);+ // the script names the approach; an AI that reads the map may take a quieter one+ const AsciiString lane = theTeam->getControllingPlayer() ?+ theTeam->getControllingPlayer()->chooseApproachLabel( &pos, waypointPathLabel, mpNdx ) : waypointPathLabel;+ pathLabel.format("%s%d", lane.str(), mpNdx);Waypoint *way = TheTerrainLogic->getClosestWaypointOnPath( &pos, pathLabel );if (!way) {return;@@ -1724,7 +1727,12 @@ void ScriptActions::doTeamFollowSkirmishApproachPath(const AsciiString& teamName}DEBUG_ASSERTLOG(TheTerrainLogic->isPurposeOfPath(way, pathLabel), ("***Wrong waypoint purpose. Make jba fix this.\n"));- if (asTeam)+ // an AI that masses parks a team too small to be a wave, and sends it later with the rest+ if (theTeam->getControllingPlayer() && theTeam->getControllingPlayer()->holdTeamForWave(theTeam, lane, mpNdx))+ {+ return;+ }+ if (asTeam){theGroup->groupFollowWaypointPathAsTeam(way, CMD_FROM_SCRIPT);} else {@@ -1771,7 +1779,10 @@ void ScriptActions::doTeamMoveToSkirmishApproachPath(const AsciiString& teamNameInt mpNdx = enemyPlayer->getMpStartIndex()+1;AsciiString pathLabel;- pathLabel.format("%s%d", waypointPathLabel.str(), mpNdx);+ // the script names the approach; an AI that reads the map may take a quieter one+ const AsciiString lane = theTeam->getControllingPlayer() ?+ theTeam->getControllingPlayer()->chooseApproachLabel( &pos, waypointPathLabel, mpNdx ) : waypointPathLabel;+ pathLabel.format("%s%d", lane.str(), mpNdx);/* This action is the slowest single thing left in a four-player skirmish frame - 40ms of a 45mslogic frame, once or twice a match, on the frame a team is told to take its approach path.The script engine already lets only one of these through per frame. The three parts arediff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 1d46fa097..e551c8381 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -8152,10 +8152,7 @@ TEST(the_difficulty_ladder_climbs_in_every_direction_it_should)CHECK( upper.m_retreatIndividualUnits >= lower.m_retreatIndividualUnits );CHECK( upper.m_retreatTeams >= lower.m_retreatTeams );CHECK( upper.m_useInfluenceMapForAttackLane >= lower.m_useInfluenceMapForAttackLane );- // ... and it is off at every rung today: measured against itself with the lane as the only- // difference and both seats played, it went 7-9 over 32 matches. See the note on the table- // in AI.cpp before switching it back on.- CHECK( !upper.m_useInfluenceMapForAttackLane );+ CHECK( upper.m_economyBuildings >= lower.m_economyBuildings );CHECK( upper.m_focusFire >= lower.m_focusFire );CHECK( upper.m_savesSciencePoints >= lower.m_savesSciencePoints );CHECK( upper.m_adaptiveHarvesters >= lower.m_adaptiveHarvesters );@@ -8184,51 +8181,103 @@ TEST(the_difficulty_ladder_climbs_in_every_direction_it_should)tanks. */TEST(counter_score_answers_what_the_enemy_actually_fields){- AIEnemyComposition allAir;- allAir.m_air = 1.0f;-- AITeamCapability aa; aa.m_hitsAir = TRUE;- AITeamCapability tanks; tanks.m_hitsGround = TRUE; tanks.m_prefersVehicles = TRUE;-- // against an all-air enemy the AA team is the answer and the tank team is not- CHECK_NEAR( 1.0f, aiCounterScore( allAir, aa ), 0.0001f );- CHECK_NEAR( 0.0f, aiCounterScore( allAir, tanks ), 0.0001f );-- // against an all-armour enemy it is the other way round: anti-tank scores its share plus the- // quarter share every ground-capable team gets- AIEnemyComposition allArmour;- allArmour.m_armour = 1.0f;- CHECK_NEAR( 1.0f, aiCounterScore( allArmour, tanks ), 0.0001f );- CHECK_NEAR( 0.0f, aiCounterScore( allArmour, aa ), 0.0001f );-- // a team that can only shoot the ground is worth something against a ground army, but far less- // than one built for it- AITeamCapability generic; generic.m_hitsGround = TRUE;- CHECK_NEAR( 0.25f, aiCounterScore( allArmour, generic ), 0.0001f );- CHECK( aiCounterScore( allArmour, generic ) < aiCounterScore( allArmour, tanks ) );+ // the matchups are the score: a team whose units beat the visible army money for money is the+ // answer, and one whose units lose to it is not+ AIEnemyComposition ground;+ ground.m_armour = 1.0f;+ AITeamCapability antiTank; antiTank.m_answer = 0.9f;+ AITeamCapability rifles; rifles.m_answer = 0.2f;+ CHECK_NEAR( 0.9f, aiCounterScore( ground, antiTank ), 0.0001f );+ CHECK( aiCounterScore( ground, antiTank ) > aiCounterScore( ground, rifles ) );// stealth is the case A1 created: the AI stopped shooting through fog, so a detector earns its// place the moment the enemy fields anything that can hideAIEnemyComposition halfStealth;halfStealth.m_armour = 1.0f;halfStealth.m_stealth = 0.5f;- AITeamCapability detector; detector.m_hitsGround = TRUE; detector.m_detectsStealth = TRUE;- CHECK( aiCounterScore( halfStealth, detector ) > aiCounterScore( halfStealth, generic ) );+ AITeamCapability detector = rifles;+ detector.m_detectsStealth = TRUE;+ CHECK( aiCounterScore( halfStealth, detector ) > aiCounterScore( halfStealth, rifles ) );// seen nothing yet -> no opinion, whatever the team is. The static priority then decides,// which is EA's behaviour and the right fallback.AIEnemyComposition unknown;- CHECK_NEAR( 0.0f, aiCounterScore( unknown, aa ), 0.0001f );- CHECK_NEAR( 0.0f, aiCounterScore( unknown, tanks ), 0.0001f );+ AITeamCapability nothingSeen;+ CHECK_NEAR( 0.0f, aiCounterScore( unknown, nothingSeen ), 0.0001f );// the score is a share, so it never leaves 0..1 however many terms a team answers- AIEnemyComposition mixed;- mixed.m_air = 0.4f; mixed.m_armour = 0.4f; mixed.m_infantry = 0.2f; mixed.m_stealth = 0.3f;AITeamCapability everything;- everything.m_hitsAir = everything.m_hitsGround = everything.m_detectsStealth = TRUE;- everything.m_prefersVehicles = everything.m_prefersInfantry = TRUE;- CHECK( aiCounterScore( mixed, everything ) <= 1.0f );- CHECK( aiCounterScore( mixed, everything ) > aiCounterScore( mixed, generic ) );+ everything.m_answer = 1.0f;+ everything.m_detectsStealth = TRUE;+ CHECK_NEAR( 1.0f, aiCounterScore( halfStealth, everything ), 0.0001f );+}+++/** The shot arithmetic under every matchup, checked against numbers read straight out of Weapon.ini+ and the Object INI rather than numbers made up to fit. */+TEST(frames_to_kill_counts_shots_delays_and_reloads)+{+ // Crusader on Crusader: 480 health, CrusaderTankGun does 60 a shell every 2000 ms (60 frames),+ // no clip. Eight shells, each paying one delay.+ AIShotPattern crusaderGun;+ crusaderGun.m_damagePerShot = 60.0f;+ crusaderGun.m_delayFrames = 60.0f;+ CHECK_NEAR( 480.0f, aiFramesToKill( 480.0f, crusaderGun ), 0.001f );++ // the same shell through HumanArmor's 10% on a 120-health Rebel: twenty shells, not two+ AIShotPattern crusaderOnInfantry = crusaderGun;+ crusaderOnInfantry.m_damagePerShot = 6.0f;+ CHECK_NEAR( 1200.0f, aiFramesToKill( 120.0f, crusaderOnInfantry ), 0.001f );++ // a clip of two with a long reload: the third shot waits for the reload, not the delay+ AIShotPattern clip;+ clip.m_damagePerShot = 50.0f;+ clip.m_delayFrames = 10.0f;+ clip.m_clipSize = 2;+ clip.m_reloadFrames = 100.0f;+ CHECK_NEAR( 120.0f, aiFramesToKill( 150.0f, clip ), 0.001f );++ // a sniper's aim is paid once, before the first shot+ clip.m_openingFrames = 15.0f;+ CHECK_NEAR( 135.0f, aiFramesToKill( 150.0f, clip ), 0.001f );++ // overkill is one shot, and it still pays its delay: two one-shot kills tie instead of both+ // reading as instant+ CHECK_NEAR( 60.0f, aiFramesToKill( 10.0f, crusaderGun ), 0.001f );++ // a weapon the armour ignores never kills+ AIShotPattern harmless;+ harmless.m_delayFrames = 30.0f;+ CHECK_EQ( AI_CANNOT_KILL, aiFramesToKill( 480.0f, harmless ) );+}+++/** One pairing as a score: money for money, log scale, and the two directions of it sum to one. */+TEST(matchup_score_is_money_for_money)+{+ // an even fight at an even price is an even trade+ CHECK_NEAR( 0.5f, aiMatchupScore( 480.0f, 480.0f, 900.0f, 900.0f ), 0.0001f );++ // twice as fast for the same money is better, and the other side of it is worse by the same amount+ const Real faster = aiMatchupScore( 240.0f, 480.0f, 900.0f, 900.0f );+ const Real slower = aiMatchupScore( 480.0f, 240.0f, 900.0f, 900.0f );+ CHECK( faster > 0.5f );+ CHECK_NEAR( 1.0f, faster + slower, 0.0001f );++ // sixteen times better is as good as it gets+ CHECK_NEAR( 1.0f, aiMatchupScore( 30.0f, 480.0f, 900.0f, 900.0f ), 0.0001f );+ CHECK_NEAR( 1.0f, aiMatchupScore( 1.0f, 480.0f, 900.0f, 900.0f ), 0.0001f );++ // an Overlord that kills twice as fast for twice the price is no bargain+ CHECK_NEAR( 0.5f, aiMatchupScore( 240.0f, 480.0f, 1800.0f, 900.0f ), 0.0001f );++ // a unit that cannot hurt the target answers none of it; one the target cannot hurt answers all+ CHECK_NEAR( 0.0f, aiMatchupScore( AI_CANNOT_KILL, 480.0f, 900.0f, 900.0f ), 0.0001f );+ CHECK_NEAR( 1.0f, aiMatchupScore( 480.0f, AI_CANNOT_KILL, 900.0f, 900.0f ), 0.0001f );+ CHECK_NEAR( 0.0f, aiMatchupScore( AI_CANNOT_KILL, AI_CANNOT_KILL, 900.0f, 900.0f ), 0.0001f );++ // a free unit has no price to weigh, so only the kill times count+ CHECK_NEAR( faster, aiMatchupScore( 240.0f, 480.0f, 0.0f, 900.0f ), 0.0001f );}@@ -8522,6 +8571,92 @@ TEST(a_cash_hoard_shortens_the_wait_but_only_so_far)}+/** Faster waits do not spend a hoard when there is nothing left to build. On Twilight Flame a+ brutal USA banked 117,206 with every team its script allowed already on the map: the fifth wave+ teams allow one copy each, so it only ever replaced losses. A hoard buys more copies. */+TEST(a_cash_hoard_allows_more_copies_of_a_team)+{+ // under two thresholds the data's limit stands+ CHECK_EQ( 1, aiHoardAllowedTeamInstances( 1, 4000, 4000 ) );+ CHECK_EQ( 1, aiHoardAllowedTeamInstances( 1, 7999, 4000 ) );++ // one more copy per two thresholds banked+ CHECK_EQ( 2, aiHoardAllowedTeamInstances( 1, 8000, 4000 ) );+ CHECK_EQ( 7, aiHoardAllowedTeamInstances( 5, 16000, 4000 ) );++ // and three more at most, however big the pile gets+ CHECK_EQ( 4, aiHoardAllowedTeamInstances( 1, 24000, 4000 ) );+ CHECK_EQ( 4, aiHoardAllowedTeamInstances( 1, 999999, 4000 ) );++ // a team the data never lets the AI build stays unbuildable+ CHECK_EQ( 0, aiHoardAllowedTeamInstances( 0, 999999, 4000 ) );++ // no threshold is the bottom rung, and EA's limit+ CHECK_EQ( 1, aiHoardAllowedTeamInstances( 1, 999999, 0 ) );+}+++/** B4, second attempt. The cash map aimed at the enemy's money and walked past his army, 7-9; this+ one counts the guns the AI knows about along each approach and takes the quietest. */+TEST(an_attack_takes_the_least_defended_lane)+{+ const Real quiet[3] = { 5000.0f, 800.0f, 2400.0f };+ CHECK_EQ( 1, aiLeastDefendedLane( quiet, 3, 0 ) );++ // nothing known anywhere: the lane the script asked for+ const Real unknown[3] = { 0.0f, 0.0f, 0.0f };+ CHECK_EQ( 2, aiLeastDefendedLane( unknown, 3, 2 ) );++ // a tie with the asked-for lane keeps it+ const Real tie[3] = { 800.0f, 800.0f, 2400.0f };+ CHECK_EQ( 0, aiLeastDefendedLane( tie, 3, 0 ) );++ // a lane the map does not have is never taken, however quiet it reads+ const Real missing[3] = { 3000.0f, -1.0f, 1000.0f };+ CHECK_EQ( 2, aiLeastDefendedLane( missing, 3, 0 ) );++ // ... and when the asked-for lane is the missing one, the quietest that exists+ const Real noCenter[3] = { -1.0f, 900.0f, 400.0f };+ CHECK_EQ( 2, aiLeastDefendedLane( noCenter, 3, 0 ) );++ // no lanes at all: the script's+ const Real none[3] = { -1.0f, -1.0f, -1.0f };+ CHECK_EQ( 1, aiLeastDefendedLane( none, 3, 1 ) );++}+++/** C2, second attempt: parked attack teams leave together once they are a wave, or once they have+ waited long enough - and never on a threshold measured against the enemy. */+TEST(a_parked_wave_goes_when_it_is_worth_sending_or_has_waited_long_enough)+{+ const Real WAVE = 6000.0f;+ const UnsignedInt MAX_HOLD = 2700;++ // a lone artillery piece waits for company+ CHECK( !aiReleaseWave( 900.0f, WAVE, 100, MAX_HOLD ) );++ // a wave's worth goes at once+ CHECK( aiReleaseWave( 6000.0f, WAVE, 100, MAX_HOLD ) );+ CHECK( aiReleaseWave( 9000.0f, WAVE, 0, MAX_HOLD ) );++ // and a trickle still attacks eventually+ CHECK( aiReleaseWave( 900.0f, WAVE, MAX_HOLD, MAX_HOLD ) );++ // nothing parked that can fight: nothing to send, however long+ CHECK( !aiReleaseWave( 0.0f, WAVE, MAX_HOLD * 10, MAX_HOLD ) );+}+++TEST(the_ladder_switches_on_reading_the_map_and_buying_at_the_top)+{+ TAiData data;+ CHECK( data.m_skill[ AISKILL_BRUTAL ].m_useInfluenceMapForAttackLane );+ CHECK( data.m_skill[ AISKILL_BRUTAL ].m_economyBuildings );+ CHECK( !data.m_skill[ AISKILL_EASY ].m_economyBuildings );+}++/** D8: role is the second axis - difficulty says how well the AI plays, role says what it istrying to do. The property that has to hold is that a role is a *preference*, not a bonus: theyall spend the same money, they spend it at different moments and on different things. If one