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.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
perf(gamelogic): keep each player's team members grouped by template
Olcay Seyganf189875c5e83
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5f80a26ee..9011f7ef0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -482,6 +482,7 @@ found and fixed, EA's own, not port damage.**- Late in a match the interface costs less: clocks and readouts reuse their text textures instead of making new ones every frame, leader aura rings and guard shields are worked out once a game frame, and health bars, rank insignia and supply readouts over a crowded screen cost about a quarter less to draw.- The interface spends less time each frame on the fog of war, leaders' aura rings and guard shields, so big late-game battles draw faster.- Late in a match the picture caught less often. Every ten seconds each computer player looked over its economy, its spending and the enemy army all in one step, 8 to 10ms of work landing on a single picture. Those three now run a fifth of a second apart. With four Hard computer players on Twilight Flame at minutes 24 and 25, pictures slower than 16.7ms went from 29 a minute to 22, and the slowest one in a hundred from 14.7ms to 14.0ms. Two more hitches got smaller in the same match. The map of where units can drive is rebuilt whenever a building goes up or comes down, and that rebuild went from 9.9ms to 7.4ms, with the ones over 8ms halved (90 to 43). A Hard computer steering its Particle Cannon beam now weighs the ground around it in 0.9ms instead of 2.6ms. Neither changes a single move: the match ends on the same checksum.+- Counting a player's units costs less. The computer's scripts and the build menu keep asking how many of some unit or building a player owns, and every answer went through every unit on every one of that player's teams. Each player now keeps its units grouped by type, so an answer looks only at the types it was asked about. Over an hour of eight Hard computer players on Twilight Flame, the step that works out the battle went from 6.15ms to 6.01ms on average and from 13.75ms to 13.25ms at the slowest one in a hundred, and pictures slower than 16.7ms fell from 1,279 to 1,072. The match ends on the same checksum.- The game no longer freezes for seconds when your hard drive is busy. It writes a log of the match as it plays, and once a second the battle itself stopped to push that log to disk. On a drive already busy with something else, Windows can hold such a write back for seconds, and the whole game stood still behind it: a 2v2 against the computer froze for 7.8 seconds on a single step. The log is written on the side now and the battle never waits for it. Three matches played while another program kept the drive busy froze for 6.2 seconds in two of them before; with the change, the slowest step in all three took 48ms.- The game's log no longer grows without limit. Players sent us logs of half a gigabyte up to 19 GB, enough to fill a disk, and the launcher could not open them to report a crash. Most of it was the network code writing a line for every order and every frame, which only a developer's build writes now: a 100-second two-player network match went from 10.9 MB of log to 175 KB, and a skirmish from 600 KB to 166 KB. Past 64 MB the log keeps its first 8 MB, which say how the game started and on what machine, and its most recent lines, so it stays under 64 MB however long you play.- The replay no longer stops the battle either. Every order given in a match went to the replay file on disk the moment it was recorded, and on a busy hard drive Windows held each of those writes back. Two long matches against the computer, played while another program kept the drive busy, stalled 115 times for over a tenth of a second, the worst for 0.63 seconds. The replay is written on the side now, about once a second. The same two matches never stalled past 35ms and finished 40% sooner. The file itself has not changed: a replay recorded by the old game and the new one from the same match is identical byte for byte, the clock times aside. A game that crashes still saves its replay up to the crash; one killed from Task Manager can lose its last second.diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.hindex ff8012a64..8c0954d14 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h@@ -655,11 +655,19 @@ public:/**a convenience routine to count the number of owned objects that match a set of ThingTemplates.You input the count and an array of ThingTemplate*, and provide an array of Int of the same- size. It fills in the array to the correct counts. This is handy because we must traverse- the player's list-of-objects only once.+ size. It fills in the array to the correct counts. It reads the per-template member lists+ below instead of walking every team, and gives the walk's answer at every call.*/void countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const * things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction = TRUE ) const;+ /**+ the per-template member lists follow the team member lists: an object is in them exactly+ while it sits on a team whose prototype this player controls. becomingTeamMember and+ TeamPrototype::setControllingPlayer are the only callers.+ */+ void addTemplateCountMember(Object *obj);+ void removeTemplateCountMember(Object *obj);+/**simply returns the number of buildings owned by this player*/@@ -999,6 +1007,13 @@ private:UnicodeString m_generalName; ///< (SAVE) This is the name of the general the player is allowed to change.PlayerTeamList m_playerTeamPrototypes; ///< ALL the teams we control, via prototype++ struct TemplateCountMembers+ {+ const ThingTemplate *m_template; ///< every object here answers getTemplate() with this+ std::vector<Object *> m_objects; ///< in no particular order; counts are sums+ };+ std::vector<TemplateCountMembers> m_templateCountMembers; ///< (NO-SAVE) every member of our teams, grouped by templatePlayerRelationMap *m_playerRelations; ///< allies & enemiesTeamRelationMap *m_teamRelations; ///< allies & enemiesdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/Team.h b/GeneralsMD/Code/GameEngine/Include/Common/Team.hindex 444c6a568..9edc485b0 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/Team.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/Team.h@@ -400,6 +400,9 @@ public:the team's list-of-objects only once.*/void countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const* things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction = TRUE ) const;++ /// whether countObjectsByThingTemplate counts this object once its template has matched+ static Bool countsTowardTemplate(const Object *obj, Bool ignoreDead, Bool ignoreUnderConstruction);/**diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cppindex fc3f6b96f..cf8d7e8bd 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp@@ -1149,6 +1149,13 @@ void Player::becomingTeamMember(Object *obj, Bool yes, Bool objectXferLoad)if (!obj)return;+ // Object::setOrRestoreTeam calls this right after the team member list changes, before+ // anything below can ask for a count, and on a load too+ if (yes)+ addTemplateCountMember(obj);+ else+ removeTemplateCountMember(obj);+// energy production/consumption hooks, note we ignore things that are UNDER_CONSTRUCTIONif( !obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ){@@ -1958,20 +1965,98 @@ void Player::iterateObjects( ObjectIterateFunc func, void *userData ) const}}+// Walk every team on every count, the way the count was taken before the lists, and log any+// difference. Debug only; define it in Release for a replay-check proof run.+#ifdef _DEBUG+#define TEMPLATE_COUNT_CHECK+#endif+//=============================================================================-void Player::countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const * things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction ) const+void Player::addTemplateCountMember(Object *obj){- Int i;+ // Object's constructor pins getTemplate() to the final override, and a map's INI overrides+ // are all hung before the first object exists, so the key holds for the object's life+ const ThingTemplate *tmpl = obj->getTemplate();+ for (std::vector<TemplateCountMembers>::iterator it = m_templateCountMembers.begin(); it != m_templateCountMembers.end(); ++it)+ {+ if (it->m_template == tmpl)+ {+ it->m_objects.push_back(obj);+ return;+ }+ }+ m_templateCountMembers.push_back(TemplateCountMembers());+ m_templateCountMembers.back().m_template = tmpl;+ m_templateCountMembers.back().m_objects.push_back(obj);+}++//=============================================================================+void Player::removeTemplateCountMember(Object *obj)+{+ const ThingTemplate *tmpl = obj->getTemplate();+ for (std::vector<TemplateCountMembers>::iterator it = m_templateCountMembers.begin(); it != m_templateCountMembers.end(); ++it)+ {+ if (it->m_template != tmpl)+ continue;++ std::vector<Object *> &objects = it->m_objects;+ for (size_t k = 0; k < objects.size(); ++k)+ {+ if (objects[k] == obj)+ {+ objects[k] = objects.back();+ objects.pop_back();+ return;+ }+ }+ break;+ }+ DEBUG_CRASH(("Player %d leaves object %d '%s' it never counted\n", getPlayerIndex(), obj->getID(), tmpl->getName().str()));+}- for (i = 0; i < numTmplates; ++i)+//=============================================================================+void Player::countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const * things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction ) const+{+ for (Int i = 0; i < numTmplates; ++i)counts[i] = 0;- for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();- it != m_playerTeamPrototypes.end();- ++it)- {- (*it)->countObjectsByThingTemplate(numTmplates, things, ignoreDead, counts, ignoreUnderConstruction);+ // The walk counts an object once, for the first template it is equivalent to, and whether it+ // counts at all is a question about the object alone. Every object in one list shares its+ // template, so one equivalence pass per list stands for all of them.+ for (std::vector<TemplateCountMembers>::const_iterator it = m_templateCountMembers.begin(); it != m_templateCountMembers.end(); ++it)+ {+ if (it->m_objects.empty())+ continue;++ Int i = 0;+ while (i < numTmplates && !it->m_template->isEquivalentTo(things[i]))+ ++i;+ if (i == numTmplates)+ continue;++ for (std::vector<Object *>::const_iterator obj = it->m_objects.begin(); obj != it->m_objects.end(); ++obj)+ {+ if (Team::countsTowardTemplate(*obj, ignoreDead, ignoreUnderConstruction))+ ++counts[i];+ }}++#ifdef TEMPLATE_COUNT_CHECK+ static UnsignedInt s_checks = 0;+ static UnsignedInt s_mismatches = 0;+ std::vector<Int> walked(numTmplates, 0);+ for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); it != m_playerTeamPrototypes.end(); ++it)+ (*it)->countObjectsByThingTemplate(numTmplates, things, ignoreDead, walked.data(), ignoreUnderConstruction);+ for (Int i = 0; i < numTmplates; ++i)+ {+ if (walked[i] != counts[i] && ++s_mismatches <= 50)+ DEBUG_LOG(("TEMPLATECOUNT MISMATCH: frame %u player %d '%s' lists %d walk %d (ignoreDead %d ignoreUnderConstruction %d)\n",+ TheGameLogic->getFrame(), getPlayerIndex(), things[i] ? things[i]->getName().str() : "(null)",+ counts[i], walked[i], ignoreDead, ignoreUnderConstruction));+ }+ if ((++s_checks & 0x3FFFF) == 0)+ DEBUG_LOG(("TEMPLATECOUNT CHECK: %u calls, %u mismatches, frame %u\n", s_checks, s_mismatches, TheGameLogic->getFrame()));+#endif}//=============================================================================diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cppindex 18d5a6382..786f55ecd 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp@@ -895,6 +895,7 @@ void TeamPrototype::setControllingPlayer(Player *newController)return;}+ Player *oldController = m_owningPlayer;if (m_owningPlayer)m_owningPlayer->removeTeamFromList(this);@@ -904,7 +905,7 @@ void TeamPrototype::setControllingPlayer(Player *newController)m_owningPlayer->addTeamToList(this);// every member changed hands without changing team; the partition counts each cell's- // objects per player and has to hear of it now+ // objects per player and has to hear of it now, and so do the players' template countsfor (DLINK_ITERATOR<Team> teamIt = iterate_TeamInstanceList(); !teamIt.done(); teamIt.advance()){for (DLINK_ITERATOR<Object> objIt = teamIt.cur()->iterate_TeamMemberList(); !objIt.done(); objIt.advance())@@ -912,6 +913,9 @@ void TeamPrototype::setControllingPlayer(Player *newController)PartitionData *pd = objIt.cur()->friend_getPartitionData();if (pd)pd->refreshCountedPlayer();+ if (oldController)+ oldController->removeTemplateCountMember(objIt.cur());+ newController->addTemplateCountMember(objIt.cur());}}}@@ -1662,6 +1666,25 @@ static Bool objectKeepsOwnerAlive(const Object *obj)return Object_keepsOwnerAlive(obj->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION), obj->getConstructionPercent());}+// ------------------------------------------------------------------------+Bool Team::countsTowardTemplate(const Object *obj, Bool ignoreDead, Bool ignoreUnderConstruction)+{+ if (ignoreDead && (obj->isEffectivelyDead() || obj->isDestroyed()))+ return false;++ if( ignoreUnderConstruction && obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) )+ return false;++ // The plan skip rides on ignoreUnderConstruction rather than running for everyone. A+ // caller that passes false is asking for sites still being built, and a plan is one of+ // them. Every caller today takes the default TRUE, and a plan carries UNDER_CONSTRUCTION,+ // so the check above already drops it; this line states the rule, it changes no count.+ if (ignoreUnderConstruction && !objectKeepsOwnerAlive(obj))+ return false;++ return true;+}+// ------------------------------------------------------------------------void Team::countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const* things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction) const{@@ -1676,17 +1699,7 @@ void Team::countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* concontinue;}- if (ignoreDead && (iter.cur()->isEffectivelyDead() || iter.cur()->isDestroyed()))- continue;-- if( ignoreUnderConstruction && iter.cur()->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) )- continue;-- // The plan skip rides on ignoreUnderConstruction rather than running for everyone. A- // caller that passes false is asking for sites still being built, and a plan is one of- // them. Every caller today takes the default TRUE, and a plan carries UNDER_CONSTRUCTION,- // so the check above already drops it; this line states the rule, it changes no count.- if (ignoreUnderConstruction && !objectKeepsOwnerAlive(iter.cur()))+ if (!countsTowardTemplate(iter.cur(), ignoreDead, ignoreUnderConstruction))continue;counts[i] += 1;