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.

fix(gamelogic): stream weapons, jet break-off, aircraft guards, target pick

Olcay Seyganb9226fe7ad77
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 263d961ff..2cfe68a02 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -557,6 +557,8 @@ found and fixed, EA's own, not port damage.**
- Artillery lands on time. The Fire Base, the Inferno Cannon, the Nuke Cannon and the campaign's battleships fire like real guns now: the shell flies a true arc and comes down the same time after it left at any range, 1.2 seconds for a Fire Base and 1.6 for the Inferno and Nuke Cannons, and the gun raises its barrel to that arc before it fires. A target close in gets a steep lob from a barrel near upright (a Fire Base fires at 57 degrees on a 108 shot, an Inferno at 77 on a 55 one), a far one a flatter shot (34 degrees at 225, 49 at 235), and the drawn barrel and the shell's way out agree to under a degree. Each flight time is the old shot's average over the gun's range, so a tank has as long to drive out from under it as it had, and a shell still follows a target that keeps moving. Before this the barrel's angle and the arc came from two places and never met. The Fire Base's howitzer fires the tanks' shell, so when tank shells went straight it fired flat under a barrel 46 degrees up; the Inferno's barrel sat at 45 whatever the range. The battleships fired from a point 65 past their front guns and from under the waterline behind them, and both turrets aimed for the front gun; every shell now leaves its own drawn muzzle. A Technical's cannon shell left 17 in front of its gun and now leaves the gun. Tank shells still fly straight.
- A SCUD or a Tomahawk flies one smooth curve to its target. A SCUD went straight up, flipped over the top at six degrees a frame, glided flat for a moment and then kinked again into its dive. Now it rolls over and comes down in a single sweep that only ever eases off, its sharpest turn 4.6 degrees a frame. The Scud Storm takes the same curve and lands within half a second of when it did. Replays recorded before this play back differently.
- Machine gun fire looks fast. The tracers of a Humvee, a Technical or a Quad Cannon crawled across the field at 300 a second and took half a second to reach a target 150 away; they now cross it in a tenth of a second, at 1,500, as streaks twice as long. Rangers, Rebels, Gattling Tanks and Cannons, Comanches and the Spectre got the same treatment. Only the picture changed: every bullet lands when it always did.
+- The Toxin Tractor and the other stream weapons spray one straight line into a building again, not a zigzag.
+- Units pick their own targets by what their weapons kill fastest. A Humvee shoots the Technical or the infantry before the tank, and a tank goes for the tank. Anything that is shooting one of your units still gets answered. Computer armies pick the same way.
## Point defense lasers back on the planes, in clips on the tanks
@@ -905,6 +907,9 @@ found and fixed, EA's own, not port damage.**
- And the bombers come down at all. A B-52, a Spectre gunship, a cargo plane and an A-10 all left the falling speed out of their data, and nought means the lift exactly cancels gravity: shot down, they flew on at cruising height, burning, and blew up in the air still level. Every one of them now falls at half gravity or better, and the fireball waits for the ground instead of going off on a timer somewhere over the map. Measured on the way in: a B-52 falls for 2.8 seconds and lands, where it used to detonate at a hundred feet. On the way home it still did not: after the drop a bomber flies off the map on a precise course that is allowed three times its normal lift, which held a dead one up with lift to spare. A bomber shot down after its run now comes down like one shot down before it.
- Jets that end up on top of their target swing wide and come back on a straight run. A Raptor that came over a tank too close to fire used to bank toward it and keep banking, with the tank sitting inside its turn: one ordered onto an Overlord driving along beside it circled the tank for two and a half seconds without a shot and needed 7.3 seconds to get its four missiles off. It now holds its heading until the tank is far enough behind to turn round on, and comes back lined up: 4 seconds. A target behind the wing or just past it gets the same treatment, where the jet used to turn in, find itself over the target again and fly out anyway. Over 42 staged passes with the Raptor, the MiG, the Aurora and the Stealth Fighter, aimed at targets beside, under and behind them, parked and driving, the slowest Raptor run went from 7.3 seconds to 6.4 and the slowest MiG run from 5.6 to 4.7; on average the Raptor empties its racks 0.3 seconds sooner and the MiG 0.26. The Aurora drops its bomb on the same frame as before, a jet lined up on its target flies the same run as before, and jets fighting aircraft are untouched. A replay recorded before this change, with jets attacking the ground, will not play back the same.
- A supply truck told to go somewhere as it pulls off the dock goes there. It used to finish the docking it had just left and drive back to the supplies, throwing your order away.
+- Jets fire as they come in and break away before the target instead of flying over it. A jet still turning onto its target no longer abandons the run.
+- Aircraft guarding an area attack buildings first, then vehicles, then infantry, so an Aurora no longer drops its bomb on a lone soldier.
+- Auto garrison also puts infantry into a friendly transport with free seats when no building nearby has room.
## The same game on both screens, and after loading
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifest
index 2b42e5ecf..42bf0fbd8 100644
--- a/GeneralsMD/Code/BuildFingerprint.manifest
+++ b/GeneralsMD/Code/BuildFingerprint.manifest
@@ -337,6 +337,7 @@ Data/Scenarios/artillery.txt
Data/Scenarios/aurorablast.txt
Data/Scenarios/aurorafog.txt
Data/Scenarios/autoorders.txt
+Data/Scenarios/autoride.txt
Data/Scenarios/avengerlasers.txt
Data/Scenarios/baseintruder_barracks.txt
Data/Scenarios/baseintruder_patriot.txt
@@ -385,6 +386,7 @@ Data/Scenarios/glowbase.txt
Data/Scenarios/glowfight.txt
Data/Scenarios/glowmicrowave.txt
Data/Scenarios/gpu1m_battle.txt
+Data/Scenarios/guardair.txt
Data/Scenarios/guardradius.txt
Data/Scenarios/gunfx.txt
Data/Scenarios/handicap.txt
@@ -411,6 +413,7 @@ Data/Scenarios/infconvoy.txt
Data/Scenarios/inferno30.txt
Data/Scenarios/infheadon.txt
Data/Scenarios/infroad.txt
+Data/Scenarios/jetbreak.txt
Data/Scenarios/jetcrash.txt
Data/Scenarios/jetpass.txt
Data/Scenarios/jetrunway.txt
@@ -520,10 +523,12 @@ Data/Scenarios/sun_cloak.txt
Data/Scenarios/sun_trees.txt
Data/Scenarios/swhole.txt
Data/Scenarios/swpair.txt
+Data/Scenarios/targetpick.txt
Data/Scenarios/technicalexit.txt
Data/Scenarios/techrespawn.txt
Data/Scenarios/towncross.txt
Data/Scenarios/toxinslope.txt
+Data/Scenarios/toxinstream.txt
Data/Scenarios/trailer_arrival.txt
Data/Scenarios/trailer_chaos.txt
Data/Scenarios/trailer_clash.txt
diff --git a/GeneralsMD/Code/Data/Scenarios/autoride.txt b/GeneralsMD/Code/Data/Scenarios/autoride.txt
new file mode 100644
index 000000000..fd72455a5
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/autoride.txt
@@ -0,0 +1,17 @@
+# The auto garrison key with no building in reach: the men board a friendly transport instead.
+#
+# Six Rangers and one empty Humvee (five seats) on the open sand in the middle of the small
+# generated map guardradius.txt uses, no building within the key's 300 radius. Expect five
+# "AUTO GARRISON: ... heads for 'AmericaVehicleHumvee'" lines and five "is in 'AmericaVehicleHumvee'",
+# and the sixth Ranger "finds no seat left after 0 buildings", because the five walking to it fill it.
+# A building in reach still comes first (autoorders.txt).
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -randommap 1 2 small -autoskirmish 2 -takeover
+# -side 0 FactionAmerica -side 1 FactionGLA -seed 1 -maxframes 900
+# -scenario autoride -logPrefix autoride_
+
+30 spawn 0 AmericaVehicleHumvee 1 700 580
+30 spawn 0 AmericaInfantryRanger 6 700 500 20
+60 autogarrison 0 AmericaInfantryRanger
+400 tally 0 AmericaVehicleHumvee
diff --git a/GeneralsMD/Code/Data/Scenarios/guardair.txt b/GeneralsMD/Code/Data/Scenarios/guardair.txt
new file mode 100644
index 000000000..5a763cd36
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/guardair.txt
@@ -0,0 +1,33 @@
+# What a guarding Aurora bombs first. It used to be the nearest thing in its circle, usually a soldier;
+# now buildings, then vehicles, then infantry, nearest within each.
+#
+# Three circles, an Aurora over each, guarding with a radius. In every circle the Red Guards stand
+# nearest the centre, so the nearest-first rule would pick them every time.
+# A: a Barracks 60 out, a Battlemaster 85 out, Red Guards 30 out -> the Barracks, class 0
+# B: a Battlemaster 140 out, Red Guards on the centre -> the Battlemaster, class 1
+# C: Red Guards alone -> a Red Guard, class 2
+# Read the first GUARD AIR line of each Aurora template. Ground guards keep the nearest.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -map "Maps\Alpine Assault\Alpine Assault.map" -autoskirmish 2 -takeover
+# -side 0 FactionAmerica -side 1 FactionChina -seed 1 -maxframes 1800
+# -scenario guardair -logPrefix guardair_
+
+30 spawn 1 ChinaBarracks 1 900 770
+30 spawn 1 ChinaTankBattleMaster 1 980 860
+30 spawn 1 ChinaInfantryRedguard 2 900 860 20
+30 spawn 0 AmericaJetAurora 1 900 830
+
+30 spawn 1 ChinaTankBattleMaster 1 1190 1210
+30 spawn 1 ChinaInfantryRedguard 2 1310 1290 20
+30 spawn 0 AirF_AmericaJetAurora 1 1310 1290
+
+30 spawn 1 ChinaInfantryRedguard 2 850 1120 20
+30 spawn 0 SupW_AmericaJetAurora 1 850 1120
+
+60 shiftguard 0 AmericaJetAurora 900 830 150
+60 shiftguard 0 AirF_AmericaJetAurora 1310 1290 200
+60 shiftguard 0 SupW_AmericaJetAurora 850 1120 120
+
+61 tally 1 ChinaBarracks
+850 tally 1 ChinaBarracks
diff --git a/GeneralsMD/Code/Data/Scenarios/jetbreak.txt b/GeneralsMD/Code/Data/Scenarios/jetbreak.txt
new file mode 100644
index 000000000..e55680a74
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/jetbreak.txt
@@ -0,0 +1,44 @@
+# Four jets at cruise, each sent head-on at a parked ground target on its own line: the run that used
+# to end with the jet over the target. It now fires from its reach on the way in and turns away at the
+# break-off distance (AIAttackAimAtTargetState::computeAttackRunGoal), so it never flies over.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -map "Maps\Twilight Flame\Twilight Flame.map" -autoskirmish 2 -takeover
+# -side 0 FactionAmerica -side 1 FactionChina -seed 7 -maxframes 1400
+# -scenario jetbreak -logPrefix jetbreak_
+#
+# Two log lines, both -scenario only. SCENARIO SHOT is every shot an aircraft fires: its dist is the
+# weapon's own range measure (between the bounding spheres) and range the weapon's reach, so the first
+# shot of a pass reads its distance against the reach. SCENARIO JET RUN is every frame a jet aims at a
+# ground target: dist centre to centre in 2D, reach (range plus both spheres), breakoff, the turn
+# radius, and BREAK OFF on the frame it turns away. The closest approach of a pass is the smallest dist
+# between its BREAK OFF and the next run in; before the fix it fell to tens of units, the jet over the
+# target. Done when every jet's closest approach stays near its breakoff's clearance (the larger of the
+# minimum range and the turn radius) and the tallies still show the targets hit.
+#
+# Target spots from jetpass.txt, where the spawn check accepts each.
+
+30 spawn 1 ChinaTankOverlord 1 2250 3300
+30 spawn 0 AmericaJetRaptor 1 1000 3300
+31 move 0 AmericaJetRaptor 4400 3300
+30 spawn 1 ChinaTankBattleMaster 1 2200 3650
+30 spawn 0 ChinaJetMIG 1 1000 3650
+31 move 0 ChinaJetMIG 4400 3650
+30 spawn 1 AmericaTankCrusader 1 2200 4000
+30 spawn 0 AmericaJetAurora 1 1000 4000
+31 move 0 AmericaJetAurora 4400 4000
+30 spawn 1 GLATankScorpion 1 2200 4350
+30 spawn 0 AmericaJetStealthFighter 1 1000 4350
+31 move 0 AmericaJetStealthFighter 4400 4350
+100 attack 0 AmericaJetRaptor 1 ChinaTankOverlord
+100 attack 0 ChinaJetMIG 1 ChinaTankBattleMaster
+100 attack 0 AmericaJetAurora 1 AmericaTankCrusader
+100 attack 0 AmericaJetStealthFighter 1 GLATankScorpion
+400 tally 1 ChinaTankOverlord
+400 tally 1 ChinaTankBattleMaster
+400 tally 1 AmericaTankCrusader
+400 tally 1 GLATankScorpion
+690 tally 1 ChinaTankOverlord
+690 tally 1 ChinaTankBattleMaster
+690 tally 1 AmericaTankCrusader
+690 tally 1 GLATankScorpion
diff --git a/GeneralsMD/Code/Data/Scenarios/jetpass.txt b/GeneralsMD/Code/Data/Scenarios/jetpass.txt
index 02b52bc64..01f6c13c6 100644
--- a/GeneralsMD/Code/Data/Scenarios/jetpass.txt
+++ b/GeneralsMD/Code/Data/Scenarios/jetpass.txt
@@ -3,7 +3,7 @@
#
# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
# -map "Maps\Twilight Flame\Twilight Flame.map" -autoskirmish 2 -takeover
-# -side 0 FactionAmerica -side 1 FactionChina -seed 7 -maxframes 700
+# -side 0 FactionAmerica -side 1 FactionChina -seed 7 -maxframes 1400
# -scenario jetpass -logPrefix jetpass_
#
# The jets reach x=2200 around frame 250. Measured 2026-10-02: before the fix the Raptor circled the
@@ -18,6 +18,13 @@
# against 800 at 490 (the Raptor turns too wide to get all four off in one pass and is still on its
# second at 650), Battle Master 222 at 290 against 234 at 500, Crusader 80 at 300 against 80 at 330,
# Scorpion 170 at 330 against 170 at 430. Every jet still hits; the wide turns cost time.
+#
+# 2026-11-04, jets break off instead of flying over (jetbreak.txt): health at 650 Overlord 700 (from
+# 450), Battle Master 234, Crusader 80, Scorpion 170. A first cut broke off on distance alone and the
+# Stealth Fighter, coming back round on the Scorpion, turned away before its nose was on it every pass
+# and never fired (370 of 370); breaking off only with the target in the aim cone fixed it. Closest
+# approach, centre to centre: Raptor 142, MiG 148, Aurora 123, Stealth 111. -maxframes counts the
+# 60 Hz logic frames, so the file's 650 needs 1400.
30 spawn 1 ChinaTankOverlord 1 2250 3300
30 spawn 0 AmericaJetRaptor 1 1000 3420
diff --git a/GeneralsMD/Code/Data/Scenarios/targetpick.txt b/GeneralsMD/Code/Data/Scenarios/targetpick.txt
new file mode 100644
index 000000000..9d06175e5
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/targetpick.txt
@@ -0,0 +1,37 @@
+# What a unit on attack move shoots first: what its weapon kills best for the time it costs, not
+# the nearest thing nor the most expensive one (aiTargetTier, aiTargetKillRate in AI.cpp).
+#
+# Three fights 750 apart on Alpine Assault, each attacker spawned 190 to 225 from its whole group,
+# outside the group's reach, with the target the nearest-first rule would have picked nearest:
+# A: a Humvee, a Battlemaster nearest and Red Guards behind it -> a Red Guard
+# B: a Crusader, Red Guards nearest and a Battlemaster behind -> the Battlemaster
+# C: a Humvee, a Battlemaster nearest and a Technical behind -> the Technical
+# Each TARGET PICK line names the pick, its tier and rate, how many candidates the search held
+# and the nearest of them. The attack-move scan is the line whose count holds the whole group;
+# the attackers' turrets also scan their own shorter sight and log a pick among what that holds
+# (the Crusader's 'of 2' at frame 69, the Humvee's Battlemaster 'of 1' while it drives to its pick).
+# Seen 2026-11-04: A frame 71 Red Guard over the nearest Battlemaster; B frame 75 the Battlemaster
+# over the nearest Red Guard; C frame 198 the Technical over the nearest Battlemaster.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -map "Maps\Alpine Assault\Alpine Assault.map" -autoskirmish 2 -takeover
+# -side 0 FactionAmerica -side 1 FactionChina -seed 1 -maxframes 1200
+# -scenario targetpick -logPrefix targetpick_
+
+30 spawn 1 ChinaTankBattleMaster 1 950 300
+30 spawn 1 ChinaInfantryRedguard 2 985 300 25
+30 spawn 0 AmericaVehicleHumvee 1 760 300
+
+30 spawn 1 ChinaInfantryRedguard 2 950 2200 25
+30 spawn 1 ChinaTankBattleMaster 1 985 2200
+30 spawn 0 AmericaTankCrusader 1 760 2200
+
+30 spawn 1 ChinaTankBattleMaster 1 950 1060
+30 spawn 1 GLAVehicleTechnical 1 985 1060
+30 spawn 0 SupW_AmericaVehicleHumvee 1 760 1060
+
+32 attackmove 0 AmericaVehicleHumvee 1400 300
+32 attackmove 0 AmericaTankCrusader 1335 2200
+32 attackmove 0 SupW_AmericaVehicleHumvee 1400 1060
+
+500 tally 1 *
diff --git a/GeneralsMD/Code/Data/Scenarios/toxinstream.txt b/GeneralsMD/Code/Data/Scenarios/toxinstream.txt
new file mode 100644
index 000000000..b44c8faec
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/toxinstream.txt
@@ -0,0 +1,21 @@
+# A Toxin Tractor spraying a power plant, for the aim of every blob in its stream. A stream weapon is
+# drawn as one line through all its blobs in the air, so each blob has to fly to the same point: the
+# power plant's middle, EA's aim. Source 22838d05 gave every shot its own point on the body, and the
+# line zigzagged over the building.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -map "Maps\Twilight Flame\Twilight Flame.map" -autoskirmish 2 -takeover
+# -side 0 FactionAmerica -side 1 FactionGLA -seed 7 -maxframes 1300
+# -scenario toxinstream -logPrefix toxinstream_
+#
+# Read the SCENARIO SHOT lines of ToxinTruckGun: the aim (x,y,z) must be one point on every line, since
+# the power plant does not move. Before the fix each line had its own. Any other weapon at an object
+# still spreads its shots over the body; this file logs only streams and aircraft.
+#
+# Power plant spot from blastcheck.txt, the truck from its Overlord block.
+
+20 spawn 0 AmericaPowerPlant 1 1230 3640
+40 spawn 1 GLAVehicleToxinTruck 1 1150 3950
+60 attack 1 GLAVehicleToxinTruck 0 AmericaPowerPlant
+60 tally 0 AmericaPowerPlant
+600 tally 0 AmericaPowerPlant
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
index b8eb7a330..c661de1da 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
@@ -52,8 +52,10 @@ class Path;
class Pathfinder;
class Player;
class PolygonTrigger;
+class SimpleObjectIterator;
class ThingTemplate;
class UpgradeTemplate;
+class WeaponBonus;
class WeaponTemplate;
enum GUICommandType : Int;
@@ -385,6 +387,36 @@ const Real AI_CANNOT_KILL = -1.0f;
* AI_CANNOT_KILL when it does no damage to it. */
Real aiFramesToKill( Real targetHealth, const AIShotPattern &shots );
+/** Every field of shots but the damage: the weapon's delays, clip and opening, at these bonuses. The
+ * AI's matchups read a template's, a unit choosing what to shoot reads its own weapon's. */
+void aiShotTiming( const WeaponTemplate *weapon, const WeaponBonus &bonus, AIShotPattern *shots );
+
+/** A unit choosing its own target (idle, attack move, after a kill, guard) ranks every candidate by
+ * this, and aiTargetBeats decides. */
+struct AITargetRating
+{
+ Int m_tier; ///< aiTargetTier
+ Real m_rate; ///< aiTargetKillRate
+ Real m_distSqr; ///< the nearer of two equal rates, for the unit that can hurt nothing there
+ ObjectID m_id; ///< the last tie, so every machine picks the same one
+};
+
+const Int AI_QUICK_KILL_FRAMES = 10 * LOGICFRAMES_PER_SECOND;
+
+/** 2 for whoever just shot us, and for an armed enemy already in reach that we kill within
+ * AI_QUICK_KILL_FRAMES; 1 for any other enemy that can shoot us; 0 for the rest. So a far target
+ * we counter never keeps a unit from turning on its shooter, and one we finish in seconds does. */
+Int aiTargetTier( Bool shotMe, Bool threatensMe, Bool inRange, Real framesToKill );
+
+/** What one target is worth per frame spent on it: value over the frames to kill it (aiFramesToKill
+ * with our best weapon against its armour and health) plus the frames to drive gap world units at
+ * speed into reach. 0 when we cannot hurt it, or it is out of reach of a unit that cannot move. */
+Real aiTargetKillRate( Real value, Real framesToKill, Real gap, Real speed );
+
+/** Whether a takes the pick from b: the higher tier, then the higher rate, then the nearer, then the
+ * lower ObjectID. */
+Bool aiTargetBeats( const AITargetRating &a, const AITargetRating &b );
+
/** One pairing as 0..1, money for money: 0.5 an even trade, 1 when my side kills sixteen times
* faster for its price (or cannot be hurt back), 0 when it cannot hurt the other side. */
Real aiMatchupScore( Real myFramesToKill, Real theirFramesToKill, Real myCost, Real theirCost );
@@ -698,6 +730,14 @@ Real aiStartOccupiedOdds( Int unlocatedEnemies, Int uncheckedPositions );
* building in the way. */
Bool aiIsIncomeNotATarget( Bool isTechBuilding, Bool isCapturable, Bool isTechBaseDefense );
+/** What a guarding aircraft bombs first: 0 a building, 1 a vehicle, 2 a soldier, 3 anything else.
+ * An Aurora guarding a circle took the nearest thing in it, usually one infantryman, and flew home
+ * to rearm while the factory beside him stood. */
+Int aiGuardAirTargetClass( Bool isStructure, Bool isVehicle, Bool isInfantry );
+/** Whether candidate a takes a guarding aircraft's pick from b: the lower class, then the nearer, then
+ * the lower ObjectID, so every machine picks the same one. */
+Bool aiGuardAirTargetBeats( Int classA, Real distSqrA, ObjectID idA, Int classB, Real distSqrB, ObjectID idB );
+
/** What a superweapon target is still worth, given one shot already aimed at it - 1.0 untouched,
* 0.0 right on top of a shot aimed this frame, climbing back over 'window' frames and with
* distance from that shot.
@@ -853,7 +893,8 @@ 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. */
+ * he has not seen decides the search. With no such building, the nearest friendly transport on the
+ * ground with a seat left by the same test (a Humvee, a Chinook, a bunkered Overlord). */
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
@@ -1131,11 +1172,17 @@ public:
ATTACK_BUILDINGS = 1 << 3,
WITHIN_ATTACK_RANGE = 1 << 4,
UNFOGGED = 1 << 5,
- PREFER_HIGH_THREAT = 1 << 6 ///< pick the biggest threat in range, not the nearest thing
+ PREFER_BEST_TARGET = 1 << 6 ///< pick by pickBestTarget, not the nearest thing
};
- Object *findClosestEnemy( const Object *me, Real range, UnsignedInt qualifiers,
+ Object *findClosestEnemy( const Object *me, Real range, UnsignedInt qualifiers,
const AttackPriorityInfo *info=NULL, PartitionFilter *optionalFilter=NULL);
+ /** The candidate me would rather shoot than any other, by aiTargetBeats, or NULL. lateFilters
+ * (NULL-terminated) are asked only of a candidate that would take the lead. */
+ Object *pickBestTarget( const Object *me, SimpleObjectIterator *candidates, PartitionFilter **lateFilters );
+ /** Whether me would rather shoot a than b, by the same rule. */
+ Bool prefersTarget( const Object *me, Object *a, Object *b );
+
Object *findClosestRepulsor( const Object *me, Real range);
Object *findClosestAlly( const Object *me, Real range, UnsignedInt qualifiers);
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
index 6f1455083..888fafcf5 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
@@ -1536,11 +1536,12 @@ public:
);
SimpleObjectIterator *iterateObjectsInRange(
- const Coord3D *pos,
- Real maxDist,
- DistanceCalculationType dc,
- PartitionFilter **filters = NULL,
- IterOrderType order = ITER_FASTEST
+ const Coord3D *pos,
+ Real maxDist,
+ DistanceCalculationType dc,
+ PartitionFilter **filters = NULL,
+ IterOrderType order = ITER_FASTEST,
+ PlayerMaskType onlyPlayers = PLAYERMASK_ALL ///< as for getClosestObject
);
SimpleObjectIterator *iterateAllObjects(PartitionFilter **filters = NULL);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
index c42fb67de..77f8fcc63 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
@@ -36,6 +36,7 @@
#include "Common/Player.h"
#include "Common/PlayerList.h"
#include "Common/PlayerTemplate.h"
+#include "Common/ThingFactory.h"
#include "Common/ThingTemplate.h"
#include "Common/Xfer.h"
#include "Common/XferCRC.h"
@@ -43,6 +44,7 @@
#include "GameLogic/AI.h"
#include "GameLogic/PartitionManager.h"
#include "GameLogic/Module/AIUpdate.h"
+#include "GameLogic/Module/BodyModule.h"
#include "GameLogic/Module/ContainModule.h"
#include "GameLogic/ScriptEngine.h"
#include "GameLogic/SidesList.h"
@@ -358,6 +360,10 @@ AI::AI( void )
/**
* Initialize the AI system
*/
+/** A build variation's own template, a Technical's chassis, has no cost; the template that lists it
+ * does (AI_targetValue). Keyed by template, so cleared with every map in AI::reset. */
+static std::map<const ThingTemplate*, const ThingTemplate*> theVariationParents;
+
void AI::init( void )
{
m_nextGroupID = 0;
@@ -396,6 +402,7 @@ void AI::reset( void )
}
m_nextGroupID = 0;
m_sweptGroupID = 0;
+ theVariationParents.clear();
m_nextFormationID = NO_FORMATION_ID;
getNextFormationID(); // increment once past NO_FORMATION_ID. jba.
m_lastBuildingPlacementFrame = 0;
@@ -781,53 +788,223 @@ static void priorityFunc(Object *obj, void *userData)
//-----------------------------------------------------------------------------
/**
- * How much an enemy is worth shooting before the others, with no Object involved so
- * test_gameengine can link straight to it - the same trick as AIAttackMove_shouldRetaliate
- * in AIStates.cpp.
- *
- * Attack move used to hand out whatever the scan found first, which is the nearest thing:
- * a group ordered through an enemy base stopped for the first dozer it passed while the
- * artillery beside it kept firing. Ranking by threat fixes the order of business.
+ * What a unit choosing its own target shoots first, with no Object involved so test_gameengine
+ * can link straight to it.
*
- * 'ThreatValue' is the INI field the threat map already feeds on, so a mod that sets it
- * decides this outright; the shipped Zero Hour INI never sets it (it is absent from every
- * file in INIZH.big), so build cost stands in - EA's own price is the only per-unit measure
- * of dangerousness the shipped data has, and it tracks it well enough (an Overlord costs
- * five times a Humvee).
+ * Idle units took the nearest thing and attack move the most expensive one, so a Humvee spent
+ * half a minute plinking a Battlemaster while the Technical beside it drove off. The rate is the
+ * enemy's money a unit takes off per frame it spends on a target: the target's worth over the
+ * frames its best weapon needs to kill it, through its armour and with the health it has left
+ * (aiFramesToKill, the AI's matchup arithmetic), plus the frames to drive into reach. A Humvee
+ * gun does a quarter of its damage to tank armour and a tank shell a tenth of its to a soldier,
+ * so each takes what it is built for, and a wounded enemy is a quicker kill than a fresh one.
*
- * Anything that can shoot back at *us* outranks anything that cannot, whatever it cost: a
- * Command Center is worth more than a Gattling tank and is still not what is killing us.
- * That is what AI_THREAT_ARMED_BONUS buys - it is larger than any build cost in the game, so
- * the two groups never interleave, and distance never moves a target out of its group either.
+ * Worth is 'ThreatValue' where a mod sets it and build cost where it does not; the shipped INI
+ * sets it nowhere.
*
- * Within a group distance does decide, because a threat we have to cross the field to reach is
- * not the one hurting us now: the worth of a target falls off with range, halving every
- * 'distanceModifier' world units away. That is the same knob the scripted attack priorities use
- * (AI INI's AttackPriorityDistanceModifier, 100.0 in the shipped data), so both notions of "worth
- * shooting" fade over the same distance. It is 0 until that INI is read - and the ctor default -
- * so a zero (or a negative, or a distance behind us) means no falloff at all rather than a
- * divide by zero.
+ * The tiers keep two old rules above the rate. Anything that can shoot back outranks anything
+ * that cannot, so a group in an enemy base does not stop for the dozer while the artillery
+ * fires. And whoever just shot us outranks everything but an armed enemy already in reach that
+ * dies within AI_QUICK_KILL_FRAMES: a far target the unit counters never keeps it from turning
+ * on its shooter, a near one it finishes in seconds does.
*/
-enum { AI_THREAT_ARMED_BONUS = 1000000 }; ///< larger than any build cost in the game
+Int aiTargetTier( Bool shotMe, Bool threatensMe, Bool inRange, Real framesToKill )
+{
+ if( shotMe || ( threatensMe && inRange && framesToKill >= 0.0f && framesToKill <= INT_TO_REAL( AI_QUICK_KILL_FRAMES ) ) )
+ return 2;
+ return threatensMe ? 1 : 0;
+}
-Int AI_threatScore( Int templateThreatValue, Int buildCost, Bool threatensMe,
- Real dist, Real distanceModifier )
+//-----------------------------------------------------------------------------
+Real aiTargetKillRate( Real value, Real framesToKill, Real gap, Real speed )
{
- Int score = (templateThreatValue > 0) ? templateThreatValue : buildCost;
- if (score < 1)
- score = 1; // a free civilian car is still worth more than nothing at all
+ if( framesToKill < 0.0f )
+ return 0.0f;
+ Real travelFrames = 0.0f;
+ if( gap > 0.0f )
+ {
+ if( speed <= 0.0f )
+ return 0.0f;
+ travelFrames = gap / speed;
+ }
+ return value / ( framesToKill + travelFrames ); // aiFramesToKill is never under one frame
+}
- if (distanceModifier > 0.0f && dist > 0.0f)
+//-----------------------------------------------------------------------------
+Bool aiTargetBeats( const AITargetRating &a, const AITargetRating &b )
+{
+ if( a.m_tier != b.m_tier )
+ return a.m_tier > b.m_tier;
+ if( a.m_rate != b.m_rate )
+ return a.m_rate > b.m_rate;
+ if( a.m_distSqr != b.m_distSqr )
+ return a.m_distSqr < b.m_distSqr;
+ return a.m_id < b.m_id;
+}
+
+// AIStates.cpp; the attack move's retaliation window, which is protected on its state
+extern Bool AIAttackMove_shouldRetaliate( UnsignedInt lastDamageFrame, UnsignedInt now, Int windowFrames,
+ Bool alreadyFightingTheAttacker, Bool canAttackTheAttacker );
+static const Int AI_SHOT_ME_FRAMES = LOGICFRAMES_PER_SECOND;
+
+/** What a target is worth: ThreatValue where a mod sets it, else what its player pays for it. */
+static Int AI_targetValue( const Object *victim )
+{
+ const ThingTemplate *tmpl = victim->getTemplate();
+ if( tmpl->getThreatValue() > 0 )
+ return tmpl->getThreatValue();
+ Int cost = tmpl->calcCostToBuild( victim->getControllingPlayer() );
+ if( cost <= 0 )
{
- score = REAL_TO_INT( score * distanceModifier / (distanceModifier + dist) );
- if (score < 1)
- score = 1; // however far off it is, it still beats finding nothing
+ std::map<const ThingTemplate*, const ThingTemplate*>::iterator known = theVariationParents.find( tmpl );
+ if( known == theVariationParents.end() )
+ {
+ const ThingTemplate *parent = NULL;
+ for( const ThingTemplate *t = TheThingFactory->firstTemplate(); t != NULL && parent == NULL; t = t->friend_getNextTemplate() )
+ {
+ const std::vector<AsciiString> &variations = t->getBuildVariations();
+ if( std::find( variations.begin(), variations.end(), tmpl->getName() ) != variations.end() )
+ parent = t;
+ }
+ known = theVariationParents.insert( std::make_pair( tmpl, parent ) ).first;
+ }
+ if( known->second != NULL )
+ cost = known->second->calcCostToBuild( victim->getControllingPlayer() );
}
+ return cost < 1 ? 1 : cost; // a free civilian car is still worth more than nothing at all
+}
- if (threatensMe)
- score += AI_THREAT_ARMED_BONUS;
+/** What me knows of victim as a target, all of it but whether victim can shoot back. */
+struct AITargetFacts
+{
+ AITargetRating m_rating;
+ Bool m_shotMe;
+ Bool m_inRange;
+ Real m_framesToKill;
+};
- return score;
+/** What the unit choosing brings to every candidate: its weapons as they fire now, once per search
+ * rather than once per candidate. */
+struct AIShooter
+{
+ const Object *m_me;
+ Weapon *m_weapon[ WEAPONSLOT_COUNT ]; ///< NULL where the slot is empty, dry, or not the unit's own to turn
+ WeaponBonus m_bonus[ WEAPONSLOT_COUNT ];
+ AIShotPattern m_timing[ WEAPONSLOT_COUNT ];
+ Real m_range[ WEAPONSLOT_COUNT ];
+ Real m_longestRange; ///< on flat ground
+ Real m_longestReach; ///< from the highest ground, the most any range check can grant
+ Real m_fastestShot; ///< the fewest frames any slot needs for its first shot, AI_CANNOT_KILL with none
+ Real m_speed;
+ ObjectID m_shooterID; ///< whoever shot the unit inside AI_SHOT_ME_FRAMES, else INVALID_ID
+};
+
+static void AI_readShooter( const Object *me, AIShooter &shooter )
+{
+ shooter.m_me = me;
+ shooter.m_longestRange = 0.0f;
+ shooter.m_longestReach = 0.0f;
+ shooter.m_fastestShot = AI_CANNOT_KILL;
+ for( Int slot = 0; slot < WEAPONSLOT_COUNT; ++slot )
+ {
+ Weapon *weapon = me->getWeaponInWeaponSlot( (WeaponSlotType)slot );
+ const UnsignedInt sources = me->getWeaponInWeaponSlotCommandSourceMask( (WeaponSlotType)slot );
+ if( weapon != NULL && ( ( weapon->getStatus() == OUT_OF_AMMO && !weapon->getAutoReloadsClip() ) ||
+ ( ( sources & ( 1 << CMD_FROM_AI ) ) == 0 && ( sources & CMD_DEFAULT_SWITCH_WEAPON ) == 0 ) ) )
+ weapon = NULL;
+ shooter.m_weapon[ slot ] = weapon;
+ if( weapon == NULL )
+ continue;
+
+ weapon->computeBonus( me, 0, shooter.m_bonus[ slot ] );
+ aiShotTiming( weapon->getTemplate(), shooter.m_bonus[ slot ], &shooter.m_timing[ slot ] );
+ shooter.m_range[ slot ] = weapon->getTemplate()->getAttackRange( shooter.m_bonus[ slot ] );
+ shooter.m_longestRange = max( shooter.m_longestRange, shooter.m_range[ slot ] );
+ shooter.m_longestReach = max( shooter.m_longestReach, shooter.m_range[ slot ] + Weapon_elevationRangeBonus( shooter.m_range[ slot ], FLT_MAX ) );
+ const AIShotPattern &t = shooter.m_timing[ slot ];
+ const Real firstShot = t.m_openingFrames + ( t.m_delayFrames > 1.0f ? t.m_delayFrames : 1.0f ); // aiFramesToKill's least
+ if( shooter.m_fastestShot < 0.0f || firstShot < shooter.m_fastestShot )
+ shooter.m_fastestShot = firstShot;
+ }
+
+ const AIUpdateInterface *ai = me->getAI();
+ shooter.m_speed = ( ai != NULL && ai->getCurLocomotor() != NULL ) ? ai->getCurLocomotorSpeed() : 0.0f;
+
+ BodyModuleInterface *body = me->getBodyModule();
+ const DamageInfo *damage = body->getLastDamageInfo(); // an inactive body keeps none
+ shooter.m_shooterID = ( damage != NULL &&
+ AIAttackMove_shouldRetaliate( body->getLastDamageTimestamp(), TheGameLogic->getFrame(), AI_SHOT_ME_FRAMES, FALSE, TRUE ) )
+ ? damage->in.m_sourceID : INVALID_ID;
+}
+
+/** The most victim could rate, from its distance and worth alone: in reach if anything could be,
+ * killed in one shot of the fastest weapon. aiTargetBeats on it decides whether the rest is read. */
+static Int AI_targetCeilingTier( const AIShooter &shooter, const Object *victim, Real distSqr )
+{
+ return ( victim->getID() == shooter.m_shooterID || distSqr <= sqr( shooter.m_longestReach ) ) ? 2 : 1;
+}
+
+static AITargetRating AI_targetCeiling( const AIShooter &shooter, const Object *victim, Real distSqr, Int value )
+{
+ AITargetRating r;
+ r.m_id = victim->getID();
+ r.m_distSqr = distSqr;
+ r.m_tier = AI_targetCeilingTier( shooter, victim, distSqr );
+ const Real gap = distSqr <= sqr( shooter.m_longestReach ) ? 0.0f : sqrt( distSqr ) - shooter.m_longestRange;
+ r.m_rate = aiTargetKillRate( INT_TO_REAL( value ), shooter.m_fastestShot, gap, shooter.m_speed );
+ return r;
+}
+
+static void AI_targetFacts( const AIShooter &shooter, const Object *victim, Real distSqr, Int value, AITargetFacts &facts )
+{
+ const Object *me = shooter.m_me;
+ facts.m_rating.m_id = victim->getID();
+ facts.m_rating.m_distSqr = distSqr;
+ facts.m_shotMe = victim->getID() == shooter.m_shooterID;
+
+ // the weapon that kills it soonest, of those this unit may turn on it by itself
+ const Real health = victim->getBodyModule()->getHealth();
+ const Int antiMask = WeaponSet::getVictimAntiMask( victim );
+ Int best = -1;
+ facts.m_framesToKill = AI_CANNOT_KILL;
+ for( Int slot = 0; slot < WEAPONSLOT_COUNT; ++slot )
+ {
+ const Weapon *weapon = shooter.m_weapon[ slot ];
+ if( weapon == NULL || ( weapon->getAntiMask() & antiMask ) == 0 )
+ continue;
+ AIShotPattern shots = shooter.m_timing[ slot ];
+ shots.m_damagePerShot = weapon->getTemplate()->estimateWeaponTemplateDamage( me, victim, NULL, shooter.m_bonus[ slot ] );
+ const Real frames = aiFramesToKill( health, shots );
+ if( frames >= 0.0f && ( best < 0 || frames < facts.m_framesToKill ) )
+ {
+ best = slot;
+ facts.m_framesToKill = frames;
+ }
+ }
+
+ facts.m_inRange = best >= 0 && shooter.m_weapon[ best ]->isWithinAttackRange( me, victim );
+ Real gap = 0.0f;
+ if( best >= 0 && !facts.m_inRange )
+ gap = sqrt( distSqr ) - shooter.m_range[ best ];
+ facts.m_rating.m_rate = aiTargetKillRate( INT_TO_REAL( value ), facts.m_framesToKill, gap, shooter.m_speed );
+ facts.m_rating.m_tier = aiTargetTier( facts.m_shotMe, TRUE, facts.m_inRange, facts.m_framesToKill );
+}
+
+static Bool AI_threatens( Object *enemy, const Object *me )
+{
+ if( !enemy->isAbleToAttack() ) // cheap bit test, and required before the call below
+ return FALSE;
+ const CanAttackResult r = enemy->getAbleToAttackSpecificObject( ATTACK_NEW_TARGET, me, CMD_FROM_AI );
+ return r == ATTACKRESULT_POSSIBLE || r == ATTACKRESULT_POSSIBLE_AFTER_MOVING;
+}
+
+/** victim's whole rating, whether it can shoot back included. */
+static AITargetRating AI_rateFully( const AIShooter &shooter, Object *victim, Real distSqr )
+{
+ AITargetFacts facts;
+ AI_targetFacts( shooter, victim, distSqr, AI_targetValue( victim ), facts );
+ facts.m_rating.m_tier = aiTargetTier( facts.m_shotMe, AI_threatens( victim, shooter.m_me ), facts.m_inRange, facts.m_framesToKill );
+ return facts.m_rating;
}
//-----------------------------------------------------------------------------
@@ -866,6 +1043,74 @@ static Bool AI_filtersAllow( PartitionFilter **filters, Object *candidate )
return true;
}
+//-----------------------------------------------------------------------------
+/**
+ * Each candidate is first rated on its distance and worth alone (AI_targetCeiling), the most it
+ * could score, so most of a crowd costs a distance; the weapons are read only for one whose
+ * ceiling beats the leader, and the expensive questions (the late filters, whether it can shoot
+ * back) only for one that then would take the lead. A near to far list sets a high bar early.
+ * The rule is a total order on ObjectID, so the pick does not depend on the order the partition
+ * hands the candidates out in.
+ */
+Object *AI::pickBestTarget( const Object *me, SimpleObjectIterator *candidates, PartitionFilter **lateFilters )
+{
+ AIShooter shooter;
+ AI_readShooter( me, shooter );
+ Object *best = NULL;
+ AITargetRating bestRating;
+ Object *nearest = NULL; // for the -scenario line only
+ Real nearestDistSqr = 0.0f;
+ Int count = 0;
+ for( Object *other = candidates->first(); other; other = candidates->next() )
+ {
+ const Real distSqr = ThePartitionManager->getDistanceSquared( me, other, FROM_BOUNDINGSPHERE_2D );
+ ++count;
+ if( nearest == NULL || distSqr < nearestDistSqr )
+ {
+ nearest = other;
+ nearestDistSqr = distSqr;
+ }
+ // the tier's ceiling is a distance and an id; the worth is a price lookup
+ if( best != NULL && AI_targetCeilingTier( shooter, other, distSqr ) < bestRating.m_tier )
+ continue;
+ const Int value = AI_targetValue( other );
+ if( best != NULL && !aiTargetBeats( AI_targetCeiling( shooter, other, distSqr, value ), bestRating ) )
+ continue;
+ AITargetFacts facts;
+ AI_targetFacts( shooter, other, distSqr, value, facts );
+ if( best != NULL && !aiTargetBeats( facts.m_rating, bestRating ) )
+ continue;
+ if( !AI_filtersAllow( lateFilters, other ) )
+ continue;
+ if( !AI_threatens( other, me ) )
+ {
+ facts.m_rating.m_tier = aiTargetTier( facts.m_shotMe, FALSE, facts.m_inRange, facts.m_framesToKill );
+ if( best != NULL && !aiTargetBeats( facts.m_rating, bestRating ) )
+ continue;
+ }
+ best = other;
+ bestRating = facts.m_rating;
+ }
+
+ // -scenario only: the pick beside the nearest candidate, which targetpick.txt reads
+ if( best != NULL && !TheGlobalData->m_scenarioFile.isEmpty() )
+ {
+ DEBUG_LOG(( "TARGET PICK: frame %d '%s' %d picks '%s' %d tier %d rate %.4f of %d, nearest '%s' %d\n",
+ TheGameLogic->getFrame(), me->getTemplate()->getName().str(), me->getID(), best->getTemplate()->getName().str(),
+ best->getID(), bestRating.m_tier, bestRating.m_rate, count, nearest->getTemplate()->getName().str(), nearest->getID() ));
+ }
+ return best;
+}
+
+//-----------------------------------------------------------------------------
+Bool AI::prefersTarget( const Object *me, Object *a, Object *b )
+{
+ AIShooter shooter;
+ AI_readShooter( me, shooter );
+ return aiTargetBeats( AI_rateFully( shooter, a, ThePartitionManager->getDistanceSquared( me, a, FROM_BOUNDINGSPHERE_2D ) ),
+ AI_rateFully( shooter, b, ThePartitionManager->getDistanceSquared( me, b, FROM_BOUNDINGSPHERE_2D ) ) );
+}
+
Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifiers,
const AttackPriorityInfo *info, PartitionFilter *optionalFilter)
{
@@ -976,52 +1221,12 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
if (info == NULL || info == TheScriptEngine->getDefaultAttackInfo())
{
- if (qualifiers & PREFER_HIGH_THREAT)
+ if (qualifiers & PREFER_BEST_TARGET)
{
- // Biggest threat in range wins; the iteration is sorted near to far, so a strict
- // improvement keeps the nearest of equal threats - which is the whole priority
- // order the caller wants: what shoots us (its own check, before we are called),
- // then what is worth shooting, then what is closest.
- Real distanceModifier = TheAI->getAiData()->m_attackPriorityDistanceModifier;
- Object *bestThreat = NULL;
- Int bestScore = 0;
- ObjectIterator *threatIter = ThePartitionManager->iterateObjectsInRange(me, range, FROM_BOUNDINGSPHERE_2D, gatherFilters, ITER_SORTED_NEAR_TO_FAR, enemyPlayers);
- MemoryPoolObjectHolder threatHolder(threatIter);
- for (Object *theEnemy = threatIter->first(); theEnemy; theEnemy = threatIter->next())
- {
- Real dist = sqrt( ThePartitionManager->getDistanceSquared(me, theEnemy, FROM_BOUNDINGSPHERE_2D) );
-
- /* Score it as if it were armed first, which is the best this candidate can possibly
- do: the armed bonus is the only thing getAbleToAttackSpecificObject decides here and
- it only ever adds. If the best it can do does not beat what we already have, the
- expensive question never has to be asked at all.
-
- Same answer as asking every time, and most of the asking gone. This is where an
- eight-player match spends its partition time - the list is every enemy in vision
- range, sorted near to far, so the first candidate sets a high bar and the far ones
- cannot clear it. */
- const Int armedScore = AI_threatScore( theEnemy->getTemplate()->getThreatValue(),
- theEnemy->getTemplate()->calcCostToBuild( theEnemy->getControllingPlayer() ),
- true, dist, distanceModifier );
- if (armedScore <= bestScore || !AI_filtersAllow(filters + numGatherFilters, theEnemy))
- continue;
-
- Bool threatensMe = theEnemy->isAbleToAttack(); // cheap bit test, and required before the call below
- if (threatensMe)
- {
- CanAttackResult r = theEnemy->getAbleToAttackSpecificObject( ATTACK_NEW_TARGET, me, CMD_FROM_AI );
- threatensMe = (r == ATTACKRESULT_POSSIBLE || r == ATTACKRESULT_POSSIBLE_AFTER_MOVING);
- }
-
- // the bonus is added last and nothing else in the score depends on it
- const Int score = threatensMe ? armedScore : (armedScore - AI_THREAT_ARMED_BONUS);
- if (score > bestScore)
- {
- bestScore = score;
- bestThreat = theEnemy;
- }
- }
- return bestThreat;
+ // gathered with the cheap filters; pickBestTarget asks the rest only of a leader
+ SimpleObjectIterator *iter = ThePartitionManager->iterateObjectsInRange(me, range, FROM_BOUNDINGSPHERE_2D, gatherFilters, ITER_SORTED_NEAR_TO_FAR, enemyPlayers);
+ MemoryPoolObjectHolder holder(iter);
+ return pickBestTarget(me, iter, filters + numGatherFilters);
}
// No additional attack info, so just return the closest one.
@@ -1033,6 +1238,17 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
Int effectivePriority=0;
Int actualPriority=0;
Real bestDistSqr=0.0f;
+ // A unit choosing its own target (PREFER_BEST_TARGET) keeps the script's priorities, distance
+ // falloff included, and breaks a tie on them by aiTargetBeats instead of the nearer: a skirmish
+ // AI's teams all carry a priority set, and without this none of its units ever chose by weapon.
+ // The leader is rated only once a tie needs it, and a tied candidate by the same prune as
+ // pickBestTarget.
+ const Bool rated = (qualifiers & PREFER_BEST_TARGET) != 0;
+ AIShooter shooter;
+ if (rated)
+ AI_readShooter(me, shooter);
+ AITargetRating bestRating;
+ Bool bestRated = FALSE;
// unsorted, see AI_attackPriorityTakesLead; each entry carries the distance the gather measured,
// which is what getDistanceSquared would measure again
SimpleObjectIterator *iter = ThePartitionManager->iterateObjectsInRange(me, range, FROM_BOUNDINGSPHERE_2D, gatherFilters, ITER_FASTEST, enemyPlayers);
@@ -1061,6 +1277,33 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
Int modPriority = curPriority-modifier;
if (modPriority < 1)
modPriority = 1;
+ if (rated && bestEnemy != NULL && modPriority == effectivePriority && curPriority == actualPriority)
+ {
+ if (!bestRated)
+ {
+ bestRating = AI_rateFully(shooter, bestEnemy, bestDistSqr);
+ bestRated = TRUE;
+ }
+ if (AI_targetCeilingTier(shooter, theEnemy, distSqr) < bestRating.m_tier)
+ continue;
+ const Int value = AI_targetValue(theEnemy);
+ if (!aiTargetBeats(AI_targetCeiling(shooter, theEnemy, distSqr, value), bestRating))
+ continue;
+ AITargetFacts facts;
+ AI_targetFacts(shooter, theEnemy, distSqr, value, facts);
+ if (!aiTargetBeats(facts.m_rating, bestRating) || !AI_filtersAllow(filters + numGatherFilters, theEnemy))
+ continue;
+ if (!AI_threatens(theEnemy, me))
+ {
+ facts.m_rating.m_tier = aiTargetTier(facts.m_shotMe, FALSE, facts.m_inRange, facts.m_framesToKill);
+ if (!aiTargetBeats(facts.m_rating, bestRating))
+ continue;
+ }
+ bestRating = facts.m_rating;
+ bestDistSqr = distSqr;
+ bestEnemy = theEnemy;
+ continue;
+ }
if (AI_attackPriorityTakesLead(modPriority, curPriority, distSqr, effectivePriority, actualPriority, bestDistSqr)
&& AI_filtersAllow(filters + numGatherFilters, theEnemy))
{
@@ -1068,8 +1311,9 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
actualPriority = curPriority;
bestDistSqr = distSqr;
bestEnemy = theEnemy;
+ bestRated = FALSE;
}
- }
+ }
if (bestEnemy) {
//DEBUG_LOG(("Find closest found %s, hunter %s, info %s\n", bestEnemy->getTemplate()->getName().str(),
// me->getTemplate()->getName().str(), info->getName().str()));
@@ -1950,6 +2194,26 @@ Bool aiIsIncomeNotATarget( Bool isTechBuilding, Bool isCapturable, Bool isTechBa
return isTechBuilding && isCapturable && !isTechBaseDefense;
}
+//-------------------------------------------------------------------------------------------------
+Int aiGuardAirTargetClass( Bool isStructure, Bool isVehicle, Bool isInfantry )
+{
+ if( isStructure )
+ return 0;
+ if( isVehicle )
+ return 1;
+ return isInfantry ? 2 : 3;
+}
+
+//-------------------------------------------------------------------------------------------------
+Bool aiGuardAirTargetBeats( Int classA, Real distSqrA, ObjectID idA, Int classB, Real distSqrB, ObjectID idB )
+{
+ if( classA != classB )
+ return classA < classB;
+ if( distSqrA != distSqrB )
+ return distSqrA < distSqrB;
+ return idA < idB;
+}
+
//-------------------------------------------------------------------------------------------------
Real aiRoleMassFraction( AIRole role )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp
index bef5b1d05..5a5c3784f 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp
@@ -324,8 +324,52 @@ Bool AIGuardMachine::lookForInnerTarget(void)
// just ask for that; the above has to find ALL objects in range, but we ignore all
// but the first (closest).
//
- Object* target = ThePartitionManager->getClosestObject(&pos, visionRange, FROM_CENTER_2D, filters, NULL, NULL, searchPlayers);
- if (target)
+ Object* target = NULL;
+ if (owner->isKindOf(KINDOF_AIRCRAFT) && !owner->getTemplate()->isEnterGuard())
+ {
+ // A plane's one bomb went on the nearest thing in the circle, usually a soldier, and it flew home
+ // to rearm with the factory beside him standing: buildings first, then vehicles, then infantry.
+ SimpleObjectIterator* iter = ThePartitionManager->iterateObjectsInRange(&pos, visionRange, FROM_CENTER_2D, filters, ITER_FASTEST);
+ MemoryPoolObjectHolder hold(iter);
+ Int bestClass = 0;
+ Real bestDistSqr = 0.0f;
+ Real distSqr;
+ for (Object* other = iter->firstWithNumeric(&distSqr); other; other = iter->nextWithNumeric(&distSqr))
+ {
+ Int otherClass = aiGuardAirTargetClass(other->isKindOf(KINDOF_STRUCTURE), other->isKindOf(KINDOF_VEHICLE), other->isKindOf(KINDOF_INFANTRY));
+ if (target == NULL || aiGuardAirTargetBeats(otherClass, distSqr, other->getID(), bestClass, bestDistSqr, target->getID()))
+ {
+ target = other;
+ bestClass = otherClass;
+ bestDistSqr = distSqr;
+ }
+ }
+ if (target)
+ DEBUG_LOG(("GUARD AIR: frame %d '%s' %d picks '%s' %d, class %d\n", TheGameLogic->getFrame(),
+ owner->getTemplate()->getName().str(), owner->getID(), target->getTemplate()->getName().str(), target->getID(), bestClass));
+ }
+ else if (!owner->getTemplate()->isEnterGuard())
+ {
+ // what its weapons kill best in the circle, the way every other unit picks its own target:
+ // gathered from enemy cells with the cheap filters, and the attack and fog questions asked
+ // only of a candidate that would take the lead (as findClosestEnemy does)
+ PartitionFilter* gather[8];
+ Int g = 0;
+ gather[g++] = &f1;
+ gather[g++] = &filterMapStatus;
+ if (area)
+ gather[g++] = &f3;
+ if (getGuardMode() == GUARDMODE_GUARD_FLYING_UNITS_ONLY)
+ gather[g++] = &f4;
+ gather[g] = NULL;
+ PartitionFilter* late[] = { &f2, &filterFogged, NULL };
+ SimpleObjectIterator* iter = ThePartitionManager->iterateObjectsInRange(&pos, visionRange, FROM_CENTER_2D, gather, ITER_FASTEST, searchPlayers);
+ MemoryPoolObjectHolder hold(iter);
+ target = TheAI->pickBestTarget(owner, iter, late);
+ }
+ else
+ target = ThePartitionManager->getClosestObject(&pos, visionRange, FROM_CENTER_2D, filters, NULL, NULL, searchPlayers);
+ if (target)
{
setNemesisID(target->getID());
return true; // Transitions to AIGuardInnerState.
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index c9146b2ba..ea516d194 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -3221,6 +3221,13 @@ static Bool shotPatternAgainst( const WeaponTemplate *weapon, const ThingTemplat
else
out->m_damagePerShot = armor.adjustDamage( type, weapon->getPrimaryDamage( bonus ) );
+ aiShotTiming( weapon, bonus, out );
+ return TRUE;
+}
+
+//-------------------------------------------------------------------------------------------------
+void aiShotTiming( const WeaponTemplate *weapon, const WeaponBonus &bonus, AIShotPattern *out )
+{
const Real rateOfFire = bonus.getField( WeaponBonus::RATE_OF_FIRE );
const Real preAttack = INT_TO_REAL( weapon->getPreAttackDelay( bonus ) );
out->m_delayFrames = INT_TO_REAL( weapon->getMinDelayBetweenShots() + weapon->getMaxDelayBetweenShots() ) * 0.5f / rateOfFire;
@@ -3243,7 +3250,6 @@ static Bool shotPatternAgainst( const WeaponTemplate *weapon, const ThingTemplat
out->m_openingFrames = preAttack;
break;
}
- return TRUE;
}
//-------------------------------------------------------------------------------------------------
@@ -12259,15 +12265,21 @@ Object *aiFindFreeGarrison( Object *unit, const Coord3D *center, Real radius, co
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 );
+ SimpleObjectIterator *nearby = ThePartitionManager->iterateObjectsInRange( center, radius, FROM_CENTER_2D, NULL, ITER_SORTED_NEAR_TO_FAR );
hold.hold( nearby );
+ // a building beats any transport, so the nearest transport with a seat waits until no building has one
+ Object *transport = NULL;
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 ) )
+ const ContainModuleInterface *contain = building->getContain();
+ if( contain == NULL || std::find( tried.begin(), tried.end(), building->getID() ) != tried.end() )
+ continue;
+ const Bool isBuilding = building->isKindOf( KINDOF_STRUCTURE );
+ if( isBuilding ? !contain->isGarrisonable() :
+ ( transport != NULL || unit->getRelationship( building ) != ALLIES || building->isAirborneTarget() || contain->isRiderChangeContain() ) )
+ continue;
+ if( !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
@@ -12276,10 +12288,13 @@ Object *aiFindFreeGarrison( Object *unit, const Coord3D *center, Real radius, co
// 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 )
+ if( TheActionManager->openSeatsAsSeen( unit, building, CMD_FROM_PLAYER ) <= walkers )
+ continue;
+ if( isBuilding )
return building;
+ transport = building;
}
- return NULL;
+ return transport;
}
//----------------------------------------------------------------------------------------------------------
@@ -15128,7 +15143,7 @@ static Real groundAttackRange( const Object *obj );
/** A unit's contribution to an exchange: what it can still take, and what it can still deal. The
* threat value the data already carries stands in for damage per second - it is what
- * AI_threatScore uses for the same purpose. */
+ * aiTargetKillRate's value uses for the same purpose. */
static void addToForce( const Object *obj, Real *health, Real *power )
{
if( obj == NULL || obj->isEffectivelyDead() )
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
index b2c1cd2ed..1f320ec73 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
@@ -4113,13 +4113,17 @@ StateReturnType AIAttackMoveToState::update()
else
{
//
- // Something is shooting us while we are busy with somebody else: turn on it instead.
+ // Something is shooting us while we are busy with somebody else: turn on it instead,
+ // unless the one we are on is in reach and nearly dead (see aiTargetTier).
// On our own scan clock, so a fight cannot be restarted every frame by splash damage.
//
UnsignedInt now = TheGameLogic->getFrame();
if (now >= m_frameToScanOn)
{
Object *shooter = findRetaliationTarget();
+ Object *victim = TheGameLogic->findObjectByID(m_victimID);
+ if (shooter && victim && TheAI->prefersTarget(owner, victim, shooter))
+ shooter = NULL;
if (shooter)
{
stopEngaging();
@@ -4185,11 +4189,15 @@ StateReturnType AIAttackMoveToState::update()
// While the approach is suspended the search is narrowed to what is already in range, so a
// distant high-threat target cannot crowd out the enemy standing next to us - and an empty
// clip means there is nothing worth stopping for at all (see canHitFromHere).
- if (nextObjectToAttack == NULL && (mayApproach || !owner->isOutOfAmmo()))
+ // ... unless the scan finds something in reach it kills in seconds (see aiTargetTier), which
+ // is all that can beat the shooter, so with one the scan looks no further than the weapon reaches
+ if (mayApproach || !owner->isOutOfAmmo())
{
- nextObjectToAttack = ai->getNextMoodTarget( true, false, true, !mayApproach );
- if (nextObjectToAttack != NULL && !mayApproach && nextObjectToAttack->getID() == m_victimID)
- nextObjectToAttack = NULL; // the one we just failed on
+ Object *scanned = ai->getNextMoodTarget( true, false, true, !mayApproach || nextObjectToAttack != NULL );
+ if (scanned != NULL && !mayApproach && scanned->getID() == m_victimID)
+ scanned = NULL; // the one we just failed on
+ if (scanned != NULL && (nextObjectToAttack == NULL || TheAI->prefersTarget(owner, scanned, nextObjectToAttack)))
+ nextObjectToAttack = scanned;
}
if (nextObjectToAttack != NULL)
@@ -5613,7 +5621,9 @@ Bool AIAttackAim_needsRunOut( Real relX, Real relY, Real turnRadius, Real cosAim
* not bring it into the aim cone before it is inside the weapon's minimum range: beside the cockpit, or
* just behind. Turning in from there only ever ends with the target under the plane, so the jet holds its
* heading instead until the target is the minimum range and a full turn circle away, then comes back round
- * with that much straight run left to fire in. Aircraft against aircraft keep the straight chase.
+ * with that much straight run left to fire in. A jet coming in on the target fires from its reach and
+ * turns away at the break-off distance rather than flying on over it. Aircraft against aircraft keep
+ * the straight chase.
*/
Coord3D AIAttackAimAtTargetState::computeAttackRunGoal( Object *source, const Weapon *weapon, const Coord3D &targetPos,
Real relAngle, Real aimDelta )
@@ -5643,19 +5653,58 @@ Coord3D AIAttackAimAtTargetState::computeAttackRunGoal( Object *source, const We
minRange += victim->getGeometryInfo().getBoundingSphereRadius();
const Real runOutDist = minRange + 2.0f*turnRadius + entryDist;
- if (m_isRunningOut)
- m_isRunningOut = dx*dx + dy*dy < sqr(runOutDist);
+ // Breaking off: a jet that flew on at its target after firing went over it and only came round on the
+ // far side. It turns away instead once it is close enough that a turn begun now (after the roll-in)
+ // still passes the target at the clearance, the larger of the minimum range and the turn radius:
+ // a circle of radius R begun at distance d from a point dead ahead passes it at sqrt(d*d + R*R) - R.
+ // The shots fly between the weapon's reach and that distance. A weapon whose reach is shorter than
+ // it has to fly in closer to fire at all, so it keeps the straight run. Only a jet with the target in
+ // its aim cone breaks off, the frame it can fire: one still turning in (a Stealth Fighter that came
+ // back round on a Scorpion 120 off its wing) broke off before the cone every pass and never fired.
+ const Real distSqr = dx*dx + dy*dy;
+ const Real along = dx*dir->x + dy*dir->y;
+ const Real clearance = max(minRange, turnRadius);
+ const Real breakOffDist = entryDist + sqrt(clearance*clearance + 2.0f*clearance*turnRadius);
+ Real reach = weapon->getAttackRange(source) + source->getGeometryInfo().getBoundingSphereRadius();
+ if (victim)
+ reach += victim->getGeometryInfo().getBoundingSphereRadius();
+ const Bool breaksOff = !m_isRunningOut && fabs(relAngle) < aimDelta && breakOffDist < reach &&
+ distSqr < sqr(breakOffDist);
+
+ if (breaksOff)
+ m_isRunningOut = TRUE;
+ else if (m_isRunningOut)
+ m_isRunningOut = distSqr < sqr(runOutDist);
else if (fabs(relAngle) >= aimDelta)
- m_isRunningOut = AIAttackAim_needsRunOut(dx*dir->x + dy*dir->y - entryDist, dir->x*dy - dir->y*dx, turnRadius,
+ m_isRunningOut = AIAttackAim_needsRunOut(along - entryDist, dir->x*dy - dir->y*dx, turnRadius,
Cos(aimDelta), minRange);
+ // -scenario only: the run, frame by frame, which jetbreak.txt reads
+ if (!TheGlobalData->m_scenarioFile.isEmpty())
+ {
+ DEBUG_LOG(("SCENARIO JET RUN: frame %d '%s' %d dist %.0f reach %.0f breakoff %.0f turn %.0f%s%s\n",
+ TheGameLogic->getFrame(), source->getTemplate()->getName().str(), source->getID(), sqrt(distSqr), reach,
+ breakOffDist, turnRadius, m_isRunningOut ? " running out" : "", breaksOff ? " BREAK OFF" : ""));
+ }
+
if (!m_isRunningOut)
return targetPos;
- Coord3D ahead = *pos;
- ahead.x += dir->x * runOutDist;
- ahead.y += dir->y * runOutDist;
- return ahead;
+ // still facing the target: turn away from it, to the side it is not on; once it is behind, hold the
+ // heading until there is room to come back round
+ Coord3D goal = *pos;
+ const Real dist = sqrt(distSqr);
+ if (along > 0.0f && dist > 0.0f)
+ {
+ goal.x -= dx / dist * runOutDist;
+ goal.y -= dy / dist * runOutDist;
+ }
+ else
+ {
+ goal.x += dir->x * runOutDist;
+ goal.y += dir->y * runOutDist;
+ }
+ return goal;
}
//----------------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
index 72bc25ca5..443e42f38 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
@@ -3922,15 +3922,16 @@ SimpleObjectIterator *PartitionManager::iterateObjectsInRange(
const Coord3D *pos,
Real maxDist,
DistanceCalculationType dc,
- PartitionFilter **filters,
- IterOrderType order
+ PartitionFilter **filters,
+ IterOrderType order,
+ PlayerMaskType onlyPlayers
)
{
MemoryPoolObjectHolder iterHolder;
SimpleObjectIterator *iter = newInstance(SimpleObjectIterator);
iterHolder.hold(iter);
- getClosestObjects(NULL, pos, maxDist, dc, filters, iter, NULL, NULL);
+ getClosestObjects(NULL, pos, maxDist, dc, filters, iter, NULL, NULL, onlyPlayers);
iter->sort(order);
iterHolder.release();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index 2c4ea05e3..478897e1d 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -7156,15 +7156,11 @@ Object* AIUpdateInterface::getNextMoodTarget( Bool calledByAI, Bool calledDuring
}
//
- // A caller that closes with what it finds picks the biggest threat in range instead of the
- // nearest thing (see AI_threatScore). Walking up to a dozer while the artillery next to it
- // keeps firing is only sensible for a unit that cannot move to a better target - and this
- // caller can.
+ // Every caller picks what its weapons kill best for the time it takes rather than the nearest
+ // thing (see aiTargetTier): a Humvee the Technical, a tank the tank, and whoever is shooting it
+ // before anything it would have to drive to.
//
- if (allowOutOfWeaponRangeTargets)
- {
- flags |= AI::PREFER_HIGH_THREAT;
- }
+ flags |= AI::PREFER_BEST_TARGET;
//
// ... and an aircraft only makes that long look forward - see PartitionFilterForwardArc.
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp
index 8eec485ba..d3bb50785 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp
@@ -1013,11 +1013,29 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate
}
// where on the victim this shot lands (Weapon::randomPointOnBody); a bridge keeps its attack point.
- // Drawn whether or not anything is drawn, as it comes from the logic stream.
+ // Drawn whether or not anything is drawn, as it comes from the logic stream. A stream weapon (the
+ // Toxin Tractor's spray, a flamethrower) is drawn as one line through all its blobs in the air, so
+ // a point of its own per blob bent that line into a zigzag: every blob of a stream goes to the
+ // victim's middle, EA's aim, and the line stays straight.
Coord3D aimPos;
const Bool aimsOnBody = victimObj != NULL && !victimObj->isKindOf( KINDOF_BRIDGE );
if( aimsOnBody )
- Weapon::randomPointOnBody( victimObj, aimPos );
+ {
+ if( m_projectileStreamName.isEmpty() )
+ Weapon::randomPointOnBody( victimObj, aimPos );
+ else
+ victimObj->getGeometryInfo().getCenterPosition( *victimObj->getPosition(), aimPos );
+ }
+
+ // -scenario only: one line a shot for the streams and the aircraft, which their scenarios read
+ if( aimsOnBody && !TheGlobalData->m_scenarioFile.isEmpty() &&
+ ( !m_projectileStreamName.isEmpty() || sourceObj->isKindOf( KINDOF_AIRCRAFT ) ) )
+ {
+ DEBUG_LOG(( "SCENARIO SHOT: frame %d '%s' %d '%s' at '%s' %d dist %.0f range %.0f aim (%.1f,%.1f,%.1f)\n",
+ TheGameLogic->getFrame(), sourceObj->getTemplate()->getName().str(), sourceObj->getID(), m_name.str(),
+ victimObj->getTemplate()->getName().str(), victimObj->getID(), sqrtf( distSqr ), getAttackRange( bonus ),
+ aimPos.x, aimPos.y, aimPos.z ));
+ }
// call this even if FXList is null, because this also handles stuff like Gun Barrel Recoil
if (sourceObj && sourceObj->getDrawable())
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 5445b70dd..893ef89e1 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -3323,53 +3323,98 @@ TEST(attack_move_still_shoots_what_it_can_already_reach)
CHECK( AIAttackMove_mayTakeTarget( true, true, false, 1030, 1030 ) );
}
-/* AI.cpp: on attack move the scan ranks what it finds by threat instead of handing
- back the nearest thing. */
-extern Int AI_threatScore( Int templateThreatValue, Int buildCost, Bool threatensMe,
- Real dist, Real distanceModifier );
-
-TEST(attack_move_shoots_the_biggest_threat_first)
-{
- const Real MOD = 100.0f; /* AttackPriorityDistanceModifier, shipped value */
- const Real HERE = 0.0f;
-
- /* a mod that sets ThreatValue decides outright; build cost only stands in for it. */
- CHECK( AI_threatScore( 50, 4000, false, HERE, MOD ) > AI_threatScore( 40, 5000, false, HERE, MOD ) );
-
- /* the shipped INI sets ThreatValue nowhere, so cost has to do the ranking:
- an Overlord-priced tank over a Humvee-priced one. */
- CHECK( AI_threatScore( 0, 1200, true, HERE, MOD ) > AI_threatScore( 0, 700, true, HERE, MOD ) );
-
- /* anything that can shoot back outranks anything that cannot, whatever it cost -
- a Command Center is worth more than a Gattling tank and is still not what is
- killing us - and no distance may move a target out of its group, or a unit would
- walk past the artillery firing at it to reach a far off barracks. */
- CHECK( AI_threatScore( 0, 1, true, HERE, MOD ) > AI_threatScore( 0, 5000, false, HERE, MOD ) );
- CHECK( AI_threatScore( 1, 0, true, HERE, MOD ) > AI_threatScore( 9999, 0, false, HERE, MOD ) );
- CHECK( AI_threatScore( 0, 1, true, 9999.0f, MOD ) > AI_threatScore( 0, 5000, false, HERE, MOD ) );
-
- /* free civilian junk still scores, otherwise a scan that found only that would
- report "nothing here" and the unit would walk past what it was told to clear. */
- CHECK( AI_threatScore( 0, 0, false, HERE, MOD ) > 0 );
- CHECK( AI_threatScore( 0, 0, false, 9999.0f, MOD ) > 0 );
-
- /* worth halves every modifier of distance. */
- CHECK_EQ( AI_threatScore( 0, 1000, false, MOD, MOD ), 500 );
- CHECK_EQ( AI_threatScore( 0, 1000, false, 3.0f*MOD, MOD ), 250 );
-
- /* so the same unit closer up wins, and a big enough threat still outranks a cheap
- one underfoot: an Overlord a modifier away beats a Ranger at our feet. */
- CHECK( AI_threatScore( 0, 1200, true, 10.0f, MOD ) > AI_threatScore( 0, 1200, true, 200.0f, MOD ) );
- CHECK( AI_threatScore( 0, 2000, true, MOD, MOD ) > AI_threatScore( 0, 225, true, HERE, MOD ) );
-
- /* equal threats at equal range must tie exactly: the scan is sorted near to far and
- keeps the first of a tie, which is how "then the closest one" gets honoured. */
- CHECK_EQ( AI_threatScore( 0, 900, true, 50.0f, MOD ), AI_threatScore( 0, 900, true, 50.0f, MOD ) );
-
- /* the modifier is 0 until the AI INI is read, and a target can measure as behind us
- from a bounding sphere: neither may divide by zero or invert the ranking. */
- CHECK_EQ( AI_threatScore( 0, 1000, false, 500.0f, 0.0f ), 1000 );
- CHECK_EQ( AI_threatScore( 0, 1000, false, -5.0f, MOD ), 1000 );
+/* AI.cpp: a unit choosing its own target takes what its weapon kills best for the time it
+ costs, not the nearest thing (idle) or the most expensive one (attack move). The numbers are
+ the shipped INI's: HumveeGun 10 a shot every 12 frames, CrusaderTankGun 60 every 120; tank armour
+ takes a quarter of the Humvee's, truck armour half, a soldier a tenth of the tank's. */
+static AITargetRating targetRating( Int tier, Real rate, Real distSqr, ObjectID id )
+{
+ AITargetRating r;
+ r.m_tier = tier;
+ r.m_rate = rate;
+ r.m_distSqr = distSqr;
+ r.m_id = id;
+ return r;
+}
+
+TEST(a_unit_shoots_what_its_weapon_kills_best)
+{
+ AIShotPattern humvee;
+ humvee.m_delayFrames = 12.0f;
+ AIShotPattern tank;
+ tank.m_delayFrames = 120.0f;
+ const Real SPEED = 2.0f;
+
+ /* a Humvee: the Technical (500, 180 health) over the Battlemaster (800, 400), and a Red Guard
+ (300, 120) over the Battlemaster too */
+ humvee.m_damagePerShot = 2.5f;
+ const Real humveeOnTank = aiTargetKillRate( 800.0f, aiFramesToKill( 400.0f, humvee ), 0.0f, SPEED );
+ humvee.m_damagePerShot = 5.0f;
+ const Real humveeOnTruck = aiTargetKillRate( 500.0f, aiFramesToKill( 180.0f, humvee ), 0.0f, SPEED );
+ humvee.m_damagePerShot = 10.0f;
+ const Real humveeOnSoldier = aiTargetKillRate( 300.0f, aiFramesToKill( 120.0f, humvee ), 0.0f, SPEED );
+ CHECK( humveeOnTruck > humveeOnTank );
+ CHECK( humveeOnSoldier > humveeOnTank );
+
+ /* a Crusader: the Battlemaster over the Red Guard */
+ tank.m_damagePerShot = 60.0f;
+ const Real tankOnTank = aiTargetKillRate( 800.0f, aiFramesToKill( 400.0f, tank ), 0.0f, SPEED );
+ tank.m_damagePerShot = 6.0f;
+ const Real tankOnSoldier = aiTargetKillRate( 300.0f, aiFramesToKill( 120.0f, tank ), 0.0f, SPEED );
+ CHECK( tankOnTank > tankOnSoldier );
+
+ /* a wounded enemy is a quicker kill than a fresh one of the same kind */
+ tank.m_damagePerShot = 60.0f;
+ CHECK( aiTargetKillRate( 800.0f, aiFramesToKill( 100.0f, tank ), 0.0f, SPEED ) > tankOnTank );
+
+ /* the drive into reach counts: the same Battlemaster 600 units out of reach is worth less, and
+ one out of reach of a unit that cannot move is worth nothing */
+ const Real tankFrames = aiFramesToKill( 400.0f, tank );
+ CHECK_NEAR( 800.0f / ( tankFrames + 300.0f ), aiTargetKillRate( 800.0f, tankFrames, 600.0f, SPEED ), 0.0001f );
+ CHECK_NEAR( 0.0f, aiTargetKillRate( 800.0f, tankFrames, 600.0f, 0.0f ), 0.0001f );
+ CHECK_NEAR( tankOnTank, aiTargetKillRate( 800.0f, tankFrames, 0.0f, 0.0f ), 0.0001f );
+
+ /* nothing it can hurt rates 0, which still beats having no target: a unit with nothing it
+ counters fires at whatever is there, the nearest first */
+ CHECK_NEAR( 0.0f, aiTargetKillRate( 800.0f, AI_CANNOT_KILL, 0.0f, SPEED ), 0.0001f );
+ CHECK( aiTargetBeats( targetRating( 1, 0.0f, 100.0f, (ObjectID)9 ), targetRating( 1, 0.0f, 400.0f, (ObjectID)2 ) ) );
+
+ /* the tiers: whoever just shot us is 2 wherever it stands; an armed enemy in reach that dies
+ within the quick-kill window is 2 too; any other armed one 1; one that cannot shoot back 0,
+ however quickly it dies */
+ const Real QUICK = INT_TO_REAL( AI_QUICK_KILL_FRAMES );
+ CHECK_EQ( aiTargetTier( TRUE, TRUE, FALSE, 5000.0f ), 2 );
+ CHECK_EQ( aiTargetTier( TRUE, FALSE, FALSE, AI_CANNOT_KILL ), 2 );
+ CHECK_EQ( aiTargetTier( FALSE, TRUE, TRUE, QUICK ), 2 );
+ CHECK_EQ( aiTargetTier( FALSE, TRUE, TRUE, QUICK + 1.0f ), 1 );
+ CHECK_EQ( aiTargetTier( FALSE, TRUE, FALSE, 60.0f ), 1 );
+ CHECK_EQ( aiTargetTier( FALSE, TRUE, TRUE, AI_CANNOT_KILL ), 1 );
+ CHECK_EQ( aiTargetTier( FALSE, FALSE, TRUE, 60.0f ), 0 );
+
+ /* so the Battlemaster shooting the Humvee beats a Technical it would have to drive to, and
+ loses to one already in reach that it finishes in seconds, on the rate */
+ humvee.m_damagePerShot = 2.5f;
+ const Real humveeTankFrames = aiFramesToKill( 400.0f, humvee );
+ humvee.m_damagePerShot = 5.0f;
+ const Real humveeTruckFrames = aiFramesToKill( 180.0f, humvee );
+ CHECK_NEAR( 1920.0f, humveeTankFrames, 0.001f );
+ CHECK_NEAR( 432.0f, humveeTruckFrames, 0.001f );
+ CHECK( aiTargetBeats( targetRating( aiTargetTier( TRUE, TRUE, TRUE, humveeTankFrames ), humveeOnTank, 0.0f, (ObjectID)9 ),
+ targetRating( aiTargetTier( FALSE, TRUE, FALSE, humveeTruckFrames ), humveeOnTruck, 0.0f, (ObjectID)2 ) ) );
+ CHECK( aiTargetBeats( targetRating( aiTargetTier( FALSE, TRUE, TRUE, humveeTruckFrames ), humveeOnTruck, 0.0f, (ObjectID)9 ),
+ targetRating( aiTargetTier( TRUE, TRUE, TRUE, humveeTankFrames ), humveeOnTank, 0.0f, (ObjectID)2 ) ) );
+
+ /* armed beats unarmed whatever the rate: no stopping for the dozer under the artillery */
+ CHECK( aiTargetBeats( targetRating( 1, 0.01f, 0.0f, (ObjectID)9 ), targetRating( 0, 100.0f, 0.0f, (ObjectID)2 ) ) );
+
+ /* a total order: tier, rate, distance, then the lower ObjectID, the same whichever is asked
+ first, so the pick never depends on the order the partition hands candidates out in */
+ const AITargetRating a = targetRating( 1, 0.5f, 100.0f, (ObjectID)2 );
+ const AITargetRating b = targetRating( 1, 0.5f, 100.0f, (ObjectID)9 );
+ CHECK( aiTargetBeats( a, b ) );
+ CHECK( !aiTargetBeats( b, a ) );
+ CHECK( !aiTargetBeats( a, a ) );
+ CHECK( aiTargetBeats( targetRating( 1, 0.6f, 900.0f, (ObjectID)9 ), a ) );
}
/* AI.cpp: the scripted-priority search a hunter runs over the whole map picks in one pass over
@@ -16588,6 +16633,32 @@ TEST(massing_waits_for_a_force_but_never_waits_for_ever)
// the sixty-second valve wins over everything, so a wave can never be parked for ever
CHECK( !aiShouldMass( 1.0f, 100000.0f, DEFENSIVE, TRUE, FALSE ) );
+/** An Aurora guarding a circle dropped its one bomb on the nearest thing in it, usually a soldier.
+ A guarding aircraft now takes buildings, then vehicles, then infantry, nearest within a class, and
+ the lower ObjectID on an exact tie so every machine picks the same one. */
+TEST(a_guarding_aircraft_bombs_buildings_then_vehicles_then_infantry)
+{
+ const Int building = aiGuardAirTargetClass( TRUE, FALSE, FALSE );
+ const Int vehicle = aiGuardAirTargetClass( FALSE, TRUE, FALSE );
+ const Int soldier = aiGuardAirTargetClass( FALSE, FALSE, TRUE );
+ const Int other = aiGuardAirTargetClass( FALSE, FALSE, FALSE );
+ CHECK( building < vehicle );
+ CHECK( vehicle < soldier );
+ CHECK( soldier < other );
+
+ // a far building beats a soldier under the plane, and a far vehicle beats him too
+ CHECK( aiGuardAirTargetBeats( building, 640000.0f, (ObjectID)9, soldier, 100.0f, (ObjectID)2 ) );
+ CHECK( aiGuardAirTargetBeats( vehicle, 640000.0f, (ObjectID)9, soldier, 100.0f, (ObjectID)2 ) );
+ CHECK( !aiGuardAirTargetBeats( soldier, 100.0f, (ObjectID)2, vehicle, 640000.0f, (ObjectID)9 ) );
+
+ // within a class the nearer one, and on an exact tie the lower id, whichever is asked first
+ CHECK( aiGuardAirTargetBeats( vehicle, 100.0f, (ObjectID)9, vehicle, 400.0f, (ObjectID)2 ) );
+ CHECK( aiGuardAirTargetBeats( vehicle, 100.0f, (ObjectID)2, vehicle, 100.0f, (ObjectID)9 ) );
+ CHECK( !aiGuardAirTargetBeats( vehicle, 100.0f, (ObjectID)9, vehicle, 100.0f, (ObjectID)2 ) );
+ CHECK( !aiGuardAirTargetBeats( vehicle, 100.0f, (ObjectID)2, vehicle, 100.0f, (ObjectID)2 ) );
+}
+
+
// so does a fight at home: nothing sits at a rally point while the base is being hit
CHECK( !aiShouldMass( 1.0f, 100000.0f, DEFENSIVE, FALSE, TRUE ) );