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.

perf(gamelogic): cheaper ai regrouping, enemy-masked searches and sight

Olcay Seygan7ebfcf174594
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
index 19d216118..7d17789d6 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h
@@ -855,11 +855,16 @@ public:
protected:
Pathfinder *m_pathfinder; ///< the pathfinding system
std::list<AIGroup *> m_groupList; ///< the list of AIGroups
+ /// where each live group sits in m_groupList, so destroyGroup need not walk it. Looked up by
+ /// address and never iterated: m_groupList alone keeps the order the CRC walks
+ std::unordered_map<AIGroup *, std::list<AIGroup *>::iterator> m_groupIndex;
TAiData *m_aiData;
void newOverride(void);
void addSideInfo(AISideInfo *info);
-
+ void sweepEmptyGroups( void ); ///< destroy the groups made since the last sweep that nobody joined
+
UnsignedInt m_nextGroupID;
+ UnsignedInt m_sweptGroupID; ///< every group up to this ID has been through sweepEmptyGroups
FormationID m_nextFormationID;
UnsignedInt m_lastBuildingPlacementFrame; ///< cleared by reset: a static here outlived the match and deferred the next match's first placement on one machine only
};
@@ -1539,6 +1544,7 @@ public:
void queueUpgrade( const UpgradeTemplate *upgrade ); ///< queue an upgrade
void add( Object *obj ); ///< add object to group
+ void addTeam( Team *team ); ///< add() every team member, in team order (Team::getTeamAsAIGroup)
// returns true if remove destroyed the group for us.
Bool remove( Object *obj);
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
index f975600af..328977335 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
@@ -330,20 +330,23 @@ struct ShroudStatusStoreRestore
class PartitionCell : public Snapshot // not MPO: allocated in an array
{
private:
+ // A cell is near 300 bytes and the walks over cells - range queries, collision passes, sight
+ // tests, moving an Object's coverage - read only these first few fields of each, so they sit
+ // together at the front where one cache line holds them; the per-player arrays follow.
CellAndObjectIntersection* m_firstCoiInCell; ///< list of COIs in this cell (may be null).
- ShroudLevel m_shroudLevel[MAX_PLAYER_COUNT];
- Short m_airLookers[MAX_PLAYER_COUNT]; ///< lookers whose circle takes in the air over this cell, hills and roofs or not
+ Short m_coiCount; ///< number of COIs in this cell.
+ PlayerMaskType m_playerCoiMask; ///< players whose m_playerCoiCount is nonzero
+ Short m_cellX; ///< x-coord of this cell within the Partition Mgr coords (NOT in world coords)
+ Short m_cellY; ///< y-coord of this cell within the Partition Mgr coords (NOT in world coords)
#ifdef PM_CACHE_TERRAIN_HEIGHT
Real m_loTerrainZ; ///< lowest terrain-pt in this cell
Real m_hiTerrainZ; ///< highest terrain-pt in this cell
#endif
+ UnsignedShort m_playerCoiCount[MAX_PLAYER_COUNT]; ///< COIs in this cell whose Object belongs to each player
+ ShroudLevel m_shroudLevel[MAX_PLAYER_COUNT];
+ Short m_airLookers[MAX_PLAYER_COUNT]; ///< lookers whose circle takes in the air over this cell, hills and roofs or not
Int m_threatValue[MAX_PLAYER_COUNT];
Int m_cashValue[MAX_PLAYER_COUNT];
- Short m_coiCount; ///< number of COIs in this cell.
- UnsignedShort m_playerCoiCount[MAX_PLAYER_COUNT]; ///< COIs in this cell whose Object belongs to each player
- PlayerMaskType m_playerCoiMask; ///< players whose m_playerCoiCount is nonzero
- Short m_cellX; ///< x-coord of this cell within the Partition Mgr coords (NOT in world coords)
- Short m_cellY; ///< y-coord of this cell within the Partition Mgr coords (NOT in world coords)
public:
@@ -397,6 +400,7 @@ public:
void getCellCenterPos(Real& x, Real& y);
inline CellAndObjectIntersection *getFirstCoiInCell() { return m_firstCoiInCell; }
+ inline const void *getHotFieldsAddress() const { return &m_firstCoiInCell; } ///< for a prefetch hint only
#ifdef _DEBUG
void validateCoiList();
@@ -429,6 +433,8 @@ private:
};
Object *m_object; ///< Object this module is for
+ Int m_doneFlag; ///< beside m_object: a range query reads both of every COI it walks
+ Int m_coiInUseCount; ///< number of COIs that are actually in use; the whole-map walk reads it with m_object and m_next
GhostObject *m_ghostObject; ///< Temporary object used when real object is gone but player thinks it's there because of fog.
PartitionData *m_next; ///< next module in master list
PartitionData *m_prev; ///< prev module in master list
@@ -436,9 +442,7 @@ private:
PartitionData *m_prevDirty;
Int m_coiArrayCount; ///< number of COIs allocated (may be more than are in use)
- Int m_coiInUseCount; ///< number of COIs that are actually in use
- CellAndObjectIntersection *m_coiArray; ///< The array of COIs
- Int m_doneFlag;
+ CellAndObjectIntersection *m_coiArray; ///< The array of COIs
Int m_countedPlayer; ///< player index this module's COIs are counted under in their cells, -1 for none
DirtyStatus m_dirtyStatus;
ObjectShroudStatus m_shroudedness[MAX_PLAYER_COUNT];
@@ -1447,17 +1451,19 @@ public:
// given a distance in world coords, return the number of cells needed to cover that distance (rounding up)
Int worldToCellDist(Real w);
+ /** onlyPlayers, here and on the overloads below that take it, skips every cell no Object of those
+ players touches. Pass it only when the filters already reject every Object outside them (an
+ ALLOW_ENEMIES relationship filter with the asker's Team::getEnemyPlayerMask), so the answer is
+ the one a full search gives. */
Object *getClosestObject(
- const Object *obj,
- Real maxDist,
- DistanceCalculationType dc,
- PartitionFilter **filters = NULL,
+ const Object *obj,
+ Real maxDist,
+ DistanceCalculationType dc,
+ PartitionFilter **filters = NULL,
Real *closestDist = NULL,
- Coord3D *closestDistVec = NULL
+ Coord3D *closestDistVec = NULL,
+ PlayerMaskType onlyPlayers = PLAYERMASK_ALL
);
- /** onlyPlayers skips every cell no Object of those players touches. Pass it only when the filters
- already reject every Object outside them (an ALLOW_ENEMIES relationship filter with the asker's
- Team::getEnemyPlayerMask), so the answer is the one a full search gives. */
Object *getClosestObject(
const Coord3D *pos,
Real maxDist,
@@ -1494,11 +1500,12 @@ public:
#endif
SimpleObjectIterator *iterateObjectsInRange(
- const Object *obj,
- Real maxDist,
- DistanceCalculationType dc,
- PartitionFilter **filters = NULL,
- IterOrderType order = ITER_FASTEST
+ const Object *obj,
+ Real maxDist,
+ DistanceCalculationType dc,
+ PartitionFilter **filters = NULL,
+ IterOrderType order = ITER_FASTEST,
+ PlayerMaskType onlyPlayers = PLAYERMASK_ALL ///< as for getClosestObject
);
SimpleObjectIterator *iterateObjectsInRange(
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp
index 564a5eaff..dd6fa482f 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp
@@ -1455,11 +1455,7 @@ void Team::getTeamAsAIGroup(AIGroup *pAIGroup)
// Should this clear out the pAIGroup that it receives? I don't think so, but that
// would go here if so. jkmcd
- for (DLINK_ITERATOR<Object> iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) {
- if (iter.cur()) {
- pAIGroup->add(iter.cur());
- }
- }
+ pAIGroup->addTeam(this);
}
@@ -1526,6 +1522,10 @@ PlayerMaskType Team::getEnemyPlayerMask() const
for (Int i = 0; i < ThePlayerList->getPlayerCount(); ++i)
{
Player *player = ThePlayerList->getNthPlayer(i);
+ // a default team a script handed to another player (doTransferTeamToPlayer) answers for that
+ // player instead, and no longer for its own player's other teams
+ if (player->getDefaultTeam()->getControllingPlayer() != player)
+ return PLAYERMASK_ALL;
if (getRelationship(player->getDefaultTeam()) == ENEMIES)
mask |= player->getPlayerMask();
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
index e2992b7a3..58080de8c 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
@@ -359,13 +359,21 @@ AI::AI( void )
void AI::init( void )
{
m_nextGroupID = 0;
+ m_sweptGroupID = 0;
}
+#ifdef DEBUG_LOGGING
+static Int theSweptGroups = 0; ///< temporary: groups sweepEmptyGroups destroyed this match
+#endif
+
/**
* Reset the AI system in preparation for a new map
*/
void AI::reset( void )
{
+#ifdef DEBUG_LOGGING
+ theSweptGroups = 0;
+#endif
m_pathfinder->reset();
while (m_aiData && m_aiData->m_next) {
TAiData *cur = m_aiData;
@@ -385,6 +393,7 @@ void AI::reset( void )
}
}
m_nextGroupID = 0;
+ m_sweptGroupID = 0;
m_nextFormationID = NO_FORMATION_ID;
getNextFormationID(); // increment once past NO_FORMATION_ID. jba.
m_lastBuildingPlacementFrame = 0;
@@ -440,6 +449,8 @@ void AI::update( void )
end = Clock_Ticks();
s_lastPathfindMS = aiElapsedMS( start, afterPathfind );
s_lastPlayerUpdateMS = aiElapsedMS( afterPathfind, end );
+
+ sweepEmptyGroups();
}
/**
@@ -585,6 +596,7 @@ AIGroup *AI::createGroup( void )
// add it to the list
// DEBUG_LOG(("***AIGROUP %x is being added to m_groupList.\n", group ));
m_groupList.push_back( group );
+ m_groupIndex[ group ] = --m_groupList.end();
return group;
}
@@ -594,22 +606,69 @@ AIGroup *AI::createGroup( void )
*/
void AI::destroyGroup( AIGroup *group )
{
- std::list<AIGroup *>::iterator i = std::find( m_groupList.begin(), m_groupList.end(), group );
+ std::unordered_map<AIGroup *, std::list<AIGroup *>::iterator>::iterator i = m_groupIndex.find( group );
- // make sure group is actually in the list
- if (i == m_groupList.end())
+ // make sure group is actually in the list: a caller can hold one that emptied and destroyed itself,
+ // and the group's own destructor comes back here through remove()
+ if (i == m_groupIndex.end())
return;
DEBUG_ASSERTCRASH(group != NULL, ("A NULL group made its way into the AIGroup list.. jkmcd"));
// remove it
// DEBUG_LOG(("***AIGROUP %x is being removed from m_groupList.\n", group ));
- m_groupList.erase( i );
+ m_groupList.erase( i->second );
+ m_groupIndex.erase( i );
// destroy group
group->deleteInstance();
}
+/**
+ * Destroy every group made since the last sweep that is still empty.
+ *
+ * remove() destroys a group when its last member leaves, so a group that never had a member was
+ * never destroyed at all: a sequential script or a script action asking a team with nobody left in
+ * it whether it is idle (ScriptEngine::evaluateAndProgressAllSequentialScripts, the ScriptActions
+ * team actions) left one behind every time, and each stayed in m_groupList, walked by the CRC every
+ * frame, for the rest of the match. Nothing keeps a group past the call that made it, so by the end
+ * of the AI update an empty one is garbage. Groups leave the list only by being destroyed and are
+ * appended with rising IDs, so the ones made since the last sweep are its tail, and one that had a
+ * member once is destroyed by remove() the moment it empties.
+ */
+void AI::sweepEmptyGroups( void )
+{
+ std::list<AIGroup *>::iterator it = m_groupList.end();
+ while (it != m_groupList.begin())
+ {
+ std::list<AIGroup *>::iterator prev = it;
+ --prev;
+ if ((*prev)->getID() <= m_sweptGroupID)
+ break;
+ it = prev;
+ }
+ while (it != m_groupList.end())
+ {
+ AIGroup *group = *it;
+ ++it;
+ if (group->isEmpty())
+ {
+ destroyGroup( group );
+#ifdef DEBUG_LOGGING
+ ++theSweptGroups;
+#endif
+ }
+ }
+ m_sweptGroupID = m_nextGroupID;
+
+#ifdef DEBUG_LOGGING
+ // temporary: what the list holds once a minute, and how many groups it used to keep by now
+ if (TheGameLogic->getFrame() % (60 * LOGICFRAMES_PER_SECOND) == 0)
+ DEBUG_LOG(("AI GROUPS frame %d: %d listed, %d empty swept this match\n", TheGameLogic->getFrame(),
+ (Int)m_groupList.size(), theSweptGroups));
+#endif
+}
+
/**
* Given an ID, return the associated AIGroup
*/
@@ -885,7 +944,12 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
filters[numFilters] = NULL;
- if (info == NULL || info == TheScriptEngine->getDefaultAttackInfo())
+ // filterObvious goes first in both lists and lets only ENEMIES through, so a cell holding no
+ // enemy player's Object cannot hold an answer and the searches below pass over it: the same
+ // objects reach the filters in the same order, and no filter after the first ever sees the rest
+ const PlayerMaskType enemyPlayers = me->getTeam()->getEnemyPlayerMask();
+
+ if (info == NULL || info == TheScriptEngine->getDefaultAttackInfo())
{
if (qualifiers & PREFER_HIGH_THREAT)
{
@@ -896,7 +960,7 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
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);
+ 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())
{
@@ -936,14 +1000,14 @@ Object *AI::findClosestEnemy( const Object *me, Real range, UnsignedInt qualifie
}
// No additional attack info, so just return the closest one.
- Object* o = ThePartitionManager->getClosestObject( me, range, FROM_BOUNDINGSPHERE_2D, filters );
+ Object* o = ThePartitionManager->getClosestObject( me, range, FROM_BOUNDINGSPHERE_2D, filters, NULL, NULL, enemyPlayers );
return o;
}
Object *bestEnemy = NULL;
Int effectivePriority=0;
Int actualPriority=0;
- ObjectIterator *iter = ThePartitionManager->iterateObjectsInRange(me, range, FROM_BOUNDINGSPHERE_2D, gatherFilters, ITER_SORTED_NEAR_TO_FAR);
+ ObjectIterator *iter = ThePartitionManager->iterateObjectsInRange(me, range, FROM_BOUNDINGSPHERE_2D, gatherFilters, ITER_SORTED_NEAR_TO_FAR, enemyPlayers);
MemoryPoolObjectHolder holder(iter);
for (Object *theEnemy = iter->first(); theEnemy; theEnemy = iter->next())
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
index fa55217f7..439e589d8 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
@@ -172,19 +172,15 @@ Bool AIGroup::isMember( Object *obj )
}
/**
- * Add object to group.
+ * Whether add() takes the object.
* Only allow AI agents into the group.
*/
-void AIGroup::add( Object *obj )
+static Bool canJoinGroup( Object *obj )
{
-// DEBUG_LOG(("***AIGROUP %x is adding Object %x (%s).\n", this, obj, obj->getTemplate()->getName().str()));
- DEBUG_ASSERTCRASH(obj != NULL, ("trying to add null obj to AIGroup"));
- if (obj == NULL)
- return;
-
- AIUpdateInterface *ai = obj->getAIUpdateInterface();
+ if (obj->getAIUpdateInterface() != NULL)
+ return TRUE;
- //If this object doesn't have an AIUpdateInterface, then
+ //If this object doesn't have an AIUpdateInterface, then
//don't add it to the group UNLESS it is a structure! Structures
//with AIUpdateInterfaces also issue similar commands, but those
//commands don't need AI updates... they are instant commands like
@@ -192,10 +188,21 @@ void AIGroup::add( Object *obj )
KindOfMaskType validNonAIKindofs;
validNonAIKindofs.set(KINDOF_STRUCTURE);
validNonAIKindofs.set(KINDOF_ALWAYS_SELECTABLE);
- if( ai == NULL && !obj->isAnyKindOf( validNonAIKindofs ) )
- {
+ return obj->isAnyKindOf( validNonAIKindofs );
+}
+
+/**
+ * Add object to group.
+ */
+void AIGroup::add( Object *obj )
+{
+// DEBUG_LOG(("***AIGROUP %x is adding Object %x (%s).\n", this, obj, obj->getTemplate()->getName().str()));
+ DEBUG_ASSERTCRASH(obj != NULL, ("trying to add null obj to AIGroup"));
+ if (obj == NULL)
+ return;
+
+ if (!canJoinGroup( obj ))
return;
- }
// add to group's list of objects
m_memberList.push_back( obj );
@@ -208,6 +215,62 @@ void AIGroup::add( Object *obj )
m_dirty = true;
}
+/**
+ * Add every member of the team, as calling add() on each in team order does.
+ *
+ * A team moving as a group is rebuilt into a fresh group on every update of every member
+ * (AIFollowWaypointPathState::update), so it nearly always arrives here as exactly the group it was
+ * put in last time: the same objects in the same order and nobody else. Then the list nodes move
+ * across instead of each one being freed from the old group and allocated in this one, and the
+ * members, their order, both groups' counts and dirty bits and the old group's destruction come out
+ * as the add() loop leaves them.
+ */
+void AIGroup::addTeam( Team *team )
+{
+ AIGroup *from = NULL;
+ ListObjectPtrIt fromIt;
+ UnsignedInt count = 0;
+ Bool exact = m_memberList.empty();
+ for (DLINK_ITERATOR<Object> iter = team->iterate_TeamMemberList(); exact && !iter.done(); iter.advance())
+ {
+ Object *obj = iter.cur();
+ if (obj == NULL || !canJoinGroup( obj ))
+ continue;
+ if (from == NULL)
+ {
+ from = obj->getGroup();
+ if (from == NULL || from == this)
+ break;
+ fromIt = from->m_memberList.begin();
+ }
+ exact = obj->getGroup() == from && fromIt != from->m_memberList.end() && *fromIt == obj;
+ if (exact)
+ {
+ ++fromIt;
+ ++count;
+ }
+ }
+
+ if (exact && from != NULL && from != this && fromIt == from->m_memberList.end())
+ {
+ m_memberList.splice( m_memberList.end(), from->m_memberList );
+ m_memberListSize += count;
+ // each leaves 'from', whose list is already empty, so its remove() finds nothing to do
+ for (ListObjectPtrIt it = m_memberList.begin(); it != m_memberList.end(); ++it)
+ (*it)->enterGroup( this );
+ m_dirty = true;
+ // the add() loop destroys it on the last member, as remove() does any group it empties
+ TheAI->destroyGroup( from );
+ return;
+ }
+
+ for (DLINK_ITERATOR<Object> iter = team->iterate_TeamMemberList(); !iter.done(); iter.advance())
+ {
+ if (iter.cur())
+ add( iter.cur() );
+ }
+}
+
/**
* Remove object from group
*/
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
index 6c4b463c3..cd91fe428 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
@@ -86,6 +86,20 @@
#include <float.h>
+/* A hint that a cache line is about to be read. It reads nothing the program sees and decides
+ nothing, so no result can depend on it; on a compiler without one it is no code at all. */
+#if defined(__GNUC__) || defined(__clang__)
+ #define PM_PREFETCH(addr) __builtin_prefetch(addr)
+#elif defined(_M_X64) || defined(_M_IX86)
+ #include <xmmintrin.h>
+ #define PM_PREFETCH(addr) _mm_prefetch((const char *)(addr), _MM_HINT_T0)
+#elif defined(_M_ARM64)
+ #include <intrin.h>
+ #define PM_PREFETCH(addr) __prefetch(addr)
+#else
+ #define PM_PREFETCH(addr) ((void)0)
+#endif
+
#ifdef _DEBUG
//#include "GameClient/InGameUI.h" // for debugHints
#include "Common/PlayerList.h"
@@ -1745,10 +1759,13 @@ ObjectShroudStatus PartitionData::getShroudedStatus(Int playerIndex)
}
// answered before the cache, so no snapshot is taken and the site is not marked as seen: the
- // building that goes up there later is news to this player like any other
- if (m_object && Object_isPlanHiddenFrom(m_object->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION),
- m_object->getConstructionPercent(),
- ThePlayerList->getNthPlayer(playerIndex)->getRelationship(m_object->getTeam())))
+ // building that goes up there later is news to this player like any other. Only a plan nobody
+ // has started can be hidden, so the relationship lookup waits until the Object is one.
+ if (m_object && Object_isAwaitingBuilder(m_object->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION),
+ m_object->getConstructionPercent()) &&
+ Object_isPlanHiddenFrom(m_object->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION),
+ m_object->getConstructionPercent(),
+ ThePlayerList->getNthPlayer(playerIndex)->getRelationship(m_object->getTeam())))
return OBJECTSHROUD_SHROUDED;
#ifndef DISABLE_INVALID_PREVENTION
@@ -3522,6 +3539,11 @@ Object *PartitionManager::getClosestObjects(
m_radiusVec[curRadius] contains a list of the cells (foo) that could
contain objects that are <= (curRadius * cellSize) distance away from cell (0,0).
*/
+ /* The cells of a ring lie scattered through a grid of cells some 300 bytes apiece, so nearly every
+ one is a cache miss, and the empty-or-not test on each keeps the processor from running ahead to
+ the next. So each step asks for the cell a few places further on, and its line is in by the time
+ the walk gets there. The walk itself, its order and what it finds are unchanged. */
+ const Int GCO_PREFETCH_AHEAD = 8;
for (Int curRadius = 0; curRadius <= maxRadiusLimit; ++curRadius)
{
const OffsetVec& offsets = m_radiusVec[curRadius];
@@ -3529,6 +3551,14 @@ Object *PartitionManager::getClosestObjects(
continue;
for (OffsetVec::const_iterator it = offsets.begin(); it != offsets.end(); ++it)
{
+ if (offsets.end() - it > GCO_PREFETCH_AHEAD)
+ {
+ const ICoord2D& ahead = *(it + GCO_PREFETCH_AHEAD);
+ const PartitionCell *aheadCell = getCellAt(cellCenterX + ahead.x, cellCenterY + ahead.y);
+ if (aheadCell)
+ PM_PREFETCH(aheadCell->getHotFieldsAddress());
+ }
+
PartitionCell* thisCell = getCellAt(cellCenterX + it->x, cellCenterY + it->y);
if (thisCell == NULL)
continue;
@@ -3696,10 +3726,11 @@ Object *PartitionManager::getClosestObject(
DistanceCalculationType dc,
PartitionFilter **filters,
Real *closestDist,
- Coord3D *closestDistVec
+ Coord3D *closestDistVec,
+ PlayerMaskType onlyPlayers
)
{
- return getClosestObjects(obj, NULL, maxDist, dc, filters, NULL, closestDist, closestDistVec);
+ return getClosestObjects(obj, NULL, maxDist, dc, filters, NULL, closestDist, closestDistVec, onlyPlayers);
}
//-----------------------------------------------------------------------------
@@ -3839,18 +3870,19 @@ Real PartitionManager::getRelativeAngle2D( const Object *obj, const Coord3D *pos
//-----------------------------------------------------------------------------
SimpleObjectIterator *PartitionManager::iterateObjectsInRange(
- const Object *obj,
- Real maxDist,
- DistanceCalculationType dc,
- PartitionFilter **filters,
- IterOrderType order
+ const Object *obj,
+ Real maxDist,
+ DistanceCalculationType dc,
+ PartitionFilter **filters,
+ IterOrderType order,
+ PlayerMaskType onlyPlayers
)
{
MemoryPoolObjectHolder iterHolder;
SimpleObjectIterator *iter = newInstance(SimpleObjectIterator);
iterHolder.hold(iter);
- getClosestObjects(obj, NULL, maxDist, dc, filters, iter, NULL, NULL);
+ getClosestObjects(obj, NULL, maxDist, dc, filters, iter, NULL, NULL, onlyPlayers);
iter->sort(order);
iterHolder.release();
@@ -4487,6 +4519,13 @@ static Real sightGroundHeight( PartitionCell *cell )
if( bridge->peekBridgeInfo()->curDamageState == BODY_RUBBLE )
continue;
+ // isPointOnBridge turns away any point outside the deck's bounds before anything else, and the
+ // nine samples lie between these four edges, so a grid the bounds miss can skip all nine
+ const Region2D *bounds = bridge->getBounds();
+ if( centerX + halfCell < bounds->lo.x || centerX - halfCell > bounds->hi.x ||
+ centerY + halfCell < bounds->lo.y || centerY - halfCell > bounds->hi.y )
+ continue;
+
for( Int sampleY = -1; sampleY <= 1; ++sampleY )
{
for( Int sampleX = -1; sampleX <= 1; ++sampleX )
@@ -4515,10 +4554,12 @@ static Real sightBlockingHeight( PartitionCell *cell, const Object *looker, cons
if( obj == NULL || obj == looker || obj == lookerContainer )
continue;
- if( !obj->isKindOf( KINDOF_STRUCTURE ) && !obj->isKindOf( KINDOF_SHRUBBERY ) )
+ // one template lookup for the three questions; Object::isKindOf is this same lookup each time
+ const ThingTemplate *tmpl = obj->getTemplate();
+ if( !tmpl->isKindOf( KINDOF_STRUCTURE ) && !tmpl->isKindOf( KINDOF_SHRUBBERY ) )
continue;
- if( obj->isKindOf( KINDOF_BRIDGE ) )
+ if( tmpl->isKindOf( KINDOF_BRIDGE ) )
continue;
if( Object_isAwaitingBuilder( obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ), obj->getConstructionPercent() ) )
@@ -4529,6 +4570,22 @@ static Real sightBlockingHeight( PartitionCell *cell, const Object *looker, cons
return height;
}
+//-----------------------------------------------------------------------------
+struct RowReach
+{
+ Int m_centerX;
+ Int m_cornerY; ///< cell row of m_reach[0]
+ Int *m_reach; ///< per row, how many cells either side of the middle the circle takes in
+};
+
+//-----------------------------------------------------------------------------
+static void hLineRowReach( Int /*x1*/, Int x2, Int y, void *rowsVoid )
+{
+ RowReach *rows = (RowReach *)rowsVoid;
+ Int &reach = rows->m_reach[ y - rows->m_cornerY ];
+ reach = max( reach, x2 - rows->m_centerX );
+}
+
//-----------------------------------------------------------------------------
void PartitionManager::doBlockedShroudReveal( SightingInfo *sighting, const Object *looker, Real flatRange )
{
@@ -4543,14 +4600,32 @@ void PartitionManager::doBlockedShroudReveal( SightingInfo *sighting, const Obje
heights.resize( side * side );
sightMargin.resize( side * side );
+ /* Only the cells of the reveal's circle are ever applied: applyRecordedReveal draws this same circle
+ over the recording, now and again at the undo. Each of them takes its sight line only from cells
+ nearer the middle that the circle holds too (its rows narrow outwards, and the inner neighbour
+ findSightMargins reads is no further out on either axis), so the corners of the square outside it,
+ a fifth of the square, need no height, and each would have been a walk over every Object standing
+ there. They are recorded as revealing nothing. */
+ static std::vector<Int> rowReach;
+ rowReach.assign( side, -1 );
+ RowReach rows = { cellCenterX, cellCenterY - cellRadius, &rowReach[0] };
+ DiscreteCircle circle( cellCenterX, cellCenterY, cellRadius );
+ circle.drawCircle( hLineRowReach, &rows );
+
for( Int offsetY = -cellRadius; offsetY <= cellRadius; ++offsetY )
{
+ const Int reach = rowReach[ offsetY + cellRadius ];
const Int cellY = min( max( cellCenterY + offsetY, 0 ), m_cellCountY - 1 );
for( Int offsetX = -cellRadius; offsetX <= cellRadius; ++offsetX )
{
+ Real &height = heights[ ( offsetY + cellRadius ) * side + offsetX + cellRadius ];
+ if( abs( offsetX ) > reach )
+ {
+ height = 0.0f;
+ continue;
+ }
const Int cellX = min( max( cellCenterX + offsetX, 0 ), m_cellCountX - 1 );
- heights[ ( offsetY + cellRadius ) * side + offsetX + cellRadius ] =
- sightBlockingHeight( getCellAt( cellX, cellY ), looker, lookerContainer );
+ height = sightBlockingHeight( getCellAt( cellX, cellY ), looker, lookerContainer );
}
}
@@ -4565,6 +4640,11 @@ void PartitionManager::doBlockedShroudReveal( SightingInfo *sighting, const Obje
{
const Int offsetX = cell % side - cellRadius;
const Int offsetY = cell / side - cellRadius;
+ if( abs( offsetX ) > rowReach[ offsetY + cellRadius ] )
+ {
+ sighting->m_revealedCells[ cell ] = 0;
+ continue;
+ }
Bool revealed = sightMargin[ cell ] >= 0.0f;
if( revealed && stretched )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index c2f9ddea8..c0a91b582 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -3171,81 +3171,41 @@ Int GameLogic::rebalanceChildSleepyUpdate(Int i)
DEBUG_ASSERTCRASH(i >= 0 && i < m_sleepyUpdates.size(), ("bad sleepy idx"));
-// this function gets the brunt of the work (we frequently
-// balance down, not up), so this one is hand-unrolled for
-// max efficiency. I have left the pristine non-unrolled
-// version present for clarity. (Yes, this is worth doing.) (srj)
-#if 1
- SleepyEntry* pI = &m_sleepyUpdates[i];
-
- // our children are i*2 and i*2+1
- Int child = ((i+1)<<1)-1;
- // data() + n, not &m_sleepyUpdates[n]: both are only addresses until the loop below has checked
- // them against pSZ, and the same addresses in a release build, but a Debug build's checked
- // operator[] aborts on any n past the end, which child and size() often are (W3).
- SleepyEntry* pChild = m_sleepyUpdates.data() + child;
- SleepyEntry* pSZ = m_sleepyUpdates.data() + m_sleepyUpdates.size(); // yes, this is off the end.
-
- while (pChild < pSZ)
+ /* Every sleepy module that runs sinks from the top of this heap again, so this is the busiest loop
+ of the scheduler. The sinking entry moves down through a hole: each child that has to rise moves
+ up one slot and takes its new index, and the sinking entry is written once, where it stops.
+ Swapping at every level wrote both entries and both modules' indices each time, and every module
+ is a cache line of its own. The comparisons are the ones the swapping walk made, so every entry
+ ends in the same slot, ties included, and the modules run in the same order. Which child sorts
+ first is a coin toss a branch keeps guessing wrong, so the pick is a sum instead. */
+ SleepyEntry *entries = m_sleepyUpdates.data();
+ const Int sz = (Int)m_sleepyUpdates.size();
+ const SleepyEntry sinking = entries[i];
+ const Int start = i;
+
+ // our children are i*2+1 and i*2+2
+ Int child = ((i+1)<<1)-1;
+ while (child < sz)
{
// choose the higher-priority of the two children; we must be higher-pri than that.
- if (pChild < pSZ-1 && isLowerPriority(*pChild, *(pChild+1)))
- {
- ++pChild;
- ++child;
- }
+ if (child < sz-1)
+ child += (Int)isLowerPriority(entries[child], entries[child+1]);
// if we're higher-pri than our children, we're done.
- if (!isLowerPriority(*pI, *pChild))
- {
+ if (!isLowerPriority(sinking, entries[child]))
break;
- }
-
- // doh. swap with the highest-pri child we have.
- SleepyEntry a = *pChild;
- SleepyEntry b = *pI;
-
- *pI = a;
- *pChild = b;
-
- a.module->friend_setIndexInLogic(i);
- b.module->friend_setIndexInLogic(child);
+ entries[i] = entries[child];
+ entries[i].module->friend_setIndexInLogic(i);
i = child;
- pI = pChild;
-
child = ((i+1)<<1)-1;
- pChild = m_sleepyUpdates.data() + child;
- }
-#else
- // our children are i*2 and i*2+1
- Int sz = m_sleepyUpdates.size();
- Int child = ((i+1)<<1)-1;
- while (child < sz)
- {
- // choose the higher-priority of the two children; we must be higher-pri than that.
- if (child < sz-1 && isLowerPriority(m_sleepyUpdates[child], m_sleepyUpdates[child+1]))
- ++child;
-
- // if we're higher-pri than our children, we're done.
- if (!isLowerPriority(m_sleepyUpdates[i], m_sleepyUpdates[child]))
- {
- break;
- }
-
- // doh. swap with the highest-pri child we have.
- SleepyEntry a = m_sleepyUpdates[child];
- SleepyEntry b = m_sleepyUpdates[i];
-
- m_sleepyUpdates[i] = a;
- m_sleepyUpdates[child] = b;
+ }
- a.module->friend_setIndexInLogic(i);
- b.module->friend_setIndexInLogic(child);
- i = child;
- child = ((i+1)<<1)-1;
- }
-#endif
+ if (i != start)
+ {
+ entries[i] = sinking;
+ sinking.module->friend_setIndexInLogic(i);
+ }
return i;
}