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): a base under attack spends its bank on the fight
Olcay Seygandad673e2e5c3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f82db09d9..290f28d5c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -123,7 +123,7 @@ found and fixed — EA's own, not port damage.**- Its aircraft are left out of it. A retreat order was what took a parked jet off the runway, so while a fight raged near the airfield the whole wing took off, flew at the base, landed, and did it again every few seconds instead of ever reaching you. Aircraft already fly home on their own when the load is spent.- Matches finish. Two of these opponents used to fail to settle 65% of their games inside sixteen minutes; it is half that now, and they end in under seven minutes on average instead of ten.- The retreat actually happens now, on Normal as well as Hard. The order home was handed to units that were already fighting, and the game laid it over their attack instead of replacing it, so a team told to break off carried on driving at what it was shooting, and its aggressive mood turned any walk that did start into a fight on the way. A unit that makes it home gets its mood back when it stops walking.-- It no longer runs from a fight in its own base. Home was where the retreat went, so when you rushed a Normal or Hard computer early, every defender was outnumbered, read the fight as lost, and was ordered back to the middle of the base it was already standing in, walking and not shooting, again every second and a half. Sixteen rebels and four Scorpions sent into a Hard USA base a minute in went a full minute without losing one. A fight at home is now fought where it is. While the base is being hit the computer also keeps its attack groups at home: nothing it has gathered leaves on a wave, nothing waiting to leave gathers out on the road, and the groups guarding the base are no longer called away to join an attack. What was gathered goes once none of your units it knows of stands in its base, or half a minute after the last hit. It still has little to fight with a minute in; the opening goes on buildings first. Replays recorded before this change play out differently.+- It no longer runs from a fight in its own base. Home was where the retreat went, so when you rushed a Normal or Hard computer early, every defender was outnumbered, read the fight as lost, and was ordered back to the middle of the base it was already standing in, walking and not shooting, again every second and a half. Sixteen rebels and four Scorpions sent into a Hard USA base a minute in went a full minute without losing one. A fight at home is now fought where it is. While the base is being hit the computer also keeps its attack groups at home: nothing it has gathered leaves on a wave, nothing waiting to leave gathers out on the road, and the groups guarding the base are no longer called away to join an attack. What was gathered goes once none of your units it knows of stands in its base, or half a minute after the last hit. And it spends on the fight. A minute in, its opening has gone on buildings: a Hard USA had two soldiers and 8,000 in the bank when that rush arrived. Now a base under attack trains fighters from every factory that has room, each one picked against whatever of yours it has the least answer to yet, so sixteen rebels and four Scorpions get Rangers as well as Missile Defenders. It stops buying income buildings and extra factories until the fight is over, puts a gun up between the middle of its base and your units when it finds the room, and sends what it has at home at you once there is enough of it to matter; a handful sent out by twos only feeds you. Over four matches the USA left 36 of those 64 rebels alive where it had left 49. China and GLA already train at the pace their barracks allow, and came out about where they were. Replays recorded before this change play out differently.## Hard fights each unit from where it is strongestdiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.hindex 08c19f332..d1b410574 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h@@ -510,6 +510,8 @@ protected:Bool isOutOnOrders(const Object *obj) const; ///< away from home with something to doBool isAtHome(const Coord3D *pos) const; ///< within two base radii of the base centerBool isBaseUnderAttack(void) const; ///< hit lately, with a known enemy that can shoot standing at home+ Object *homeIntruder(Int *count, std::vector<AIVisibleEnemy> *army) const; ///< the enemy nearest the base center while the base is under attack+ void defendHome(void); ///< a base under attack trains fighters from its bank and sends its idle units inReal waitingPower(Team *team, AIGroup *group) const; ///< what a team has for a wave, less the members out on orders; they join the group if one is given/** How hard this AI leans on its current enemy: its chance against him, looked at again on thediff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cppindex d32262238..129cb71b3 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp@@ -5217,6 +5217,10 @@ void AIPlayer::doEconomy( void )// the hoard threshold, and each of them is bought on every pass the bank allows one ...if( m_player->getMoney()->countMoney() <= profile->m_cashHoardThreshold )return;+ // ... unless the base is being hit: then the bank and the dozers are defendHome's. A rushed China+ // put up an Internet Center and a second barracks while sixteen rebels stood in its base.+ if( isBaseUnderAttack() )+ return;buyMoneyUnits();if( !m_player->getCanBuildBase() || !m_baseCenterSet )@@ -6010,23 +6014,251 @@ Bool AIPlayer::isAtHome( const Coord3D *pos ) const* the enemy's base would have kept every wave at home. */Bool AIPlayer::isBaseUnderAttack( void ) const{+ return homeIntruder( NULL, NULL ) != NULL;+}++/** The known enemy standing nearest the base center while the base is under attack (isBaseUnderAttack),+ * how many of them stand at home and, one entry a kind, what they cost; NULL when the base is not+ * under attack. */+Object *AIPlayer::homeIntruder( Int *count, std::vector<AIVisibleEnemy> *army ) const+{+ if( count )+ *count = 0;const UnsignedInt attacked = m_player->getAttackedFrame();if( !m_baseCenterSet || attacked == 0 || attacked + 30 * LOGICFRAMES_PER_SECOND <= TheGameLogic->getFrame() )- return FALSE;+ return NULL;PartitionFilterAlive filterAlive;PartitionFilterOnMap filterOnMap;PartitionFilter *filters[] = { &filterAlive, &filterOnMap, NULL };ObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( &m_baseCenter, 2.0f * m_baseRadius, FROM_CENTER_2D, filters );MemoryPoolObjectHolder hold( iter );+ Object *nearest = NULL;+ Real nearestSqr = 0.0f;for( Object *obj = iter->first(); obj; obj = iter->next() ){if( obj->isKindOf( KINDOF_PROJECTILE ) || m_player->getRelationship( obj->getTeam() ) != ENEMIES )continue;- if( obj->isAbleToAttack() && observerKnowsAbout( obj, m_player->getPlayerIndex() ) )- return TRUE;+ if( !obj->isAbleToAttack() || !observerKnowsAbout( obj, m_player->getPlayerIndex() ) )+ continue;+ if( count == NULL )+ return obj; // only asked whether there is one+ ++*count;+ if( army )+ addToVisibleArmy( army, obj->getTemplate(), obj->getControllingPlayer(),+ INT_TO_REAL( obj->getTemplate()->calcCostToBuild( obj->getControllingPlayer() ) ) );+ const Real distSqr = sqr( obj->getPosition()->x - m_baseCenter.x ) + sqr( obj->getPosition()->y - m_baseCenter.y );+ if( nearest == NULL || distSqr < nearestSqr )+ {+ nearest = obj;+ nearestSqr = distSqr;+ }}- return FALSE;+ return nearest;+}++/** Everything that can build a unit, finished and standing. */+static void collectFactories( Object *obj, void *userData )+{+ if( obj->isEffectivelyDead() || !obj->isKindOf( KINDOF_STRUCTURE ) || obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) ||+ obj->getProductionUpdateInterface() == NULL )+ return;+ ((std::vector<Object *> *)userData)->push_back( obj );+}++static void collectOwned( Object *obj, void *userData )+{+ ((std::vector<Object *> *)userData)->push_back( obj );+}++/** A base defense of this player's is going up. */+static void findDefenseUnderConstruction( Object *obj, void *userData )+{+ if( obj->isKindOf( KINDOF_FS_BASE_DEFENSE ) && obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )+ *(Bool *)userData = TRUE;+}++/** The fighting unit off this factory's buttons that answers one kind of intruder best, money for+ * money, and the dearer of two that answer it equally. Not a worker, a gatherer, a hacker or an+ * aircraft: a jet flies its sortie and goes home, and the fight is at the door. */+static const ThingTemplate *bestDefender( Object *factory, const Player *owner, const AIVisibleEnemy &enemy )+{+ const CommandSet *commandSet = TheControlBar->findCommandSet( factory->getCommandSetString() );+ if( commandSet == NULL )+ return NULL;++ const ThingTemplate *best = NULL;+ Real bestScore = -1.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 ) ||+ TheBuildAssistant->canMakeUnit( factory, tmpl ) != CANMAKE_OK )+ continue;++ const Int cost = tmpl->calcCostToBuild( owner );+ const Real score = aiMatchupScore( templateFramesToKill( tmpl, enemy.m_template ),+ templateFramesToKill( enemy.m_template, tmpl ), INT_TO_REAL( cost ), enemy.m_cost );+ if( best == NULL || score > bestScore || (score == bestScore && cost > bestCost) )+ {+ best = tmpl;+ bestScore = score;+ bestCost = cost;+ }+ }+ return best;+}++/** Count a unit of ours, standing or on order, against the kind of intruder it answers best. */+static void creditAnswer( const ThingTemplate *tmpl, const Player *owner, const std::vector<AIVisibleEnemy> &army, std::vector<Real> *answered )+{+ if( tmpl == NULL || army.empty() || !tmpl->canPossiblyHaveAnyWeapon() )+ return;+ const Real cost = INT_TO_REAL( tmpl->calcCostToBuild( owner ) );+ size_t best = 0;+ Real bestScore = -1.0f;+ for( size_t k = 0; k < army.size(); ++k )+ {+ const Real score = aiMatchupScore( templateFramesToKill( tmpl, army[ k ].m_template ),+ templateFramesToKill( army[ k ].m_template, tmpl ), cost, army[ k ].m_cost );+ if( score > bestScore )+ {+ best = k;+ bestScore = score;+ }+ }+ (*answered)[ best ] += cost;+}++//----------------------------------------------------------------------------------------------------------+/** A base under attack spends its bank on the fight. A Hard USA rushed a minute in had two fighting+ * units and 8,000 in the bank, because the opening goes on buildings first and the team plan trains+ * at its own pace: sixteen rebels stood in its base for a minute and lost one. So while the base is+ * hit every factory that can train a fighter queues two, for as long as the money lasts, and whatever+ * of ours stands idle at home is sent at the intruder nearest the middle of the base. Each one is the+ * best answer to the kind of intruder the least answered so far, money for money: answering the whole+ * crowd at once picked Missile Defenders against sixteen rebels and four Scorpions, since the tanks+ * weigh as much as the rifles and a rocket beats a tank by more than it loses to a rifle. Every rung+ * and every side: the factories' own buttons say what can be trained. */+//----------------------------------------------------------------------------------------------------------+void AIPlayer::defendHome( void )+{+ if( !isSkirmishAI() )+ return;+ Int intruders = 0;+ std::vector<AIVisibleEnemy> army;+ Object *intruder = homeIntruder( &intruders, &army );+ if( intruder == NULL )+ return;++ // Two deep. The queue this builds reads to doEconomy as a barracks that cannot keep up, and a rushed+ // China bought a second barracks in the middle of the fight where its next building used to be the+ // war factory; doEconomy buys nothing while the base is hit, which is what keeps that out.+ const Int EMERGENCY_QUEUE = 2;+ std::vector<Object *> owned;+ m_player->iterateObjects( collectOwned, &owned );+ std::vector<Object *> factories;+ m_player->iterateObjects( collectFactories, &factories );++ // what is already answering: the fighters at home and everything in the factories' queues+ std::vector<Real> answered( army.size(), 0.0f );+ for( std::vector<Object *>::const_iterator o = owned.begin(); o != owned.end(); ++o )+ {+ if( !(*o)->isEffectivelyDead() && !(*o)->isKindOf( KINDOF_STRUCTURE ) && isAtHome( (*o)->getPosition() ) && leavesToFinish( *o ) )+ creditAnswer( (*o)->getTemplate(), m_player, army, &answered );+ }+ for( std::vector<Object *>::const_iterator f = factories.begin(); f != factories.end(); ++f )+ {+ const ProductionUpdateInterface *pu = (*f)->getProductionUpdateInterface();+ for( const ProductionEntry *entry = pu->firstProduction(); entry; entry = pu->nextProduction( entry ) )+ if( entry->getProductionType() == PRODUCTION_UNIT ) // an upgrade shares the pointer's storage+ creditAnswer( entry->getProductionObject(), m_player, army, &answered );+ }++ for( std::vector<Object *>::const_iterator f = factories.begin(); f != factories.end(); ++f )+ {+ ProductionUpdateInterface *pu = (*f)->getProductionUpdateInterface();+ while( pu->getProductionCount() < EMERGENCY_QUEUE )+ {+ // the kind with the most of its worth still unanswered, the first seen of two alike+ size_t kind = 0;+ for( size_t k = 1; k < army.size(); ++k )+ if( army[ k ].m_weight - answered[ k ] > army[ kind ].m_weight - answered[ kind ] )+ kind = k;+ const ThingTemplate *unit = bestDefender( *f, m_player, army[ kind ] );+ if( unit == NULL || !pu->queueCreateUnit( unit, pu->requestUniqueUnitID() ) )+ break;+ answered[ kind ] += INT_TO_REAL( unit->calcCostToBuild( m_player ) );+ DEBUG_LOG(("AI DEFEND frame %d player %d trains '%s' at '%s' against %d intruders, %d in the bank\n",+ TheGameLogic->getFrame(), m_player->getPlayerIndex(), unit->getName().str(), (*f)->getTemplate()->getName().str(),+ intruders, m_player->getMoney()->countMoney()));+ }+ }++ // a gun between the middle of the base and the intruder, one at a time: the factories train one+ // unit at a time whatever the bank holds, and a China with 12,500 and one barracks spent 5,000 of+ // it over the minute its base was being hit+ Object *dozer = NULL;+ m_player->iterateObjects( findAnyDozer, &dozer );+ if( dozer && m_player->getCanBuildBase() )+ {+ const ThingTemplate *defense = buildableOfKind( dozer, GUI_COMMAND_DOZER_CONSTRUCT, KINDOF_FS_BASE_DEFENSE );+ Bool going = FALSE;+ m_player->iterateObjects( findDefenseUnderConstruction, &going );+ if( defense && !going && !priorityBuildPending( m_player, defense ) )+ {+ Coord3D spot = m_baseCenter;+ Coord2D toward;+ toward.x = intruder->getPosition()->x - m_baseCenter.x;+ toward.y = intruder->getPosition()->y - m_baseCenter.y;+ if( toward.length() > 0.0f )+ {+ toward.normalize();+ spot.x += toward.x * DEFENSE_STANDOFF * m_baseRadius;+ spot.y += toward.y * DEFENSE_STANDOFF * m_baseRadius;+ }+ const Bool placed = placeNear( defense, &spot, 0.0f, FALSE );+ DEBUG_LOG(("AI DEFEND frame %d player %d %s a '%s' against the intruder, %d in the bank\n", TheGameLogic->getFrame(),+ m_player->getPlayerIndex(), placed ? "puts up" : "has no room for", defense->getName().str(), m_player->getMoney()->countMoney()));+ }+ }++ // whatever stands at home with nothing to do but guard goes at the intruder, once there is enough of+ // it: a rushed China sent its Tank Hunters out by twos into sixteen rebels and lost them, where they+ // had stood by the Gattling Cannon and let it do the work+ Real homePower = 0.0f;+ for( std::vector<Object *>::const_iterator o = owned.begin(); o != owned.end(); ++o )+ {+ if( !(*o)->isEffectivelyDead() && !(*o)->isKindOf( KINDOF_STRUCTURE ) && isAtHome( (*o)->getPosition() ) && leavesToFinish( *o ) )+ homePower += aiCombatPower( *o );+ }+ Real intruderWorth = 0.0f;+ for( std::vector<AIVisibleEnemy>::const_iterator k = army.begin(); k != army.end(); ++k )+ intruderWorth += k->m_weight;+ if( homePower < 0.5f * intruderWorth )+ return;++ Int sent = 0;+ for( std::vector<Object *>::const_iterator o = owned.begin(); o != owned.end(); ++o )+ {+ Object *obj = *o;+ if( obj->isEffectivelyDead() || obj->isContained() || obj->getAI() == NULL || obj->isKindOf( KINDOF_IMMOBILE ) ||+ !isAtHome( obj->getPosition() ) || !leavesToFinish( obj ) )+ continue;+ const StateID state = obj->getAI()->getCurrentStateID();+ if( state != AI_IDLE && state != AI_GUARD && state != AI_GUARD_RETALIATE && state != AI_MOVE_AND_TIGHTEN )+ continue;+ obj->getAI()->aiAttackMoveToPosition( intruder->getPosition(), NO_MAX_SHOTS_LIMIT, CMD_FROM_AI );+ ++sent;+ }+ if( sent > 0 )+ DEBUG_LOG(("AI DEFEND frame %d player %d sends %d idle units at the intruder at (%.0f,%.0f)\n", TheGameLogic->getFrame(),+ m_player->getPlayerIndex(), sent, intruder->getPosition()->x, intruder->getPosition()->y));}/** What a team has to put into a wave, and those members into the group when one is given. Not the@@ -6356,6 +6588,7 @@ void AIPlayer::doWaves( void )return;updatePressure();+ defendHome();sendIdleAttackTeams();sendIdleUnitsHunting();@@ -8791,6 +9024,11 @@ void AIPlayer::doScouting( void )return;m_scoutTimer = SCOUT_CHECK_RATE;+ // no new scout out of a base being hit: a rushed China sent two of the Red Guards it had just+ // trained for the fight off to look at the map+ if( isBaseUnderAttack() )+ return;+const AIDifficultyProfile *profile = getSkillProfile();Int wanted = profile->m_maxScouts;if( wanted < 1 ) wanted = 1;