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(ai): path congestion cost, production bar and selection line on health bars

Olcay Seyganf04cd396fde7
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
index 8b783d943..21891dcca 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
@@ -150,6 +150,7 @@ public:
Path();
PathNode *getFirstNode( void ) { return m_path; }
+ const PathNode *getFirstNode( void ) const { return m_path; }
PathNode *getLastNode( void ) { return m_pathTail; }
void updateLastNode( const Coord3D *pos );
@@ -174,6 +175,10 @@ public:
/// Given a location, return closest location on path, and along-path dist to end as function result
void markOptimized(void) {m_isOptimized = true;}
+ Bool isUsageRegistered(void) const {return m_usageHead != NULL;}
+ const PathNode *getUsageHead(void) const {return m_usageHead;}
+ void setUsageHead(const PathNode *node) const {m_usageHead = node;}
+
protected:
// snapshot interface
virtual void crc( Xfer *xfer );
@@ -188,6 +193,7 @@ protected:
PathNode* m_pathTail;
Bool m_isOptimized; ///< True if the path has been optimized
Bool m_blockedByAlly; ///< An ally needs to move off of this path.
+ mutable const PathNode *m_usageHead; ///< First raw node still counted in Pathfinder's congestion map (NULL = not registered); cells behind the unit are released as it advances, ~Path releases the rest.
// caching info for computePointOnPath.
Bool m_cpopValid;
Int m_cpopCountdown; ///< We only return the same cpop MAX_CPOP times. It is occasionally possible to get stuck.
@@ -670,7 +676,14 @@ public:
Bool worldToCell( const Coord3D *pos, ICoord2D *cell ); ///< Given a world position, return grid cell coordinate
const ICoord2D *getExtent(void) const {return &m_extent.hi;}
-
+
+ /// Congestion map: how many live unit paths run through each cell. A* charges extra per path, so
+ /// units ordered along the same route spread into parallel lanes instead of stacking on one line.
+ void registerPathUsage( const Path *path );
+ void unregisterPathUsage( const Path *path );
+ void releasePathUsageBefore( const Path *path, const PathNode *node ); ///< unit has passed everything before node
+ void adjustPathUsage( const PathNode *from, const PathNode *to, Int delta ); ///< [from, to) raw nodes, +1/-1
+
void setIgnoreObstacleID( ObjectID objID ); ///< if non-zero, the pathfinder will ignore the given obstacle
Bool validMovementPosition( Bool isCrusher, LocomotorSurfaceTypeMask acceptableSurfaces, PathfindCell *toCell, PathfindCell *fromCell = NULL ); ///< Return true if given position is a valid movement location
@@ -835,6 +848,8 @@ private:
/// This uses WAY too much memory. Should at least be array of pointers to cells w/ many fewer cells
PathfindCell *m_blockOfMapCells; ///< Pathfinding map - contains iconic representation of the map
PathfindCell **m_map; ///< Pathfinding map indexes - contains matrix indexing into the map.
+ UnsignedByte *m_pathUsage; ///< Congestion map, (hi.x+1)*(hi.y+1), indexed [x*(hi.y+1)+y]
+ Int getPathUsage( Int x, Int y ) const;
IRegion2D m_extent; ///< Grid extent limits
IRegion2D m_logicalExtent; ///< Logical grid extent limits
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
index 2f808b6e6..e1a8ce076 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
@@ -57,6 +57,8 @@
#include "GameLogic/Module/BodyModule.h"
#include "GameLogic/Module/ContainModule.h"
#include "GameLogic/Module/PhysicsUpdate.h"
+#include "GameLogic/Module/ProductionUpdate.h"
+#include "Common/Upgrade.h"
#include "GameLogic/Module/StealthUpdate.h"
#include "GameLogic/Module/StickyBombUpdate.h"
#include "GameLogic/Module/BattlePlanUpdate.h"
@@ -3945,10 +3947,52 @@ void Drawable::drawHealthBar(const IRegion2D* healthBarRegion)
TheDisplay->drawOpenRect( healthBarRegion->lo.x, healthBarRegion->lo.y, healthBoxWidth, healthBoxHeight,
healthBoxOutlineSize, outlineColor );
- // draw a filled bar for the health
- TheDisplay->drawFillRect( healthBarRegion->lo.x + 1, healthBarRegion->lo.y + 1,
- (healthBoxWidth - 2) * healthRatio, healthBoxHeight - 2,
- color );
+ // selected drawables get a white overline (1px gap above the bar; below collides with the container pips) so they stand out now that all bars are always on
+ // (+1: drawOpenRect covers width+1 columns, drawFillRect only width)
+ if( isSelected() )
+ TheDisplay->drawFillRect( healthBarRegion->lo.x, healthBarRegion->lo.y - 2, healthBoxWidth + 1, 1,
+ GameMakeColor( 255, 255, 255, 255 ) );
+
+ // own producers show a yellow production-progress bar above the (selection) line, with seconds left at its top-left
+ ProductionUpdateInterface *pu = obj->isLocallyControlled() ? obj->getProductionUpdateInterface() : NULL;
+ const ProductionEntry *pe = pu ? pu->firstProduction() : NULL;
+ if( pe )
+ {
+ Int prodY = healthBarRegion->lo.y - 3 - healthBoxHeight;
+ Real pct = pe->getPercentComplete();
+ TheDisplay->drawOpenRect( healthBarRegion->lo.x, prodY, healthBoxWidth, healthBoxHeight,
+ healthBoxOutlineSize, GameMakeColor( 128, 128, 0, 255 ) );
+ TheDisplay->drawFillRect( healthBarRegion->lo.x + 1, prodY + 1,
+ (healthBoxWidth - 2) * pct * 0.01f, healthBoxHeight - 2,
+ GameMakeColor( 255, 255, 0, 255 ) );
+
+ Player *player = obj->getControllingPlayer();
+ Int totalFrames = pe->getProductionType() == PRODUCTION_UNIT
+ ? pe->getProductionObject()->calcTimeToBuild( player )
+ : pe->getProductionUpgrade()->calcTimeToBuild( player );
+ // clamp: the entry lingers at >100% while the unit exits the factory
+ Int secondsLeft = REAL_TO_INT_CEIL( totalFrames * (1.0f - pct * 0.01f) / LOGICFRAMES_PER_SECOND );
+ if( secondsLeft < 0 )
+ secondsLeft = 0;
+
+ // one shared string: draw() renders immediately, and the manager lives for the whole app
+ static DisplayString *prodTimeString = NULL;
+ if( prodTimeString == NULL )
+ {
+ prodTimeString = TheDisplayStringManager->newDisplayString();
+ prodTimeString->setFont( TheFontLibrary->getFont( TheInGameUI->getDrawableCaptionFontName(),
+ TheGlobalLanguageData->adjustFontSize( TheInGameUI->getDrawableCaptionPointSize() - 2 ),
+ FALSE ) );
+ }
+ UnicodeString text;
+ text.format( L"%ds", secondsLeft );
+ if( prodTimeString->getText().compare( text ) != 0 )
+ prodTimeString->setText( text );
+ Int textW, textH;
+ prodTimeString->getSize( &textW, &textH );
+ prodTimeString->draw( healthBarRegion->lo.x, prodY - textH,
+ GameMakeColor( 255, 255, 255, 255 ), GameMakeColor( 0, 0, 0, 255 ) );
+ }
} // end if
} // end drawHealthBar
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
index 96a21dc5c..4fdd40bc6 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
@@ -245,6 +245,7 @@ m_path(NULL),
m_pathTail(NULL),
m_isOptimized(FALSE),
m_blockedByAlly(FALSE),
+m_usageHead(NULL),
m_cpopRecentStart(NULL),
m_cpopCountdown(MAX_CPOP),
m_cpopValid(FALSE)
@@ -259,7 +260,10 @@ Path::~Path( void )
{
PathNode *node, *nextNode;
- // delete all of the path nodes
+ if (m_usageHead && TheAI && TheAI->pathfinder())
+ TheAI->pathfinder()->unregisterPathUsage(this);
+
+ // delete all of the path nodes
for( node = m_path; node; node = nextNode )
{
nextNode = node->getNext();
@@ -452,10 +456,13 @@ void Path::appendNode( const Coord3D *pos, PathfindLayerEnum layer )
void Path::updateLastNode( const Coord3D *pos )
{
PathfindLayerEnum layer = TheTerrainLogic->getLayerForDestination(pos);
+ // Keep the congestion map honest: uncount the old tail cell, recount the new one.
+ if (m_usageHead) TheAI->pathfinder()->adjustPathUsage(m_pathTail, NULL, -1);
if (m_pathTail) {
m_pathTail->setPosition(pos);
m_pathTail->setLayer(layer);
}
+ if (m_usageHead) TheAI->pathfinder()->adjustPathUsage(m_pathTail, NULL, +1);
if (m_isOptimized && m_pathTail)
{
PathNode *node = m_path;
@@ -877,6 +884,9 @@ void Path::computePointOnPath(
#ifdef CPOP_STARTS_FROM_PREV_SEG
m_cpopRecentStart = closeNode;
#endif
+ // Everything before the closest segment is behind us - stop charging others for it.
+ if (m_usageHead && closeNode)
+ TheAI->pathfinder()->releasePathUsageBefore(this, closeNode);
//
// Compute the goal movement position for this agent
@@ -1672,6 +1682,9 @@ PathfindCell *PathfindCell::removeFromClosedList( PathfindCell *list )
const Int COST_ORTHOGONAL = 10;
const Int COST_DIAGONAL = 14;
+// ponytail: congestion knob, per other-unit path crossing a cell of our footprint. Rebuild to tune;
+// move into AIData INI if it needs per-map tweaking.
+const Int PATH_CONGESTION_COST = COST_ORTHOGONAL;
const Real COST_TO_DISTANCE_FACTOR = 1.0f/10.0f;
const Real COST_TO_DISTANCE_FACTOR_SQR = COST_TO_DISTANCE_FACTOR*COST_TO_DISTANCE_FACTOR;
@@ -3825,7 +3838,7 @@ void PathfindLayer::classifyWallMapCell( Int i, Int j , PathfindCell *cell, Obje
//----------------------- Pathfinder ---------------------------------------
-Pathfinder::Pathfinder( void ) :m_map(NULL)
+Pathfinder::Pathfinder( void ) :m_map(NULL), m_pathUsage(NULL)
{
debugPath = NULL;
PathfindCellInfo::allocateCellInfos();
@@ -3846,10 +3859,14 @@ void Pathfinder::reset( void )
delete []m_blockOfMapCells;
m_blockOfMapCells = NULL;
}
- if (m_map) {
+ if (m_map) {
delete [] m_map;
m_map = NULL;
}
+ if (m_pathUsage) {
+ delete [] m_pathUsage;
+ m_pathUsage = NULL;
+ }
Int i;
for (i=0; i<=LAYER_LAST; i++) {
@@ -4576,6 +4593,8 @@ void Pathfinder::newMap( void )
for (i=0; i<=bounds.hi.x; i++) {
m_map[i] = &m_blockOfMapCells[i*(bounds.hi.y+1)];
}
+ m_pathUsage = MSGNEW("PathfindMapCells") UnsignedByte[(bounds.hi.x+1)*(bounds.hi.y+1)];
+ memset(m_pathUsage, 0, (bounds.hi.x+1)*(bounds.hi.y+1));
for (i=0; i<LAYER_LAST; i++) {
if (!m_layers[i].isUnused()) {
m_layers[i].allocateCells(&m_extent);
@@ -5179,7 +5198,53 @@ void Pathfinder::snapClosestGoalPosition(Object *obj, Coord3D *pos)
//DEBUG_LOG(("Couldn't find goal.\n"));
}
-/**
+//-------------------------------------------------------------------------------------------------
+// Congestion map. Each registered path stamps the cell under every raw node (one per A* cell).
+Int Pathfinder::getPathUsage( Int x, Int y ) const
+{
+ if (!m_pathUsage || x < m_extent.lo.x || x > m_extent.hi.x || y < m_extent.lo.y || y > m_extent.hi.y)
+ return 0;
+ return m_pathUsage[x*(m_extent.hi.y+1)+y];
+}
+
+void Pathfinder::adjustPathUsage( const PathNode *from, const PathNode *to, Int delta )
+{
+ if (!m_pathUsage) return; // map torn down; counts went with it
+ for (const PathNode *node = from; node && node != to; node = node->getNext()) {
+ ICoord2D cell;
+ if (worldToCell(node->getPosition(), &cell)) continue; // off map
+ UnsignedByte &u = m_pathUsage[cell.x*(m_extent.hi.y+1)+cell.y];
+ if (delta > 0) { if (u < 255) u++; }
+ else { if (u > 0) u--; }
+ }
+}
+
+void Pathfinder::registerPathUsage( const Path *path )
+{
+ if (!path || path->isUsageRegistered() || !m_pathUsage || !path->getFirstNode()) return;
+ adjustPathUsage(path->getFirstNode(), NULL, +1);
+ path->setUsageHead(path->getFirstNode());
+}
+
+void Pathfinder::unregisterPathUsage( const Path *path )
+{
+ if (!path || !path->isUsageRegistered()) return;
+ adjustPathUsage(path->getUsageHead(), NULL, -1);
+ path->setUsageHead(NULL);
+}
+
+void Pathfinder::releasePathUsageBefore( const Path *path, const PathNode *node )
+{
+ if (!path || !path->isUsageRegistered() || !node) return;
+ // node must lie at or after the head; if the unit got shoved back behind it, nothing new to release.
+ const PathNode *n = path->getUsageHead();
+ while (n && n != node) n = n->getNext();
+ if (!n) return;
+ adjustPathUsage(path->getUsageHead(), node, -1);
+ path->setUsageHead(node);
+}
+
+/**
* Returns coordinates of goal.
*
*/
@@ -6125,6 +6190,9 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
Bool canPathThroughUnits = false;
if (obj && obj->getAIUpdateInterface()) {
canPathThroughUnits = obj->getAIUpdateInterface()->canPathThroughUnits();
+ // Our own current path must not repel us while we repath (the caller only destroys it
+ // once the new one is built). O(1) after the first neighbour expansion of a search.
+ unregisterPathUsage(obj->getAIUpdateInterface()->getPath());
}
Bool isCrusher = obj ? obj->getCrusherLevel() > 0 : false;
if (attackDistance==NO_ATTACK && !m_isTunneling && !locomotorSet.isDownhillOnly() && goalCell) {
@@ -6284,6 +6352,15 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
if (info.allyMoving && dx<10 && dy<10) {
newCostSoFar += 3*COST_DIAGONAL;
}
+ if (m_pathUsage) {
+ // Other units' live paths through our footprint: pay per path so we pick a parallel lane.
+ Int usage = 0;
+ Int above = radius + (centerInCell ? 1 : 0);
+ for (Int ux = newCellCoord.x-radius; ux < newCellCoord.x+above; ux++)
+ for (Int uy = newCellCoord.y-radius; uy < newCellCoord.y+above; uy++)
+ usage += getPathUsage(ux, uy);
+ newCostSoFar += usage * PATH_CONGESTION_COST;
+ }
if (newCell->getType() == PathfindCell::CELL_CLIFF && !newCell->getPinched() ) {
Coord3D fromPos;
fromPos.x = parentCell->getXIndex() * PATHFIND_CELL_SIZE_F ;
@@ -8991,6 +9068,8 @@ Path *Pathfinder::buildActualPath( const Object *obj, LocomotorSurfaceTypeMask a
// cleanup the path by checking line of sight
path->optimize(obj, acceptableSurfaces, blocked);
+ registerPathUsage(path);
+
#if defined _DEBUG || defined _INTERNAL
if (TheGlobalData->m_debugAI==AI_DEBUG_PATHS)
{
@@ -10515,6 +10594,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet
// cleanup the path by checking line of sight
path->optimize(obj, locomotorSet.getValidSurfaces(), blocked);
+ registerPathUsage(path);
parentCell->releaseInfo();
cleanOpenAndClosedLists();
candidateGoal->releaseInfo();