Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

feat(gameengine): extend range and sight from high ground

Olcay Seygane9b67350e0ac
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 66e57c371..b9754f5bd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -312,6 +312,7 @@ found and fixed — EA's own, not port damage.**
- A tank drives out the moment it is paid for. The factory doors only began opening once the vehicle was already finished, and it stood inside waiting for them, so every single unit cost its build time plus the whole door animation on top - on every tank, all game. The doors now start moving during the last seconds of the build and are open on the frame the unit is done. And they stay open while there is another vehicle behind him, however long that takes: a factory working through a queue keeps its doors up and shuts them when the queue runs out, instead of dropping and hauling them back for every unit. That was worth watching in its own right - there is no artwork for a door that changes its mind partway, so a door caught mid-close and pulled back open snapped wide in a single frame.
- A unit lifts the fog only half as far again as its guns reach: enough to spot what it is about to fight, not enough to scout. A rifleman used to see well past the range of his rifle, so any cheap soldier was a scout. Artillery that outshoots its own eyes still needs a spotter, and units with no weapon at all, like bulldozers and supply trucks, keep the sight they had. Buildings are unchanged.
- Hills and buildings block sight. A tank at the foot of a ridge used to see straight through it to the far side, and a squad in a city saw through every block around it. Now the fog stays on whatever a ridge, a building or a tree hides, yours, the enemy's or a civilian's, and a unit on high ground looks down over everything below it. Aircraft fly above it all and see past. Soldiers garrisoned in a building still see out of it; its own walls do not blind them.
+- High ground pays. A tank on a ridge now shoots, sees and picks its targets further down the slope than it could on the flat: three steps of range for every step of height over its target, up to twice its usual reach. Firing uphill costs nothing, and aircraft get no bonus from flying. Defences count too, and the range ring you see while placing one bends outward wherever the ground falls away, so you can site a Gattling Cannon on a hill and see exactly what it covers.
## One crate, one collector
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
index 447e10ae1..573e6cda1 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
@@ -1386,8 +1386,10 @@ public:
/** Reveal the circle around an eye except where a hill or a building stands between the eye and
the ground, and record in the sighting which cells that was. The looker never hides behind
- itself or the building it sits in. */
- void doBlockedShroudReveal( SightingInfo *sighting, const Object *looker );
+ itself or the building it sits in. The sighting's range is the furthest the looker could see
+ from high ground; a cell lies inside it only as far as flatRange stretches from the height the
+ looker stands above that cell. */
+ void doBlockedShroudReveal( SightingInfo *sighting, const Object *looker, Real flatRange );
void doShroudCover( Real centerX, Real centerY, Real radius, PlayerMaskType playerMask);
void undoShroudCover( Real centerX, Real centerY, Real radius, PlayerMaskType playerMask);
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h
index 8dd103d6a..95d06baa2 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h
@@ -897,5 +897,11 @@ private:
// EXTERNALS //////////////////////////////////////////////////////////////////////////////////////
extern WeaponStore *TheWeaponStore;
+///< how much further a range reaches from heightAboveTarget above what it is aimed at; never less
+extern Real Weapon_elevationRangeBonus( Real range, Real heightAboveTarget );
+
+///< range as source reaches something standing at targetZ; an aircraft gets no high ground
+extern Real Weapon_elevatedRange( const Object *source, Real range, Real targetZ );
+
#endif // __WEAPON_H_
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
index 8dbb5bdda..e32d9744c 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
@@ -150,7 +150,8 @@ enum
REACH_OUTLINE_SEGMENTS = 256, ///< straight pieces round one reach circle
REACH_CROSSING_HALVINGS = 8, ///< halvings that find where one circle's outline enters another
- REACH_OUTLINE_ALPHA = 230 ///< the outline in the owner's colour, a touch see-through
+ REACH_OUTLINE_ALPHA = 230, ///< the outline in the owner's colour, a touch see-through
+ ELEVATED_REACH_PASSES = 3 ///< where the ground under the edge is read moves with the edge
};
static const Real REACH_OUTLINE_WIDTH = 1.0f;
@@ -1694,6 +1695,26 @@ static Real templateReach( const ThingTemplate *tmpl )
return range > 0.0f ? range + tmpl->getTemplateGeometryInfo().getBoundingCircleRadius() : 0.0f;
}
+//-------------------------------------------------------------------------------------------------
+/** A structure's flat reach, templateReach, along one direction from where it stands: further
+ * wherever the ground it looks down on lies below it, by the same high ground bonus its weapon,
+ * of templatePlacementRange, is tested with. How far the edge goes decides whose ground height
+ * it gets, so it is settled over a few passes. */
+//-------------------------------------------------------------------------------------------------
+static Real elevatedReach( Real reach, Real range, const Coord3D &center, Real angle )
+{
+ const Real dirX = Cos( angle );
+ const Real dirY = Sin( angle );
+
+ Real along = reach;
+ for( Int pass = 0; pass < ELEVATED_REACH_PASSES; pass++ )
+ {
+ const Real groundZ = TheTerrainLogic->getGroundHeight( center.x + dirX * along, center.y + dirY * along );
+ along = reach + Weapon_elevationRangeBonus( range, center.z - groundZ );
+ }
+ return along;
+}
+
//-------------------------------------------------------------------------------------------------
// The top left drop-down. Row 0 is its header; each row after it is one strip, its words, the
// GlobalData switch it flips and the Options.ini key that switch is saved under.
@@ -1943,17 +1964,32 @@ static void fillSpanRows( std::vector< std::vector< ICoord2D > > &rows, Color co
//-------------------------------------------------------------------------------------------------
/** A defence's reach cut into the blind-spot polar grid: sector ray covers the angles from ray to
- * ray + 1, ring ring the distances from ring to ring + 1 ring widths. blocked is empty for a
- * defence that shoots whatever is in range. */
+ * ray + 1, ring ring the distances from ring to ring + 1 ring widths. reach is how far each sector
+ * goes, longer down a slope, and radius the longest of them. blocked is empty for a defence that
+ * shoots whatever is in range. */
//-------------------------------------------------------------------------------------------------
struct ReachView
{
- Coord2D center;
+ Coord3D center;
Real radius;
+ std::vector< Real > reach;
Int rings;
std::vector< Bool > blocked;
};
+static void traceReachView( ReachView &view, const ThingTemplate *tmpl )
+{
+ const Real flatReach = templateReach( tmpl );
+ const Real range = templatePlacementRange( tmpl );
+ view.reach.resize( BLIND_SPOT_RAYS );
+ view.radius = 0.0f;
+ for( Int ray = 0; ray < BLIND_SPOT_RAYS; ray++ )
+ {
+ view.reach[ ray ] = elevatedReach( flatReach, range, view.center, 2.0f * PI * ( ray + 0.5f ) / BLIND_SPOT_RAYS );
+ view.radius = max( view.radius, view.reach[ ray ] );
+ }
+}
+
static Bool templateNeedsLineOfSight( const ThingTemplate *tmpl )
{
return TheAI->getAiData()->m_attackUsesLineOfSight && tmpl->isKindOf( KINDOF_ATTACK_NEEDS_LINE_OF_SIGHT );
@@ -1993,7 +2029,8 @@ static void lookRoundReach( ReachView &view, Real eyeZ, ObjectID self )
const Bool behindHill = targetSlope < horizonSlope;
horizonSlope = max( horizonSlope, ( groundZ - LOS_TERRAIN_SLOP - eyeZ ) / along );
- view.blocked[ ray * view.rings + ring ] = behindBuilding || behindHill;
+ const Bool inReach = ( ring + 0.5f ) * BLIND_SPOT_RING_WIDTH < view.reach[ ray ];
+ view.blocked[ ray * view.rings + ring ] = inReach && ( behindBuilding || behindHill );
}
}
}
@@ -2005,13 +2042,16 @@ static Bool reachViewHits( const ReachView &view, Real x, Real y )
const Real distance = sqrtf( sqr( dx ) + sqr( dy ) );
if( distance >= view.radius )
return FALSE;
- if( view.blocked.empty() )
- return TRUE;
Real angle = atan2( dy, dx );
if( angle < 0.0f )
angle += 2.0f * PI;
const Int ray = min( (Int)( angle * BLIND_SPOT_RAYS / ( 2.0f * PI ) ), BLIND_SPOT_RAYS - 1 );
+ if( distance >= view.reach[ ray ] )
+ return FALSE;
+ if( view.blocked.empty() )
+ return TRUE;
+
const Int ring = min( (Int)( distance / BLIND_SPOT_RING_WIDTH ), view.rings - 1 );
return !view.blocked[ ray * view.rings + ring ];
}
@@ -2051,9 +2091,9 @@ void InGameUI::drawPlacementBlindSpots( void )
ReachView pending;
pending.center.x = center.x;
pending.center.y = center.y;
- pending.radius = m_placementRingRadius;
- const Real eyeZ = TheTerrainLogic->getGroundHeight( center.x, center.y )
- + m_pendingPlaceType->getTemplateGeometryInfo().getMaxHeightAbovePosition();
+ pending.center.z = TheTerrainLogic->getGroundHeight( center.x, center.y );
+ traceReachView( pending, m_pendingPlaceType );
+ const Real eyeZ = pending.center.z + m_pendingPlaceType->getTemplateGeometryInfo().getMaxHeightAbovePosition();
lookRoundReach( pending, eyeZ, INVALID_ID );
const Real range = pending.radius;
@@ -2069,13 +2109,16 @@ void InGameUI::drawPlacementBlindSpots( void )
if( obj->getControllingPlayer() != local && local->getRelationship( obj->getTeam() ) != ALLIES )
continue;
+ const Real flatReach = templateReach( obj->getTemplate() );
+ const Real furthest = flatReach + Weapon_elevationRangeBonus( templatePlacementRange( obj->getTemplate() ), FLT_MAX );
+ const Coord3D *position = obj->getPosition();
+ if( flatReach <= 0.0f || sqr( position->x - center.x ) + sqr( position->y - center.y ) >= sqr( furthest + range ) )
+ continue;
+
ReachView guard;
- guard.radius = templateReach( obj->getTemplate() );
- guard.center.x = obj->getPosition()->x;
- guard.center.y = obj->getPosition()->y;
+ guard.center = *position;
guard.rings = 0;
- if( guard.radius <= 0.0f || sqr( guard.center.x - center.x ) + sqr( guard.center.y - center.y ) >= sqr( guard.radius + range ) )
- continue;
+ traceReachView( guard, obj->getTemplate() );
if( templateNeedsLineOfSight( obj->getTemplate() ) )
lookRoundReach( guard, obj->getPosition()->z + obj->getGeometryInfo().getMaxHeightAbovePosition(), obj->getID() );
@@ -2162,18 +2205,52 @@ static Bool projectGroundPoint( Real x, Real y, ICoord2D *screen )
struct ReachCircle
{
- Coord2D center;
- Real radius;
+ Coord3D center;
+ Real radius; ///< the furthest the outline goes
+ std::vector< Real > outline; ///< the reach at the start of each outline segment, longer down a slope
const Player *owner;
};
+static void traceReachCircle( ReachCircle &circle, const ThingTemplate *tmpl )
+{
+ const Real flatReach = templateReach( tmpl );
+ const Real range = templatePlacementRange( tmpl );
+ circle.outline.resize( REACH_OUTLINE_SEGMENTS );
+ circle.radius = 0.0f;
+ for( Int segment = 0; segment < REACH_OUTLINE_SEGMENTS; segment++ )
+ {
+ circle.outline[ segment ] = elevatedReach( flatReach, range, circle.center, 2.0f * PI * segment / REACH_OUTLINE_SEGMENTS );
+ circle.radius = max( circle.radius, circle.outline[ segment ] );
+ }
+}
+
+/// the reach toward an angle from 0 to two pi, read between the outline corners either side of it
+static Real reachAtAngle( const ReachCircle &circle, Real angle )
+{
+ const Real at = angle * REACH_OUTLINE_SEGMENTS / ( 2.0f * PI );
+ const Int from = min( (Int)at, REACH_OUTLINE_SEGMENTS - 1 );
+ const Real part = at - from;
+ return circle.outline[ from ] * ( 1.0f - part ) + circle.outline[ ( from + 1 ) % REACH_OUTLINE_SEGMENTS ] * part;
+}
+
/// inside another circle of the same player's; two players' circles cross, each in its own colour
static Bool insideOtherReach( const std::vector< ReachCircle > &circles, size_t self, Real x, Real y )
{
for( size_t c = 0; c < circles.size(); c++ )
{
- if( c != self && circles[ c ].owner == circles[ self ].owner
- && sqr( x - circles[ c ].center.x ) + sqr( y - circles[ c ].center.y ) < sqr( circles[ c ].radius ) )
+ if( c == self || circles[ c ].owner != circles[ self ].owner )
+ continue;
+
+ const Real dx = x - circles[ c ].center.x;
+ const Real dy = y - circles[ c ].center.y;
+ const Real distanceSqr = sqr( dx ) + sqr( dy );
+ if( distanceSqr >= sqr( circles[ c ].radius ) )
+ continue;
+
+ Real angle = atan2( dy, dx );
+ if( angle < 0.0f )
+ angle += 2.0f * PI;
+ if( distanceSqr < sqr( reachAtAngle( circles[ c ], angle ) ) )
return TRUE;
}
return FALSE;
@@ -2212,8 +2289,9 @@ void InGameUI::drawPlacementReach( void )
ReachCircle pending;
pending.center.x = m_placeIcon[ 0 ]->getPosition()->x;
pending.center.y = m_placeIcon[ 0 ]->getPosition()->y;
- pending.radius = m_placementRingRadius;
+ pending.center.z = TheTerrainLogic->getGroundHeight( pending.center.x, pending.center.y );
pending.owner = local;
+ traceReachCircle( pending, m_pendingPlaceType );
circles.push_back( pending );
}
@@ -2224,13 +2302,12 @@ void InGameUI::drawPlacementReach( void )
if( obj->getControllingPlayer() != local && obj->getShroudedStatus( local->getPlayerIndex() ) >= OBJECTSHROUD_FOGGED )
continue;
- ReachCircle placed;
- placed.radius = templateReach( obj->getTemplate() );
- if( placed.radius <= 0.0f )
+ if( templateReach( obj->getTemplate() ) <= 0.0f )
continue;
- placed.center.x = obj->getPosition()->x;
- placed.center.y = obj->getPosition()->y;
+ ReachCircle placed;
+ placed.center = *obj->getPosition();
placed.owner = obj->getControllingPlayer();
+ traceReachCircle( placed, obj->getTemplate() );
circles.push_back( placed );
}
@@ -2248,8 +2325,9 @@ void InGameUI::drawPlacementReach( void )
Bool inside[ 2 ];
for( Int e = 0; e < 2; e++ )
{
- ends[ e ][ 0 ] = circle.center.x + Cos( angles[ e ] ) * circle.radius;
- ends[ e ][ 1 ] = circle.center.y + Sin( angles[ e ] ) * circle.radius;
+ const Real reach = reachAtAngle( circle, angles[ e ] );
+ ends[ e ][ 0 ] = circle.center.x + Cos( angles[ e ] ) * reach;
+ ends[ e ][ 1 ] = circle.center.y + Sin( angles[ e ] ) * reach;
inside[ e ] = insideOtherReach( circles, c, ends[ e ][ 0 ], ends[ e ][ 1 ] );
}
if( inside[ 0 ] && inside[ 1 ] )
@@ -2263,14 +2341,16 @@ void InGameUI::drawPlacementReach( void )
for( Int halving = 0; halving < REACH_CROSSING_HALVINGS; halving++ )
{
const Real middle = 0.5f * ( outsideAngle + insideAngle );
- if( insideOtherReach( circles, c, circle.center.x + Cos( middle ) * circle.radius, circle.center.y + Sin( middle ) * circle.radius ) )
+ const Real middleReach = reachAtAngle( circle, middle );
+ if( insideOtherReach( circles, c, circle.center.x + Cos( middle ) * middleReach, circle.center.y + Sin( middle ) * middleReach ) )
insideAngle = middle;
else
outsideAngle = middle;
}
const Int cut = inside[ 0 ] ? 0 : 1;
- ends[ cut ][ 0 ] = circle.center.x + Cos( outsideAngle ) * circle.radius;
- ends[ cut ][ 1 ] = circle.center.y + Sin( outsideAngle ) * circle.radius;
+ const Real cutReach = reachAtAngle( circle, outsideAngle );
+ ends[ cut ][ 0 ] = circle.center.x + Cos( outsideAngle ) * cutReach;
+ ends[ cut ][ 1 ] = circle.center.y + Sin( outsideAngle ) * cutReach;
}
ICoord2D from, to;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
index e2e17ab94..ae1a1000a 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
@@ -5236,10 +5236,11 @@ void Object::look()
Coord3D eye = *getPosition();
eye.z += getGeometryInfo().getMaxHeightAbovePosition();
+ // out to the furthest the high ground could carry it; each cell is cut back to its own height
m_partitionLastLook->m_where = eye;
m_partitionLastLook->m_forWhom = lookingMask;
- m_partitionLastLook->m_howFar = shroudClearingRange;
- ThePartitionManager->doBlockedShroudReveal( m_partitionLastLook, this );
+ m_partitionLastLook->m_howFar = Weapon_elevatedRange( this, shroudClearingRange, -FLT_MAX );
+ ThePartitionManager->doBlockedShroudReveal( m_partitionLastLook, this, shroudClearingRange );
// DEBUG_LOG(( "A %s looks at %f, %f for %x at range %f\n",
// getTemplate()->getName().str(),
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
index 20bbb72da..b5d6ffee9 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
@@ -77,6 +77,7 @@
#include "GameLogic/PolygonTrigger.h"
#include "GameLogic/Squad.h"
#include "GameLogic/GhostObject.h"
+#include "GameLogic/Weapon.h"
#include "GameClient/Line2D.h"
#include "GameClient/ControlBar.h"
@@ -4331,7 +4332,7 @@ static Real sightBlockingHeight( PartitionCell *cell, const Object *looker, cons
}
//-----------------------------------------------------------------------------
-void PartitionManager::doBlockedShroudReveal( SightingInfo *sighting, const Object *looker )
+void PartitionManager::doBlockedShroudReveal( SightingInfo *sighting, const Object *looker, Real flatRange )
{
Int cellCenterX, cellCenterY;
worldToCell( sighting->m_where.x, sighting->m_where.y, &cellCenterX, &cellCenterY );
@@ -4357,9 +4358,22 @@ void PartitionManager::doBlockedShroudReveal( SightingInfo *sighting, const Obje
PartitionManager_findSightMargins( &heights[0], cellRadius, m_cellSize, sighting->m_where.z, &sightMargin[0] );
+ // r * ( r + 1 ) rather than r squared: the circle the reveal is drawn with is a Bresenham one,
+ // and on flat ground this has to keep every cell of it
+ const Bool stretched = sighting->m_howFar > flatRange;
sighting->m_revealedCells.resize( side * side );
for( Int cell = 0; cell < side * side; ++cell )
- sighting->m_revealedCells[ cell ] = sightMargin[ cell ] >= 0.0f;
+ {
+ Bool revealed = sightMargin[ cell ] >= 0.0f;
+ if( revealed && stretched )
+ {
+ const Int offsetX = cell % side - cellRadius;
+ const Int offsetY = cell / side - cellRadius;
+ const Int reachCells = sightCellRadius( Weapon_elevatedRange( looker, flatRange, heights[ cell ] ) );
+ revealed = offsetX * offsetX + offsetY * offsetY <= reachCells * ( reachCells + 1 );
+ }
+ sighting->m_revealedCells[ cell ] = revealed;
+ }
applyRecordedReveal( sighting, TRUE );
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index f5cf88ab2..17ac78ea0 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -6171,6 +6171,32 @@ public:
#endif
};
+//-------------------------------------------------------------------------------------------------
+/** A ground unit looks as far as the high ground lets it shoot: the scan runs out to the largest
+ * reach any height could give, and this cuts each enemy back to the reach its own height gives. */
+//-------------------------------------------------------------------------------------------------
+class PartitionFilterElevatedReach : public PartitionFilter
+{
+private:
+ const Object *m_self;
+ Real m_range; ///< the search distance on flat ground
+
+public:
+ PartitionFilterElevatedReach( const Object *self, Real range )
+ : m_self( self ), m_range( range )
+ { }
+
+ virtual Bool allow( Object *other )
+ {
+ const Real reach = Weapon_elevatedRange( m_self, m_range, other->getPosition()->z );
+ return ThePartitionManager->getDistanceSquared( m_self, other, FROM_BOUNDINGSPHERE_2D ) <= reach * reach;
+ }
+
+#if defined(_DEBUG) || defined(_INTERNAL)
+ virtual const char* debugGetName() { return "PartitionFilterElevatedReach"; }
+#endif
+};
+
Object* AIUpdateInterface::getNextMoodTarget( Bool calledByAI, Bool calledDuringIdle, Bool allowOutOfWeaponRangeTargets, Bool requireWithinWeaponRange )
{
Object *obj = getObject();
@@ -6372,9 +6398,15 @@ Object* AIUpdateInterface::getNextMoodTarget( Bool calledByAI, Bool calledDuring
// ... and an aircraft only makes that long look forward - see PartitionFilterForwardArc.
//
PartitionFilterForwardArc filterArc( obj, obj->getLargestWeaponRange() );
+ PartitionFilterElevatedReach filterHeight( obj, rangeToFindWithin );
PartitionFilter *arc = NULL;
if( allowOutOfWeaponRangeTargets && obj->isKindOf( KINDOF_AIRCRAFT ) )
arc = &filterArc;
+ else if( !obj->isKindOf( KINDOF_AIRCRAFT ) && container == NULL )
+ {
+ arc = &filterHeight;
+ rangeToFindWithin += Weapon_elevationRangeBonus( rangeToFindWithin, FLT_MAX );
+ }
Object *newVictim = TheAI->findClosestEnemy(obj, rangeToFindWithin, flags, getAttackInfo(), arc);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp
index 0c99b26cd..77c5b5e07 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp
@@ -96,6 +96,32 @@
// damage is ALWAYS 3d
const DistanceCalculationType DAMAGE_RANGE_CALC_TYPE = FROM_BOUNDINGSPHERE_3D;
+//-------------------------------------------------------------------------------------------------
+/** High ground. Range is measured flat, so a tank on a ridge used to reach no further than one in
+ * the valley below it. Every world unit it stands above its target now adds three units of range,
+ * up to the range itself again. Standing lower costs nothing: the approach to a target is
+ * planned with the flat range and never knows the target's height, so a shorter range uphill would
+ * park the attacker just outside it. */
+//-------------------------------------------------------------------------------------------------
+static const Real ELEVATION_RANGE_PER_HEIGHT = 3.0f;
+static const Real ELEVATION_RANGE_CAP = 1.0f;
+
+Real Weapon_elevationRangeBonus( Real range, Real heightAboveTarget )
+{
+ if( heightAboveTarget <= 0.0f )
+ return 0.0f;
+
+ return min( heightAboveTarget * ELEVATION_RANGE_PER_HEIGHT, range * ELEVATION_RANGE_CAP );
+}
+
+Real Weapon_elevatedRange( const Object *source, Real range, Real targetZ )
+{
+ if( source->isKindOf( KINDOF_AIRCRAFT ) )
+ return range;
+
+ return range + Weapon_elevationRangeBonus( range, source->getPosition()->z - targetZ );
+}
+
//-------------------------------------------------------------------------------------------------
static void parsePerVetLevelAsciiString( INI* ini, void* /*instance*/, void * store, const void* /*userData*/ )
{
@@ -878,7 +904,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate
//Only perform this check if the weapon isn't a leech range weapon (which can have unlimited range!)
if( !ignoreRanges && !isLeechRangeWeapon() )
{
- Real attackRangeSqr = sqr(getAttackRange(bonus));
+ Real attackRangeSqr = sqr(Weapon_elevatedRange(sourceObj, getAttackRange(bonus), victimPos->z));
if (distSqr > attackRangeSqr)
{
//DEBUG_ASSERTCRASH(distSqr < 5*5 || distSqr < attackRangeSqr*1.2f, ("*** victim is out of range (%f vs %f) of this weapon -- why did we attempt to fire?\n",sqrtf(distSqr),sqrtf(attackRangeSqr)));
@@ -2230,7 +2256,7 @@ Bool Weapon::isSourceObjectWithGoalPositionWithinAttackRange( const Object *sour
Bool Weapon::isWithinAttackRange(const Object *source, const Coord3D* pos) const
{
Real distSqr = ThePartitionManager->getDistanceSquared( source, pos, ATTACK_RANGE_CALC_TYPE );
- Real attackRangeSqr = sqr(getAttackRange(source));
+ Real attackRangeSqr = sqr(Weapon_elevatedRange(source, getAttackRange(source), pos->z));
Real minAttackRangeSqr = sqr(m_template->getMinimumAttackRange());
#ifdef RATIONALIZE_ATTACK_RANGE
if (distSqr < minAttackRangeSqr)
@@ -2247,7 +2273,7 @@ Bool Weapon::isWithinAttackRange(const Object *source, const Coord3D* pos) const
Bool Weapon::isWithinAttackRange(const Object *source, const Object *target) const
{
Real distSqr;
- Real attackRangeSqr = sqr(getAttackRange(source));
+ Real attackRangeSqr = sqr(Weapon_elevatedRange(source, getAttackRange(source), target->getPosition()->z));
if( !target->isKindOf(KINDOF_BRIDGE) )
{
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index da61bdf09..52d3064c5 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -122,6 +122,7 @@
#include "GameClient/Drawable.h"
#include "Common/BuildAssistant.h"
#include "GameLogic/Object.h"
+#include "GameLogic/Weapon.h"
#include "GameClient/CommandXlat.h"
#include "Common/ActionManager.h"
#include "GameLogic/PartitionManager.h"
@@ -6492,6 +6493,16 @@ TEST(an_armed_unit_sees_little_further_than_it_can_shoot)
CHECK_NEAR( Object_armedShroudClearingRange( 0.0f, 100.0f ), 0.0f, 0.0001f );
}
+/** Three units of range for every unit of height over the target, never more than doubling the
+ range, and nothing taken away for standing lower. */
+TEST(high_ground_reaches_further_and_low_ground_no_shorter)
+{
+ CHECK_NEAR( Weapon_elevationRangeBonus( 200.0f, 20.0f ), 60.0f, 0.0001f );
+ CHECK_NEAR( Weapon_elevationRangeBonus( 200.0f, 400.0f ), 200.0f, 0.0001f );
+ CHECK_NEAR( Weapon_elevationRangeBonus( 200.0f, FLT_MAX ), 200.0f, 0.0001f );
+ CHECK_NEAR( Weapon_elevationRangeBonus( 200.0f, 0.0f ), 0.0f, 0.0001f );
+ CHECK_NEAR( Weapon_elevationRangeBonus( 200.0f, -40.0f ), 0.0f, 0.0001f );
+}
/** A hill hides the ground behind it. Standing in the middle of flat ground with a wall of high cells
two to the east, the unit sees the wall and nothing past it, and sees everything to the west. Put