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): cut collision and sight cost of big air battles

Olcay Seygan11a1dc68d775
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 259df864e..022c15042 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -450,6 +450,7 @@ found and fixed, EA's own, not port damage.**
- Only the particles past the limit move to the card; everything under it is drawn exactly as before, with its shadows, its place in the smoke map and its sorting. The old path stays on `-d3d9`, on the Classic graphics setting, in headless runs and on macOS and Linux, and `-gpuparticles 0` turns the new one off.
- Big fights no longer drag the picture down into the twenties. Every moving tank and soldier, and every puff of smoke, goes to the graphics card through one shared scratch area, and it was so small that a big fight on Bombardment Beach filled it about fifty times a frame. Each refill made the processor wait for the card, 8 to 12ms of every frame, while the card sat two thirds idle. The area is made full size once now and refills about seven times a frame, in 0.02ms. The same 16,000-frame battle, fast-forwarded, finishes in 226 seconds where it took between 263 and 325, and the seconds that fell under 50 frames a second went from 125 or more to 4.
- Crowded battles run a good deal faster. At 1080p, thirty Inferno Cannons against twenty Crusaders went from 153 to 227 frames a second, and six Brutal computer players on one map from 146 to 240. The slowest one frame in twenty got 22 to 34% shorter, and the slowest one in a hundred 16 to 29%. The game stopped re-sending lights, materials, textures and card settings that had not changed, stopped relighting the terrain when no light had moved, stopped adding up the glow of every fire particle twice, and widened low-colour textures with a lookup instead of arithmetic on each pixel. The new renderer keeps the old one's settings back until something actually reads them, re-sends only the half of each draw's settings that changed, and remembers each patch of ground's colours, its blend coordinates and its tread marks between frames. Units whose shadow cannot reach the screen are no longer drawn into the shadow map, except on maps with reflecting water. The command bar and the console replay what they drew last frame when nothing under them moved, and the HUD checks for changes without rebuilding its text. The rules side runs 4% quicker too: locking, the lists of nearby units, the sleeping-unit schedule and text strings all got cheaper. The picture matches the old build in all eight test views on both renderers, and a recorded match plays back to the same checksum.
+- Huge air raids on custom maps no longer drag the battle. On AOD Super V, 400 Raptors and 250 A-10s diving on a base held by 170 Paladins and 50 Avengers put one picture in sixteen past a 60 Hz refresh; now it is one in fifty, and the average step that works out the battle fell from 7.7 to 6.4 ms. Every pair of planes brushing wings in the sky went through the memory manager and a search of an overcrowded list, and every plane's sight checked each aircraft around it for a roof that could block its view. Both are gone, and the battle plays out to the same checksum, replays included.
- A long match costs less late in the game. Four Hard computer players on Twilight Flame, well into the match, went from 111.6 to 136.2 frames a second, and the step that works out the battle from 5.59ms to 4.78ms. The computer left every group it had made and never filled in a list the game went through on every step until the match ended, and that list is cleared now. A unit looking for something to shoot passes over ground that holds nobody it could shoot at, sight is worked out with fewer lookups, and the smoke and fire are gone through once per step instead of once for every picture. Eight views over five maps came out the same as before.
- Every moving unit's skeleton was worked out three times a picture, once for its shadow, once for the scene and once more for the outline drawn when it stands behind a building. It is worked out once now, and late in the same match the animation costs 60% less. With the rules step finding the next unit due for an update a little faster, minutes 24 to 26 went from 119.8 to 123.7 frames a second, and the match still ends on the same checksum.
- Shadows in a big battle cost about a third of what they did. With some 560 tanks, soldiers and buildings throwing a shadow on Twilight Flame, the sun's shadows took 0.90 ms of every picture and now take 0.36, never more than half a millisecond in any second of the fight. Every copy of the same model now goes to the graphics card in one batch, so the shadows that took 916 separate draws take 121, and the card itself spends half as long on them. The shadows land on the same pixels they did.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h
index 86d7cbe3b..0c449ea7a 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h
@@ -833,6 +833,7 @@ private:
// modules
BehaviorModule** m_behaviors; // BehaviorModule, not BehaviorModuleInterface
+ CollideModuleInterface** m_collides; ///< the m_behaviors that are collide modules, in their order, null-terminated
// cache these, for convenience
ContainModuleInterface* m_contain;
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectIter.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectIter.h
index 25d8a9577..562087ce7 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectIter.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectIter.h
@@ -93,26 +93,25 @@ class SimpleObjectIterator : public ObjectIterator
MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(SimpleObjectIterator, "SimpleObjectIteratorPool" )
private:
- class PooledClump;
-
struct Clump
{
Clump *m_nextClump;
Object *m_obj;
- PooledClump *m_pooled; // NULL when the clump is one of m_inlineClumps
Real m_numeric; // typically, dist-squared
};
- // a query that finds more than INLINE_CLUMPS objects takes the rest from the pool
- class PooledClump : public MemoryPoolObject
+ enum { INLINE_CLUMPS = 64, POOLED_CLUMPS = 64 };
+
+ // a query that finds more than INLINE_CLUMPS objects takes the rest from the pool, POOLED_CLUMPS
+ // to a block
+ class PooledClumps : public MemoryPoolObject
{
- MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(PooledClump, "SimpleObjectIteratorClumpPool" )
+ MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(PooledClumps, "SimpleObjectIteratorClumpPool" )
public:
- Clump m_clump;
+ PooledClumps *m_nextBlock;
+ Clump m_clumps[POOLED_CLUMPS];
};
- enum { INLINE_CLUMPS = 64 };
-
typedef Real (*ClumpCompareProc)(Clump *a, Clump *b);
static ClumpCompareProc theClumpCompareProcs[];
@@ -127,6 +126,8 @@ private:
Int m_clumpCount;
Int m_inlineClumpsUsed;
Clump m_inlineClumps[INLINE_CLUMPS];
+ PooledClumps *m_pooledBlocks; // newest first
+ Int m_pooledClumpsUsed; // in m_pooledBlocks, the newest
void reset();
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
index d79f6fa9b..98d8c50e3 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h
@@ -338,6 +338,7 @@ private:
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)
+ UnsignedShort m_sightBlockerCoiCount; ///< COIs here of structures and shrubbery, the things that can hide what is behind them
#ifdef PM_CACHE_TERRAIN_HEIGHT
Real m_loTerrainZ; ///< lowest terrain-pt in this cell
Real m_hiTerrainZ; ///< highest terrain-pt in this cell
@@ -368,6 +369,9 @@ public:
Bool hasCoiOfPlayers( PlayerMaskType players ) const { return (m_playerCoiMask & players) != 0; } ///< does any Object of these players touch this cell?
void addPlayerCoi( Int playerIndex );
void removePlayerCoi( Int playerIndex );
+ Bool hasSightBlockerCoi() const { return m_sightBlockerCoiCount != 0; } ///< false: no structure or shrub touches this cell
+ void addSightBlockerCoi() { ++m_sightBlockerCoiCount; }
+ void removeSightBlockerCoi() { DEBUG_ASSERTCRASH(m_sightBlockerCoiCount > 0, ("sight blocker coi count underflow")); --m_sightBlockerCoiCount; }
Int getCellX() const { return m_cellX; }
Int getCellY() const { return m_cellY; }
@@ -444,6 +448,8 @@ private:
Int m_coiArrayCount; ///< number of COIs allocated (may be more than are in use)
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
+ Bool m_sightBlocker; ///< its COIs count in their cells' m_sightBlockerCoiCount; fixed from attachToObject on
+ Bool m_noCollide; ///< its Object is KINDOF_NO_COLLIDE, for collidesWith
DirtyStatus m_dirtyStatus;
ObjectShroudStatus m_shroudedness[MAX_PLAYER_COUNT];
ObjectShroudStatus m_shroudednessPrevious[MAX_PLAYER_COUNT]; ///<previous frames value of m_shroudedness
@@ -609,6 +615,7 @@ public:
void friend_updateCellsTouched() { updateCellsTouched(); } ///< this is only for use by PartitionManager
Int friend_getCoiInUseCount() { return m_coiInUseCount; } ///< this is only for use by PartitionManager
Int friend_getCountedPlayer() const { return m_countedPlayer; } ///< only for CellAndObjectIntersection
+ Bool friend_isSightBlocker() const { return m_sightBlocker; } ///< only for CellAndObjectIntersection
void refreshCountedPlayer(); ///< move this module's per-player cell counts to its Object's current controlling player
Bool friend_collidesWith(const PartitionData *that, CollideLocAndNormal *cinfo) const { return collidesWith(that, cinfo); } ///< this is only for use by PartitionContactList
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp
index bf3b0f410..81b3cd618 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp
@@ -91,7 +91,6 @@ struct PoolSizeRec
// not const -- we might override from INI
static PoolSizeRec sizes[] =
{
- { "PartitionContactListNode", 2048, 512 },
{ "BattleshipUpdate", 32, 32 },
{ "FlyToDestAndDestroyUpdate", 32, 32 },
{ "MusicTrack", 32, 32 },
@@ -160,7 +159,7 @@ static PoolSizeRec sizes[] =
{ "LocomotorTemplate", 192, 32 },
{ "ObjectPool", 1500, 256 },
{ "SimpleObjectIteratorPool", 32, 32 },
- { "SimpleObjectIteratorClumpPool", 4096, 32 },
+ { "SimpleObjectIteratorClumpPool", 64, 16 },
{ "PartitionDataPool", 2048, 512 },
{ "BuildEntry", 32, 32 },
{ "Weapon", 4096, 32 },
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
index 9b0a2c7f3..f8994de6d 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
@@ -475,6 +475,23 @@ Object::Object( const ThingTemplate *tt, const ObjectStatusMaskType &objectStatu
*curB = NULL;
+ // onCollide asks every module for its collide interface on every collision, and a swarm of
+ // aircraft collides tens of thousands of times a frame (issue 144); the answer never changes
+ Int collideCount = 0;
+ for (BehaviorModule** m = m_behaviors; *m; ++m)
+ {
+ if ((*m)->getCollide())
+ ++collideCount;
+ }
+ m_collides = MSGNEW("ModulePtrs") CollideModuleInterface*[collideCount + 1];
+ CollideModuleInterface** curC = m_collides;
+ for (BehaviorModule** m = m_behaviors; *m; ++m)
+ {
+ if (CollideModuleInterface* collide = (*m)->getCollide())
+ *curC++ = collide;
+ }
+ *curC = NULL;
+
AIUpdateInterface *ai = getAIUpdateInterface();
if (ai) {
ai->setAttitude(getTeam()->getPrototype()->getTemplateInfo()->m_initialTeamAttitude);
@@ -678,8 +695,10 @@ Object::~Object()
*b = NULL; // in case other modules call findModule from their dtor!
}
- delete [] m_behaviors;
+ delete [] m_behaviors;
m_behaviors = NULL;
+ delete [] m_collides;
+ m_collides = NULL;
if( m_experienceTracker )
m_experienceTracker->deleteInstance();
@@ -2594,11 +2613,9 @@ void Object::updateTriggerAreaFlags()
//-------------------------------------------------------------------------------------------------
void Object::onCollide( Object *other, const Coord3D *loc, const Coord3D *normal )
{
- for (BehaviorModule** m = m_behaviors; *m; ++m)
+ for (CollideModuleInterface** c = m_collides; *c; ++c)
{
- CollideModuleInterface* collide = (*m)->getCollide();
- if (!collide)
- continue;
+ CollideModuleInterface* collide = *c;
// check each time thru the loop, in case a collide module sets it
if( getStatusBits().test( OBJECT_STATUS_NO_COLLISIONS ) )
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
index 50645d1fa..732991951 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp
@@ -151,7 +151,8 @@ const Real HUGE_DIST_SQR = (HUGE_DIST*HUGE_DIST);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-static PartitionContactList* TheContactList = NULL;
+static PartitionContactList* TheContactList = NULL; ///< set only while PartitionManager::update runs
+static PartitionContactList* thePairStore = NULL; ///< the list update reuses every frame
//-----------------------------------------------------------------------------
// Local Types
@@ -1012,51 +1013,46 @@ PartitionManager *ThePartitionManager = NULL; ///< the object manager singleton
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-class PartitionContactListNode : public MemoryPoolObject
-{
- MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(PartitionContactListNode, "PartitionContactListNode" )
-
-public:
- PartitionContactListNode* m_nextHash; ///< next node with same hash value
- PartitionContactListNode* m_next; ///< next node
- PartitionData* m_obj; ///< one object that is possibly colliding
- PartitionData* m_other; ///< the other object (or null for collisions with the terrain)
- Int m_hashValue;///< index into hash table
-};
-
-inline PartitionContactListNode::~PartitionContactListNode() { }
-
-//-----------------------------------------------------------------------------
-
+/*
+ The pairs one PartitionManager::update finds, kept from frame to frame so that nothing is
+ allocated per pair. EA's list took a pool block per pair through the pool's lock, and found
+ duplicates in a fixed 5381-socket chained hash; four hundred Raptors over one base make tens of
+ thousands of pairs a frame, so the chains grew long: the search was the costliest function of
+ that fight and the blocks were half of all the pool lock's work (issue 144, AOD Super V with
+ 650 jets). Here the pairs sit in an array in the order they
+ were found and the duplicate check is an open-addressed table that doubles with the pair count.
+ EA's list was walked newest first, so processContactList walks the array from the back: the
+ same pairs, compared by the same pointers, reach onCollide in the same order.
+*/
class PartitionContactList
{
private:
- /*
- socketcount should be prime (and "not too close to a power of 2) for best results.
-
- if this one isn't large enough, try this website:
- http://www.utm.edu/research/primes/lists/small/1000.txt
+ struct Contact
+ {
+ PartitionData* m_obj; ///< one object that is possibly colliding
+ PartitionData* m_other; ///< the other object
+ UnsignedInt m_hash; ///< hashPartitionPair of the two
+ };
- So how is this chosen? Eh, pretty much based on experimentation.
- */
- enum { PartitionContactList_SOCKET_COUNT = 5381 };
+ struct Slot
+ {
+ Int m_contact; ///< index into m_contacts
+ UnsignedInt m_generation; ///< the slot is empty unless this is m_generation
+ };
+ enum { FIRST_SLOT_COUNT = 4096 }; // a power of two; 32KB, about the size of EA's table
- PartitionContactListNode* m_contactHash[PartitionContactList_SOCKET_COUNT];
- PartitionContactListNode* m_contactList;
+ std::vector<Contact> m_contacts;
+ std::vector<Slot> m_slots;
+ UnsignedInt m_generation;
-public:
+ void growSlots();
- PartitionContactList()
- {
- memset(m_contactHash, 0, sizeof(m_contactHash));
- m_contactList = NULL;
- }
+public:
- ~PartitionContactList()
+ PartitionContactList() : m_slots(FIRST_SLOT_COUNT), m_generation(1)
{
- resetContactList();
}
/**
@@ -1231,6 +1227,8 @@ void CellAndObjectIntersection::addCoverage(PartitionCell *cell, PartitionData *
{
cell->friend_addToCellList(this);
cell->addPlayerCoi(module->friend_getCountedPlayer());
+ if (module->friend_isSightBlocker())
+ cell->addSightBlockerCoi();
}
m_cell = cell;
@@ -1248,6 +1246,8 @@ void CellAndObjectIntersection::removeAllCoverage()
m_cell->friend_removeFromCellList(this);
m_cell->removePlayerCoi(m_module->friend_getCountedPlayer());
+ if (m_module->friend_isSightBlocker())
+ m_cell->removeSightBlockerCoi();
m_cell = NULL;
m_module = NULL;
}
@@ -1266,6 +1266,7 @@ PartitionCell::PartitionCell()
m_firstCoiInCell = NULL;
m_coiCount = 0;
m_playerCoiMask = PLAYERMASK_NONE;
+ m_sightBlockerCoiCount = 0;
#ifdef PM_CACHE_TERRAIN_HEIGHT
m_loTerrainZ = HUGE_DIST; // huge positive
m_hiTerrainZ = -HUGE_DIST; // huge negative
@@ -1662,6 +1663,8 @@ PartitionData::PartitionData()
m_coiInUseCount = 0;
m_doneFlag = 0;
m_countedPlayer = -1;
+ m_sightBlocker = FALSE;
+ m_noCollide = FALSE;
m_dirtyStatus = NOT_DIRTY;
m_lastCell = NULL;
for (int i = 0; i < MAX_PLAYER_COUNT; ++i)
@@ -2150,21 +2153,27 @@ Bool PartitionData::collidesWith(const PartitionData *that, CollideLocAndNormal
const Object *thisObj = this->getObject();
const Object *thatObj = that->getObject();
- if( thisObj->isKindOf( KINDOF_NO_COLLIDE ) || thatObj->isKindOf( KINDOF_NO_COLLIDE ) )
+ // the kind, read once in attachToObject, since the template never changes
+ if( this->m_noCollide || that->m_noCollide )
return FALSE; // A collision extent of zero size is still a point and can collide, but we don't always want to.
- CollideInfo thisInfo(thisObj->getPosition(), thisObj->getGeometryInfo(), thisObj->getOrientation());
- CollideInfo thatInfo(thatObj->getPosition(), thatObj->getGeometryInfo(), thatObj->getOrientation());
-
- // invariant for all geometries: first do z collision check.
- Real thisTop = thisInfo.position.z + thisInfo.geom.getMaxHeightAbovePosition();
- Real thisBot = thisInfo.position.z - thisInfo.geom.getMaxHeightBelowPosition();
- Real thatTop = thatInfo.position.z + thatInfo.geom.getMaxHeightAbovePosition();
- Real thatBot = thatInfo.position.z - thatInfo.geom.getMaxHeightBelowPosition();
+ // invariant for all geometries: first do z collision check. Most pairs a crowd makes end here,
+ // so the two CollideInfo copies wait until they are needed.
+ const GeometryInfo& thisGeomInfo = thisObj->getGeometryInfo();
+ const GeometryInfo& thatGeomInfo = thatObj->getGeometryInfo();
+ Real thisZ = thisObj->getPosition()->z;
+ Real thatZ = thatObj->getPosition()->z;
+ Real thisTop = thisZ + thisGeomInfo.getMaxHeightAbovePosition();
+ Real thisBot = thisZ - thisGeomInfo.getMaxHeightBelowPosition();
+ Real thatTop = thatZ + thatGeomInfo.getMaxHeightAbovePosition();
+ Real thatBot = thatZ - thatGeomInfo.getMaxHeightBelowPosition();
if (thisTop >= thatBot && thisBot <= thatTop)
{
- GeometryType thisGeom = thisObj->getGeometryInfo().getGeomType();
- GeometryType thatGeom = thatObj->getGeometryInfo().getGeomType();
+ CollideInfo thisInfo(thisObj->getPosition(), thisGeomInfo, thisObj->getOrientation());
+ CollideInfo thatInfo(thatObj->getPosition(), thatGeomInfo, thatObj->getOrientation());
+
+ GeometryType thisGeom = thisGeomInfo.getGeomType();
+ GeometryType thatGeom = thatGeomInfo.getGeomType();
//
// NOTE: This assumes geometry enumerations that start at GEOMETRY_FIRST AND depends on the
@@ -2454,6 +2463,10 @@ void PartitionData::attachToObject(Object* object)
// remember who contains us
m_object = object;
+ // what sightBlockingHeight looks for; an Object's template, and so its kinds, never changes
+ m_sightBlocker = object->isKindOf(KINDOF_STRUCTURE) || object->isKindOf(KINDOF_SHRUBBERY);
+ m_noCollide = object->isKindOf(KINDOF_NO_COLLIDE);
+
// we only snapshot things that are immobile and have something to draw. Don't need ghostobjects for others.
if (object->isKindOf(KINDOF_IMMOBILE))
{ const ThingTemplate *tmplate=object->getTemplate();
@@ -2556,19 +2569,16 @@ void PartitionData::detachFromGhostObject(void)
}
//-----------------------------------------------------------------------------
-inline UnsignedInt hash2ints(Int a, Int b)
+/** [a,b] hashes to the same value as [b,a]. It hashes the addresses, which differ from machine to
+ machine, and that is safe here: the hash only says where in the table a pair is looked for, and
+ the order the pairs are handled in is the order they were found (PartitionContactList). Hashing
+ the ObjectIDs instead read every candidate's Object, a cache miss per candidate. */
+inline UnsignedInt hashPartitionPair(const PartitionData *a, const PartitionData *b)
{
- // do it this way so that [a,b] always hashes to the same value as [b,a].
- // this is unsophisticated but reasonable, since all ObjectIDs will
- // quite likely be well below 65536...
- if (a < b)
- {
- return (a<<16)+b;
- }
- else
- {
- return (b<<16)+a;
- }
+ unsigned long long lo = (unsigned long long)(uintptr_t)(a < b ? a : b);
+ unsigned long long hi = (unsigned long long)(uintptr_t)(a < b ? b : a);
+ unsigned long long key = ((lo * 0x9E3779B97F4A7C15ull) ^ hi) * 0xBF58476D1CE4E5B9ull;
+ return (UnsignedInt)(key >> 32);
}
@@ -2582,98 +2592,66 @@ void PartitionContactList::addToContactList( PartitionData *obj, PartitionData *
if (obj == other || obj == NULL || other == NULL)
return;
- Object* obj_obj = obj->getObject();
- Object* other_obj = other->getObject();
- if (obj_obj == NULL || other_obj == NULL)
+ if (obj->getObject() == NULL || other->getObject() == NULL)
return;
- // compute hash index based on object's ids.
- UnsignedInt hashValue = hash2ints(obj_obj->getID(), other_obj->getID());
- hashValue %= PartitionContactList_SOCKET_COUNT;
+ UnsignedInt hashValue = hashPartitionPair(obj, other);
+ UnsignedInt mask = (UnsignedInt)m_slots.size() - 1;
- // make sure given hit has not already been recorded
- for (PartitionContactListNode* cd = m_contactHash[ hashValue ]; cd; cd = cd->m_nextHash )
+ // make sure given hit has not already been recorded
+ for (UnsignedInt i = hashValue & mask; ; i = (i + 1) & mask)
{
- if ((cd->m_obj == obj && cd->m_other == other) ||
- (cd->m_obj == other && cd->m_other == obj))
+ Slot& slot = m_slots[i];
+ if (slot.m_generation != m_generation)
{
- // already noted
+ // new hit
+ slot.m_contact = (Int)m_contacts.size();
+ slot.m_generation = m_generation;
+ Contact ncd = { obj, other, hashValue };
+ m_contacts.push_back(ncd);
+ if (m_contacts.size() * 2 > m_slots.size())
+ growSlots();
return;
}
- }
-
- // new hit
- PartitionContactListNode *ncd = newInstance(PartitionContactListNode);
- ncd->m_obj = obj;
- ncd->m_other = other;
- ncd->m_hashValue = hashValue;
-
- // add to hash table
- ncd->m_nextHash = m_contactHash[ hashValue ];
- m_contactHash[ hashValue ] = ncd;
- // add to list of contacts for this frame
- ncd->m_next = m_contactList;
- m_contactList = ncd;
-
-
-#if 0
-
-Int depth = 0;
-for (PartitionContactListNode *cd2 = m_contactHash[ hashValue ]; cd2; cd2 = cd2->m_nextHash )
-{
- depth++;
-}
-if (depth > 3)
-{
- DEBUG_LOG(("depth is %d for %s %08lx (%d) - %s %08lx (%d)\n",
- depth,obj_obj->getTemplate()->getName().str(),obj_obj,obj_obj->getID(),
- other_obj->getTemplate()->getName().str(),other_obj,other_obj->getID()
- ));
-
- for (cd2 = m_contactHash[ hashValue ]; cd2; cd2 = cd2->m_nextHash )
- {
- UnsignedInt rawhash = djb2hash2ints(cd2->m_obj->getObject()->getID(), cd2->m_other->getObject()->getID());
- //hashValue %= PartitionContactList_SOCKET_COUNT;
-
-
- DEBUG_LOG(("ENTRY: %s %08lx (%d) - %s %08lx (%d) [rawhash %d]\n",
- cd2->m_obj->getObject()->getTemplate()->getName().str(),cd2->m_obj->getObject(),cd2->m_obj->getObject()->getID(),
- cd2->m_other->getObject()->getTemplate()->getName().str(),cd2->m_other->getObject(),cd2->m_other->getObject()->getID(),
- rawhash));
+ const Contact& cd = m_contacts[slot.m_contact];
+ if ((cd.m_obj == obj && cd.m_other == other) ||
+ (cd.m_obj == other && cd.m_other == obj))
+ {
+ // already noted
+ return;
+ }
}
}
-static Real aggtotal = 0;
-static Real aggfull = 0;
-static Real aggcount = 0;
-for (int ii = 0; ii < PartitionContactList_SOCKET_COUNT; ++ii)
+//-----------------------------------------------------------------------------
+void PartitionContactList::growSlots()
{
- if (m_contactHash[ii])
- aggfull += 1.0f;
+ // every slot goes back to empty (generation 0, which m_generation never is) and each pair is
+ // put down again by its own hash
+ m_slots.assign(m_slots.size() * 2, Slot());
- for (cd2 = m_contactHash[ ii ]; cd2; cd2 = cd2->m_nextHash )
+ UnsignedInt mask = (UnsignedInt)m_slots.size() - 1;
+ for (Int c = 0; c < (Int)m_contacts.size(); ++c)
{
- aggtotal += 1.0f;
+ UnsignedInt i = m_contacts[c].m_hash & mask;
+ while (m_slots[i].m_generation == m_generation)
+ i = (i + 1) & mask;
+ m_slots[i].m_contact = c;
+ m_slots[i].m_generation = m_generation;
}
-}
-aggcount += 1.0f;
-DEBUG_ASSERTLOG(((Int)aggcount)%1000!=0,("avg hash depth at %f is %f, fullness %f%%\n",
-aggcount,aggtotal/(aggcount*PartitionContactList_SOCKET_COUNT),(aggfull*100)/(aggcount*PartitionContactList_SOCKET_COUNT)));
-#endif
-
-
}
//-----------------------------------------------------------------------------
void PartitionContactList::removeSpecificPartitionData(PartitionData* data)
{
- for (PartitionContactListNode* cd = m_contactList; cd; cd = cd->m_next)
+ for (size_t i = 0; i < m_contacts.size(); ++i)
{
- if (cd->m_obj == data || cd->m_other == data)
+ Contact& cd = m_contacts[i];
+ if (cd.m_obj == data || cd.m_other == data)
{
- cd->m_obj = NULL;
- cd->m_other = NULL;
+ cd.m_obj = NULL;
+ cd.m_other = NULL;
}
}
}
@@ -2681,23 +2659,36 @@ void PartitionContactList::removeSpecificPartitionData(PartitionData* data)
//-----------------------------------------------------------------------------
void PartitionContactList::resetContactList()
{
- // remove items from hash table
- PartitionContactListNode* cdnext;
- for (PartitionContactListNode* cd = m_contactList; cd; cd = cdnext)
- {
- cdnext = cd->m_next;
- cd->deleteInstance();
+ // a table one air battle grew to megabytes would make every later frame's lookups miss the
+ // cache, so it goes back down once the frame before needed a sixteenth of it
+ size_t lastCount = m_contacts.size();
+ m_contacts.clear();
+ if (m_slots.size() > FIRST_SLOT_COUNT && lastCount * 16 < m_slots.size())
+ {
+ size_t size = FIRST_SLOT_COUNT;
+ while (size < lastCount * 4)
+ size *= 2;
+ std::vector<Slot>(size).swap(m_slots);
+ m_generation = 1;
+ return;
}
- memset(m_contactHash, 0, sizeof(m_contactHash));
- m_contactList = NULL;
+ // a new generation empties every slot at once; only when the count wraps are they rewritten
+ if (++m_generation == 0)
+ {
+ m_slots.assign(m_slots.size(), Slot());
+ m_generation = 1;
+ }
}
//-----------------------------------------------------------------------------
void PartitionContactList::processContactList()
{
- for (PartitionContactListNode* cd = m_contactList; cd; cd = cd->m_next)
+ // newest first, the order EA's linked list was walked in. Nothing below adds a pair, so the
+ // array does not move under the pointer.
+ for (Int i = (Int)m_contacts.size() - 1; i >= 0; --i)
{
+ Contact* cd = &m_contacts[i];
if (cd->m_obj == NULL || cd->m_other == NULL)
continue;
@@ -2783,6 +2774,9 @@ PartitionManager::~PartitionManager()
shutdown();
+ delete thePairStore;
+ thePairStore = NULL;
+
} // end ~PartitionManager
//-----------------------------------------------------------------------------
@@ -2947,7 +2941,10 @@ void PartitionManager::update()
m_updatedSinceLastReset = true;
}
- PartitionContactList ctList;
+ if (thePairStore == NULL)
+ thePairStore = MSGNEW("PartitionContactList") PartitionContactList;
+ PartitionContactList& ctList = *thePairStore;
+ ctList.resetContactList();
TheContactList = &ctList;
while (m_dirtyModules)
{
@@ -4555,6 +4552,12 @@ static Real sightGroundHeight( PartitionCell *cell )
static Real sightBlockingHeight( PartitionCell *cell, const Object *looker, const Object *lookerContainer )
{
Real height = sightGroundHeight( cell );
+
+ // the walk below takes only structures and shrubbery, and a cell under a swarm of aircraft can hold
+ // a hundred COIs of neither (issue 144)
+ if( !cell->hasSightBlockerCoi() )
+ return height;
+
for( CellAndObjectIntersection *coi = cell->getFirstCoiInCell(); coi; coi = coi->getNextCoi() )
{
// a ghost object has no Object behind it
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cpp
index 2ff15dce7..f0ad1ba07 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cpp
@@ -46,7 +46,7 @@ SimpleObjectIterator::ClumpCompareProc SimpleObjectIterator::theClumpCompareProc
};
//=============================================================================
-SimpleObjectIterator::PooledClump::~PooledClump()
+SimpleObjectIterator::PooledClumps::~PooledClumps()
{
}
@@ -57,6 +57,8 @@ SimpleObjectIterator::SimpleObjectIterator()
m_curClump = NULL;
m_clumpCount = 0;
m_inlineClumpsUsed = 0;
+ m_pooledBlocks = NULL;
+ m_pooledClumpsUsed = 0;
}
//=============================================================================
@@ -66,15 +68,15 @@ SimpleObjectIterator::~SimpleObjectIterator()
}
//=============================================================================
-/* The first INLINE_CLUMPS objects a query finds go into the iterator's own array, and only the
- rest take a pool block each. A gathering range query used to allocate one per object found.
- On an eight-player match (111 such queries a logic frame) recycling them through a free list
- measured at nothing, 1.24ms to 1.26, since the pool is a free list already and its lock is
- uncontended. A dense fight of several hundred units makes far more of these queries, each one
- finding dozens of neighbours, and that is the case this array is for; its gain there has not
- been measured yet. Which slot a clump lives
- in never reaches the order: insert still pushes at the head and sort compares only m_numeric
- or the build cost, so the output is the same object sequence as before. */
+/* The first INLINE_CLUMPS objects a query finds go into the iterator's own array, and the rest
+ into pool blocks of POOLED_CLUMPS each. A gathering range query used to allocate one per object
+ found. On an eight-player match (111 such queries a logic frame) recycling them through a free
+ list measured at nothing, 1.24ms to 1.26, since the pool is a free list already and its lock is
+ uncontended. A dense fight is another matter: fifty Avengers' point defence lasers each sweeping
+ six hundred aircraft took a block per aircraft, and those allocations and their frees were a
+ quarter of the pool lock's work in that fight (issue 144), hence the blocks. Which slot a clump
+ lives in never reaches the order: insert still pushes at the head and sort compares only
+ m_numeric or the build cost, so the output is the same object sequence as before. */
void SimpleObjectIterator::insert(Object *obj, Real numeric)
{
DEBUG_ASSERTCRASH(obj, ("sorry, no nulls allowed here"));
@@ -83,13 +85,17 @@ void SimpleObjectIterator::insert(Object *obj, Real numeric)
if (m_inlineClumpsUsed < INLINE_CLUMPS)
{
clump = &m_inlineClumps[m_inlineClumpsUsed++];
- clump->m_pooled = NULL;
}
else
{
- PooledClump *pooled = newInstance(PooledClump);
- clump = &pooled->m_clump;
- clump->m_pooled = pooled;
+ if (m_pooledBlocks == NULL || m_pooledClumpsUsed == POOLED_CLUMPS)
+ {
+ PooledClumps *block = newInstance(PooledClumps);
+ block->m_nextBlock = m_pooledBlocks;
+ m_pooledBlocks = block;
+ m_pooledClumpsUsed = 0;
+ }
+ clump = &m_pooledBlocks->m_clumps[m_pooledClumpsUsed++];
}
clump->m_nextClump = m_firstClump;
@@ -128,20 +134,18 @@ void SimpleObjectIterator::reset()
//=============================================================================
void SimpleObjectIterator::makeEmpty()
{
- while (m_firstClump)
+ while (m_pooledBlocks)
{
- Clump *next = m_firstClump->m_nextClump;
- if (m_firstClump->m_pooled)
- m_firstClump->m_pooled->deleteInstance();
- m_firstClump = next;
- --m_clumpCount;
+ PooledClumps *next = m_pooledBlocks->m_nextBlock;
+ m_pooledBlocks->deleteInstance();
+ m_pooledBlocks = next;
}
- DEBUG_ASSERTCRASH(m_clumpCount == 0, ("hmm"));
m_firstClump = NULL;
m_curClump = NULL;
m_clumpCount = 0;
m_inlineClumpsUsed = 0;
+ m_pooledClumpsUsed = 0;
}
//=============================================================================