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): ai buys army upgrades and spends past a bank target
Olcay Seyganc0999ddcfd9a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 696666643..8b1151299 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -176,6 +176,7 @@ found and fixed — EA's own, not port damage.**- 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. A tank factory or a barracks gets another copy when units are waiting in its queue, and a factory that was destroyed is put back. Airfields keep going up for as long as the money is there. Supply drop zones and black markets go up one after another as soon as the bank is past a small cushion, whatever else it is buying; they used to wait until production had nothing to ask for, which on a busy map was never, and over twelve four-player matches the count went from 5 to 95. Internet centers follow that same rule. The spot search used to give up two rings outside the opening base, so a full base simply stopped. It now keeps looking further out until the map ends, for factories and power plants; the income buildings stay at home. Strategy centers, propaganda centers and palaces stop at three, so one of them blowing up leaves the tech tree standing. Extra factories still go beside the newest expansion it holds, nearer the fighting. China trains a hacker from every barracks that has room in its queue, not one barracks at a time: 120 hackers across those matches became 375. A hacker left standing still is put to work. It stops at six, an internet center's four plus a couple, because nothing counted them before: a Hard Tank General trained 67 over twenty thousand frames, about two thirds of everything it spent, and every one of them went through the barracks queue its army was waiting in. A player watching it from the other side of the map said China's tank general builds nothing but infantry, and he was right. Seven now, and the teams at the top of its build list are tanks. The limit grows with the match: one hacker for every four fighting units, never more than its Internet Centers have seats for plus four working outside, and never fewer than four. A computer that has not built an army does not buy an economy instead, and one with a full Internet Center and ninety units behind it keeps eight. Replays recorded before this change play out differently.- Hard saves up for what it needs most. It used to buy whatever the bank covered the moment it covered it, so the drop zone it needed waited while tank after tank rolled off the line. Every purchase is ranked now: income and power come first for the opening six minutes, the army after that, and when the top one cannot be paid for yet its price is set aside and anything that ranks lower waits until the bank holds more than that price. The saving never turns into a hoard. It lapses after forty seconds, and once the bank is past Hard's cash cushion nothing waits at all. The first drop zone and the first black market also go up in those opening minutes without waiting for the cushion. Over twenty matches with Hard computers on Winter Wolf, 27 computer players had a drop zone or black market standing where 19 had, the first one came at five and a half minutes instead of seven and a half, and 104 of them went up against 46. Replays recorded before this change play out differently.+- The computer researches upgrades on its own, and spends its bank. Upgrades used to come only from a fixed list in its plan, written before anyone knew what it would build. It now looks at the army it actually has and buys the upgrade that army gets the most out of for the price, and an army that beats what it has seen of yours counts for more. Buildings count for little there, so a GLA no longer opens with Fortified Structure. It also keeps a bank of so many seconds of its income and spends anything past that: an upgrade it would otherwise have waited on, extra units from idle factories, and on Hard another war factory or barracks whenever half a minute goes by without the bank coming down. Hard holds half a minute of income, spends what is over it on extra units at up to three times the rate it earns, builds up to eight factories, one every half minute whenever its bank passes twice what it means to keep, and starts upgrading at three minutes. Medium holds a minute, tops its army up at a tenth of Hard's rate, keeps to the factories its plan lays out and starts upgrading at seven. Easy holds two minutes, tops up at a twentieth of Hard's rate, keeps to its plan's factories too and waits twelve minutes and for a much bigger army before it buys an upgrade. Saving up for the most important purchase, which only Hard did, now runs on every difficulty, each below its own bank. Over six matches of Hard against Medium, on a build one small fix short of this one (Medium and Easy now count the factories their plan has yet to build), Hard ended on 1,600 in the bank on average where it had ended on about 12,000, and won all three that finished. Replays recorded before this change play out differently.- 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 reads the odds before it attacks. Every attack was sized the same way whoever it was aimed at, so a computer with an army at home went on waiting for a full wave while the enemy across the map had nothing left to fight with. It now weighs its own army against what it has seen of yours, and an army it cannot see it assumes is growing back towards the size of its own. It has to be looking at your buildings before it believes it is ahead. Ahead by about two to one with your base in view, Hard stops waiting and sends each group as it forms. Ahead by about six to one, the computer on any difficulty sends the guards it used to keep at home for the whole match hunting as well, half a minute apart. Outnumbered two to one, Hard and Medium keep their groups at home until twice the usual wave has gathered, and a handful is never sent into an army that size. Two leaks went with it. Units that reached the end of their road into your base used to stop there and wait for something to shoot at them; they now go looking. A group that got reinforcements at home was ordered out again as a whole, which marched the half already fighting in your base back to the middle of the map to start the walk over. Only the ones at home leave now. Over sixteen Hard against Hard matches on Twilight Flame stopped at seventeen minutes, the five that finished took 12 minutes 26 seconds on average where they had taken 13 minutes 55. The other eleven still ran to the stop: the side that is ahead kills units faster than buildings, and a defender with 120,000 in the bank replaces them at its own door. Replays recorded before this change play out differently.diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.hindex 3bfa3c037..906580ba6 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h@@ -215,6 +215,16 @@ struct AIDifficultyProfileBool m_engageGate; ///< weigh a fight by unit against unit, not money alone; nothing leaves home on its ownBool m_answerArmy; ///< remember the enemy army it has seen, and train the answer to the biggest part of itBool m_massUnit; ///< pick one unit the enemy has no answer to, build a fist of it and hit with it++ // Spending: how big a bank it keeps, and what it buys past it (AIPlayer::doSpending)+ Real m_bankTargetSeconds; ///< the bank it keeps, in seconds of its own income; 0 = no purchase queue and no spend rule+ Int m_bankTargetFloor; ///< ... and never less than this, which is all of it before any income is measured+ Real m_upgradePayoff; ///< an upgrade is bought when what it improves is worth this many times its price, half that past the bank target+ Real m_upgradeStartSeconds; ///< and not before this far into the match+ Real m_upgradeNonCombatWeight; ///< what a building or an unarmed unit counts for next to a fighting unit when an upgrade is weighed+ Real m_surplusShare; ///< of the income over aiSurplusBudget's window, how much a bank over target may train as extra units+ Int m_maxProduction; ///< war factories, barracks and airfields together, beyond which the spend rule adds none+ Real m_factoryBankMultiple; ///< past this many times the bank target a factory is added whatever the bank's trend; 0 = only on the trend};//-------------------------------------------------------------------------------------------------@@ -476,7 +486,7 @@ const UnsignedInt AI_PURCHASE_EARLY_FRAMES = 6 * 60 * LOGICFRAMES_PER_SECOND;* gatherers and no drop zone. */Int aiPurchaseScore( AIPurchaseKind kind, Bool earlyGame );-/** A Hard skirmish AI's purchase queue. Every spender asks it before it pays, with a stable key (a+/** A skirmish AI's purchase queue, on every rung with a bank target. Every spender asks it before it pays, with a stable key (a* template id), the price, its score and whether the thing could start right now (an idle factory,* a dozer). It remembers one request: the best one it could not afford. That one has the money* saved for it, and nothing that ranks below it is bought while the purchase would take the bank@@ -486,7 +496,7 @@ Int aiPurchaseScore( AIPurchaseKind kind, Bool earlyGame );* builds waiting all match and a queue that waits on all of them never buys anything. Only a* request that could start now reserves. A reservation whose spender stops asking goes after* AI_PURCHASE_STALE_FRAMES, one that is not met in AI_PURCHASE_HOLD_FRAMES goes and may not reserve- * again for as long, and above the hoard threshold (or the reserved price, if that is more) nothing+ * again for as long, and above hoardAt, the bank target (or the reserved price, if that is more) nothing* is held back at all, so the queue never makes the bank grow past one reserved price. Ties go to* the lower key. */struct AIPurchaseQueue@@ -522,6 +532,38 @@ struct AIPurchaseQueueconst UnsignedInt AI_PURCHASE_STALE_FRAMES = 20 * LOGICFRAMES_PER_SECOND;const UnsignedInt AI_PURCHASE_HOLD_FRAMES = 40 * LOGICFRAMES_PER_SECOND;+/** How long a stretch of income is measured over before the rate is taken again. */+const UnsignedInt AI_INCOME_WINDOW_FRAMES = 30 * LOGICFRAMES_PER_SECOND;++/** The bank a computer player keeps: seconds of its income, and never under the floor. */+Int aiBankTarget( Real incomePerSecond, Real seconds, Int floor );++/** Another factory, measured rather than guessed: fewer than cap stand, and the bank is over its target+ * and no lower than it was an income window ago, so what stands is not spending what comes in, or it is+ * past multiple times the target whatever its trend (a busy Hard AI's bank swings, and the trend alone+ * almost never fired). multiple 0 leaves only the trend. */+Bool aiWantsMoreProduction( Int bank, Int bankWindowAgo, Int target, Int standing, Int cap, Real multiple );++/** How much a bank over its target may put into extra units on one spend pass: share of the income of+ * AI_SURPLUS_INCOME_SECONDS, and never what takes the bank under target. At share 1 that is three+ * passes' income a pass, which drains a pile; a rung with a small share only tops its plan up. */+Int aiSurplusBudget( Int bank, Int target, Real incomePerSecond, Real share );+const Real AI_SURPLUS_INCOME_SECONDS = 30.0f;++/** What a unit counts for when an upgrade is weighed: 1 with nothing known of the enemy or no weight+ * on it, up to 2 for a unit that wins every trade against what the enemy fields and down to 0 for+ * one that loses them all. matchup is its value-weighted aiMatchupScore against the enemy army. */+Real aiCounterFit( Real matchup, Real weight );++/** What one thing an upgrade would change counts for, as a share of its price: a fighting unit its+ * aiCounterFit, a building or an unarmed unit the rung's nonCombatWeight. */+Real aiUpgradeWeight( Bool fights, Real fit, Real nonCombatWeight );++/** The upgrade to buy out of count candidates: the one whose covered value (what of the army it+ * improves, each thing weighed by aiUpgradeWeight) is the most times its price, if that is at least+ * payoff, or half of payoff when the bank is past its target. -1 for none. Ties go to the first. */+Int aiPickUpgrade( const Real *covered, const Int *cost, Int count, Real payoff, Bool overTarget );+/** 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. */diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.hindex fdbb3b6ea..bad84d15f 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h@@ -340,10 +340,25 @@ protected:* tech building so one of them blowing up leaves the tree standing. */virtual void doSuperweapons(void);- /** The purchase queue (AIPurchaseQueue): every Hard skirmish spender asks before it pays, and the- * thing at the top that cannot be afforded yet has the money saved for it. Off, every ask is yes- * and the engine's own money check decides, as before. */+ /** The purchase queue (AIPurchaseQueue): every skirmish spender asks before it pays, on every rung+ * with a bank target, and the thing at the top that cannot be afforded yet has the money saved for+ * it. Off, every ask is yes and the engine's own money check decides, as before. */Bool purchaseQueueOn(void);++ /** The spend rule, on every rung with a bank target. Measures the income, and with the bank past+ * aiBankTarget spends what is over it: upgrades at half the payoff, extra units from idle factories+ * within aiSurplusBudget, and another factory when the bank has not come down over an income window+ * (aiWantsMoreProduction). Upgrades that pay for the army are bought below the target as well,+ * through the purchase queue. */+ void doSpending(void);+ Int bankTarget(void); ///< what the bank keeps, from the income measured last+ void buyUpgradesForArmy(Bool overTarget); ///< the player upgrade the standing army gets the most out of+ void addProductionForIncome(Int bank, Int bankWindowAgo, Int target); ///< another factory, while what stands does not bring the bank down+ void trainSurplus(Int budget); ///< a unit from each idle factory, within budget+ Int m_incomeMark; ///< money earned in all, when the income was last measured ...+ UnsignedInt m_incomeMarkFrame; ///< ... and the frame, 0 for never+ Int m_bankMark; ///< ... and the bank then+ Real m_incomePerSecond; ///< smoothed over the windows measured so farBool purchaseAllowed(Int key, Int cost, AIPurchaseKind kind, Bool startable, const AsciiString &what);void purchased(Int key, Int cost, AIPurchaseKind kind, const AsciiString &what);Bool buyUnit(ProductionUpdateInterface *pu, const ThingTemplate *unit, AIPurchaseKind kind); ///< queueCreateUnit through the queuediff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex a0d51104e..e3540218d 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -2609,6 +2609,10 @@ static void updateHeadlessRun( void )// the exchange in money, on a line of its own so the PLAYER line's readers keep matching itDEBUG_LOG(("HEADLESS VALUE %d: units worth %d lost, %d killed\n", i,score->getUnitValueLost(), score->getUnitValueDestroyed()));+ // the bank as it stands. Starting money plus earned minus spent is not it: the score keeper's+ // spent counts buildings and upgrades and never a unit, and that sum read a Hard AI ending on+ // under 2,000 as one sitting on 52,000+ DEBUG_LOG(("HEADLESS BANK %d: %d in the bank\n", i, p->getMoney()->countMoney()));}if (scouting)diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cppindex 3b42bd413..0c5a6531b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp@@ -1108,12 +1108,44 @@ Real AI::getAdjustedVisionRangeForObject(const Object *object, Int factorsToCons* from 48% to 40% and stragglers from 17% to 14% of deaths; massU on top shortened the matches* and lost more for what it killed (0.70 against 0.64), so it stays off until it earns its place.*- * scoutS maxSc decis cntr mass ttk indiv team infl focus save harv expand guard hoard econ micro gate answer massU */+ *+ * The last eight columns came in on 2026-10-10, on every rung. bankS and floor are the bank each+ * rung keeps before it spends past its plan: Hard holds thirty seconds of its income, Medium a+ * minute, Easy two, and the floor is the whole target until an income is measured. Below the+ * target the purchase queue saves for the best thing it cannot afford; above it nothing is saved+ * for and an upgrade needs half the payoff. payoff and upgr are when an upgrade is worth its+ * price: what it improves has to be worth that many times the price, and the match has to be that+ * many seconds old. nonc is what a building or an unarmed unit counts for there next to a fighting+ * unit. share is how much of thirty seconds' income an idle factory may turn into extra units on+ * a pass with the bank over target, and maxF the most war factories, barracks and airfields the+ * rule puts up, one an income window while the bank is over target and not falling, or past fMult+ * times the target whatever it is doing (0 for never).+ *+ * The first cut counted buildings at full price, so Fortified Structure was every GLA's first+ * upgrade; spent every idle factory's worth of surplus on every rung, so Medium's peak army rose+ * from 67 to 99 and Hard against Medium went from 3-0 to 1-1; and sized production at a guessed 60+ * a second a factory, so a Hard AI earning 93 a second wanted the two factories it had. The second+ * cut (share 0.10/0.25/1.00, maxF 3/4/8, the trend alone) took Fortified Structure off the top, but+ * Medium had idle factories, took 62 surplus units and four factories a match, peaked at 112 against+ * Hard's 112 and drew all six. So Medium and Easy keep to their plan's two war factories and a+ * barracks (maxF 3, with the plan's unbuilt ones counted, so the rule adds none), and their share is+ * cut to 0.10 and 0.05: Medium's 62 surplus units at 0.25 become about 25, the 25 Easy took at 0.10+ * when its army was fine, and Easy's half of that keeps it under Medium. Hard alone adds factories,+ * and also past twice its target whatever the trend (fMult). With that Hard beat Medium 3-0 over+ * 45,000 frames and Medium beat Easy 4-0.+ *+ * Hard's hoard was never there in the mirror. The batch read the bank as starting money plus earned+ * minus spent, and the score keeper's spent counts buildings and upgrades and never a unit: that sum+ * said 52,000 to 59,000 where the bank itself ended between 10 and 4,000, before this rule and after+ * it. Against Medium it ended on 12,300 on average before and 1,600 after. HEADLESS BANK prints the+ * bank itself now.+ *+ * scoutS maxSc decis cntr mass ttk indiv team infl focus save harv expand guard hoard econ micro gate answer massU bankS floor payoff upgr nonc share maxF fMult */static const AIDifficultyProfile s_defaultSkillLadder[ AISKILL_COUNT ] ={- /* Easy */ { 75.0f, 1, 7.0f, 0.00f, FALSE, 0.00f, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, 0, FALSE, FALSE, FALSE, FALSE, FALSE },- /* Medium */ { 45.0f, 1, 3.0f, 0.50f, FALSE, 0.35f, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, 6000, FALSE, FALSE, FALSE, FALSE, FALSE },- /* Brutal */ { 25.0f, 2, 1.5f, 1.00f, TRUE, 0.50f, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 4000, TRUE, TRUE, TRUE, TRUE, FALSE }+ /* Easy */ { 75.0f, 1, 7.0f, 0.00f, FALSE, 0.00f, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, 0, FALSE, FALSE, FALSE, FALSE, FALSE, 120.0f, 6000, 4.0f, 720.0f, 0.05f, 0.05f, 3, 0.0f },+ /* Medium */ { 45.0f, 1, 3.0f, 0.50f, FALSE, 0.35f, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, 6000, FALSE, FALSE, FALSE, FALSE, FALSE, 60.0f, 5000, 2.5f, 420.0f, 0.05f, 0.10f, 3, 0.0f },+ /* Hard */ { 25.0f, 2, 1.5f, 1.00f, TRUE, 0.50f, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 4000, TRUE, TRUE, TRUE, TRUE, FALSE, 30.0f, 4000, 1.5f, 180.0f, 0.05f, 1.00f, 8, 2.0f }};//-------------------------------------------------------------------------------------------------@@ -1471,6 +1503,63 @@ AIPurchaseQueue::Verdict AIPurchaseQueue::ask( Int key, Int cost, Int score, Booreturn RESERVED;}+//-------------------------------------------------------------------------------------------------+Int aiBankTarget( Real incomePerSecond, Real seconds, Int floor )+{+ const Int byIncome = REAL_TO_INT_FLOOR( incomePerSecond * seconds );+ return byIncome > floor ? byIncome : floor;+}++//-------------------------------------------------------------------------------------------------+Bool aiWantsMoreProduction( Int bank, Int bankWindowAgo, Int target, Int standing, Int cap, Real multiple )+{+ if( standing >= cap || bank <= target )+ return FALSE;+ return bank >= bankWindowAgo || (multiple > 0.0f && INT_TO_REAL( bank ) > multiple * INT_TO_REAL( target ));+}++//-------------------------------------------------------------------------------------------------+Int aiSurplusBudget( Int bank, Int target, Real incomePerSecond, Real share )+{+ const Int excess = bank - target;+ if( excess <= 0 )+ return 0;+ const Int byIncome = REAL_TO_INT_FLOOR( share * incomePerSecond * AI_SURPLUS_INCOME_SECONDS );+ return byIncome < excess ? byIncome : excess;+}++//-------------------------------------------------------------------------------------------------+Real aiCounterFit( Real matchup, Real weight )+{+ return 1.0f + weight * (2.0f * matchup - 1.0f);+}++//-------------------------------------------------------------------------------------------------+Real aiUpgradeWeight( Bool fights, Real fit, Real nonCombatWeight )+{+ return fights ? fit : nonCombatWeight;+}++//-------------------------------------------------------------------------------------------------+Int aiPickUpgrade( const Real *covered, const Int *cost, Int count, Real payoff, Bool overTarget )+{+ const Real needed = overTarget ? 0.5f * payoff : payoff;+ Int best = -1;+ Real bestTimes = 0.0f;+ for( Int i = 0; i < count; ++i )+ {+ if( cost[ i ] <= 0 || covered[ i ] <= 0.0f )+ continue;+ const Real times = covered[ i ] / INT_TO_REAL( cost[ i ] );+ if( times >= needed && (best < 0 || times > bestTimes) )+ {+ best = i;+ bestTimes = times;+ }+ }+ return best;+}+//-------------------------------------------------------------------------------------------------Int aiLeastDefendedLane( const Real *laneFirepower, Int laneCount, Int requestedLane ){@@ -1692,6 +1781,14 @@ void AI::parseSkillLevel(INI *ini, void *instance, void* /*store*/, const void*{ "EngageGate", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_engageGate ) },{ "AnswerArmy", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_answerArmy ) },{ "MassUnit", INI::parseBool, NULL, offsetof( AIDifficultyProfile, m_massUnit ) },+ { "BankTargetSeconds", INI::parseReal, NULL, offsetof( AIDifficultyProfile, m_bankTargetSeconds ) },+ { "BankTargetFloor", INI::parseInt, NULL, offsetof( AIDifficultyProfile, m_bankTargetFloor ) },+ { "UpgradePayoff", INI::parseReal, NULL, offsetof( AIDifficultyProfile, m_upgradePayoff ) },+ { "UpgradeStartSeconds", INI::parseReal, NULL, offsetof( AIDifficultyProfile, m_upgradeStartSeconds ) },+ { "UpgradeNonCombatWeight", INI::parseReal, NULL, offsetof( AIDifficultyProfile, m_upgradeNonCombatWeight ) },+ { "SurplusShare", INI::parseReal, NULL, offsetof( AIDifficultyProfile, m_surplusShare ) },+ { "MaxProduction", INI::parseInt, NULL, offsetof( AIDifficultyProfile, m_maxProduction ) },+ { "FactoryBankMultiple", INI::parseReal, NULL, offsetof( AIDifficultyProfile, m_factoryBankMultiple ) },{ NULL, NULL, NULL, 0 }};diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cppindex 970234307..273d684e2 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp@@ -380,6 +380,10 @@ m_role(AIROLE_AGGRESSIVE)m_ambulance[ slot ].spot.zero();}m_ambulanceLost = 0;+ m_incomeMark = 0;+ m_incomeMarkFrame = 0;+ m_bankMark = 0;+ m_incomePerSecond = 0.0f;m_healerSeconds = 0;m_healerClearSeconds = 0;m_captureTimer = 1;@@ -4792,6 +4796,7 @@ void AIPlayer::update( void )AI_PHASE( AIP_CAPTURE, doCapture() ); // ... and the money that is standing around.AI_PHASE( AIP_CAPTURE, doHijack() ); // Take the enemy's tanks rather than shoot them.AI_PHASE( AIP_ECONOMY, doEconomy() ); // ... and the money sitting in the bank.+ AI_PHASE( AIP_ECONOMY, doSpending() ); // Upgrades for the army, and whatever is over the bank target.AI_PHASE( AIP_POWER, doPower() ); // Keep the lights on, and out of reach.AI_PHASE( AIP_ECONOMY, doSuperweapons() ); // The big guns, as soon as they can be bought.AI_PHASE( AIP_WAVE, rememberEnemies() ); // Write down the enemy army in sight.@@ -6272,12 +6277,18 @@ void AIPlayer::doSuperweapons( void )}//-----------------------------------------------------------------------------------------------------------/** The purchase queue. Hard skirmish only, the rung that already spends on its own economy; Easy and- * Medium, and every campaign AI, buy exactly as they did. */+/** The purchase queue. Every skirmish rung with a bank target, each saving below its own target; every+ * campaign AI buys exactly as it did. *///----------------------------------------------------------------------------------------------------------Bool AIPlayer::purchaseQueueOn( void ){- return isSkirmishAI() && getSkillProfile()->m_economyBuildings && getSkillProfile()->m_cashHoardThreshold > 0;+ return isSkirmishAI() && getSkillProfile()->m_bankTargetSeconds > 0.0f;+}++Int AIPlayer::bankTarget( void )+{+ const AIDifficultyProfile *profile = getSkillProfile();+ return aiBankTarget( m_incomePerSecond, profile->m_bankTargetSeconds, profile->m_bankTargetFloor );}AIPurchaseKind AIPlayer::purchaseKindOf( const ThingTemplate *tmpl )@@ -6313,13 +6324,13 @@ Bool AIPlayer::purchaseAllowed( Int key, Int cost, AIPurchaseKind kind, Bool staheld, money));const Int score = aiPurchaseScore( kind, now < AI_PURCHASE_EARLY_FRAMES );- const AIPurchaseQueue::Verdict verdict = m_purchases.ask( key, cost, score, startable, money,- getSkillProfile()->m_cashHoardThreshold, now );+ const Int target = bankTarget();+ const AIPurchaseQueue::Verdict verdict = m_purchases.ask( key, cost, score, startable, money, target, now );if( verdict == AIPurchaseQueue::RESERVED ){m_purchaseSavingFor = what;- DEBUG_LOG(("AI QUEUE frame %d player %d saves for '%s', %d of %d in the bank, score %d\n", now,- m_player->getPlayerIndex(), what.str(), money, cost, score));+ DEBUG_LOG(("AI QUEUE frame %d player %d saves for '%s', %d of %d in the bank, score %d, bank target %d\n", now,+ m_player->getPlayerIndex(), what.str(), money, cost, score, target));}return verdict == AIPurchaseQueue::BUY;}@@ -7190,6 +7201,313 @@ void AIPlayer::answerArmy( void )}}+/** How a unit of ours trades with the enemy army this AI remembers, money for money: the value-weighted+ * mean of aiMatchupScore over every kind in it, 0.5 with nothing remembered. */+static Real armyMatchup( const ThingTemplate *tmpl, const Player *owner, const std::vector<AIVisibleEnemy> &army )+{+ const Real cost = INT_TO_REAL( tmpl->calcCostToBuild( owner ) );+ Real weighed = 0.0f;+ Real scored = 0.0f;+ for( size_t k = 0; k < army.size(); ++k )+ {+ weighed += army[ k ].m_weight;+ scored += army[ k ].m_weight * aiMatchupScore( templateFramesToKill( tmpl, army[ k ].m_template ),+ templateFramesToKill( army[ k ].m_template, tmpl ), cost, army[ k ].m_cost );+ }+ return weighed > 0.0f ? scored / weighed : 0.5f;+}++/** The fighting unit off this factory's buttons a bank over its target goes on: the best trade against+ * the remembered enemy army as far as the rung counters at all (aiCounterFit), and the dearer of two+ * that score the same, so a rung that never counters buys the heaviest thing the factory makes. Not a+ * worker, a gatherer, a hacker or a jet; a helicopter stays with the army, so it may. */+static const ThingTemplate *surplusUnit( Object *factory, const Player *owner, const std::vector<AIVisibleEnemy> &army, Real weight )+{+ const CommandSet *commandSet = TheControlBar->findCommandSet( factory->getCommandSetString() );+ if( commandSet == NULL )+ return NULL;++ const ThingTemplate *best = NULL;+ Real bestFit = 0.0f;+ Int bestCost = 0;+ for( Int i = 0; i < MAX_COMMANDS_PER_SET; ++i )+ {+ const CommandButton *button = commandSet->getCommandButton( i );+ if( button == NULL || button->getCommandType() != GUI_COMMAND_UNIT_BUILD )+ continue;+ const ThingTemplate *tmpl = button->getThingTemplate();+ if( tmpl == NULL || !tmpl->canPossiblyHaveAnyWeapon() || tmpl->isKindOf( KINDOF_DOZER ) || tmpl->isKindOf( KINDOF_HARVESTER ) ||+ tmpl->isKindOf( KINDOF_MONEY_HACKER ) || (tmpl->isKindOf( KINDOF_AIRCRAFT ) && !tmpl->isKindOf( KINDOF_PRODUCED_AT_HELIPAD )) ||+ TheBuildAssistant->canMakeUnit( factory, tmpl ) != CANMAKE_OK )+ continue;+ const Int cost = tmpl->calcCostToBuild( owner );+ const Real fit = aiCounterFit( armyMatchup( tmpl, owner, army ), weight );+ if( best == NULL || fit > bestFit || (fit == bestFit && cost > bestCost) )+ {+ best = tmpl;+ bestFit = fit;+ bestCost = cost;+ }+ }+ return best;+}++//----------------------------------------------------------------------------------------------------------+/** The bank a computer kept was the part of its income nothing was ever bought with: a Hard AI facing+ * Medium ended its matches on 12,300 on average, a Medium one on up to 62,000. So every rung+ * keeps a bank of so many seconds of what it actually earns (m_bankTargetSeconds, aiBankTarget), and+ * what is over that goes on upgrades, on extra units within the rung's share (aiSurplusBudget), and+ * on another factory once an income window shows the bank is not coming down (aiWantsMoreProduction).+ * The upgrades that pay for the standing army are bought below the target as well, each rung from+ * its own point in the match, and all of it goes through the purchase queue, which keeps below the+ * same target. */+//----------------------------------------------------------------------------------------------------------+void AIPlayer::doSpending( void )+{+ if( !purchaseQueueOn() )+ return;+ const UnsignedInt now = TheGameLogic->getFrame();+ if( (now + computeUpdatePhase( m_player->getPlayerIndex(), ECONOMY_CHECK_RATE )) % ECONOMY_CHECK_RATE != 0 )+ return;++ // the income, off what the score screen counts as earned: gathered, hacked, captured and given+ const Int bank = (Int)m_player->getMoney()->countMoney();+ const Int earned = m_player->getScoreKeeper()->getTotalMoneyEarned();+ Bool windowEnded = FALSE;+ Int bankWindowAgo = bank;+ if( now - m_incomeMarkFrame >= AI_INCOME_WINDOW_FRAMES )+ {+ const Real window = INT_TO_REAL( earned - m_incomeMark ) * LOGICFRAMES_PER_SECOND / INT_TO_REAL( now - m_incomeMarkFrame );+ windowEnded = m_incomeMarkFrame != 0; // the first window has no bank before it to compare with+ bankWindowAgo = m_bankMark;+ m_incomePerSecond = m_incomeMarkFrame == 0 ? window : 0.5f * (m_incomePerSecond + window);+ m_incomeMark = earned;+ m_incomeMarkFrame = now;+ m_bankMark = bank;+ DEBUG_LOG(("AI ECONOMY frame %d player %d earns %.0f a second, %d in the bank (%d a window ago), bank target %d, %s\n", now,+ m_player->getPlayerIndex(), m_incomePerSecond, bank, bankWindowAgo, bankTarget(), bank > bankTarget() ? "spends the rest" : "keeps it"));+ }++ if( isBaseUnderAttack() )+ return; // defendHome's+ const Int target = bankTarget();+ const Bool overTarget = bank > target;+ buyUpgradesForArmy( overTarget );+ if( !overTarget )+ return;+ if( windowEnded )+ addProductionForIncome( bank, bankWindowAgo, target );+ trainSurplus( aiSurplusBudget( (Int)m_player->getMoney()->countMoney(), target, m_incomePerSecond, getSkillProfile()->m_surplusShare ) );+}++//----------------------------------------------------------------------------------------------------------+/** Only the scripts ever bought an upgrade, from a list written before anyone knew what the AI would+ * field. This buys the one player upgrade, of every one a standing building offers, that the army on+ * the field gets the most out of for its price: every fighting unit the upgrade would change counts+ * at its price weighed by how it trades with the enemy army this AI remembers (aiCounterFit, as far+ * as the rung counters), a building or an unarmed unit at m_upgradeNonCombatWeight of its price (at+ * full price a GLA base made Fortified Structure the first upgrade of every match), and it is bought when that sum is m_upgradePayoff times+ * the price, half that when the bank is over its target. One a pass, not before m_upgradeStartSeconds,+ * at the building with the shortest queue that offers it, through the purchase queue like everything+ * else. */+//----------------------------------------------------------------------------------------------------------+void AIPlayer::buyUpgradesForArmy( Bool overTarget )+{+ const AIDifficultyProfile *profile = getSkillProfile();+ const UnsignedInt now = TheGameLogic->getFrame();+ if( INT_TO_REAL( now ) < profile->m_upgradeStartSeconds * LOGICFRAMES_PER_SECOND )+ return;++ // every player upgrade a building of ours offers and we could start: not owned, not on order, every+ // science its button asks for held+ std::vector<Object *> factories;+ m_player->iterateObjects( collectFactories, &factories );+ std::vector<const UpgradeTemplate *> upgrades;+ std::vector<Object *> where;+ for( std::vector<Object *>::const_iterator f = factories.begin(); f != factories.end(); ++f )+ {+ const CommandSet *commandSet = TheControlBar->findCommandSet( (*f)->getCommandSetString() );+ if( commandSet == NULL )+ continue;+ const UnsignedInt queued = (*f)->getProductionUpdateInterface()->getProductionCount();+ for( Int i = 0; i < MAX_COMMANDS_PER_SET; ++i )+ {+ const CommandButton *button = commandSet->getCommandButton( i );+ if( button == NULL || button->getCommandType() != GUI_COMMAND_PLAYER_UPGRADE || button->getUpgradeTemplate() == NULL )+ continue;+ const UpgradeTemplate *upgrade = button->getUpgradeTemplate();+ if( m_player->hasUpgradeComplete( upgrade ) || m_player->hasUpgradeInProduction( upgrade ) )+ continue;+ Bool sciences = TRUE;+ for( size_t s = 0; s < button->getScienceVec().size(); ++s )+ if( !m_player->hasScience( button->getScienceVec()[ s ] ) )+ sciences = FALSE;+ if( !sciences )+ continue;+ size_t u = 0;+ while( u < upgrades.size() && upgrades[ u ] != upgrade )+ ++u;+ if( u == upgrades.size() )+ {+ upgrades.push_back( upgrade );+ where.push_back( *f );+ }+ else if( queued < where[ u ]->getProductionUpdateInterface()->getProductionCount() )+ where[ u ] = *f;+ }+ }+ if( upgrades.empty() )+ return;++ // what each would improve, a fighting unit at its price times how it trades+ std::vector<AIVisibleEnemy> army;+ rememberedArmy( &army );+ std::vector<Object *> owned;+ m_player->iterateObjects( collectOwned, &owned );+ std::vector<Real> covered( upgrades.size(), 0.0f );+ std::vector<const ThingTemplate *> fitTemplate; // the fit by template, worked out once a pass+ std::vector<Real> fitValue;+ for( std::vector<Object *>::const_iterator o = owned.begin(); o != owned.end(); ++o )+ {+ const Object *obj = *o;+ if( obj->isEffectivelyDead() || obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )+ continue;+ const ThingTemplate *tmpl = obj->getTemplate();+ const Bool fights = !obj->isKindOf( KINDOF_STRUCTURE ) && tmpl->canPossiblyHaveAnyWeapon();+ Real fit = 1.0f;+ if( fights && !army.empty() )+ {+ size_t t = 0;+ while( t < fitTemplate.size() && fitTemplate[ t ] != tmpl )+ ++t;+ if( t == fitTemplate.size() )+ {+ fitTemplate.push_back( tmpl );+ fitValue.push_back( aiCounterFit( armyMatchup( tmpl, m_player, army ), profile->m_counterCompositionWeight ) );+ }+ fit = fitValue[ t ];+ }+ const Real value = aiUpgradeWeight( fights, fit, profile->m_upgradeNonCombatWeight ) * INT_TO_REAL( tmpl->calcCostToBuild( m_player ) );+ for( size_t u = 0; u < upgrades.size(); ++u )+ if( obj->affectedByUpgrade( upgrades[ u ] ) )+ covered[ u ] += value;+ }++ std::vector<Int> cost( upgrades.size(), 0 );+ for( size_t u = 0; u < upgrades.size(); ++u )+ cost[ u ] = upgrades[ u ]->calcCostToBuild( m_player );+ const Int pick = aiPickUpgrade( &covered[ 0 ], &cost[ 0 ], (Int)upgrades.size(), profile->m_upgradePayoff, overTarget );+ if( pick < 0 )+ return;+ if( buyUpgrade( where[ pick ]->getProductionUpdateInterface(), upgrades[ pick ] ) )+ DEBUG_LOG(("AI UPGRADE frame %d player %d queues '%s' at '%s' for %d, improves %.0f of what it owns, %.1f times the price where %.1f will do, %d in the bank, bank target %d, %d enemy kinds known\n",+ now, m_player->getPlayerIndex(), upgrades[ pick ]->getUpgradeName().str(), where[ pick ]->getTemplate()->getName().str(),+ cost[ pick ], covered[ pick ], covered[ pick ] / INT_TO_REAL( cost[ pick ] ),+ overTarget ? 0.5f * profile->m_upgradePayoff : profile->m_upgradePayoff, m_player->getMoney()->countMoney(), bankTarget(),+ (Int)army.size()));+}++//----------------------------------------------------------------------------------------------------------+/** Another tank factory or barracks, whichever the base has fewer of, when an income window ends with+ * the bank over its target and no lower than a window before, or past m_factoryBankMultiple times the+ * target (aiWantsMoreProduction): what stands is not spending what comes in. One at a time, and no more than the rung's m_maxProduction war+ * factories, barracks and airfields together. A guessed spend rate a factory stood here first: a+ * Hard AI earning 93 a second wanted the two factories it had. Unbuilt plan entries count as standing,+ * or the rule adds the factory the plan is about to put up. */+//----------------------------------------------------------------------------------------------------------+void AIPlayer::addProductionForIncome( Int bank, Int bankWindowAgo, Int target )+{+ if( !m_player->getCanBuildBase() || !m_baseCenterSet )+ return;++ const Int KINDS = 3;+ const KindOfType PRODUCTION[ KINDS ] = { KINDOF_FS_WARFACTORY, KINDOF_FS_BARRACKS, KINDOF_FS_AIRFIELD };+ Int standing[ KINDS ];+ Int total = 0;+ for( Int k = 0; k < KINDS; ++k )+ {+ FactoryLoad load;+ load.kind = PRODUCTION[ k ];+ load.finished = 0;+ load.constructing = 0;+ load.idle = 0;+ load.deepest = 0;+ m_player->iterateObjects( readFactoryLoad, &load );+ if( load.constructing > 0 )+ return; // one at a time+ standing[ k ] = load.finished;+ total += load.finished;+ }+ // ... and the ones the plan has yet to put up count as standing: early on a Medium plan of two war+ // factories and a barracks had two up, and the rule added the third the plan was about to build+ Int planned = 0;+ for( BuildListInfo *info = m_player->getBuildList(); info; info = info->getNext() )+ {+ if( info->getObjectID() != INVALID_ID || !info->isBuildable() )+ continue;+ const ThingTemplate *tmpl = TheThingFactory->findTemplate( info->getTemplateName(), FALSE );+ for( Int k = 0; tmpl && k < KINDS; ++k )+ if( tmpl->isKindOf( PRODUCTION[ k ] ) )+ {+ ++planned;+ break;+ }+ }+ total += planned;+ const Int cap = getSkillProfile()->m_maxProduction;+ if( !aiWantsMoreProduction( bank, bankWindowAgo, target, total, cap, getSkillProfile()->m_factoryBankMultiple ) )+ return;++ Object *dozer = NULL;+ m_player->iterateObjects( findAnyDozer, &dozer );+ if( dozer == NULL )+ return;+ const Int first = standing[ 1 ] < standing[ 0 ] ? 1 : 0;+ for( Int k = 0; k < 2; ++k )+ {+ const KindOfType kind = PRODUCTION[ k == 0 ? first : 1 - first ];+ if( queueExtraFactory( dozer, kind, TRUE ) )+ {+ DEBUG_LOG(("AI ECONOMY frame %d player %d puts up another %s, %d of at most %d standing (%d of them planned), %d in the bank (%d a window ago), bank target %d, %.0f a second of income\n",+ TheGameLogic->getFrame(), m_player->getPlayerIndex(), kind == KINDOF_FS_WARFACTORY ? "war factory" : "barracks",+ total, cap, planned, bank, bankWindowAgo, target, m_incomePerSecond));+ return;+ }+ }+}++//----------------------------------------------------------------------------------------------------------+/** A unit from each factory with nothing in its queue, while the budget (aiSurplusBudget) covers it. It+ * joins the default team, and the next wave takes it along with the other strays. Spending every idle+ * factory's worth on every rung lifted Medium's peak army from 67 to 99 and Easy's from 34 to 67, and+ * Hard against Medium went from 3-0 to 1-1, so each rung's share of its income sets the budget. */+//----------------------------------------------------------------------------------------------------------+void AIPlayer::trainSurplus( Int budget )+{+ if( budget <= 0 )+ return;+ std::vector<AIVisibleEnemy> army;+ rememberedArmy( &army );+ std::vector<Object *> factories;+ m_player->iterateObjects( collectFactories, &factories );+ for( std::vector<Object *>::const_iterator f = factories.begin(); f != factories.end(); ++f )+ {+ ProductionUpdateInterface *pu = (*f)->getProductionUpdateInterface();+ if( pu->getProductionCount() > 0 )+ continue;+ const ThingTemplate *unit = surplusUnit( *f, m_player, army, getSkillProfile()->m_counterCompositionWeight );+ if( unit == NULL )+ continue;+ const Int cost = unit->calcCostToBuild( m_player );+ if( cost > budget || !buyUnit( pu, unit, AIBUY_ARMY ) )+ continue;+ budget -= cost;+ DEBUG_LOG(("AI ECONOMY frame %d player %d trains '%s' at '%s' out of the surplus, %d of the budget left, %d in the bank\n",+ TheGameLogic->getFrame(), m_player->getPlayerIndex(), unit->getName().str(), (*f)->getTemplate()->getName().str(),+ budget, m_player->getMoney()->countMoney()));+ }+}+/** The fist. How often it is looked at; what the enemy army has to be worth before a unit is picked* against it, and how long a dropped pick waits before the next; how good an enemy kind has to be* against the unit to count as his answer, and how much of his army that answer has to be before the@@ -13191,7 +13509,7 @@ void AIPlayer::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 21; // 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 14: gunship Chinooks and the boarding wait 15: transport Chinooks and the lent one 16: healer and raider Helixes 17: the seen-enemy ledger 18: the fist 19: the Ambulances 20: the last Ambulance lost 21: the purchase queue's reservation+ XferVersion currentVersion = 22; // 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 14: gunship Chinooks and the boarding wait 15: transport Chinooks and the lent one 16: healer and raider Helixes 17: the seen-enemy ledger 18: the fist 19: the Ambulances 20: the last Ambulance lost 21: the purchase queue's reservation 22: the measured incomeXferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );@@ -13585,6 +13903,13 @@ void AIPlayer::xfer( Xfer *xfer )xfer->xferUnsignedInt( &m_purchases.m_lapsedUntil );xfer->xferAsciiString( &m_purchaseSavingFor );}+ if( version >= 22 )+ {+ xfer->xferInt( &m_incomeMark );+ xfer->xferUnsignedInt( &m_incomeMarkFrame );+ xfer->xferInt( &m_bankMark );+ xfer->xferReal( &m_incomePerSecond );+ }// the ladder rung and the role, which are rolled once and must come back the same wayif( version >= 3 )diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 4da2f2af9..789f9d470 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -11777,6 +11777,105 @@ TEST(the_purchase_queue_saves_for_the_best_thing_it_cannot_afford)}+/** The spend rule and the upgrades: a bank of so many seconds of income, factories enough to spend the+ income, and the upgrade the army gets the most out of for its price. Each rung has its own values,+ and the ladder has to climb: Hard keeps the smallest bank and buys upgrades soonest and cheapest. */+TEST(the_bank_target_and_the_upgrade_the_army_pays_for)+{+ // seconds of income, never under the floor; nothing earned yet is the floor alone+ CHECK_EQ( 4000, aiBankTarget( 0.0f, 30.0f, 4000 ) );+ CHECK_EQ( 4000, aiBankTarget( 100.0f, 30.0f, 4000 ) );+ CHECK_EQ( 6000, aiBankTarget( 200.0f, 30.0f, 4000 ) );+ CHECK_EQ( 12000, aiBankTarget( 200.0f, 60.0f, 4000 ) );++ // another factory only when the bank is over target and has not come down over the window, and the+ // rung's cap is not reached: the first cut sized it from income and a Hard AI earning 93 a second+ // never added one to the two it had+ CHECK( aiWantsMoreProduction( 56700, 56000, 4000, 2, 8, 0.0f ) ); // over target and still rising+ CHECK( aiWantsMoreProduction( 9000, 9000, 4000, 2, 8, 0.0f ) ); // over target and flat+ CHECK( !aiWantsMoreProduction( 9000, 12000, 4000, 2, 8, 0.0f ) ); // coming down: what stands spends it+ CHECK( !aiWantsMoreProduction( 3000, 1000, 4000, 2, 8, 2.0f ) ); // under target+ CHECK( !aiWantsMoreProduction( 56700, 56000, 4000, 8, 8, 2.0f ) ); // at the cap+ CHECK( !aiWantsMoreProduction( 56700, 56000, 4000, 3, 3, 2.0f ) );+ // a busy Hard AI's bank swings, so past twice the target it adds one whatever the trend+ CHECK( aiWantsMoreProduction( 52200, 60000, 4000, 4, 8, 2.0f ) );+ CHECK( !aiWantsMoreProduction( 8000, 9000, 4000, 4, 8, 2.0f ) ); // at twice, not past it+ CHECK( !aiWantsMoreProduction( 52200, 60000, 4000, 4, 8, 0.0f ) ); // a rung without the multiple++ // the surplus budget: the rung's share of thirty seconds' income, never past the excess+ CHECK_EQ( 0, aiSurplusBudget( 3000, 4000, 100.0f, 1.0f ) ); // under target, nothing+ CHECK_EQ( 3000, aiSurplusBudget( 60000, 4000, 100.0f, 1.0f ) ); // Hard: a window's income a pass+ CHECK_EQ( 300, aiSurplusBudget( 60000, 4000, 100.0f, 0.1f ) ); // Medium+ CHECK_EQ( 150, aiSurplusBudget( 60000, 4000, 100.0f, 0.05f ) ); // Easy+ CHECK_EQ( 500, aiSurplusBudget( 4500, 4000, 100.0f, 1.0f ) ); // the excess, when that is less+ CHECK_EQ( 0, aiSurplusBudget( 60000, 4000, 0.0f, 1.0f ) ); // nothing earned, nothing extra++ // what counts toward an upgrade: a fighting unit at its fit, anything else at the rung's small weight,+ // so a base worth 20,000 is 1,000 of reason to fortify it and a 10,000 army is 10,000 of reason to arm it+ CHECK_NEAR( 1.5f, aiUpgradeWeight( TRUE, 1.5f, 0.05f ), 0.0001f );+ CHECK_NEAR( 0.05f, aiUpgradeWeight( FALSE, 1.5f, 0.05f ), 0.0001f );+ const Real fortifyOrArm[ 2 ] = { 20000.0f * aiUpgradeWeight( FALSE, 1.0f, 0.05f ), 10000.0f * aiUpgradeWeight( TRUE, 1.0f, 0.05f ) };+ const Int fortifyOrArmCost[ 2 ] = { 1000, 2000 };+ CHECK_EQ( 1, aiPickUpgrade( fortifyOrArm, fortifyOrArmCost, 2, 1.5f, FALSE ) );++ // how a unit counts: as it is when the rung does not counter or the trade is even, double when it+ // wins every trade and nothing when it loses every one+ CHECK_NEAR( 1.0f, aiCounterFit( 0.9f, 0.0f ), 0.0001f );+ CHECK_NEAR( 1.0f, aiCounterFit( 0.5f, 1.0f ), 0.0001f );+ CHECK_NEAR( 2.0f, aiCounterFit( 1.0f, 1.0f ), 0.0001f );+ CHECK_NEAR( 0.0f, aiCounterFit( 0.0f, 1.0f ), 0.0001f );+ CHECK_NEAR( 1.25f, aiCounterFit( 1.0f, 0.25f ), 0.0001f );++ // the most army for the money wins, if it clears the payoff+ const Real covered[ 4 ] = { 3000.0f, 9000.0f, 0.0f, 2400.0f };+ const Int cost[ 4 ] = { 1000, 2000, 500, 800 };+ CHECK_EQ( 1, aiPickUpgrade( covered, cost, 4, 1.5f, FALSE ) ); // 4.5 times its price beats 3+ CHECK_EQ( -1, aiPickUpgrade( covered, cost, 4, 5.0f, FALSE ) ); // nothing pays five times over ...+ CHECK_EQ( 1, aiPickUpgrade( covered, cost, 4, 9.0f, TRUE ) ); // ... and past the target half the payoff will do+ CHECK_EQ( -1, aiPickUpgrade( covered, cost, 4, 9.5f, TRUE ) );++ // an upgrade that improves nothing we own is never bought, however cheap+ const Real nothing[ 1 ] = { 0.0f };+ const Int cheap[ 1 ] = { 1 };+ CHECK_EQ( -1, aiPickUpgrade( nothing, cheap, 1, 0.0f, TRUE ) );++ // two that pay the same: the first, so the order is the buttons' and the same on every machine+ const Real even[ 2 ] = { 4000.0f, 2000.0f };+ const Int evenCost[ 2 ] = { 2000, 1000 };+ CHECK_EQ( 0, aiPickUpgrade( even, evenCost, 2, 1.0f, FALSE ) );++ // every rung has the queue and the rule, and each step up keeps a smaller bank and buys sooner+ TAiData data;+ for( Int i = 0; i < AISKILL_COUNT; ++i )+ {+ CHECK( data.m_skill[ i ].m_bankTargetSeconds > 0.0f );+ CHECK( data.m_skill[ i ].m_bankTargetFloor > 0 );+ CHECK( data.m_skill[ i ].m_upgradePayoff > 0.0f );+ CHECK( data.m_skill[ i ].m_upgradeNonCombatWeight < 0.5f );+ CHECK( data.m_skill[ i ].m_surplusShare > 0.0f && data.m_skill[ i ].m_surplusShare <= 1.0f );+ }+ CHECK_EQ( 1.0f, data.m_skill[ AISKILL_BRUTAL ].m_surplusShare ); // Hard spends all of it+ for( Int i = 1; i < AISKILL_COUNT; ++i )+ {+ const AIDifficultyProfile &lower = data.m_skill[ i - 1 ];+ const AIDifficultyProfile &upper = data.m_skill[ i ];+ CHECK( upper.m_bankTargetSeconds < lower.m_bankTargetSeconds );+ CHECK( upper.m_bankTargetFloor <= lower.m_bankTargetFloor );+ CHECK( upper.m_upgradePayoff < lower.m_upgradePayoff );+ CHECK( upper.m_upgradeStartSeconds < lower.m_upgradeStartSeconds );+ CHECK( upper.m_surplusShare > lower.m_surplusShare );+ CHECK( upper.m_maxProduction >= lower.m_maxProduction );+ }+ // Hard alone builds past its plan, and with a bank past twice its target; Medium out-armies Easy and+ // Hard out-armies Medium, which an equal share and cap for the two lower rungs had undone+ CHECK( data.m_skill[ AISKILL_BRUTAL ].m_maxProduction > data.m_skill[ AISKILL_MEDIUM ].m_maxProduction );+ CHECK( data.m_skill[ AISKILL_BRUTAL ].m_factoryBankMultiple > 0.0f );+ CHECK_EQ( 0.0f, data.m_skill[ AISKILL_MEDIUM ].m_factoryBankMultiple );+ CHECK_EQ( 0.0f, data.m_skill[ AISKILL_EASY ].m_factoryBankMultiple );+ CHECK( data.m_skill[ AISKILL_BRUTAL ].m_surplusShare >= 5.0f * data.m_skill[ AISKILL_MEDIUM ].m_surplusShare );+}++/** B4, second attempt. The cash map aimed at the enemy's money and walked past his army, 7-9; thisone counts the guns the AI knows about along each approach and takes the quietest. */TEST(an_attack_takes_the_least_defended_lane)