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 garrisons the front and lets its men out again
Olcay Seyganf3e6b3952a5a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 410cb36d8..3afd3c3a7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -197,7 +197,7 @@ found and fixed — EA's own, not port damage.**- Its helicopters fight. The computer's plan parks every Comanche and Helix on guard, and there they stayed for the whole match. Now when an attack leaves, every helicopter left on guard goes with it and flies over the army at its pace: 97 of them over eight four-player matches, where none had ever left before. A Helix buys its own upgrades, and infantry waiting for the attack climbs into any helicopter it can shoot out of.- And its helicopters carry people. On Hard, infantry waiting for the attack now boards any helicopter with a seat, not only one it can shoot out of, and a helicopter carrying riders who cannot shoot from it puts them down just short of the fight, on the first ground none of your guns it knows about can reach, from where they go on at you on foot. The boarding never worked before this either: a helicopter the plan had put on guard stayed in the air, so the riders walked up to it and turned away. The same Black Lotus was sent to one Helix three times in two minutes. A helicopter now lands for its riders. The capturer flies too: when the building it is after is a long walk away and a helicopter is waiting at home, it gets in, and the helicopter puts it down beside the building. China's attacks are mostly tanks, so its Helixes still leave with one rider more often than five.- Its infantry rides in its vehicles. The computer's plan tells a group with a Humvee to climb in and, in the same breath, to stand guard, and the guard order won before anyone took a step: over two Hard four-player matches not one soldier boarded anything, Humvee, Battle Bus or helicopter. Now soldiers standing at home climb into their own group's Humvee or Battle Bus on every difficulty, and the group goes wherever its plan sends it with them shooting from inside. Soldiers waiting for the next attack fill any Humvee, Battle Bus or helicopter at home they can shoot out of, an Overlord or Emperor carrying its battle bunker included, and that vehicle leaves with the attack. A soldier who could not shoot from a vehicle never rides in one, except in a helicopter on Hard, which puts him down short of the fight as before. China's attacks on Hard carry no infantry at all, so its Helixes flew off with the waves empty, 14 times over those two matches, though both had bought the bunker by the middle of the match. Medium and Hard now train soldiers for any helicopter seat they could shoot from that stands empty, an attack ready to leave waits up to twenty seconds for them to climb in, and an empty bunkered Helix whose soldiers are still on their way stays behind for the next attack rather than fly off unarmed. The Air Force General on Medium and Hard also buys up to two Combat Chinooks, where it only ever bought the supply Chinook before. They stay off the supply runs and fill with Rangers. On Hard they fly with the attacks, all eight shooting from inside; Medium mostly keeps them at home, loaded. Replays recorded before this change play out differently.-- Its buildings have men in them. The computer built Bunkers and Fire Bases, put up its Palace as GLA, and left every one of them empty for the whole match. Now the soldiers guarding its base and the ones standing idle at home climb into its own buildings they can shoot out of, and on Medium and Hard it trains more for the empty seats once it has money to spare. While its base is being hit, the men at home also take any empty civilian building in the base. The soldiers gathered for an attack are never taken off it for this. Over eight Hard matches on Twilight Flame, 173 soldiers went in, each of them once, 88 of them into a Palace and the rest into Fire Bases and Bunkers, with the matches' economy and number of attacks where they were. A first version bought five Red Guards for China's first Bunker a minute into the match, and the computer's own plan, finding the bank empty, sold the whole base in two of eight matches; it now waits for spare money. Replays recorded before this change play out differently.+- Its buildings have men in them. The computer built Bunkers and Fire Bases, put up its Palace as GLA, and left every one of them empty for the whole match. Now the soldiers guarding its base and the ones standing idle at home climb into its own buildings they can shoot out of, and on Medium and Hard it trains more for the empty seats once it has money to spare. While its base is being hit, the men at home also take any empty civilian building in the base. The soldiers gathered for an attack are never taken off it for this. A Bunker out at an expansion used to stay empty unless somebody happened to be standing next to it; now men walk out from home to fill it, and Medium and Hard train them for it. Out in the field, a Medium or Hard group standing still with your units close by takes the empty civilian buildings around it. Once none of your units is left near a civilian building, the men inside come out and go back to their jobs, where before they sat there for the rest of the match. On Medium and Hard they also get out of any building, a Bunker included, before it falls on them. In one Medium match on Tournament Desert the same Red Guard went into one garage eight times as GLA raids came and went. Over eight Hard matches on Twilight Flame, 173 soldiers went in, each of them once, 88 of them into a Palace and the rest into Fire Bases and Bunkers, with the matches' economy and number of attacks where they were. A first version bought five Red Guards for China's first Bunker a minute into the match, and the computer's own plan, finding the bank empty, sold the whole base in two of eight matches; it now waits for spare money. Replays recorded before this change play out differently.- Its Chinooks fly the army. A USA attack walked the whole road, at the pace of its slowest tank. Medium and Hard now buy plain Chinooks for nothing but lift, more of them the bigger the attack and the longer the road: they load tanks and soldiers at home, put them down on the attack's road short of anything the computer has seen that can shoot, and go home for the next load while the attack is under way. The drop is one a straight flight from the base reaches over quiet ground, after the first version flew seven loaded Chinooks in one match straight at a drop beyond an enemy base and lost every one. A Chinook hit hard on the way puts its load down where it is. Neither these nor the Air Force General's Combat Chinooks go on the supply runs unless nothing else is left to gather and nothing else can be bought, and the Combat Chinook is no longer ever bought as a gatherer.- Its Helixes have jobs. Every Helix the computer owned bought its upgrades in button order, so each one carried a battle bunker whatever it was up against, with napalm on top. A Helix in one of its attack or guard groups now looks at what it knows of your army first and takes the gattling cannon when most of your strength is on foot, the bunker when most of it is in vehicles, and the soldiers trained to sit in that bunker are Tank Hunters rather than Red Guards. Against GLA over four Hard matches that came out 15 bunkers to 6 cannons, each decided on the split at that moment. China on Medium and Hard also buys two Helixes as healers, a third once its army passes thirty units, each under a Propaganda Tower. They hang behind the attack over whichever of its units is most hurt, carry nobody, and pull away when they are hit or when anti-air they know of comes near; over twelve Hard matches they spent 93% of their time out of the base further from the nearest enemy gun than it could shoot. They used to bunch up over the same tank, which got nothing out of it: a unit inside two towers heals no faster than inside one. Each healer now keeps its spot at least a tower's reach, 150, from the others', going to the most hurt unit nobody else's tower already covers, or stepping sideways behind the attack until it is clear of theirs. Two more Helixes take the napalm bomb, or the Nuke General's nuclear one, and raid your base, a factory first and otherwise whatever pays for it or powers it. A raid comes in from the side your known anti-air does not cover, looks for a new way in when a gun turns up ahead, and turns for home when it is hit below half health. Over the same twelve matches 126 raids went out, 23 dropped their bomb, five buildings fell after a drop, and 31 raiders were shot down on a raid. A raider also stops bombing once its run is over. A Helix told to bomb a spot drops another bomb under itself every ten seconds until it gets a different order, and the computer's own orders never counted as one, so a raider that had bombed your base went on dropping napalm all the way home, over your soldiers on the way, and then on its own base for the rest of the match. Over eight Hard matches against America, 104 of 121 bombs fell nowhere near the building they were meant for. On the same matches now, each of the 14 bombs dropped lands on its building, and a raid that turns back before its drop no longer flies out again to finish it once it is home. The Infantry General's Helix has no tower, so it only raids. Replays recorded before this change play out differently.- The USA computer fields Ambulances. It never built one before. On Medium and Hard it buys one once eight fighting units stand and a second at twenty, and keeps them a little behind the middle of its army, short of every gun of yours it knows about. A soldier of its own under half health who stands near one walks over and climbs in, and gets out again once he is whole. Toxins, anthrax and radiation on its own side of the map get driven to and washed off. Over six Hard matches against GLA on Twilight Flame it ordered 26 Ambulances, called 10 wounded men in and sent them on 19 cleanups of its own ground. They also die a lot: 24 of the 25 that rolled out were lost, and those six matches went no better for the USA than the same six without them (no win either way, 57 kills a match where it had 66). Replays recorded before this change play out differently.diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex b2fd910cc..66ec41ff8 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -60,6 +60,16 @@ Data/Cinema/rf_orders.txtData/Cinema/rf_reach.txtData/Cinema/rf_smoke.txtData/Cinema/rf_snow.txt+Data/Cinema/rf_t2_alpine.txt+Data/Cinema/rf_t2_apex.txt+Data/Cinema/rf_t2_beach.txt+Data/Cinema/rf_t2_bitter.txt+Data/Cinema/rf_t2_desert.txt+Data/Cinema/rf_t2_heart.txt+Data/Cinema/rf_t2_night.txt+Data/Cinema/rf_t2_twilight.txt+Data/Cinema/rf_t2_wall.txt+Data/Cinema/rf_t2_wolf.txtData/Cinema/rf_tank.txtData/Cinema/rf_thumb_fa.txtData/Cinema/rf_thumb_fe.txt@@ -131,6 +141,7 @@ Data/Scenarios/driveby.txtData/Scenarios/empfriendly.txtData/Scenarios/exitmovebuild.txtData/Scenarios/exitorders.txt+Data/Scenarios/expansionbunker.txtData/Scenarios/explreel.txtData/Scenarios/glowbase.txtData/Scenarios/glowfight.txt@@ -196,6 +207,15 @@ Data/Scenarios/rf_pin.txtData/Scenarios/rf_reach.txtData/Scenarios/rf_smoke.txtData/Scenarios/rf_snow.txt+Data/Scenarios/rf_t2_alpine.txt+Data/Scenarios/rf_t2_beach.txt+Data/Scenarios/rf_t2_bitter.txt+Data/Scenarios/rf_t2_desert.txt+Data/Scenarios/rf_t2_heart.txt+Data/Scenarios/rf_t2_night.txt+Data/Scenarios/rf_t2_twilight.txt+Data/Scenarios/rf_t2_wall.txt+Data/Scenarios/rf_t2_wolf.txtData/Scenarios/rf_thumb_fa.txtData/Scenarios/rf_thumb_fe.txtData/Scenarios/rocketglow.txtdiff --git a/GeneralsMD/Code/Data/Scenarios/expansionbunker.txt b/GeneralsMD/Code/Data/Scenarios/expansionbunker.txtnew file mode 100644index 000000000..816323c02--- /dev/null+++ b/GeneralsMD/Code/Data/Scenarios/expansionbunker.txt@@ -0,0 +1,16 @@+# A Bunker far from China's base and four idle Red Guards at home, with the AI playing around them.+#+# The skirmish AI used to man only the firing buildings within reach of where its men stood, so a+# Bunker at an expansion stayed empty unless a team happened to pass it. Look for+# "AI GARRISON ... into 'ChinaBunker' ..., own, default, field" in the log: a man from home sent out+# to it. The three Bunker lines are candidates; whichever stand on legal ground are made.+#+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit+# -map "Maps\Tournament Desert\Tournament Desert.map" -autoskirmish 2 -aidiff hard+# -side 0 FactionGLA -side 1 FactionChina -seed 1 -maxframes 3000+# -scenario expansionbunker -logPrefix expbunker_++30 spawn 1 ChinaBunker 1 start1:-900:0+30 spawn 1 ChinaBunker 1 start1:0:-900+30 spawn 1 ChinaBunker 1 start1:-650:-650+30 spawn 1 ChinaInfantryRedguard 4 start1:150:150 20diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.hindex 5010a923b..31c7fc8dd 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h@@ -385,7 +385,8 @@ protected:AsciiString secondApproachLabel(const Coord3D *from, const AsciiString &taken, Int pathSuffix); ///< the quietest other road, or emptyBool loadGunships(void); ///< infantry boards the transports it can shoot out of: the wave's anything at home, a team's its own; TRUE while a firing gunship is still fillingInt buyGunshipRiders(Int freeSeats); ///< Medium and up train the men for the firing seats nobody fills; how many are in training- void garrisonBuildings(void); ///< the home guard's infantry into our own buildings it shoots out of and the empty ones at home+ void garrisonBuildings(void); ///< infantry into our own buildings it shoots out of, and into empty ones with an enemy near, at home and at the front+ void evacuateBuildings(void); ///< our men out of a building about to fall, and out of a neutral one once no enemy is nearvoid buyGunshipChinook(void); ///< Medium and up buy a supply-center transport the riders shoot out of, as a gunshipvoid doShuttles(void); ///< the transport Chinooks load at home, fly the wave's ground units to its road and come backvoid buyTransportChinook(void); ///< one more transport Chinook while the last wave needs more lift than there isdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cppindex d7bbba587..84042a60e 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp@@ -8242,6 +8242,7 @@ void AIPlayer::doWaves( void )++teams;}const Bool gunshipFilling = loadGunships();+ evacuateBuildings();garrisonBuildings(); // after the gunships: the wave's riders first, the home guard's leftovers into buildingsif( first < 0 )return;@@ -8622,25 +8623,129 @@ Bool AIPlayer::loadGunships( void )}/** One of our own buildings whose men shoot out of it - a Bunker, a Fire Base, a Palace - finished, not- * knocked out by an EMP or a hacker, and with a seat free. Not a tunnel or a heal bay. */+ * knocked out by an EMP or a hacker, and with a seat free. Not a tunnel or a heal bay, and not a map+ * building we hold, which stays a neutral seat: counted as ours, a farmhouse taken while the base was+ * hit went on taking men and buying them in a quiet base. */+static Bool isMapBuilding( const Object *obj );static void findFiringBuilding( Object *obj, void *userData ){ContainModuleInterface *contain = obj->getContain();- if( obj->isKindOf( KINDOF_STRUCTURE ) && contain && !contain->isTunnelContain() && !contain->isHealContain() &&+ if( obj->isKindOf( KINDOF_STRUCTURE ) && contain && !contain->isTunnelContain() && !contain->isHealContain() && !isMapBuilding( obj ) &&(Int)contain->getContainCount() < contain->getContainMax() && contain->isPassengerAllowedToFire() &&!obj->isEffectivelyDead() && !obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) && !obj->testStatus( OBJECT_STATUS_SOLD ) )((std::vector<Object *> *)userData)->push_back( obj );}+/** How near an enemy has to be to a neutral building for our men to go in, and how far off the last one+ * has to be before they come out again. The gap keeps them from stepping in and out of the same house+ * while a fight drifts along its edge. */+static const Real GARRISON_ENEMY_NEAR = 350.0f;+static const Real GARRISON_ENEMY_GONE = 500.0f;++/** How far from where he stands a man out in the field goes for a building, by skill. Easy takes none:+ * its men stay with their team, as they always did. */+static const Real GARRISON_FRONT_REACH[] = { 0.0f, 150.0f, 250.0f };++/** The health share under which our men leave a building before it comes down on them, by skill. A+ * civilian building hurts its men when it falls (DamagePercentToUnits). Easy stays to the end. */+static const Real GARRISON_LEAVE_HEALTH[] = { 0.0f, 0.25f, 0.4f };++/** The nearest visible enemy unit within radius of pos that is not a worker, or NULL. */+static Object *enemyWithin( Player *player, const Coord3D *pos, Real radius )+{+ PartitionFilterPlayerAffiliation filterTeam( player, (ALLOW_ALLIES|ALLOW_NEUTRAL), false );+ PartitionFilterAlive filterAlive;+ PartitionFilterRejectByObjectStatus filterStealth( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_STEALTHED ),+ MAKE_OBJECT_STATUS_MASK2( OBJECT_STATUS_DETECTED, OBJECT_STATUS_DISGUISED ) );+ PartitionFilterRejectByKindOf filterHarvesters( MAKE_KINDOF_MASK( KINDOF_HARVESTER ), KINDOFMASK_NONE );+ PartitionFilterRejectByKindOf filterDozers( MAKE_KINDOF_MASK( KINDOF_DOZER ), KINDOFMASK_NONE );+ PartitionFilter *filters[] = { &filterTeam, &filterAlive, &filterStealth, &filterHarvesters, &filterDozers, NULL };+ MemoryPoolObjectHolder hold;+ SimpleObjectIterator *around = ThePartitionManager->iterateObjectsInRange( pos, radius, FROM_BOUNDINGSPHERE_2D, filters, ITER_SORTED_NEAR_TO_FAR );+ hold.hold( around );+ // a man or a vehicle: the first version filled a farmhouse at home for an enemy Bunker standing near it+ // from the second minute, and others for an Inferno Cannon's shell and a pool of toxin+ for( Object *obj = around->first(); obj; obj = around->next() )+ if( obj->isKindOf( KINDOF_INFANTRY ) || obj->isKindOf( KINDOF_VEHICLE ) )+ return obj;+ return NULL;+}++/** A civilian building, a farmhouse or a church, which no faction builds: ours once we are in it. Its+ * template names no side, or the civilian one; a Bunker names its faction's. */+static Bool isMapBuilding( const Object *obj )+{+ const AsciiString &side = obj->getTemplate()->getDefaultOwningSide();+ return obj->getContain()->isGarrisonable() && (side.isEmpty() || side.compareNoCase( "Civilian" ) == 0);+}++/** The structure each of our men is inside, once each, in the order the men come. */+static void collectOccupiedBuildings( Object *obj, void *userData )+{+ Object *building = obj->getContainedBy();+ std::vector<Object *> *list = (std::vector<Object *> *)userData;+ if( obj->isKindOf( KINDOF_INFANTRY ) && building && building->isKindOf( KINDOF_STRUCTURE ) &&+ std::find( list->begin(), list->end(), building ) == list->end() )+ list->push_back( building );+}++//----------------------------------------------------------------------------------------------------------+/** The men garrisonBuildings put in a building stayed there for the rest of the match: a farmhouse taken+ * while the base was hit kept the next wave's infantry when the fight was long over, and a house at+ * the front kept its men while the front moved on. They come out of a map building once no enemy is+ * near it, and Medium and Hard take them out of any building, our own Bunker as well, before it falls. */+//----------------------------------------------------------------------------------------------------------+void AIPlayer::evacuateBuildings( void )+{+ if( !isSkirmishAI() )+ return;+ std::vector<Object *> buildings;+ m_player->iterateObjects( collectOccupiedBuildings, &buildings );+ for( std::vector<Object *>::const_iterator b = buildings.begin(); b != buildings.end(); ++b )+ {+ Object *building = *b;+ const BodyModuleInterface *body = building->getBodyModule();+ const Real health = body->getHealth() / body->getMaxHealth();+ const char *why = NULL;+ if( health < GARRISON_LEAVE_HEALTH[ m_skillLevel ] )+ why = "falling";+ else if( isMapBuilding( building ) && !enemyWithin( m_player, building->getPosition(), GARRISON_ENEMY_GONE ) )+ why = "quiet";+ if( why == NULL )+ continue;+ DEBUG_LOG(("AI GARRISON frame %d player %d empties '%s' %d, %d men, %s, %.0f%% health\n", TheGameLogic->getFrame(),+ m_player->getPlayerIndex(), building->getTemplate()->getName().str(), building->getID(),+ building->getContain()->getContainCount(), why, health * 100.0f));+ building->getContain()->orderAllPassengersToExit( CMD_FROM_AI, FALSE );+ }+}++/** Add the map's empty garrisonable buildings within radius of pos to seats, each once. */+static void addMapSeats( Player *player, const Coord3D *pos, Real radius, std::vector<Object *> *seats )+{+ PartitionFilterAlive filterAlive;+ PartitionFilterOnMap filterOnMap;+ PartitionFilterGarrisonableByPlayer filterGarrison( player, TRUE, CMD_FROM_AI );+ PartitionFilter *filters[] = { &filterAlive, &filterOnMap, &filterGarrison, 0 };+ MemoryPoolObjectHolder hold;+ SimpleObjectIterator *nearby = ThePartitionManager->iterateObjectsInRange( pos, radius, FROM_CENTER_2D, filters );+ hold.hold( nearby );+ for( Object *b = nearby->first(); b; b = nearby->next() )+ if( isMapBuilding( b ) && b->getContain()->isPassengerAllowedToFire() &&+ std::find( seats->begin(), seats->end(), b ) == seats->end() )+ seats->push_back( b );+}+//----------------------------------------------------------------------------------------------------------/** The computer built Bunkers and Fire Bases and never put a man in one, and walked past every empty- * farmhouse in its own base while the enemy's rebels moved in. The home guard fills them: the- * default team's infantry standing at home and the base defence teams'. Our own firing buildings take- * both, and Medium and up train men for their empty seats out of the bank (buyGunshipRiders). An empty- * neutral building at home takes the base defence teams' men, and the default team's only while the- * base is hit: the default team's idle men at home are the next wave's (addHomeStrays), and a farmhouse- * in a quiet base is not worth a wave's infantry. A wave's own men and an attack team's are never taken.- * Runs after loadGunships on the same pass, so a man it has sent to a gunship is no longer idle here. */+ * farmhouse while the enemy's rebels moved in. Our own firing buildings take the default team's+ * infantry standing at home, wherever the building is, so a Bunker at an expansion is manned from home;+ * a base defence team's men take those at home only. Medium and up train men for the empty seats out+ * of the bank (buyGunshipRiders). A map building takes our men only while an enemy is near it: at home+ * that is the base being hit, and in the field, for Medium and Hard, it is the front, where a team's+ * men standing idle or on guard go into the empty houses within their reach. evacuateBuildings lets+ * them out again. A wave's own men are never taken. Runs after loadGunships on the same pass, so a+ * man it has sent to a gunship is no longer idle here. *///----------------------------------------------------------------------------------------------------------void AIPlayer::garrisonBuildings( void ){@@ -8650,30 +8755,9 @@ void AIPlayer::garrisonBuildings( void )m_player->iterateObjects( findFiringBuilding, &seats );const size_t own = seats.size();const Real reach = 2.0f * m_baseRadius;- {- PartitionFilterAlive filterAlive;- PartitionFilterOnMap filterOnMap;- PartitionFilterGarrisonableByPlayer filterGarrison( m_player, TRUE, CMD_FROM_AI );- PartitionFilter *filters[] = { &filterAlive, &filterOnMap, &filterGarrison, 0 };- MemoryPoolObjectHolder hold;- SimpleObjectIterator *nearby = ThePartitionManager->iterateObjectsInRange( &m_baseCenter, reach, FROM_CENTER_2D, filters );- hold.hold( nearby );- for( Object *b = nearby->first(); b; b = nearby->next() )- if( b->getControllingPlayer() != m_player && b->getContain()->isPassengerAllowedToFire() )- seats.push_back( b );- }- if( seats.empty() )- return;+ const Real frontReach = GARRISON_FRONT_REACH[ m_skillLevel ];+ addMapSeats( m_player, &m_baseCenter, reach, &seats );- // seats nobody is walking to, as loadGunships counts them- std::vector<ObjectID> goals;- m_player->iterateObjects( collectBoardingGoals, &goals );- std::vector<Int> free;- for( std::vector<Object *>::const_iterator s = seats.begin(); s != seats.end(); ++s )- free.push_back( (*s)->getContain()->getContainMax() - (Int)(*s)->getContain()->getContainCount() -- (Int)std::count( goals.begin(), goals.end(), (*s)->getID() ) );-- const Bool underAttack = isBaseUnderAttack();const Team *defaultTeam = m_player->getDefaultTeam();std::vector<GunshipRider> riders;for( Player::PlayerTeamList::const_iterator t = m_player->getPlayerTeams()->begin(); t != m_player->getPlayerTeams()->end(); ++t )@@ -8684,38 +8768,71 @@ void AIPlayer::garrisonBuildings( void ){Team *team = iter.cur();const Bool isDefault = team == defaultTeam;- if( !isDefault && (!guard || !team->isActive()) )+ if( !isDefault && !team->isActive() )continue;+ Bool parked = FALSE;+ for( Int i = 0; i < MAX_HELD_TEAMS; ++i )+ if( m_heldUsed[ i ] && m_heldTeam[ i ] == team->getID() )+ parked = TRUE;+ if( parked )+ continue; // a wave'sfor( DLINK_ITERATOR<Object> m = team->iterate_TeamMemberList(); !m.done(); m.advance() ){Object *rider = m.cur();- if( !isGunshipRider( rider ) || isFallingBack( rider->getID() ) || !isAtHome( rider->getPosition() ) )+ if( !isGunshipRider( rider ) || isFallingBack( rider->getID() ) )continue;const StateID state = rider->getAI()->getCurrentStateID();if( state != AI_IDLE && state != AI_GUARD && state != AI_GUARD_RETALIATE )continue;- GunshipRider entry = { rider, isDefault ? "default" : "guard" };+ const Bool home = isAtHome( rider->getPosition() );+ if( home ? !isDefault && !guard : frontReach <= 0.0f )+ continue;+ if( !home )+ addMapSeats( m_player, rider->getPosition(), frontReach, &seats );+ GunshipRider entry = { rider, !home ? "front" : isDefault ? "default" : "guard" };riders.push_back( entry );}}}+ if( seats.empty() )+ return;++ // seats nobody is walking to, as loadGunships counts them, and whether a map building has an enemy+ // near enough to be worth going in+ std::vector<ObjectID> goals;+ m_player->iterateObjects( collectBoardingGoals, &goals );+ std::vector<Int> free;+ std::vector<const Object *> threat; // what makes a map building worth it; our own is its own reason+ for( size_t s = 0; s < seats.size(); ++s )+ {+ const BodyModuleInterface *body = seats[ s ]->getBodyModule();+ free.push_back( seats[ s ]->getContain()->getContainMax() - (Int)seats[ s ]->getContain()->getContainCount() -+ (Int)std::count( goals.begin(), goals.end(), seats[ s ]->getID() ) );+ // nobody goes into a building evacuateBuildings would take him out of again+ if( body->getHealth() < body->getMaxHealth() * GARRISON_LEAVE_HEALTH[ m_skillLevel ] )+ free.back() = 0;+ threat.push_back( s < own ? seats[ s ] : enemyWithin( m_player, seats[ s ]->getPosition(), GARRISON_ENEMY_NEAR ) );+ }for( std::vector<GunshipRider>::const_iterator r = riders.begin(); r != riders.end(); ++r ){Object *rider = r->obj;const Bool stray = strcmp( r->from, "default" ) == 0;+ const Bool front = strcmp( r->from, "front" ) == 0;Int nearest = -1;Real nearestSqr = 0.0f;for( size_t g = 0; g < seats.size(); ++g ){const Bool mine = g < own;- if( free[ g ] <= 0 || (!mine && stray && !underAttack) )+ if( free[ g ] <= 0 || threat[ g ] == NULL )continue;ContainModuleInterface *contain = seats[ g ]->getContain();if( !contain->isValidContainerFor( rider, TRUE ) || !contain->isPassengerAllowedToFire( rider->getID() ) )continue;const Real distSqr = sqr( seats[ g ]->getPosition()->x - rider->getPosition()->x ) + sqr( seats[ g ]->getPosition()->y - rider->getPosition()->y );- if( distSqr > sqr( reach ) )+ // a man at the front only within his reach; one at home to any building at home, and a stray+ // to our own anywhere: an expansion's Bunker is manned from home+ if( front ? distSqr > sqr( frontReach ) : !(mine && stray) && !isAtHome( seats[ g ]->getPosition() ) )continue;// our own building before a neutral one, then the nearest; a tie goes to the first in list orderconst Bool nearestMine = nearest >= 0 && (size_t)nearest < own;@@ -8729,23 +8846,23 @@ void AIPlayer::garrisonBuildings( void )continue;Object *building = seats[ nearest ];--free[ nearest ];- DEBUG_LOG(("AI GARRISON frame %d player %d puts '%s' %d into '%s' %d, %d of %d seats taken, %s, %s%s\n", TheGameLogic->getFrame(),+ DEBUG_LOG(("AI GARRISON frame %d player %d puts '%s' %d into '%s' %d, %d of %d seats taken, %s, %s, %s, for '%s'\n", TheGameLogic->getFrame(),m_player->getPlayerIndex(), rider->getTemplate()->getName().str(), rider->getID(), building->getTemplate()->getName().str(), building->getID(),building->getContain()->getContainCount(), building->getContain()->getContainMax(), (size_t)nearest < own ? "own" : "neutral",- r->from, underAttack ? ", base under attack" : ""));+ r->from, isAtHome( building->getPosition() ) ? "home" : "field", threat[ nearest ]->getTemplate()->getName().str()));rider->getAI()->aiEnter( building, CMD_FROM_AI );}- // men for our own empty firing seats at home: a trained rider comes out at home, and one for a Bunker at- // an expansion would stand at home with nothing to walk to. Only out of money above the cash hoard: the- // first version bought five Red Guards for China's first Bunker a minute in, and the skirmish script,- // finding the bank and the trucks short a few seconds later, sold the whole base in two of eight matches.- // The script's own Bunker team fills the Bunker anyway, in time+ // men for our own empty firing seats, at home and at the expansions: a trained rider comes out at home+ // and a stray walks from there to any of them. Only out of money above the cash hoard: the first+ // version bought five Red Guards for China's first Bunker a minute in, and the skirmish script, finding+ // the bank and the trucks short a few seconds later, sold the whole base in two of eight matches. The+ // script's own Bunker team fills the Bunker anyway, in timeif( (Int)m_player->getMoney()->countMoney() <= getSkillProfile()->m_cashHoardThreshold )return;Int freeSeats = 0;for( size_t g = 0; g < own; ++g )- if( free[ g ] > 0 && isAtHome( seats[ g ]->getPosition() ) )+ if( free[ g ] > 0 )freeSeats += free[ g ];buyGunshipRiders( freeSeats );}