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(gamelogic): stop firing at a target already doomed by shots in flight

Olcay Seygan0e5dbafe498b
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/IncomingDamage.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/IncomingDamage.h
new file mode 100644
index 000000000..2c5ab4f3f
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/IncomingDamage.h
@@ -0,0 +1,87 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// IncomingDamage.h ///////////////////////////////////////////////////////////////////////////////
+// The ledger of damage that is already on its way to a target but has not landed yet.
+//
+// A shot whose damage is delayed - a projectile in flight, or a hitscan weapon far enough away that
+// the damage is scheduled for a later frame - leaves the shooter's barrel with nothing anywhere
+// recording that the victim is, for practical purposes, already dead. Every other unit still sees
+// full health and keeps firing, so a squad routinely spends a whole volley on a target the first
+// two shots had already killed.
+//
+// Every delayed shot is booked here against its victim, with the frame its damage is expected to
+// land. Auto-targeting reads the ledger back: a target whose booked damage already covers its
+// remaining health is skipped when acquiring, and a unit that is auto-attacking one stops firing
+// and looks for something else. Nothing here touches an explicit player attack order.
+//
+// Entries expire on their own. A booking is dropped when its damage lands, and otherwise a few
+// frames after the impact was due, so a missile that is shot down or diverted by countermeasures
+// costs at most that long a pause rather than a permanent reservation.
+//
+// The ledger is logic-side and iterated in ObjectID order, so it stays deterministic across clients
+// and replays. It is deliberately not saved: bookings live under a second of game time, and a
+// loaded game simply re-books as its units fire again.
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+#pragma once
+#ifndef __INCOMINGDAMAGE_H__
+#define __INCOMINGDAMAGE_H__
+
+#include "Lib/BaseType.h"
+#include "Common/GameCommon.h"
+
+class Object;
+
+//-------------------------------------------------------------------------------------------------
+class IncomingDamageTracker
+{
+public:
+
+ /// Drop every booking. Called when the game logic resets.
+ static void reset();
+
+ /// Drop the bookings whose impact frame has come and gone. Called once per logic frame.
+ static void update(UnsignedInt currentFrame);
+
+ /**
+ Book a shot's damage against its victim, expected to land on impactFrame. The amount is what
+ the shot is estimated to actually take off the victim, i.e. after armor.
+ */
+ static void bookShot(ObjectID victim, ObjectID shooter, Real amount,
+ UnsignedInt currentFrame, UnsignedInt impactFrame);
+
+ /// A shot from this shooter has landed on this victim: release the oldest booking of the pair.
+ static void shotLanded(ObjectID victim, ObjectID shooter);
+
+ /// Total damage booked against this victim that has not landed yet.
+ static Real getBookedDamage(ObjectID victim);
+
+ /**
+ TRUE if the damage already on its way to this victim covers remainingHealth, i.e. shooting it
+ again would be wasted. Always FALSE for an object nothing has booked damage against, so the
+ common case costs one lookup in an almost always tiny table.
+ */
+ static Bool isAlreadyDoomed(ObjectID victim, Real remainingHealth);
+
+ /// The same question asked about a live object, whose health it reads for you.
+ static Bool isAlreadyDoomed(const Object *victim);
+
+};
+
+#endif // __INCOMINGDAMAGE_H__
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
index 0120b8676..422c1fdbf 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
@@ -54,6 +54,7 @@
#include "GameLogic/AITNGuard.h"
#include "GameLogic/AIStateMachine.h"
#include "GameLogic/AIPathfind.h"
+#include "GameLogic/IncomingDamage.h"
#include "GameLogic/Locomotor.h"
#include "GameLogic/PartitionManager.h"
#include "GameLogic/PolygonTrigger.h"
@@ -5552,6 +5553,18 @@ StateReturnType AIAttackFireWeaponState::update()
// if our target is dead, go ahead and stop.
if (!victim || victim->isEffectivelyDead())
return STATE_FAILURE;
+
+ //
+ // The shots already in the air add up to more than the victim has left, so this one would be
+ // spent on something that is dead the moment they land. Drop the attack: whatever put us on
+ // this target on our own initiative - guarding, attack moving, the idle scan - runs again on
+ // its own clock, and the acquisition filter now passes over this victim and hands us the next
+ // one, or nothing, in which case we simply hold. Only our own initiative is second-guessed
+ // here; an explicit order from the player is carried out as given.
+ //
+ AIUpdateInterface* ai = obj->getAI();
+ if (ai && ai->getLastCommandSource() == CMD_FROM_AI && IncomingDamageTracker::isAlreadyDoomed(victim))
+ return STATE_FAILURE;
}
WeaponSlotType wslot;
Weapon* weapon = obj->getCurrentWeapon(&wslot);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/IncomingDamage.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/IncomingDamage.cpp
new file mode 100644
index 000000000..7517c9c13
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/IncomingDamage.cpp
@@ -0,0 +1,167 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// IncomingDamage.cpp /////////////////////////////////////////////////////////////////////////////
+// The ledger of damage in flight. See IncomingDamage.h for what it is for.
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
+
+#include "GameLogic/IncomingDamage.h"
+
+#include "GameLogic/Object.h"
+#include "GameLogic/Module/BodyModule.h"
+
+#include <map>
+#include <vector>
+
+//-------------------------------------------------------------------------------------------------
+struct BookedShot
+{
+ ObjectID m_shooter; ///< who fired it, so the landing damage can release its own booking
+ Real m_amount; ///< damage it is expected to take off the victim, after armor
+ UnsignedInt m_expireFrame; ///< when the booking lapses even though nothing landed
+};
+
+typedef std::vector<BookedShot> BookedShotVec;
+
+// std::map, keyed by ObjectID: the sweep below walks it in ID order on every client.
+typedef std::map<ObjectID, BookedShotVec> BookedShotMap;
+
+static BookedShotMap theBookings;
+
+//
+// How long past the expected impact a booking is honored before it lapses. A missile that is shot
+// down or lured away by countermeasures never lands, and this is how long the target stays wrongly
+// reserved: long enough to absorb the slop in the flight-time estimate below, short enough that the
+// squad's pause is not noticeable.
+//
+static const UnsignedInt BOOKING_SLACK_FRAMES = 15;
+
+// Flight time is estimated from the weapon speed, which for a guided projectile is only a hint --
+// the projectile flies on its own locomotor. Clamp the estimate rather than trust it outright.
+static const UnsignedInt MIN_FLIGHT_FRAMES = 1;
+static const UnsignedInt MAX_FLIGHT_FRAMES = 90;
+
+//-------------------------------------------------------------------------------------------------
+void IncomingDamageTracker::reset()
+{
+ theBookings.clear();
+}
+
+//-------------------------------------------------------------------------------------------------
+void IncomingDamageTracker::update(UnsignedInt currentFrame)
+{
+ for (BookedShotMap::iterator vic = theBookings.begin(); vic != theBookings.end(); )
+ {
+ BookedShotVec& shots = vic->second;
+ for (BookedShotVec::iterator s = shots.begin(); s != shots.end(); )
+ {
+ if (currentFrame >= s->m_expireFrame)
+ s = shots.erase(s);
+ else
+ ++s;
+ }
+
+ if (shots.empty())
+ {
+ // ObjectIDs are never reused, so an emptied entry is gone for good.
+ BookedShotMap::iterator dead = vic;
+ ++vic;
+ theBookings.erase(dead);
+ }
+ else
+ {
+ ++vic;
+ }
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+void IncomingDamageTracker::bookShot(ObjectID victim, ObjectID shooter, Real amount,
+ UnsignedInt currentFrame, UnsignedInt impactFrame)
+{
+ if (victim == INVALID_ID || amount <= 0.0f)
+ return;
+
+ UnsignedInt flight = (impactFrame > currentFrame) ? (impactFrame - currentFrame) : MIN_FLIGHT_FRAMES;
+ if (flight < MIN_FLIGHT_FRAMES)
+ flight = MIN_FLIGHT_FRAMES;
+ else if (flight > MAX_FLIGHT_FRAMES)
+ flight = MAX_FLIGHT_FRAMES;
+
+ BookedShot shot;
+ shot.m_shooter = shooter;
+ shot.m_amount = amount;
+ shot.m_expireFrame = currentFrame + flight + BOOKING_SLACK_FRAMES;
+
+ theBookings[victim].push_back(shot);
+}
+
+//-------------------------------------------------------------------------------------------------
+void IncomingDamageTracker::shotLanded(ObjectID victim, ObjectID shooter)
+{
+ BookedShotMap::iterator vic = theBookings.find(victim);
+ if (vic == theBookings.end())
+ return;
+
+ BookedShotVec& shots = vic->second;
+ for (BookedShotVec::iterator s = shots.begin(); s != shots.end(); ++s)
+ {
+ if (s->m_shooter == shooter)
+ {
+ // oldest first: a shooter's shots land in the order they were fired
+ shots.erase(s);
+ break;
+ }
+ }
+
+ if (shots.empty())
+ theBookings.erase(vic);
+}
+
+//-------------------------------------------------------------------------------------------------
+Real IncomingDamageTracker::getBookedDamage(ObjectID victim)
+{
+ BookedShotMap::const_iterator vic = theBookings.find(victim);
+ if (vic == theBookings.end())
+ return 0.0f;
+
+ Real total = 0.0f;
+ const BookedShotVec& shots = vic->second;
+ for (BookedShotVec::const_iterator s = shots.begin(); s != shots.end(); ++s)
+ total += s->m_amount;
+
+ return total;
+}
+
+//-------------------------------------------------------------------------------------------------
+Bool IncomingDamageTracker::isAlreadyDoomed(ObjectID victim, Real remainingHealth)
+{
+ const Real booked = getBookedDamage(victim);
+ if (booked <= 0.0f)
+ return FALSE;
+
+ return booked >= remainingHealth;
+}
+
+//-------------------------------------------------------------------------------------------------
+Bool IncomingDamageTracker::isAlreadyDoomed(const Object *victim)
+{
+ return isAlreadyDoomed(victim->getID(), victim->getBodyModule()->getHealth());
+}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
index 2213038ca..c2337b92a 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
@@ -65,6 +65,7 @@
#include "GameLogic/AIPathfind.h"
#include "GameLogic/GameLogic.h"
+#include "GameLogic/IncomingDamage.h"
#include "GameLogic/Object.h"
#include "GameLogic/Module/AIUpdate.h"
#include "GameLogic/Module/BodyModule.h"
@@ -5372,6 +5373,16 @@ Bool PartitionFilterPossibleToAttack::allow(Object *objOther)
// disable this assert for INTERNAL builds (srj)
DEBUG_ASSERTCRASH(m_obj && m_obj->isAbleToAttack(), ("if the object is unable to attack at all, you should filter that out ahead of time!"));
#endif
+ //
+ // Someone else's shots are already in the air and already add up to more than this thing has
+ // left, so acquiring it would spend a volley on a corpse. Skipping it here is what spreads a
+ // group's fire over several targets instead of piling all of it onto the nearest one. This
+ // filter is only ever used to acquire a target on the unit's own initiative - guarding, attack
+ // moving, idle scanning - so an explicit attack order is never touched by it.
+ //
+ if (IncomingDamageTracker::isAlreadyDoomed(objOther))
+ return FALSE;
+
CanAttackResult result = m_obj->getAbleToAttackSpecificObject( m_attackType, objOther, m_commandSource );
if( result == ATTACKRESULT_POSSIBLE || result == ATTACKRESULT_POSSIBLE_AFTER_MOVING )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp
index 5d2065d6c..f68c4d3b9 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp
@@ -57,6 +57,7 @@
#include "GameLogic/Damage.h"
#include "GameLogic/ExperienceTracker.h"
#include "GameLogic/GameLogic.h"
+#include "GameLogic/IncomingDamage.h"
#include "GameLogic/AIPathfind.h"
#include "GameLogic/Module/BehaviorModule.h"
#include "GameLogic/Module/BodyModule.h"
@@ -1085,6 +1086,15 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate
when = TheGameLogic->getFrame() + delayInWholeFrames;
//DEBUG_LOG(("WeaponTemplate::fireWeaponTemplate: firing weapon in %d frames (= %d)!\n", delayInWholeFrames,when));
TheWeaponStore->setDelayedDamage(this, damagePos, when, sourceID, damageID, bonus);
+
+ // This damage is already spoken for: book it so nothing else spends a shot on a target
+ // that is dead as soon as this lands.
+ if (damageID != INVALID_ID && victimObj != NULL)
+ {
+ IncomingDamageTracker::bookShot(damageID, sourceID,
+ estimateWeaponTemplateDamage(sourceObj, victimObj, NULL, bonus),
+ TheGameLogic->getFrame(), when);
+ }
}
//-extraLogging
@@ -1139,6 +1149,19 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate
firingWeapon->newProjectileFired( sourceObj, projectile, victimObj, victimPos );//The actual logic weapon needs to know this was created.
+ // Book the projectile's damage against its victim for the length of its flight, so the rest of
+ // the squad can see that this target is already accounted for. The flight time is only an
+ // estimate - a guided projectile flies on its own locomotor - and the booking lapses on its own.
+ if (inflictDamage && victimObj != NULL && victimID != INVALID_ID)
+ {
+ const Real flightFrames = sqrtf(distSqr) / getWeaponSpeed();
+ const UnsignedInt now = TheGameLogic->getFrame();
+ IncomingDamageTracker::bookShot(victimID, sourceID,
+ estimateWeaponTemplateDamage(sourceObj, victimObj, NULL, bonus),
+ now, now + REAL_TO_INT_CEIL(flightFrames));
+ }
+
+
ProjectileUpdateInterface* pui = NULL;
for (BehaviorModule** u = projectile->getBehaviorModules(); *u; ++u)
{
@@ -1492,6 +1515,9 @@ void WeaponTemplate::dealDamageInternal(ObjectID sourceID, ObjectID victimID, co
}
curVictim->attemptDamage(&damageInfo);
+
+ // whatever was booked for this shot has now been spent
+ IncomingDamageTracker::shotLanded(curVictim->getID(), damageInfo.in.m_sourceID);
//DEBUG_ASSERTLOG(damageInfo.out.m_noEffect, ("WeaponTemplate::dealDamageInternal: dealt to %s %08lx: attempted %f, actual %f (%f)\n",
// curVictim->getTemplate()->getName().str(),curVictim,
// damageInfo.in.m_amount, damageInfo.out.m_actualDamageDealt, damageInfo.out.m_actualDamageClipped));
@@ -1627,6 +1653,8 @@ void WeaponStore::update()
++ddi;
}
}
+
+ IncomingDamageTracker::update(TheGameLogic->getFrame());
}
//-------------------------------------------------------------------------------------------------
@@ -1663,6 +1691,7 @@ void WeaponStore::reset()
}
deleteAllDelayedDamage();
+ IncomingDamageTracker::reset();
resetWeaponTemplates();
}