Skip to content

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.

feat(gameengine): auto garrison and auto repair keys

Olcay Seygana268302d3c02
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 58af43050..d861b638d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -801,6 +801,10 @@ found and fixed, EA's own, not port damage.**
- Ctrl+D takes every unit of the kinds you have selected that is on the screen, and pressed twice inside half a second takes them across the whole map. One tank selected and two keystrokes is your whole armour, wherever it is standing. It was on Shift+Ctrl+E, which is three fingers for something you do in every fight, and it only ever reached across the map when the screen had nothing left to give - so the wide selection happened to you instead of being asked for.
- Next idle unit selects the next combat unit standing with no orders, and the camera stays where you had it, so you can give it an order on the minimap without leaving the fight in front of you. Press again for the one after. It starts without a key; set one on the Hotkeys page. The idle worker key, I, no longer moves the camera either, while the idle worker button on the bar still takes you to the worker.
- That key comes in one per arm as well, so finding the jet that landed and sat down no longer means paging past every idle tank first. Select all idle units takes every combat unit standing with no orders on the screen without moving the view, or across the whole map when the screen has none, and pressed twice inside half a second it takes the whole map anyway. An aircraft-only and a vehicles-only version sit beside it. All of them start without a key.
+- Garrison nearby buildings fills a town with one key. The infantry you have selected walk into the buildings around them, and when one fills the rest move on to the next, until the area has no free seat. You used to split the squad and click each building yourself.
+- Go get repaired or healed clears a mixed selection after a fight. Each unit goes to its own nearest building that can fix it, a tank to a repair bay and a wounded soldier to where he heals, so nobody has to sort them first. Both keys start unassigned; set them on the Hotkeys tab in Options or on the launcher's Hotkeys page.
+- Soldiers no longer stand beside a building they were sent into. On Alpine Assault a man walking to one of the rail yard huts stopped at its wall and never went in, whether you clicked or pressed the key.
+- Replays recorded before this change no longer match.
- Shift and a number puts what you have selected into that control group and keeps everyone already in it, the way StarCraft does it. Fresh tanks off the line join group 1 with one key, where you used to select group 1, shift-click the new tanks in and press Ctrl+1 again. The selection stays as it is. Retail used Shift and a number to pull a group into your selection instead; that is gone, and Alt and the number still centres the view on the group.
- Ordering a very large army works. A selection of more than 254 units reaches the game whole, and Ctrl+number groups keep all their units.
- Hold Alt and drag with the middle mouse button, or hold Alt and turn the wheel, to tilt the camera between 20 and 60 degrees. Home resets heading, tilt and zoom, the way Numpad 5 does.
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifest
index 029e4d93f..0e3aa9bbd 100644
--- a/GeneralsMD/Code/BuildFingerprint.manifest
+++ b/GeneralsMD/Code/BuildFingerprint.manifest
@@ -240,6 +240,7 @@ Data/Scenarios/ambulanceguard.txt
Data/Scenarios/artillery.txt
Data/Scenarios/aurorablast.txt
Data/Scenarios/aurorafog.txt
+Data/Scenarios/autoorders.txt
Data/Scenarios/avengerlasers.txt
Data/Scenarios/baseintruder_barracks.txt
Data/Scenarios/baseintruder_patriot.txt
@@ -423,6 +424,7 @@ Data/Scenarios/sun_cloak.txt
Data/Scenarios/sun_trees.txt
Data/Scenarios/swhole.txt
Data/Scenarios/swpair.txt
+Data/Scenarios/technicalexit.txt
Data/Scenarios/techrespawn.txt
Data/Scenarios/towncross.txt
Data/Scenarios/toxinslope.txt
diff --git a/GeneralsMD/Code/Data/French/Generals.str b/GeneralsMD/Code/Data/French/Generals.str
index 98b596764..1452873bb 100644
--- a/GeneralsMD/Code/Data/French/Generals.str
+++ b/GeneralsMD/Code/Data/French/Generals.str
@@ -17281,6 +17281,14 @@ GUI:HotkeysCommandBEGIN_PREFER_SELECTION
"Ajouter à la sélection (maintenir)"
END
+GUI:HotkeysCommandAUTO_GARRISON
+"Occuper les bâtiments proches"
+END
+
+GUI:HotkeysCommandAUTO_REPAIR
+"Aller se faire réparer ou soigner"
+END
+
GUI:LoadModeSkirmish
"Escarmouche"
END
diff --git a/GeneralsMD/Code/Data/German/Generals.str b/GeneralsMD/Code/Data/German/Generals.str
index 5ec48b795..3bb21ccc3 100644
--- a/GeneralsMD/Code/Data/German/Generals.str
+++ b/GeneralsMD/Code/Data/German/Generals.str
@@ -15385,6 +15385,14 @@ GUI:HotkeysCommandBEGIN_PREFER_SELECTION
"Zur Auswahl hinzufügen (halten)"
END
+GUI:HotkeysCommandAUTO_GARRISON
+"Gebäude in der Nähe besetzen"
+END
+
+GUI:HotkeysCommandAUTO_REPAIR
+"Reparieren oder heilen lassen"
+END
+
GUI:MoneyTransferTitle
"Geld senden"
END
diff --git a/GeneralsMD/Code/Data/Patch.str b/GeneralsMD/Code/Data/Patch.str
index dee70b4bb..6a45b06a3 100644
--- a/GeneralsMD/Code/Data/Patch.str
+++ b/GeneralsMD/Code/Data/Patch.str
@@ -1958,6 +1958,14 @@ GUI:HotkeysCommandBEGIN_PREFER_SELECTION
"Add to selection (hold)"
END
+GUI:HotkeysCommandAUTO_GARRISON
+"Garrison nearby buildings"
+END
+
+GUI:HotkeysCommandAUTO_REPAIR
+"Go get repaired or healed"
+END
+
// The match load screen (LoadScreenBoard in LoadScreen.cpp)
GUI:LoadModeSkirmish
"Skirmish"
diff --git a/GeneralsMD/Code/Data/Russian/Generals.str b/GeneralsMD/Code/Data/Russian/Generals.str
index bf94f91b3..32f8cdf4c 100644
--- a/GeneralsMD/Code/Data/Russian/Generals.str
+++ b/GeneralsMD/Code/Data/Russian/Generals.str
@@ -17233,6 +17233,14 @@ GUI:HotkeysCommandBEGIN_PREFER_SELECTION
"Добавить к выделению (удерживать)"
END
+GUI:HotkeysCommandAUTO_GARRISON
+"Занять здания поблизости"
+END
+
+GUI:HotkeysCommandAUTO_REPAIR
+"Идти на ремонт или лечение"
+END
+
GUI:LoadModeSkirmish
"Схватка"
END
diff --git a/GeneralsMD/Code/Data/Scenarios/autoorders.txt b/GeneralsMD/Code/Data/Scenarios/autoorders.txt
new file mode 100644
index 000000000..aee037c82
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/autoorders.txt
@@ -0,0 +1,83 @@
+# The auto garrison and auto repair keys, sent as the keys' own messages.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -map "Maps\Alpine Assault\Alpine Assault.map" -autoskirmish 2 -takeover
+# -side 0 FactionChina -side 1 FactionAmerica -seed 1 -maxframes 3000
+# -scenario autoorders -logPrefix autoorders_
+#
+# Read the AUTO GARRISON and AUTO REPAIR lines; each paragraph below says what they should show.
+# Frames in those lines are logic frames, twice the ones here.
+#
+# findFirstMatching takes the newest object, so the Bunker the Tank Hunters are sent to is spawned last.
+
+30 spawn 0 ChinaBunker 1 620 780
+30 spawn 0 ChinaBunker 1 760 920
+30 spawn 0 ChinaBunker 1 1000 1060
+31 spawn 0 ChinaBunker 1 880 1000
+30 spawn 0 ChinaBarracks 1 900 770
+30 spawn 0 ChinaWarFactory 1 1200 860
+
+# Seven Red Guards press 90 from a Bunker with five seats: five head for it and two for the next,
+# because the walkers count against the seats. Five Tank Hunters beside its door are sent in as well,
+# so it fills early, and each Red Guard it turns away has a "building 2 of this search" line for the
+# next one. Every Red Guard ends "is in", none of them in the Bunker at 620 780, past the 300 radius.
+31 spawn 0 ChinaInfantryRedguard 7 950 960 20
+31 spawn 0 ChinaInfantryTankHunter 5 880 930 15
+60 autogarrison 0 ChinaInfantryRedguard
+61 clickenter 0 ChinaInfantryTankHunter 0 ChinaBunker
+400 tally 0 ChinaInfantryRedguard 7
+
+# Never in sight and neutral, a schoolhouse 270 away and a pub 250 away would both take a right click,
+# and would answer from what really stands there, so the search leaves them out: "finds no seat left
+# after 0 buildings".
+31 spawn 0 GLAInfantryRebel 1 860 1470
+60 autogarrison 0 GLAInfantryRebel
+
+# The middle of hut 206 is no cell, and from the east a man's path ends 4 units short of touching its
+# wall: he still goes in, "is in" with no "building 2".
+31 spawn 0 ChinaInfantryHacker 1 810 1140
+60 autogarrison 0 ChinaInfantryHacker
+
+# A player's order ends a search: the Ranger has one "heads for" line and no "is in".
+31 spawn 0 AmericaInfantryRanger 1 880 1100
+420 autogarrison 0 AmericaInfantryRanger
+421 clickstop 0 AmericaInfantryRanger
+
+# The enemy gets into the hut first: the Missile Defender goes on to another building, "building 2",
+# where a plain click would have him shoot at it.
+430 spawn 0 AmericaInfantryMissileDefender 1 840 1086
+430 spawn 1 GLAInfantryRebel 3 800 1086 10
+431 autogarrison 0 AmericaInfantryMissileDefender
+432 clickenter 1 GLAInfantryRebel civilian QuonsetHut01
+
+# An enemy Pathfinder sits unseen in a pub: the man who walks in throws him out, "is in", and the
+# Pathfinder's tally at 600 reads 0 inside.
+440 spawn 1 AmericaInfantryPathfinder 1 1097 960
+441 clickenter 1 AmericaInfantryPathfinder civilian GermanPub01
+520 tally 1 AmericaInfantryPathfinder
+520 spawn 0 GLAInfantryTunnelDefender 1 1097 930
+521 autogarrison 0 GLAInfantryTunnelDefender
+600 tally 1 AmericaInfantryPathfinder
+600 tally 0 GLAInfantryTunnelDefender
+
+# A man still on his exit path takes no order: "waits until it stands idle", then "heads for" once out.
+# The Red Guard comes out on 1041 here; the men already inside are not touched.
+440 produce 0 ChinaBarracks ChinaInfantryRedguard 1
+1041 autogarrison 0 ChinaInfantryRedguard
+1400 tally 0 ChinaInfantryRedguard
+
+# The hurt Battle Master heads for the War Factory and the hurt Worker for the Barracks. The unhurt
+# Gattling Tank, kept away from the fight, has no line.
+620 spawn 0 ChinaTankBattleMaster 1 1040 900
+620 spawn 0 ChinaTankGattling 1 1200 1160
+620 spawn 0 GLAInfantryWorker 1 1100 900
+620 spawn 1 AmericaTankCrusader 3 980 940 30
+620 spawn 1 AmericaInfantryRanger 1 1100 940
+625 attack 1 AmericaTankCrusader 0 ChinaTankBattleMaster
+625 attack 1 AmericaInfantryRanger 0 GLAInfantryWorker
+680 move 1 AmericaTankCrusader 1500 1400
+680 move 1 AmericaInfantryRanger 1500 1400
+700 autorepair 0 ChinaTankBattleMaster
+700 autorepair 0 ChinaTankGattling
+700 autorepair 0 GLAInfantryWorker
+701 tally 0 ChinaTankGattling
diff --git a/GeneralsMD/Code/Data/Turkish/Generals.str b/GeneralsMD/Code/Data/Turkish/Generals.str
index 03fd27624..8978ef04c 100644
--- a/GeneralsMD/Code/Data/Turkish/Generals.str
+++ b/GeneralsMD/Code/Data/Turkish/Generals.str
@@ -16349,6 +16349,14 @@ GUI:HotkeysCommandBEGIN_PREFER_SELECTION
"Seçime ekle (basılı tut)"
END
+GUI:HotkeysCommandAUTO_GARRISON
+"Yakındaki binalara mevzilen"
+END
+
+GUI:HotkeysCommandAUTO_REPAIR
+"Tamir olmaya ya da iyileşmeye git"
+END
+
// Maç yükleme ekranı (LoadScreen.cpp içindeki LoadScreenBoard)
GUI:LoadModeSkirmish
"Çatışma"
diff --git a/GeneralsMD/Code/Data/Ukrainian/Generals.str b/GeneralsMD/Code/Data/Ukrainian/Generals.str
index f68fa450c..3293fde71 100644
--- a/GeneralsMD/Code/Data/Ukrainian/Generals.str
+++ b/GeneralsMD/Code/Data/Ukrainian/Generals.str
@@ -17233,6 +17233,14 @@ GUI:HotkeysCommandBEGIN_PREFER_SELECTION
"Додати до виділення (утримувати)"
END
+GUI:HotkeysCommandAUTO_GARRISON
+"Зайняти будівлі поблизу"
+END
+
+GUI:HotkeysCommandAUTO_REPAIR
+"Іти на ремонт або лікування"
+END
+
GUI:LoadModeSkirmish
"Сутичка"
END
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ActionManager.h b/GeneralsMD/Code/GameEngine/Include/Common/ActionManager.h
index 6297d2607..4bc163175 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/ActionManager.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/ActionManager.h
@@ -93,6 +93,7 @@ public:
Bool canRepairObject( const Object *obj, const Object *objectToRepair, CommandSourceType commandSource );
Bool canResumeConstructionOf( const Object *obj, const Object *objectBeingConstructed, CommandSourceType commandSource );
Bool canEnterObject( const Object *obj, const Object *objectToEnter, CommandSourceType commandSource, CanEnterType mode );
+ Int openSeatsAsSeen( const Object *obj, const Object *building, CommandSourceType commandSource ); ///< a building's free seats, by what canEnterObject judges a fogged one on
CanAttackResult getCanAttackObject( const Object *obj, const Object *objectToAttack, CommandSourceType commandSource, AbleToAttackType attackType );
Bool canConvertObjectToCarBomb( const Object *obj, const Object *objectToConvert, CommandSourceType commandSource );
Bool canHijackVehicle( const Object *obj, const Object *ObjectToHijack, CommandSourceType commandSource ); // LORENZEN
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/MessageStream.h b/GeneralsMD/Code/GameEngine/Include/Common/MessageStream.h
index 73be61cdf..7416f9a9e 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/MessageStream.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/MessageStream.h
@@ -312,6 +312,8 @@ public:
MSG_META_TOGGLE_ATTACKMOVE, ///< enter attack-move mode
MSG_META_TOGGLE_FORCEATTACK, ///< arm force fire for the next order click (fork)
MSG_META_HOLD_POSITION, ///< hold position: guard in place, no pursuit (fork)
+ MSG_META_AUTO_GARRISON, ///< selected infantry garrison the buildings around them (fork)
+ MSG_META_AUTO_REPAIR, ///< selected units go to their own nearest building that mends them (fork)
MSG_META_TOGGLE_GUARD, ///< arm guard for the next order click or drag (fork)
MSG_META_TOGGLE_MOVE, ///< arm a plain move for the next order click or drag (fork)
MSG_META_TOGGLE_PAUSE, ///< pause/unpause, single player and replay only (fork)
@@ -671,6 +673,8 @@ public:
MSG_SET_REPEAT_UNIT, ///< (Int template ID, objectID producer, Bool on) the factory builds that unit on repeat, or stops (fork)
MSG_TRANSFER_MONEY, ///< (Int player index, Int amount) the sender hands that much of his money to another player (fork)
MSG_TEAM_REQUEST, ///< (Int AITeamRequestKind, Location) the sender asks his computer allies for help, money or to join his attack (fork)
+ MSG_DO_AUTO_GARRISON, ///< Every selected soldier looks for a free seat around where he stands (fork)
+ MSG_DO_AUTO_REPAIR, ///< Every selected unit goes to its own nearest building that mends it (fork)
MSG_BEGIN_DEBUG_NETWORK_MESSAGES = 1900, ///< network messages that exist only in debug/internal builds. all grouped separately.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
index 23798046a..7d53b611a 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
@@ -837,6 +837,14 @@ static const UnsignedInt AI_COOP_JOIN_FRAMES = 120 * LOGICFRAMES_PER_SECOND;
void aiPostTeamRequest( Player *from, AITeamRequestKind kind, Int enemy, const Coord3D *pos );
/** The enemy of this player's who owns what stands nearest pos, -1 for none within reach. */
Int aiEnemyNear( const Player *of, const Coord3D *pos );
+/** The nearest of this player's own buildings that mends this unit, a repair pad for a vehicle, an
+ * airfield for an aircraft, a heal pad for infantry, or NULL. A unit at full health has none. */
+Object *aiFindMender( Player *player, Object *unit, CommandSourceType cmdSource );
+/** The building within radius of center a soldier goes for next, or NULL: the one nearest center that
+ * is not in tried, that a player's order may enter, and that has a seat left after the owner's other
+ * men walking to it. A building its owner has neither in sight nor remembers is left out, so nothing
+ * he has not seen decides the search. */
+Object *aiFindFreeGarrison( Object *unit, const Coord3D *center, Real radius, const std::vector<ObjectID> &tried );
/** 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,
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
index c0d850f14..abf9a6e5f 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
@@ -770,6 +770,8 @@ public:
const Coord3D *getTunnelTripGoal() const { return &m_tunnelTripGoal; } ///< where the trip ends, once out of the far mouth
Bool isExitingProducer() const; ///< still driving the exit path out of the structure that built it
TunnelTripEnd getTunnelTripEnd() const { return m_tunnelTripEnd; } ///< how the leg from the far mouth is walked
+ void startGarrisonSearch(); ///< the auto garrison key: into the nearest free seat around here, and on to the next while a building turns the unit away
+ Bool isSeekingGarrison() const { return m_isSeekingGarrison; } ///< on an auto garrison search, so a building lost on the way is no target
#if defined(_DEBUG) || defined(_INTERNAL)
inline const Coord3D *friend_getRequestedDestination() const { return &m_requestedDestination; }
inline const Coord3D *friend_getRequestedDestination2() const { return &m_requestedDestination2; }
@@ -843,6 +845,8 @@ private:
/// TRUE when `other` gets the line and we are the one who has to do something about it
Bool crowdOutranksMe( Object *other ) const;
+ void enterNextFreeGarrison(); ///< one step of startGarrisonSearch's search
+
private:
UnsignedInt m_priorWaypointID; ///< ID of the path we follwed to before the most recent one
UnsignedInt m_currentWaypointID; ///< ID of the most recent one...
@@ -963,6 +967,9 @@ private:
Coord3D m_tunnelTripGoal; ///< Where a move order sent us before a tunnel shortened the way there.
Bool m_hasTunnelTrip; ///< True from the order to enter a tunnel until the walk from the exit to m_tunnelTripGoal is ordered.
TunnelTripEnd m_tunnelTripEnd; ///< How the last leg from the far mouth to m_tunnelTripGoal is walked.
+ Bool m_isSeekingGarrison; ///< True from the auto garrison key until the unit is inside, is out of seats or is given another order.
+ Coord3D m_garrisonSearchCenter; ///< Where the unit stood when the key was pressed; the area it searches is around this.
+ std::vector<ObjectID> m_garrisonSearchTried; ///< The buildings this search has walked to, each only once, which is what ends it.
// Locomotors -------------------------------------------------------------------------------------------------
enum LocoGoalType // Note - written out in save/load xfer, don't change these numbers. jba.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
index 28cd65525..4ff3c1635 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
@@ -96,6 +96,8 @@ enum ScenarioActionType
SCENARIO_ACTION_REPEAT, ///< repeat <slot> <building> <template> on|off; the Ctrl+Alt build key, as MSG_SET_REPEAT_UNIT onto the message stream
SCENARIO_ACTION_GIVEMONEY, ///< givemoney <slot> <targetSlot> <amount>; the Tab screen's Send, as MSG_TRANSFER_MONEY onto the message stream
SCENARIO_ACTION_CLICKSTOP, ///< clickstop <slot> <selector>; the Stop key, the group idle MSG_DO_STOP gives (CMD_FROM_PLAYER)
+ SCENARIO_ACTION_AUTOGARRISON, ///< autogarrison <slot> <selector>; the auto garrison key, as MSG_DO_AUTO_GARRISON
+ SCENARIO_ACTION_AUTOREPAIR, ///< autorepair <slot> <selector>; the auto repair key, as MSG_DO_AUTO_REPAIR
SCENARIO_ACTION_REACHPROOF, ///< reachproof <slot> <selector> <targetSlot> <probe> [samples]; every matching defence's reach overlay against the logic, the probe stood on each sample point (ReachOverlay_prove)
SCENARIO_ACTION_TOPUP ///< topup <slot> <template> <objects>; from now on, while the world holds fewer objects than that, this line's turn makes one on the road from the seat's start to the map's centre and attack-moves it there
};
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/MessageStream.cpp b/GeneralsMD/Code/GameEngine/Source/Common/MessageStream.cpp
index e7f3d31f2..e5b9d9e99 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/MessageStream.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/MessageStream.cpp
@@ -384,6 +384,8 @@ AsciiString GameMessage::getCommandTypeAsAsciiString(GameMessage::Type t)
CHECK_IF(MSG_META_TOGGLE_FORCEATTACK)
CHECK_IF(MSG_META_TOGGLE_PURCHASE_SCIENCE)
CHECK_IF(MSG_META_HOLD_POSITION)
+ CHECK_IF(MSG_META_AUTO_GARRISON)
+ CHECK_IF(MSG_META_AUTO_REPAIR)
CHECK_IF(MSG_META_TOGGLE_GUARD)
CHECK_IF(MSG_META_TOGGLE_MOVE)
CHECK_IF(MSG_META_TOGGLE_PAUSE)
@@ -677,6 +679,8 @@ AsciiString GameMessage::getCommandTypeAsAsciiString(GameMessage::Type t)
CHECK_IF(MSG_SET_REPEAT_UNIT)
CHECK_IF(MSG_TRANSFER_MONEY)
CHECK_IF(MSG_TEAM_REQUEST)
+ CHECK_IF(MSG_DO_AUTO_GARRISON)
+ CHECK_IF(MSG_DO_AUTO_REPAIR)
CHECK_IF(MSG_DO_GUARD_OBJECT)
CHECK_IF(MSG_DO_STOP)
CHECK_IF(MSG_DO_SCATTER)
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp
index 9ae9ae784..229479c44 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp
@@ -869,6 +869,13 @@ Bool ActionManager::canEnterObject( const Object *obj, const Object *objectToEnt
}
+// ------------------------------------------------------------------------------------------------
+// ------------------------------------------------------------------------------------------------
+Int ActionManager::openSeatsAsSeen( const Object *obj, const Object *building, CommandSourceType commandSource )
+{
+ const ContainModuleInterface *contain = building->getContain();
+ return contain ? contain->getContainMax() - nonStealthOccupantsAsSeen( obj, building, commandSource, contain ) : 0;
+}
// ------------------------------------------------------------------------------------------------
/** The best answer any soldier firing out of obj gives, or ATTACKRESULT_NOT_POSSIBLE */
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp
index fc7d65124..e3716fb1e 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp
@@ -562,7 +562,16 @@ void pickAndPlayUnitVoiceResponse( const DrawableList *list, GameMessage::Type m
objectWithSound = obj;
skip = true;
break;
-
+
+ case GameMessage::MSG_DO_AUTO_GARRISON:
+ if( obj->isKindOf( KINDOF_INFANTRY ) )
+ {
+ soundToPlayPtr = templ->getPerUnitSound( "VoiceGarrison" );
+ objectWithSound = obj;
+ skip = true;
+ }
+ break;
+
case GameMessage::MSG_DO_MOVETO:
case GameMessage::MSG_DO_ATTACKMOVETO:
case GameMessage::MSG_GET_REPAIRED:
@@ -3771,6 +3780,32 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage
break;
}
+ //
+ // Auto garrison and auto repair: each unit picks its own building on the logic side, from what
+ // its owner has seen, so all these carry is the key.
+ //
+ case GameMessage::MSG_META_AUTO_GARRISON:
+ {
+ if( TheInGameUI->getSelectCount() > 0 )
+ {
+ TheMessageStream->appendMessage( GameMessage::MSG_DO_AUTO_GARRISON );
+ pickAndPlayUnitVoiceResponse( TheInGameUI->getAllSelectedDrawables(), GameMessage::MSG_DO_AUTO_GARRISON );
+ disp = DESTROY_MESSAGE;
+ }
+ break;
+ }
+
+ case GameMessage::MSG_META_AUTO_REPAIR:
+ {
+ if( TheInGameUI->getSelectCount() > 0 )
+ {
+ TheMessageStream->appendMessage( GameMessage::MSG_DO_AUTO_REPAIR );
+ pickAndPlayUnitVoiceResponse( TheInGameUI->getAllSelectedDrawables(), GameMessage::MSG_GET_REPAIRED );
+ disp = DESTROY_MESSAGE;
+ }
+ break;
+ }
+
case GameMessage::MSG_META_BEGIN_CAMERA_ROTATE_LEFT:
DEBUG_ASSERTCRASH(!TheInGameUI->isCameraRotatingLeft(), ("Setting rotate camera left, but it's already set!"));
TheInGameUI->setCameraRotateLeft( true );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp
index bb16594e7..15879fcef 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp
@@ -969,6 +969,8 @@ std::vector< HotkeyCommandRow > Hotkeys_commandRows( const std::string& commandM
unbound.push_back( commandRow( "SIGNAL_DEFEND", "INFORMATION" ) );
unbound.push_back( commandRow( "SIGNAL_ATTENTION", "INFORMATION" ) );
unbound.push_back( commandRow( "REQUEST_MONEY", "INFORMATION" ) );
+ unbound.push_back( commandRow( "AUTO_GARRISON", "CONTROL" ) );
+ unbound.push_back( commandRow( "AUTO_REPAIR", "CONTROL" ) );
char name[ 32 ];
for( Int slot = 1; slot <= 8; slot++ )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp
index 03d9152cd..6aa2df582 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp
@@ -194,6 +194,8 @@ static const LookupListRec GameMessageMetaTypeNames[] =
{ "TOGGLE_FORCEATTACK", GameMessage::MSG_META_TOGGLE_FORCEATTACK },
{ "TOGGLE_PURCHASE_SCIENCE", GameMessage::MSG_META_TOGGLE_PURCHASE_SCIENCE },
{ "HOLD_POSITION", GameMessage::MSG_META_HOLD_POSITION },
+ { "AUTO_GARRISON", GameMessage::MSG_META_AUTO_GARRISON },
+ { "AUTO_REPAIR", GameMessage::MSG_META_AUTO_REPAIR },
{ "TOGGLE_GUARD", GameMessage::MSG_META_TOGGLE_GUARD },
{ "TOGGLE_MOVE", GameMessage::MSG_META_TOGGLE_MOVE },
{ "TOGGLE_PAUSE", GameMessage::MSG_META_TOGGLE_PAUSE },
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 46cf08c45..63d4ccea4 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -11269,6 +11269,37 @@ static void addMapSeats( Player *player, const Coord3D *pos, Real radius, std::v
seats->push_back( b );
}
+// ponytail: the order is by distance from center, not from where the soldier is by now, so a man turned
+// away at the far edge can cross the area; a nearest-to-him pass if players notice the walk
+Object *aiFindFreeGarrison( Object *unit, const Coord3D *center, Real radius, const std::vector<ObjectID> &tried )
+{
+ std::vector<ObjectID> goals;
+ unit->getControllingPlayer()->iterateObjects( collectBoardingGoals, &goals );
+ AIUpdateInterface *ai = unit->getAI();
+ const Int owner = unit->getControllingPlayer()->getPlayerIndex();
+ PartitionFilterGarrisonable filterGarrisonable( TRUE );
+ PartitionFilter *filters[] = { &filterGarrisonable, 0 };
+ MemoryPoolObjectHolder hold;
+ SimpleObjectIterator *nearby = ThePartitionManager->iterateObjectsInRange( center, radius, FROM_CENTER_2D, filters, ITER_SORTED_NEAR_TO_FAR );
+ hold.hold( nearby );
+ for( Object *building = nearby->first(); building; building = nearby->next() )
+ {
+ if( !building->isKindOf( KINDOF_STRUCTURE ) || std::find( tried.begin(), tried.end(), building->getID() ) != tried.end() ||
+ !TheActionManager->canEnterObject( unit, building, CMD_FROM_PLAYER, CHECK_CAPACITY ) )
+ continue;
+ // a house never in sight has no memory to read, so what really stands there would decide it, and
+ // skipping one the enemy holds would give him away
+ if( !building->friend_getPartitionData()->isInSightOf( owner ) && building->getSeenStateFor( owner ) == NULL )
+ continue;
+ // a press while he is already walking to it does not take his own seat from him
+ const Bool walkingThere = ai->getCurrentStateID() == AI_ENTER && ai->getGoalObject() == building;
+ const Int walkers = (Int)std::count( goals.begin(), goals.end(), building->getID() ) - (walkingThere ? 1 : 0);
+ if( TheActionManager->openSeatsAsSeen( unit, building, CMD_FROM_PLAYER ) > walkers )
+ return building;
+ }
+ return NULL;
+}
+
//----------------------------------------------------------------------------------------------------------
/** The computer built Bunkers and Fire Bases and never put a man in one, and walked past every empty
* farmhouse while the enemy's rebels moved in. Our own firing buildings take the default team's
@@ -13710,8 +13741,6 @@ void AIPlayer::doAmbulances( void )
}
}
-static Object *findMender( Player *player, Object *unit );
-
void AIPlayer::steerAmbulance( Int slot, const std::vector<AIKnownGun> &guns )
{
DutyAmbulance &duty = m_ambulance[ slot ];
@@ -13815,7 +13844,7 @@ void AIPlayer::steerAmbulance( Int slot, const std::vector<AIKnownGun> &guns )
// badly hurt, and out of reach now: to be repaired, riders and all, who go on healing inside
if( body->getHealth() < AMBULANCE_REPAIR_HEALTH * body->getMaxHealth() )
{
- Object *mender = findMender( m_player, ambulance );
+ Object *mender = aiFindMender( m_player, ambulance, CMD_FROM_AI );
if( mender && TheActionManager->canGetRepairedAt( ambulance, mender, CMD_FROM_AI ) )
{
if( state != AI_DOCK && state != AI_ENTER && state < 1000 )
@@ -14033,9 +14062,8 @@ Bool AIRetreat_rankPullsOut( Int rank, Real healthFraction, Bool inFight, Real r
return inFight && healthFraction < RANK_UNHURT && ratio < min( retreatRatio * (1.0f + RANK_RATIO_STEP * rank), 1.0f );
}
-/** The nearest of our own buildings that mends this unit - a repair pad for a vehicle, a heal pad for
- * infantry - or NULL. Ties go to the first in the object list. */
-static Object *findMender( Player *player, Object *unit )
+/** Ties go to the first in the object list. */
+Object *aiFindMender( Player *player, Object *unit, CommandSourceType cmdSource )
{
std::vector<Object *> owned;
player->iterateObjects( collectOwned, &owned );
@@ -14044,7 +14072,7 @@ static Object *findMender( Player *player, Object *unit )
for( std::vector<Object *>::const_iterator o = owned.begin(); o != owned.end(); ++o )
{
if( !(*o)->isKindOf( KINDOF_STRUCTURE ) ||
- !(TheActionManager->canGetRepairedAt( unit, *o, CMD_FROM_AI ) || TheActionManager->canGetHealedAt( unit, *o, CMD_FROM_AI )) )
+ !(TheActionManager->canGetRepairedAt( unit, *o, cmdSource ) || TheActionManager->canGetHealedAt( unit, *o, cmdSource )) )
continue;
const Real distSqr = sqr( (*o)->getPosition()->x - unit->getPosition()->x ) + sqr( (*o)->getPosition()->y - unit->getPosition()->y );
if( best == NULL || distSqr < bestSqr )
@@ -14092,7 +14120,7 @@ void AIPlayer::pullOutRanked( Team *team, Bool inFight, Real ratio )
const Real health = obj->getBodyModule()->getHealth() / obj->getBodyModule()->getMaxHealth();
if( !AIRetreat_rankPullsOut( rank, health, inFight, ratio, getSkillProfile()->m_retreatTtkRatio ) )
continue;
- Object *mender = findMender( m_player, obj );
+ Object *mender = aiFindMender( m_player, obj, CMD_FROM_AI );
if( mender == NULL && isAtHome( obj->getPosition() ) )
continue; // home already, and nothing there mends it
// one already walking there from an earlier pass whose row has since gone
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
index 8274cc28c..eebe4f16a 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
@@ -7104,6 +7104,10 @@ void AIEnterState::onExit( StateExitType status )
}
}
+/** How far off a house's wall the end of a man's path still counts as reaching it: a cell and a half, the
+ most the nearest free cell leaves between him and the wall. */
+static const Real GARRISON_DOOR_REACH = 1.5f * PATHFIND_CELL_SIZE_F;
+
//----------------------------------------------------------------------------------------------------------
/** Do the two objects' vertical extents touch at all? */
static Bool hasVerticalOverlap( const Object* a, const Object* b )
@@ -7149,7 +7153,8 @@ StateReturnType AIEnterState::update()
Expected result: Based on test plan: Instead of just stopping when enemy units garrison building first, they should continue and attack the building.
*/
- if( obj->getRelationship(goal) == ENEMIES && obj->getAI() )
+ // a soldier on an auto garrison search moves on to the next building instead (AIUpdateInterface::update)
+ if( obj->getRelationship(goal) == ENEMIES && obj->getAI() && !obj->getAI()->isSeekingGarrison() )
{
CanAttackResult result = TheActionManager->getCanAttackObject(obj, goal, obj->getAI()->getLastCommandSource(), ATTACK_NEW_TARGET);
if( result == ATTACKRESULT_POSSIBLE || result == ATTACKRESULT_POSSIBLE_AFTER_MOVING )
@@ -7210,12 +7215,28 @@ StateReturnType AIEnterState::update()
radius = goal->getGeometryInfo().getMajorRadius();
}
Bool closeEnough = dx*dx+dy*dy < sqr(radius);
- if (closeEnough) {
+ ContainModuleInterface* contain = goal->getContain();
+ if (contain && contain->isGarrisonable())
+ {
+ // A house's middle is no cell a man can stand on, so his path ends on the nearest free cell,
+ // which can leave him a few units short of the wall with nothing to collide with: on Alpine
+ // Assault a man walking to one hut stood 4 units off its east wall, click or no click. So
+ // this is the wall's collision, with what it does about somebody else's men inside.
+ const Real reachRadius = obj->getGeometryInfo().getBoundingCircleRadius() + GARRISON_DOOR_REACH;
+ const GeometryInfo reach( GEOMETRY_CYLINDER, FALSE, obj->getGeometryInfo().getMaxHeightAbovePosition(), reachRadius, reachRadius );
+ if (closeEnough || ThePartitionManager->geomCollidesWithGeom( obj->getPosition(), reach, obj->getOrientation(),
+ goal->getPosition(), goal->getGeometryInfo(), goal->getOrientation() ))
+ {
+ Coord3D normal;
+ normal.set( 0.0f, 0.0f, 1.0f );
+ goal->onCollide( obj, obj->getPosition(), &normal );
+ }
+ }
+ else if (closeEnough) {
// Grab the container and force ourselves into it.
// This case is primarily to handle transports on the map border for scripted setup.
// The partition manager doesn't generate collisions in the border area, so we have to
// add ourselves. jba.
- ContainModuleInterface* contain = goal->getContain();
if (obj->isKindOf(KINDOF_INFANTRY) && goal->isDisabledByType(DISABLED_UNMANNED))
{
goal->takeOverUnmanned(obj); // a driver, not a passenger - see OpenContain::onCollide
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/OrderQueue.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/OrderQueue.cpp
index 9dae5b34d..55573f505 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/OrderQueue.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/OrderQueue.cpp
@@ -374,6 +374,8 @@ Bool OrderQueue::isOrder( GameMessage::Type type )
case GameMessage::MSG_DO_GUARD_POSITION:
case GameMessage::MSG_DO_GUARD_OBJECT:
case GameMessage::MSG_DO_HOLD_POSITION:
+ case GameMessage::MSG_DO_AUTO_GARRISON:
+ case GameMessage::MSG_DO_AUTO_REPAIR:
case GameMessage::MSG_DO_STOP:
case GameMessage::MSG_DO_SCATTER:
case GameMessage::MSG_DO_FORMATION_MOVETO:
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index 20ef020dc..e51764d36 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -384,6 +384,8 @@ AIUpdateInterface::AIUpdateInterface( Thing *thing, const ModuleData* moduleData
m_tunnelTripGoal.zero();
m_hasTunnelTrip = FALSE;
m_tunnelTripEnd = TUNNEL_TRIP_MOVE;
+ m_isSeekingGarrison = FALSE;
+ m_garrisonSearchCenter.zero();
m_locomotorSet.clear();
m_curLocomotor = NULL;
m_curLocomotorSet = LOCOMOTORSET_INVALID;
@@ -1353,6 +1355,22 @@ UpdateSleepTime AIUpdateInterface::update( void )
stRet = STATE_CONTINUE;
}
+ // An auto garrison: idle inside means the seat is taken and the search is over; idle outside means
+ // the building turned the unit away, full, gone, taken or out of reach, and the next one gets its turn.
+ if (m_isSeekingGarrison && getAIStateType() == AI_IDLE)
+ {
+ const Object *building = getObject()->getContainedBy();
+ if (building != NULL)
+ {
+ DEBUG_LOG(("AUTO GARRISON: frame %d '%s' %d is in '%s' %d\n", TheGameLogic->getFrame(), getObject()->getTemplate()->getName().str(),
+ getObject()->getID(), building->getTemplate()->getName().str(), building->getID()));
+ m_isSeekingGarrison = FALSE;
+ }
+ else
+ enterNextFreeGarrison();
+ stRet = STATE_CONTINUE;
+ }
+
if (IS_STATE_SLEEP(stRet))
{
Int frames = GET_STATE_SLEEP_FRAMES(stRet);
@@ -4721,6 +4739,10 @@ void AIUpdateInterface::aiDoCommand(const AICommandParms* parms)
if (parms->m_cmdSource != CMD_FROM_AI)
m_hasTunnelTrip = FALSE;
+ // So does an auto garrison, which walks on player's enters of its own and sets itself again after each.
+ if (parms->m_cmdSource != CMD_FROM_AI)
+ m_isSeekingGarrison = FALSE;
+
#ifdef ALLOW_SURRENDER
// surrendered items have very limited options, and only via AI cmds
if (isSurrendered())
@@ -5536,6 +5558,59 @@ void AIUpdateInterface::endTunnelTrip()
m_hasTunnelTrip = FALSE;
}
+/** How far from where a soldier stood when the auto garrison key was pressed he looks for a seat. */
+static const Real AUTO_GARRISON_RADIUS = 300.0f;
+
+//----------------------------------------------------------------------------------------
+void AIUpdateInterface::startGarrisonSearch()
+{
+ m_garrisonSearchCenter = *getObject()->getPosition();
+ m_garrisonSearchTried.clear();
+
+ // A man still on his exit path, or a hacker at his gear, would only have the order held for later,
+ // off everybody's seat count and with the search forgotten when it is carried out. So he is got
+ // ready, and the search starts from update()'s idle block once he stands there.
+ const HackInternetAIInterface *hacker = getHackInternetAIInterface();
+ if (hacker != NULL && hacker->isHackingPackingOrUnpacking())
+ aiIdle( CMD_FROM_AI );
+ else if (!isExitingProducer())
+ {
+ enterNextFreeGarrison();
+ return;
+ }
+ friend_dropOrdersAfterExit();
+ m_isSeekingGarrison = TRUE;
+ DEBUG_LOG(("AUTO GARRISON: frame %d '%s' %d waits until it stands idle\n", TheGameLogic->getFrame(),
+ getObject()->getTemplate()->getName().str(), getObject()->getID()));
+}
+
+//----------------------------------------------------------------------------------------
+/**
+ * Walk to the next building with a seat, or end the search. Uses a player's order, so a fogged building
+ * is judged as the player last saw it all the way to the door. A building goes on the tried list whatever
+ * becomes of the walk, so a door nobody can reach costs one try and the search always ends.
+ */
+void AIUpdateInterface::enterNextFreeGarrison()
+{
+ Object *me = getObject();
+ Object *building = aiFindFreeGarrison( me, &m_garrisonSearchCenter, AUTO_GARRISON_RADIUS, m_garrisonSearchTried );
+ if (building == NULL)
+ {
+ DEBUG_LOG(("AUTO GARRISON: frame %d '%s' %d finds no seat left after %d buildings\n", TheGameLogic->getFrame(),
+ me->getTemplate()->getName().str(), me->getID(), (Int)m_garrisonSearchTried.size()));
+ m_isSeekingGarrison = FALSE;
+ return;
+ }
+
+ // a player's enter ends any search (aiDoCommand), so the search is set after it
+ aiEnter( building, CMD_FROM_PLAYER );
+ m_garrisonSearchTried.push_back( building->getID() );
+ m_isSeekingGarrison = TRUE;
+ DEBUG_LOG(("AUTO GARRISON: frame %d '%s' %d heads for '%s' %d, building %d of this search\n", TheGameLogic->getFrame(),
+ me->getTemplate()->getName().str(), me->getID(), building->getTemplate()->getName().str(), building->getID(),
+ (Int)m_garrisonSearchTried.size()));
+}
+
//----------------------------------------------------------------------------------------
/**
* Follow the path defined by the given array of points
@@ -7511,12 +7586,13 @@ void AIUpdateInterface::crc( Xfer *x )
* 18: the target a helicopter keeps shooting while it moves away
* 19: the radius a player's guard order set
* 20: the aggressive stance
- * 21: the player's orders held until the exit path is done */
+ * 21: the player's orders held until the exit path is done
+ * 22: the auto garrison search */
// ------------------------------------------------------------------------------------------------
void AIUpdateInterface::xfer( Xfer *xfer )
{
// version
- const XferVersion currentVersion = 21;
+ const XferVersion currentVersion = 22;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -7866,6 +7942,14 @@ void AIUpdateInterface::xfer( Xfer *xfer )
m_ordersAfterExit[i].doXfer(xfer);
}
+ if (version >= 22)
+ {
+ // a save made while a soldier is on his way to a building owes him the rest of the search
+ xfer->xferBool(&m_isSeekingGarrison);
+ xfer->xferCoord3D(&m_garrisonSearchCenter);
+ xfer->xferSTLObjectIDVector(&m_garrisonSearchTried);
+ }
+
} // end xfer
// ------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
index 7ce480c9b..e45e1bcef 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
@@ -34,6 +34,7 @@
#include "Lib/WideCharFns.h"
+#include "Common/ActionManager.h"
#include "Common/CRCDebug.h"
#include "Common/DrawnPath.h"
#include "Common/GameAudio.h"
@@ -1263,6 +1264,60 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, AIGroup *orderedGroup
break;
}
+ //---------------------------------------------------------------------------------------------
+ //
+ // Auto garrison (fork). Each soldier looks around the spot he stands on, in group order, so
+ // the men already sent count against the seats the next one is offered.
+ //
+ case GameMessage::MSG_DO_AUTO_GARRISON:
+ {
+ if (currentlySelectedGroup == NULL)
+ break;
+
+ const VecObjectID ids = currentlySelectedGroup->getAllIDs();
+ for (VecObjectID::const_iterator it = ids.begin(); it != ids.end(); ++it)
+ {
+ Object *obj = TheGameLogic->findObjectByID( *it );
+ if (!obj || obj->getControllingPlayer() != thisPlayer || !obj->isKindOf( KINDOF_INFANTRY ) || obj->isContained() || !obj->getAIUpdateInterface())
+ continue;
+
+ obj->releaseWeaponLock( LOCKED_TEMPORARILY ); // as MSG_ENTER does
+ obj->getAIUpdateInterface()->startGarrisonSearch();
+ }
+ break;
+ }
+
+ //---------------------------------------------------------------------------------------------
+ //
+ // Auto repair (fork). Each unit goes to its own nearest building that mends it; aiFindMender
+ // finds none for a unit at full health.
+ //
+ case GameMessage::MSG_DO_AUTO_REPAIR:
+ {
+ if (currentlySelectedGroup == NULL)
+ break;
+
+ const VecObjectID ids = currentlySelectedGroup->getAllIDs();
+ for (VecObjectID::const_iterator it = ids.begin(); it != ids.end(); ++it)
+ {
+ Object *obj = TheGameLogic->findObjectByID( *it );
+ if (!obj || obj->getControllingPlayer() != thisPlayer || obj->isContained() || !obj->getAIUpdateInterface())
+ continue;
+
+ Object *mender = aiFindMender( thisPlayer, obj, CMD_FROM_PLAYER );
+ if (mender == NULL)
+ continue;
+
+ DEBUG_LOG(( "AUTO REPAIR: frame %d '%s' %d heads for '%s' %d\n", getFrame(), obj->getTemplate()->getName().str(),
+ obj->getID(), mender->getTemplate()->getName().str(), mender->getID() ));
+ if (TheActionManager->canGetRepairedAt( obj, mender, CMD_FROM_PLAYER ))
+ obj->getAIUpdateInterface()->aiGetRepaired( mender, CMD_FROM_PLAYER );
+ else
+ obj->getAIUpdateInterface()->aiGetHealed( mender, CMD_FROM_PLAYER );
+ }
+ break;
+ }
+
//---------------------------------------------------------------------------------------------
//
// Formation move (fork). The player drags a line and the selection spreads itself along
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
index 179cb25c9..7fc45c663 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
@@ -204,6 +204,10 @@ static Bool parseActionType( const AsciiString &token, ScenarioActionType *actio
*action = SCENARIO_ACTION_STOP;
else if (token == "clickstop")
*action = SCENARIO_ACTION_CLICKSTOP;
+ else if (token == "autogarrison")
+ *action = SCENARIO_ACTION_AUTOGARRISON;
+ else if (token == "autorepair")
+ *action = SCENARIO_ACTION_AUTOREPAIR;
else if (token == "arrive")
*action = SCENARIO_ACTION_ARRIVE;
else if (token == "particles")
@@ -359,6 +363,8 @@ static Int tokensNeededFor( ScenarioActionType action )
case SCENARIO_ACTION_REACHPROOF: return SCENARIO_TOKENS_ATTACK;
case SCENARIO_ACTION_STOP: return SCENARIO_TOKENS_STOP;
case SCENARIO_ACTION_CLICKSTOP: return SCENARIO_TOKENS_STOP;
+ case SCENARIO_ACTION_AUTOGARRISON: return SCENARIO_TOKENS_STOP;
+ case SCENARIO_ACTION_AUTOREPAIR: return SCENARIO_TOKENS_STOP;
case SCENARIO_ACTION_TALLY: return SCENARIO_TOKENS_STOP;
case SCENARIO_ACTION_PURCHASE: return SCENARIO_TOKENS_STOP;
case SCENARIO_ACTION_ARRIVE: return SCENARIO_TOKENS_ARRIVE;
@@ -533,6 +539,8 @@ ScenarioParseResult ScenarioDrill_parseLine( const char *line, ScenarioAction *a
case SCENARIO_ACTION_STOP:
case SCENARIO_ACTION_CLICKSTOP:
+ case SCENARIO_ACTION_AUTOGARRISON:
+ case SCENARIO_ACTION_AUTOREPAIR:
case SCENARIO_ACTION_PURCHASE:
break;
}
@@ -1911,6 +1919,20 @@ static Bool executeOrder( const ScenarioAction &action, Player *player, const Co
case SCENARIO_ACTION_WEAPONAT:
return executeWeaponAt( action, player, dest, group, taken ); // the dispatcher again
+ case SCENARIO_ACTION_AUTOGARRISON:
+ case SCENARIO_ACTION_AUTOREPAIR:
+ {
+ // the key's message, through the dispatcher, which destroys the group
+ GameMessage *msg = newInstance( GameMessage )( action.action == SCENARIO_ACTION_AUTOGARRISON ? GameMessage::MSG_DO_AUTO_GARRISON : GameMessage::MSG_DO_AUTO_REPAIR );
+ msg->friend_setPlayerIndex( player->getPlayerIndex() );
+ TheGameLogic->logicMessageDispatcher( msg, group );
+ msg->deleteInstance();
+ DEBUG_LOG(("SCENARIO: frame %d %s slot %d '%s' x%d\n", action.frame,
+ action.action == SCENARIO_ACTION_AUTOGARRISON ? "autogarrison" : "autorepair",
+ action.slot, action.selector.str(), taken));
+ return TRUE;
+ }
+
case SCENARIO_ACTION_FORCEGROUND:
{
// the attack key's click on open ground, through the dispatcher, which destroys the group
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 007e26c04..06a356548 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -2166,14 +2166,18 @@ TEST(hotkeys_every_row_the_page_lists_is_a_command_the_game_knows)
const std::vector< HotkeyCommandRow > rows = Hotkeys_commandRows( HOTKEYS_COMMAND_MAP );
MetaNameProbe names;
Int idle = 0;
+ Int autoOrders = 0;
for( size_t each = 0; each < rows.size(); each++ )
{
CHECK( names.findGameMessageMetaType( rows[ each ].id.c_str() ) != GameMessage::MSG_INVALID );
for( size_t name = 0; name < sizeof( IDLE ) / sizeof( IDLE[ 0 ] ); name++ )
if( rows[ each ].id == IDLE[ name ] && rows[ each ].category == "SELECTION" && rows[ each ].binding.key.empty() )
idle++;
+ if( ( rows[ each ].id == "AUTO_GARRISON" || rows[ each ].id == "AUTO_REPAIR" ) && rows[ each ].category == "CONTROL" && rows[ each ].binding.key.empty() )
+ autoOrders++;
}
CHECK_EQ( idle, 6 );
+ CHECK_EQ( autoOrders, 2 );
}
TEST(hotkeys_file_the_launcher_wrote_comes_back_byte_for_byte)
@@ -19722,6 +19726,14 @@ TEST(scenario_parses_the_order_lines)
CHECK_STR( action.name.str(), "aggressive" );
CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 stance 0 * bold", &action ), (Int)SCENARIO_PARSE_BAD_ACTION );
CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 stance 0 *", &action ), (Int)SCENARIO_PARSE_MISSING_ARGS );
+
+ // the auto garrison and auto repair keys
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 autogarrison 0 ChinaInfantryRedguard", &action ), (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_AUTOGARRISON );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 autorepair 0 *", &action ), (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_AUTOREPAIR );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 autorepair 0", &action ), (Int)SCENARIO_PARSE_MISSING_ARGS );
+
CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 hunt 0 * 900 700", &action ), (Int)SCENARIO_PARSE_BAD_ACTION );
CHECK_EQ( (Int)ScenarioDrill_parseLine( "700 power 1 GLAScudStorm start0:0:300", &action ),