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): spread once-a-second work and AI tactics over frames

Olcay Seygan3b3644376e52
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a3bd1b479..b225eeeca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -472,6 +472,7 @@ found and fixed, EA's own, not port damage.**
- 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.
- Every armed unit stopped asking its model to show its loaded missiles. Each one asked on every step of the battle, and only the Tomahawk, the Scud Launcher, the Scorpion and the Scud Storm carry missiles you can see on the model; for the hundreds of others the answer was nothing, and it still had to be queued and read back. Those four keep asking, so their racks still empty and refill as they fire and reload. Over an hour of eight Hard computer players on Twilight Flame the battle step went from 7.15ms to 6.81ms on average, pictures slower than 16.7ms fell from 7,065 to 5,826, and minute 50 ran at 8.6ms a picture instead of 10.7. The match ends on the same checksum.
- Computer players' scripts stopped searching the whole map for units that are not on it. The Stealth General's GPS Scrambler script looks for its own Quad Cannon on every step, and with none left the search still walked the map square by square to be sure; it now first asks whether anyone holds one, and a search that reaches past the edge of the map stops at the last square that is on it. Over 114,000 steps of eight Hard computer players on Twilight Flame the battle step went from 5.63ms to 5.37ms on average and from 14.5ms to 14.0ms at the slowest one in a thousand, and the match took 733 seconds instead of 763. The match ends on the same checksum.
+- Late in a match the battle stopped doing a whole second's chores on one step. Once a second every ranked leader went through the army to see who stood in its aura, each unit took its self-repair, every neutral building its repair, and each Hard computer player redrew its map of enemy fire in one go. Those lumps reached 2 to 6ms on a step already near its limit. Every unit now has its own step of the second and Hard's fire map fills in piece by piece, so an aura or a threat reading can be up to two seconds old where it was one.
- 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/Data/Scenarios/rankaura.txt b/GeneralsMD/Code/Data/Scenarios/rankaura.txt
index 17fd67840..63b3eebb3 100644
--- a/GeneralsMD/Code/Data/Scenarios/rankaura.txt
+++ b/GeneralsMD/Code/Data/Scenarios/rankaura.txt
@@ -10,6 +10,8 @@
# and the Cobra (both get its 0.10 at frame 60) and walks to the same Kirpi: beside the Altay it gives
# the Altay 0.10 (frame 600), and once inside the Altay drops back to the Sungur's 0.05 (frame 960)
# while the Beret itself holds nothing. The Kirpi, a vehicle outside, takes the Altay's 0.10.
+# Those frames are from when one pass did every object. Each now takes its aura on its own frame of
+# the second, so a line comes up to two seconds later, and the Engineer gets one before it climbs in.
#
# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
# -map "Maps\Twilight Flame\Twilight Flame.map" -autoskirmish 2 -takeover
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIInfluenceMap.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIInfluenceMap.h
index 6013007e9..3b253a80e 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIInfluenceMap.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIInfluenceMap.h
@@ -66,6 +66,7 @@ public:
void xfer( Xfer *xfer );
void markBuilt( UnsignedInt frame ) { m_builtFrame = frame; m_built = TRUE; }
+ void markUnbuilt() { m_built = FALSE; }
Bool isBuilt() const { return m_built; }
UnsignedInt getBuiltFrame() const { return m_builtFrame; }
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
index 9407e6b06..e0af31f96 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPlayer.h
@@ -829,7 +829,11 @@ protected:
/** What this player knows can shoot at each patch of the map, and what it has there itself. */
AIInfluenceMap m_influence;
- void rebuildInfluence(void);
+ AIInfluenceMap m_influenceNext; ///< Hard's: what this round's objects have stamped so far; it becomes m_influence when the round ends
+ void updateInfluence(void); ///< Hard's map, one share of the objects a frame
+ void rebuildInfluence(void); ///< the whole map on one frame
+ void stampInfluence(AIInfluenceMap &map, const Object *obj);
+ void stampFireReports(AIInfluenceMap &map);
void ensureInfluence(void); ///< the map, no older than this rung reads it; below Hard this is what draws it
Bool hasTacticalMap(void) const; ///< Hard's map, for the reads the rungs below it do not make
Bool quietGround(const Coord3D *from, const Real *gun, Coord3D *spot); ///< where to go from here to be off the map's guns and clear of this one (x, y, reach, or NULL); FALSE when no way gets out
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
index e27fd812d..4bb86ed6f 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
@@ -170,7 +170,7 @@ public:
UnsignedInt getFrameForClient( void ) const { return m_frameForClient; } ///< the frame the last tick ran, for the client's clock (LogicThread::runTick)
UnsignedInt getCRC( Int mode = CRC_CACHED, AsciiString deepCRCFileName = AsciiString::TheEmptyString ); ///< Returns the CRC
- void setObjectIDCounter( ObjectID nextObjID ) { m_nextObjID = nextObjID; }
+ void setObjectIDCounter( ObjectID nextObjID ) { m_nextObjID = nextObjID; m_nextObjIDFromSave = nextObjID; }
ObjectID getObjectIDCounter( void ) { return m_nextObjID; }
//-----------------------------------------------------------------------------------------------
@@ -429,6 +429,7 @@ private:
ObjectPointerList m_objectsToDestroy; ///< List of things that need to be destroyed at end of frame
ObjectID m_nextObjID; ///< For allocating object id's
+ ObjectID m_nextObjIDFromSave; ///< The counter a save held, for loadPostProcess
void setDefaults( Bool loadSaveGame ); ///< Set default values of class object
void processDestroyList( void ); ///< Destroy all pending objects on the destroy list
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h
index 5e0164162..59d2d50c1 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h
@@ -301,8 +301,8 @@ public:
// the ladder's perks and the auras leaders give (RankPerk, RankAura in GlobalData.h)
Real getRankPerk( RankPerk perk ) const; ///< what my grade carries, 0 without a ladder
Real getRankAura( RankAura aura ) const; ///< the strongest leader's on me now
- void clearRankAuras(); ///< the once-a-second pass starts over; RALLY runs on
- void raiseRankAura( RankAura aura, Real strength ); ///< a leader has me in range; the stronger stays
+ void takeGatheredRankAuras(); ///< my turn this second: what leaders gave me since my last turn is what I hold; RALLY runs on
+ void raiseRankAura( RankAura aura, Real strength ); ///< a leader had me in range on its turn; the stronger stays until my next turn
void raiseRankRally( Real strength, UnsignedInt until ); ///< a fallen leader's rally; the stronger stays, the later end
Real getRankSightScalar() const; ///< my own sight perk times the sight aura on me
Real getRankDamageTakenScalar() const; ///< guard, rally and the still guard perk, multiplied
@@ -813,7 +813,8 @@ private:
Real m_shroudClearingRange; ///< looking range for shroud ONLY
Real m_shroudRange; ///< like looking range, this is how far I shroud others' looks
Int m_sightJammerCount; ///< enemy jammers in whose field this stands; above zero its sight shrinks to a few feet
- Real m_rankAura[ RANK_AURA_COUNT ]; ///< the strongest leader's of each kind, refilled once a second
+ Real m_rankAura[ RANK_AURA_COUNT ]; ///< the strongest leader's of each kind, refilled on my turn once a second
+ Real m_rankAuraGathered[ RANK_AURA_PASSED ]; ///< what the leaders' turns have given me since my last turn
UnsignedInt m_rankRallyUntil; ///< the frame the death rally on me ends
Bool m_forgoRankRally; ///< set and read within one kill, so not saved
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIInfluenceMap.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIInfluenceMap.cpp
index e070aefb1..2974e603c 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIInfluenceMap.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIInfluenceMap.cpp
@@ -81,15 +81,19 @@ void AIInfluenceMap::stamp( std::vector<Real> &layer, Real x, Real y, Real z, Re
const Int colHi = min<Int>( m_cols - 1, REAL_TO_INT_FLOOR( (x + farthest - m_originX) / m_cellSize ) );
const Int rowLo = max<Int>( 0, REAL_TO_INT_FLOOR( (y - farthest - m_originY) / m_cellSize ) );
const Int rowHi = min<Int>( m_rows - 1, REAL_TO_INT_FLOOR( (y + farthest - m_originY) / m_cellSize ) );
+ const Real rangeSqr = sqr( range ), farthestSqr = sqr( farthest );
for( Int row = rowLo; row <= rowHi; ++row )
{
const Real cy = m_originY + (row + 0.5f) * m_cellSize;
for( Int col = colLo; col <= colHi; ++col )
{
- const Int index = row * m_cols + col;
const Real cx = m_originX + (col + 0.5f) * m_cellSize;
- const Real reach = range + Weapon_highGroundRangeBonus( range, z - m_height[ index ] );
- if( sqr( cx - x ) + sqr( cy - y ) <= sqr( reach ) )
+ const Real distSqr = sqr( cx - x ) + sqr( cy - y );
+ // the bonus is never below 0 nor past the cap, so the height only decides the ring between
+ if( distSqr > farthestSqr )
+ continue;
+ const Int index = row * m_cols + col;
+ if( distSqr <= rangeSqr || distSqr <= sqr( range + Weapon_highGroundRangeBonus( range, z - m_height[ index ] ) ) )
layer[ index ] += power;
}
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 400a321a5..35a6b5f9d 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -14461,8 +14461,8 @@ Bool AIPlayer::doFallback( Team *team )
}
//----------------------------------------------------------------------------------------------------------
-/** How often each fighting unit is looked at. This and the map's rung clock are on the frame and the
- * player's slot, so there is no timer to save and every machine does it on the same frame. */
+/** How often each fighting unit is looked at. This and the map's rung clock go by the frame and the
+ * object's ID, so there is no timer to save and every machine does it on the same frame. */
static const Int TACTICS_RATE = LOGICFRAMES_PER_SECOND / 3;
/** Kiting. A unit steps back from something it outranges once that thing is inside its own reach
@@ -14913,6 +14913,82 @@ static Real firingHeight( const Object *obj )
* observerKnowsAbout, the same line every other decision here draws, so a gun it has never seen
* does not steer it and a bunker it saw once keeps doing so. */
//----------------------------------------------------------------------------------------------------------
+void AIPlayer::stampInfluence( AIInfluenceMap &map, const Object *obj )
+{
+ if( obj->isEffectivelyDead() || obj->isKindOf( KINDOF_PROJECTILE ) )
+ return;
+ const Bool mine = obj->getControllingPlayer() == m_player;
+ const Relationship relation = m_player->getRelationship( obj->getTeam() );
+ // the friendly layer is for the tactics alone, so the rungs below Hard do not pay for it
+ if( (mine || relation == ALLIES) ? !getSkillProfile()->m_tacticalMicro : relation != ENEMIES )
+ return;
+ const Real power = aiCombatPower( obj );
+ if( power <= 0.0f )
+ return;
+ const Real range = groundAttackRange( obj );
+ if( range <= 0.0f )
+ return;
+ const Coord3D *pos = obj->getPosition();
+ if( mine || relation == ALLIES )
+ map.stampFriend( pos->x, pos->y, firingHeight( obj ), range, power );
+ else if( observerKnowsAbout( obj, m_player->getPlayerIndex() ) )
+ map.stampEnemy( pos->x, pos->y, firingHeight( obj ), range, power );
+}
+
+/** The guns it knows of only by their shells, where they stood at the last one. */
+void AIPlayer::stampFireReports( AIInfluenceMap &map )
+{
+ const Int me = m_player->getPlayerIndex();
+ for( size_t r = 0; r < m_fireReports.size(); ++r )
+ {
+ const FireReport &report = m_fireReports[ r ];
+ Object *shooter = reportedShooter( report );
+ if( shooter && !observerKnowsAbout( gunCarrier( shooter ), me ) )
+ map.stampEnemy( report.at.x, report.at.y, report.at.z, report.reach, report.power );
+ }
+}
+
+/** Stamping the whole map in one frame was 2 to 6 ms a player a second at minute 30, the largest of the
+ * burst frames the AI owned. So on Hard's clock each object stamps once a round on the frame its ID falls
+ * on, into a map nobody reads, and that map takes over when the player's round ends: the map read is
+ * whole, its oldest stamp up to two rounds old where it used to be one. */
+void AIPlayer::updateInfluence( void )
+{
+ // the first look takes everything at once, so nothing reads a map that is not whole
+ if( !m_influence.isBuilt() )
+ rebuildInfluence();
+ // the first round, or a save from before there were two; a map that starts mid-round is short of
+ // objects and goes, and the first full round takes over
+ if( !m_influenceNext.isSized() )
+ {
+ m_influenceNext = m_influence;
+ m_influenceNext.clear();
+ m_influenceNext.markUnbuilt();
+ }
+
+ const UnsignedInt now = TheGameLogic->getFrame();
+ const Int round = rungFrames( getSkillProfile()->m_influenceSeconds );
+ const UnsignedInt turn = now % (UnsignedInt)round;
+ // ponytail: one walk of every object a player a frame, about 10000 ID tests at minute 30; one
+ // shared list a frame if that ever shows beside the stamps
+ for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )
+ if( (UnsignedInt)obj->getID() % (UnsignedInt)round == turn )
+ stampInfluence( m_influenceNext, obj );
+
+ if( (now + computeUpdatePhase( m_player->getPlayerIndex(), round )) % round == 0 )
+ {
+ if( m_influenceNext.isBuilt() )
+ {
+ stampFireReports( m_influenceNext );
+ std::swap( m_influence, m_influenceNext );
+ m_influence.markBuilt( now );
+ }
+ m_influenceNext.clear();
+ m_influenceNext.markBuilt( now );
+ }
+}
+
+/** The whole map on one frame: Hard's first look, and every draw below Hard. */
void AIPlayer::rebuildInfluence( void )
{
if( !m_influence.isSized() )
@@ -14932,50 +15008,22 @@ void AIPlayer::rebuildInfluence( void )
}
m_influence.clear();
- const Int me = m_player->getPlayerIndex();
- // the friendly layer is for the tactics alone, so the rungs below Hard do not pay for it
- const Bool friends = getSkillProfile()->m_tacticalMicro;
for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )
- {
- if( obj->isEffectivelyDead() || obj->isKindOf( KINDOF_PROJECTILE ) )
- continue;
- const Bool mine = obj->getControllingPlayer() == m_player;
- const Relationship relation = m_player->getRelationship( obj->getTeam() );
- if( (mine || relation == ALLIES) ? !friends : relation != ENEMIES )
- continue;
- const Real power = aiCombatPower( obj );
- if( power <= 0.0f )
- continue;
- const Real range = groundAttackRange( obj );
- if( range <= 0.0f )
- continue;
- const Coord3D *pos = obj->getPosition();
- if( mine || relation == ALLIES )
- m_influence.stampFriend( pos->x, pos->y, firingHeight( obj ), range, power );
- else if( observerKnowsAbout( obj, me ) )
- m_influence.stampEnemy( pos->x, pos->y, firingHeight( obj ), range, power );
- }
- // and the guns it knows of only by their shells, where they stood at the last one
- for( size_t r = 0; r < m_fireReports.size(); ++r )
- {
- const FireReport &report = m_fireReports[ r ];
- Object *shooter = reportedShooter( report );
- if( shooter && !observerKnowsAbout( gunCarrier( shooter ), me ) )
- m_influence.stampEnemy( report.at.x, report.at.y, report.at.z, report.reach, report.power );
- }
+ stampInfluence( m_influence, obj );
+ stampFireReports( m_influence );
m_influence.markBuilt( TheGameLogic->getFrame() );
}
-/** Hard draws its map on the clock (doTactics), and everything below Hard draws it here, when it has
- * something to read it for and it is older than the rung's m_influenceSeconds: rebuildInfluence is already
- * a fifth of Hard's AI update, and a quiet match has nothing to read it for. -notactics stays off the map
- * altogether, and every read of one never drawn is nothing there. */
+/** Hard stamps its map over the frames of its clock (updateInfluence), and everything below Hard draws it
+ * here, when it has something to read it for and it is older than the rung's m_influenceSeconds: a whole
+ * draw costs 2 to 6 ms late in a match, and a quiet match has nothing to read it for. -notactics stays off
+ * the map altogether, and every read of one never drawn is nothing there. */
void AIPlayer::ensureInfluence( void )
{
if( measuringWithoutTactics() )
return;
// ponytail: below Hard one whole walk of the objects on one frame, every two or four seconds at most while
- // something asks; Hard's costs 2.38 ms on a late frame. Stamp it over frames as Hard's when that lands
+ // something asks. Stamp it over frames as Hard's if that ever shows in a tail
const AIDifficultyProfile *profile = getSkillProfile();
if( m_influence.isBuilt() && (profile->m_tacticalMicro ||
TheGameLogic->getFrame() - m_influence.getBuiltFrame() < (UnsignedInt)rungFrames( profile->m_influenceSeconds )) )
@@ -15169,6 +15217,21 @@ Bool AIPlayer::measuringWithoutTactics( void ) const
(ThePlayerList->getSlotIndex( m_player->getPlayerIndex() ) & 1) == TheGlobalData->m_noTacticsSlotParity;
}
+/** Those of the player's objects whose turn in the look falls on this frame. */
+struct FireLookTurn
+{
+ UnsignedInt look;
+ UnsignedInt frameOfLook;
+ std::vector<Object *> units;
+};
+
+static void collectFireLookTurn( Object *obj, void *userData )
+{
+ FireLookTurn *turn = (FireLookTurn *)userData;
+ if( (UnsignedInt)obj->getID() % turn->look == turn->frameOfLook )
+ turn->units.push_back( obj );
+}
+
void AIPlayer::doTactics( void )
{
if( measuringWithoutTactics() )
@@ -15178,25 +15241,24 @@ void AIPlayer::doTactics( void )
const Bool tactics = getSkillProfile()->m_tacticalMicro;
if( tactics )
- {
- const Int rebuildRate = rungFrames( getSkillProfile()->m_influenceSeconds );
- if( !m_influence.isBuilt() || (now + computeUpdatePhase( me, rebuildRate )) % rebuildRate == 0 )
- rebuildInfluence();
- }
+ updateInfluence();
answerFire();
- if( (now + computeUpdatePhase( me, TACTICS_RATE )) % TACTICS_RATE != 0 )
- return;
-
+ // each unit once every TACTICS_RATE frames, on the frame its ID falls on, not a whole army on one
if( tactics && m_baseCenterSet )
{
- std::vector<Object *> units;
- m_player->iterateObjects( collectObject, &units );
- for( size_t i = 0; i < units.size(); ++i )
- tacticsFor( units[ i ] );
+ FireLookTurn turn;
+ turn.look = TACTICS_RATE;
+ turn.frameOfLook = now % turn.look;
+ m_player->iterateObjects( collectFireLookTurn, &turn );
+ for( size_t i = 0; i < turn.units.size(); ++i )
+ tacticsFor( turn.units[ i ] );
}
+ if( (now + computeUpdatePhase( me, TACTICS_RATE )) % TACTICS_RATE != 0 )
+ return;
+
// ponytail: a linear list searched per unit, a few hundred rows at most; a map keyed on the ID if
// armies ever grow past that
for( size_t i = 0; i < m_tactics.size(); )
@@ -15999,23 +16061,8 @@ AIFireAnswer AIPlayer::answerHit( Object *obj, Object *shooter, Object *gun )
return answer;
}
-/** Those of the player's objects whose turn in the look falls on this frame. */
-struct FireLookTurn
-{
- UnsignedInt look;
- UnsignedInt frameOfLook;
- std::vector<Object *> units;
-};
-
-static void collectFireLookTurn( Object *obj, void *userData )
-{
- FireLookTurn *turn = (FireLookTurn *)userData;
- if( (UnsignedInt)obj->getID() % turn->look == turn->frameOfLook )
- turn->units.push_back( obj );
-}
-
//----------------------------------------------------------------------------------------------------------
-/** The owner: "bu ai lar artik su influence map i falan biraz ciddiye alsinlar, hedef aliniyorlar hala
+/** The owner:"bu ai lar artik su influence map i falan biraz ciddiye alsinlar, hedef aliniyorlar hala
* devam ediyorlar ayni yerde." A unit idle or parked under a long gun only acquires what it can see, a
* wave on its road only what its mood looks for, and one shooting a building stays on the building with
* a tower on it, and none of the rest of the AI asked who was hitting them. So once in each of the rung's
@@ -18208,7 +18255,7 @@ void AIPlayer::xfer( Xfer *xfer )
{
// version
- XferVersion currentVersion = 32; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker 9: tactical steps 10: the ferry and dropped riders 11: the outward placement ring 12: the pressure level 13: falling back 14: gunship Chinooks and the boarding wait 15: transport Chinooks and the lent one 16: healer and raider Helixes 17: the seen-enemy ledger 18: the fist 19: the Ambulances 20: the last Ambulance lost 21: the purchase queue's reservation 22: the measured income 23: the Ambulances bought 24: the starting fortune 25: the factory backlog clocks 26: the personality 27: the team request inbox 28: the last aircraft refused for parking 29: the watched sites and the cooled spots 30: the factory backlog as a window of passes 31: the factories that let a unit out since the last pass 32: the guns known by their shells, the answers to fire
+ XferVersion currentVersion = 33; // 2: scout 3: rung and role 4: scouting stamps 5: the capturer 6: parked waves 7: superweapon aims 8: the hijacker 9: tactical steps 10: the ferry and dropped riders 11: the outward placement ring 12: the pressure level 13: falling back 14: gunship Chinooks and the boarding wait 15: transport Chinooks and the lent one 16: healer and raider Helixes 17: the seen-enemy ledger 18: the fist 19: the Ambulances 20: the last Ambulance lost 21: the purchase queue's reservation 22: the measured income 23: the Ambulances bought 24: the starting fortune 25: the factory backlog clocks 26: the personality 27: the team request inbox 28: the last aircraft refused for parking 29: the watched sites and the cooled spots 30: the factory backlog as a window of passes 31: the factories that let a unit out since the last pass 32: the guns known by their shells, the answers to fire 33: the influence map being stamped
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -18742,6 +18789,10 @@ void AIPlayer::xfer( Xfer *xfer )
}
}
+ // the influence map half stamped, or a loaded game's next map would be missing the round's first half
+ if( version >= 33 )
+ m_influenceNext.xfer( xfer );
+
} // end xfer
// ------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
index 8b5fb0ae1..b8d3dca47 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp
@@ -309,6 +309,8 @@ Object::Object( const ThingTemplate *tt, const ObjectStatusMaskType &objectStatu
m_sightJammerCount = 0;
for( Int aura = 0; aura < RANK_AURA_COUNT; ++aura )
m_rankAura[ aura ] = 0.0f;
+ for( Int aura = 0; aura < RANK_AURA_PASSED; ++aura )
+ m_rankAuraGathered[ aura ] = 0.0f;
m_rankRallyUntil = 0;
m_forgoRankRally = FALSE;
@@ -4559,13 +4561,14 @@ static void xferModule( Xfer *xfer, BehaviorModule *module, const Object *obj )
* 13: how many enemy jammers are cutting its sight
* 14: the rank auras on it and when its death rally ends
* 15: the six aura kinds mend, pace, drill, steady, capture and spoils
+ * 16: the auras gathered since its last turn of the once-a-second pass
*/
//-------------------------------------------------------------------------------------------------
void Object::xfer( Xfer *xfer )
{
// version
- const XferVersion currentVersion = 15;
+ const XferVersion currentVersion = 16;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -5044,6 +5047,12 @@ void Object::xfer( Xfer *xfer )
if( version >= 14 )
xfer->xferUnsignedInt( &m_rankRallyUntil );
+ if( version >= 16 )
+ {
+ for( Int aura = 0; aura < RANK_AURA_PASSED; ++aura )
+ xfer->xferReal( &m_rankAuraGathered[ aura ] );
+ }
+
} // end xfer
//-------------------------------------------------------------------------------------------------
@@ -5603,16 +5612,19 @@ Real Object::getRankAura( RankAura aura ) const
}
//-------------------------------------------------------------------------------------------------
-void Object::clearRankAuras()
+void Object::takeGatheredRankAuras()
{
for( Int aura = 0; aura < RANK_AURA_PASSED; ++aura )
- m_rankAura[ aura ] = 0.0f;
+ {
+ m_rankAura[ aura ] = m_rankAuraGathered[ aura ];
+ m_rankAuraGathered[ aura ] = 0.0f;
+ }
}
//-------------------------------------------------------------------------------------------------
void Object::raiseRankAura( RankAura aura, Real strength )
{
- m_rankAura[ aura ] = MAX( m_rankAura[ aura ], strength );
+ m_rankAuraGathered[ aura ] = MAX( m_rankAuraGathered[ aura ], strength );
}
//-------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index 0e75ea30b..f2bce8c32 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -260,6 +260,7 @@ GameLogic::GameLogic( void )
m_objList = NULL;
m_curUpdateModule = NULL;
m_nextObjID = INVALID_ID;
+ m_nextObjIDFromSave = INVALID_ID;
m_startNewGame = FALSE;
m_gameMode = GAME_NONE;
m_rankLevelLimit = 1000;
@@ -2756,14 +2757,22 @@ void GameLogic::processDestroyList( void )
UpdateModulePtr sleepyUpdatesForThisObject[MAX_SUO];
Int numSUO = 0;
- for (std::vector<SleepyEntry>::iterator it2 = m_sleepyUpdates.begin(); it2 != m_sleepyUpdates.end(); ++it2)
+ /* The object's own modules say where they sit in the heap, which is the order a scan of the whole
+ heap met them in. That scan, one per death, took 3.7 ms of a 17 ms frame in a late fight. */
+ for (BehaviorModule** b = currentObject->getBehaviorModules(); *b && numSUO < MAX_SUO; ++b)
{
- UpdateModulePtr u = it2->module;
- if (u->friend_getObject() == currentObject && numSUO < MAX_SUO)
+#ifdef DIRECT_UPDATEMODULE_ACCESS
+ UpdateModulePtr u = (UpdateModulePtr)((*b)->getUpdate());
+#else
+ UpdateModulePtr u = (*b)->getUpdate();
+#endif
+ if (u && u->friend_getIndexInLogic() >= 0)
{
sleepyUpdatesForThisObject[numSUO++] = u;
}
}
+ std::sort(sleepyUpdatesForThisObject, sleepyUpdatesForThisObject + numSUO,
+ [](UpdateModulePtr a, UpdateModulePtr b) { return a->friend_getIndexInLogic() < b->friend_getIndexInLogic(); });
for (--numSUO; numSUO >= 0; --numSUO)
{
@@ -4064,128 +4073,116 @@ static void unitTimings(void)
#endif
//-------------------------------------------------------------------------------------------------
-/** The rank auras, once a second (docs/plans/RANK-LADDER.md in the wrapper). Every unit's slots are
- * cleared, then each leader writes its strength into the slots of the friendly units within its
- * radius, keeping the larger, so three leaders of one kind give the strongest one's and the walk's
- * order does not matter. A leader never reaches itself; each kind has its own radius, and reaches
- * units, only infantry, or units and buildings as its line says. The DETECT perk works here too: a
- * stealthed enemy within its radius stays detected until the next pass. Afterwards a unit whose
- * sight moved looks again, one whose pace moved takes its new speed, and a drill aura teaches. */
+/** The rank auras (docs/plans/RANK-LADDER.md in the wrapper), each object on its own frame of the second
+ * (oncePerSecondTurn), so a late game's leaders do not all walk the object list on one frame. A
+ * leader's turn writes its strength into the gathered slots of the friendly units within
+ * its radius, keeping the larger, so three leaders of one kind give the strongest one's and the
+ * order of the turns does not matter. A unit's own turn takes what was gathered since its last one,
+ * every leader's once, as what it holds. A leader never reaches itself; each kind has its own
+ * radius, and reaches units, only infantry, or units and buildings as its line says. The DETECT perk
+ * works here too: a stealthed enemy within its radius stays detected until the leader's next turn.
+ * A unit whose sight moved looks again, one whose pace moved takes its new speed, and a drill aura
+ * teaches. */
//-------------------------------------------------------------------------------------------------
-static void updateRankAuras( Object *objList )
+static void rankAuraTake( Object *obj )
{
- struct Before { Real sight; Real aura[ RANK_AURA_PASSED ]; };
- static std::vector<Before> before;
- before.clear();
- for( Object *obj = objList; obj; obj = obj->getNextObject() )
+ const Real sightBefore = obj->getRankSightScalar();
+ Real before[ RANK_AURA_PASSED ];
+ for( Int aura = 0; aura < RANK_AURA_PASSED; ++aura )
+ before[ aura ] = obj->getRankAura( (RankAura)aura );
+ obj->takeGatheredRankAuras();
+
+ // a unit that came into or left a leader's reach logs what it holds now
+ Bool moved = FALSE;
+ for( Int aura = 0; aura < RANK_AURA_PASSED; ++aura )
+ moved = moved || obj->getRankAura( (RankAura)aura ) != before[ aura ];
+ if( moved )
+ DEBUG_LOG(("RANK AURA frame=%d id=%d template=%s grade=%d rof=%.2f sight=%.2f guard=%.2f range=%.2f"
+ " mend=%.4f pace=%.2f drill=%.0f steady=%.2f capture=%.2f spoils=%.2f\n",
+ TheGameLogic->getFrame(), obj->getID(), obj->getTemplate()->getName().str(), obj->getRankGrade(),
+ obj->getRankAura( RANK_AURA_RATE_OF_FIRE ), obj->getRankAura( RANK_AURA_SIGHT ),
+ obj->getRankAura( RANK_AURA_GUARD ), obj->getRankAura( RANK_AURA_RANGE ),
+ obj->getRankAura( RANK_AURA_MEND ), obj->getRankAura( RANK_AURA_PACE ), obj->getRankAura( RANK_AURA_DRILL ),
+ obj->getRankAura( RANK_AURA_STEADY ), obj->getRankAura( RANK_AURA_CAPTURE ), obj->getRankAura( RANK_AURA_SPOILS )));
+ obj->onRankSightChanged( sightBefore );
+ if( obj->getRankAura( RANK_AURA_PACE ) != before[ RANK_AURA_PACE ] && obj->getAIUpdateInterface() )
+ obj->getAIUpdateInterface()->refreshVeterancySpeed();
+
+ // a drill aura teaches a unit of a ladder up to its cap, through the one-grade clip; one that
+ // passes its points on (a pilot's sink) learns nothing here
+ const Int drillCap = REAL_TO_INT_FLOOR( obj->getRankAura( RANK_AURA_DRILL ) );
+ const RankLadder *drillLadder = drillCap > 0 ? TheGlobalData->getRankLadder( obj->getTemplate() ) : NULL;
+ ExperienceTracker *tracker = obj->getExperienceTracker();
+ if( drillLadder && !obj->isEffectivelyDead() && tracker->isTrainable() && tracker->getExperienceSink() == INVALID_ID )
{
- Before was;
- was.sight = obj->getRankSightScalar();
- for( Int aura = 0; aura < RANK_AURA_PASSED; ++aura )
- was.aura[ aura ] = obj->getRankAura( (RankAura)aura );
- before.push_back( was );
- obj->clearRankAuras();
+ const Int gain = drillLadder->drillGain( RankLadder::unitValue( obj->getTemplate() ), tracker->getCurrentExperience(),
+ drillCap, TheGlobalData->m_rankDrillRate );
+ if( gain > 0 )
+ tracker->addExperiencePoints( gain, FALSE );
}
+}
+
+static void rankAuraGive( Object *leader )
+{
+ const RankLadder *ladder = TheGlobalData->getRankLadder( leader->getTemplate() );
+ // a leader inside a building, a bunker or a transport leads nobody and spots nothing
+ if( ladder == NULL || leader->isEffectivelyDead() || leader->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION )
+ || leader->getContainedBy() )
+ return;
+ const Int grade = leader->getRankGrade();
+ Real strength[ RANK_AURA_PASSED ], radiusSqr[ RANK_AURA_PASSED ];
+ RankReach reach[ RANK_AURA_PASSED ];
+ Bool gives = FALSE;
+ for( Int aura = 0; aura < RANK_AURA_PASSED; ++aura )
+ {
+ strength[ aura ] = ladder->aura( grade, (RankAura)aura );
+ const Real radius = ladder->auraRadius( grade, (RankAura)aura );
+ radiusSqr[ aura ] = radius * radius;
+ reach[ aura ] = ladder->auraReach( grade, (RankAura)aura );
+ gives = gives || strength[ aura ] > 0.0f;
+ }
+ gives = gives && leader->leadsRankAuras();
+ const Real detect = ladder->perk( grade, RANK_PERK_DETECT );
+ if( !gives && detect <= 0.0f )
+ return;
- for( Object *leader = objList; leader; leader = leader->getNextObject() )
+ const Coord3D *at = leader->getPosition();
+ for( Object *other = TheGameLogic->getFirstObject(); other; other = other->getNextObject() )
{
- const RankLadder *ladder = TheGlobalData->getRankLadder( leader->getTemplate() );
- // a leader inside a building, a bunker or a transport leads nobody and spots nothing
- if( ladder == NULL || leader->isEffectivelyDead() || leader->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION )
- || leader->getContainedBy() )
+ if( other == leader || other->isEffectivelyDead() || other->getContainedBy() )
continue;
- const Int grade = leader->getRankGrade();
- Real strength[ RANK_AURA_PASSED ], radiusSqr[ RANK_AURA_PASSED ];
- RankReach reach[ RANK_AURA_PASSED ];
- Bool gives = FALSE;
- for( Int aura = 0; aura < RANK_AURA_PASSED; ++aura )
+ const Real dx = other->getPosition()->x - at->x, dy = other->getPosition()->y - at->y;
+ const Real distSqr = dx * dx + dy * dy;
+ if( detect > 0.0f && distSqr <= detect * detect && other->getStealth()
+ && other->testStatus( OBJECT_STATUS_STEALTHED ) && leader->getRelationship( other ) == ENEMIES )
{
- strength[ aura ] = ladder->aura( grade, (RankAura)aura );
- const Real radius = ladder->auraRadius( grade, (RankAura)aura );
- radiusSqr[ aura ] = radius * radius;
- reach[ aura ] = ladder->auraReach( grade, (RankAura)aura );
- gives = gives || strength[ aura ] > 0.0f;
- }
- gives = gives && leader->leadsRankAuras();
- const Real detect = ladder->perk( grade, RANK_PERK_DETECT );
- if( !gives && detect <= 0.0f )
- continue;
-
- const Coord3D *at = leader->getPosition();
- for( Object *other = objList; other; other = other->getNextObject() )
- {
- if( other == leader || other->isEffectivelyDead() || other->getContainedBy() )
- continue;
- const Real dx = other->getPosition()->x - at->x, dy = other->getPosition()->y - at->y;
- const Real distSqr = dx * dx + dy * dy;
- if( detect > 0.0f && distSqr <= detect * detect && other->getStealth()
- && other->testStatus( OBJECT_STATUS_STEALTHED ) && leader->getRelationship( other ) == ENEMIES )
+ // a fresh find pings the leader's owner the way StealthDetectorUpdate does, after the tick
+ if( !other->testStatus( OBJECT_STATUS_DETECTED ) && ThePlayerList->getLocalPlayer() == leader->getControllingPlayer() )
{
- // a fresh find pings the leader's owner the way StealthDetectorUpdate does, after the tick
- if( !other->testStatus( OBJECT_STATUS_DETECTED ) && ThePlayerList->getLocalPlayer() == leader->getControllingPlayer() )
+ const Coord3D found = *other->getPosition();
+ const Int playerIndex = leader->getControllingPlayer()->getPlayerIndex();
+ const EvaMessage message = other->getStealth()->getEnemyDetectionEvaEvent();
+ LogicThread::callAfterTick( [found, playerIndex, message]()
{
- const Coord3D found = *other->getPosition();
- const Int playerIndex = leader->getControllingPlayer()->getPlayerIndex();
- const EvaMessage message = other->getStealth()->getEnemyDetectionEvaEvent();
- LogicThread::callAfterTick( [found, playerIndex, message]()
- {
- if( !TheRadar->tryEvent( RADAR_EVENT_STEALTH_DISCOVERED, &found ) )
- return;
- static AudioEventRTS discoveredSound = TheAudio->getMiscAudio()->m_stealthDiscoveredSound;
- discoveredSound.setPlayerIndex( playerIndex );
- TheAudio->addAudioEvent( &discoveredSound );
- TheInGameUI->message( TheGameText->fetch( "MESSAGE:StealthDiscovered" ) );
- if( message != EVA_Invalid && TheEva != NULL )
- TheEva->setShouldPlay( message );
- } );
- }
- other->getStealth()->markAsDetected( LOGICFRAMES_PER_SECOND + 1 );
+ if( !TheRadar->tryEvent( RADAR_EVENT_STEALTH_DISCOVERED, &found ) )
+ return;
+ static AudioEventRTS discoveredSound = TheAudio->getMiscAudio()->m_stealthDiscoveredSound;
+ discoveredSound.setPlayerIndex( playerIndex );
+ TheAudio->addAudioEvent( &discoveredSound );
+ TheInGameUI->message( TheGameText->fetch( "MESSAGE:StealthDiscovered" ) );
+ if( message != EVA_Invalid && TheEva != NULL )
+ TheEva->setShouldPlay( message );
+ } );
}
- if( !gives || leader->getRelationship( other ) != ALLIES )
- continue;
- const Bool structure = other->isKindOf( KINDOF_STRUCTURE ), infantry = other->isKindOf( KINDOF_INFANTRY );
- for( Int aura = 0; aura < RANK_AURA_PASSED; ++aura )
- if( strength[ aura ] > 0.0f && distSqr <= radiusSqr[ aura ]
- && ( structure ? reach[ aura ] == RANK_REACH_STRUCTURES : reach[ aura ] != RANK_REACH_INFANTRY || infantry ) )
- other->raiseRankAura( (RankAura)aura, strength[ aura ] );
+ other->getStealth()->markAsDetected( LOGICFRAMES_PER_SECOND + 1 );
}
- }
-
- // a unit that came into or left a leader's reach logs what it holds now
- size_t index = 0;
- for( Object *obj = objList; obj; obj = obj->getNextObject(), ++index )
- {
- Bool moved = FALSE;
+ if( !gives || leader->getRelationship( other ) != ALLIES )
+ continue;
+ const Bool structure = other->isKindOf( KINDOF_STRUCTURE ), infantry = other->isKindOf( KINDOF_INFANTRY );
for( Int aura = 0; aura < RANK_AURA_PASSED; ++aura )
- moved = moved || obj->getRankAura( (RankAura)aura ) != before[ index ].aura[ aura ];
- if( moved )
- DEBUG_LOG(("RANK AURA frame=%d id=%d template=%s grade=%d rof=%.2f sight=%.2f guard=%.2f range=%.2f"
- " mend=%.4f pace=%.2f drill=%.0f steady=%.2f capture=%.2f spoils=%.2f\n",
- TheGameLogic->getFrame(), obj->getID(), obj->getTemplate()->getName().str(), obj->getRankGrade(),
- obj->getRankAura( RANK_AURA_RATE_OF_FIRE ), obj->getRankAura( RANK_AURA_SIGHT ),
- obj->getRankAura( RANK_AURA_GUARD ), obj->getRankAura( RANK_AURA_RANGE ),
- obj->getRankAura( RANK_AURA_MEND ), obj->getRankAura( RANK_AURA_PACE ), obj->getRankAura( RANK_AURA_DRILL ),
- obj->getRankAura( RANK_AURA_STEADY ), obj->getRankAura( RANK_AURA_CAPTURE ), obj->getRankAura( RANK_AURA_SPOILS )));
- obj->onRankSightChanged( before[ index ].sight );
- if( obj->getRankAura( RANK_AURA_PACE ) != before[ index ].aura[ RANK_AURA_PACE ] && obj->getAIUpdateInterface() )
- obj->getAIUpdateInterface()->refreshVeterancySpeed();
- }
-
- // a drill aura teaches a unit of a ladder up to its cap, through the one-grade clip; one that
- // passes its points on (a pilot's sink) learns nothing here. Apart from the walk above, since a
- // promotion may hand out an upgrade that makes an object.
- for( Object *obj = objList; obj; obj = obj->getNextObject() )
- {
- const Int drillCap = REAL_TO_INT_FLOOR( obj->getRankAura( RANK_AURA_DRILL ) );
- const RankLadder *ladder = drillCap > 0 ? TheGlobalData->getRankLadder( obj->getTemplate() ) : NULL;
- ExperienceTracker *tracker = obj->getExperienceTracker();
- if( ladder && !obj->isEffectivelyDead() && tracker->isTrainable() && tracker->getExperienceSink() == INVALID_ID )
- {
- const Int gain = ladder->drillGain( RankLadder::unitValue( obj->getTemplate() ), tracker->getCurrentExperience(),
- drillCap, TheGlobalData->m_rankDrillRate );
- if( gain > 0 )
- tracker->addExperiencePoints( gain, FALSE );
- }
+ if( strength[ aura ] > 0.0f && distSqr <= radiusSqr[ aura ]
+ && ( structure ? reach[ aura ] == RANK_REACH_STRUCTURES : reach[ aura ] != RANK_REACH_INFANTRY || infantry ) )
+ other->raiseRankAura( (RankAura)aura, strength[ aura ] );
}
}
@@ -4587,41 +4584,33 @@ static void peaceTimeTick( void )
three percent a second a hospital cleared with a flamethrower was whole again before the squad
that cleared it had walked over to it, so taking a building off somebody bought you nothing.
- Once a second, off the same object walk peace time uses. Tech buildings and garrisonable
- structures are the test; KINDOF_CAPTURABLE is not, because it sits on every faction structure
- as well - Black Lotus takes those - and would hand every command center on the map a free
- repair crew. */
-static void neutralBuildingRepairTick( void )
+ Once a second, on the building's turn. Tech buildings and garrisonable structures are the
+ test; KINDOF_CAPTURABLE is not, because it sits on every faction structure as well - Black Lotus
+ takes those - and would hand every command center on the map a free repair crew. */
+static void neutralBuildingRepair( Object *obj )
{
- const UnsignedInt now = TheGameLogic->getFrame();
- if( now % LOGICFRAMES_PER_SECOND != 0 )
- return;
-
const UnsignedInt quietFrames = 10 * LOGICFRAMES_PER_SECOND;
const Real repairFractionPerSecond = 0.0125f;
- for( Object *obj = TheGameLogic->getFirstObject(); obj != NULL; obj = obj->getNextObject() )
- {
- if( !obj->isKindOf( KINDOF_STRUCTURE ) || obj->isEffectivelyDead() )
- continue;
- if( obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )
- continue;
+ if( !obj->isKindOf( KINDOF_STRUCTURE ) || obj->isEffectivelyDead() )
+ return;
+ if( obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )
+ return;
- ContainModuleInterface *contain = obj->getContain();
- const Bool mendsItself = obj->isKindOf( KINDOF_TECH_BUILDING )
- || obj->isKindOf( KINDOF_TECH_BASE_DEFENSE )
- || ( contain != NULL && contain->isGarrisonable() );
- if( !mendsItself )
- continue;
+ ContainModuleInterface *contain = obj->getContain();
+ const Bool mendsItself = obj->isKindOf( KINDOF_TECH_BUILDING )
+ || obj->isKindOf( KINDOF_TECH_BASE_DEFENSE )
+ || ( contain != NULL && contain->isGarrisonable() );
+ if( !mendsItself )
+ return;
- BodyModuleInterface *body = obj->getBodyModule();
- if( body->getHealth() >= body->getMaxHealth() )
- continue;
- if( body->getLastDamageTimestamp() + quietFrames > now )
- continue;
+ BodyModuleInterface *body = obj->getBodyModule();
+ if( body->getHealth() >= body->getMaxHealth() )
+ return;
+ if( body->getLastDamageTimestamp() + quietFrames > TheGameLogic->getFrame() )
+ return;
- obj->attemptHealing( body->getMaxHealth() * repairFractionPerSecond, obj );
- }
+ obj->attemptHealing( body->getMaxHealth() * repairFractionPerSecond, obj );
}
/** A unit that can still take something off a wreck besides the money in it. */
@@ -4712,86 +4701,112 @@ static Bool hasEnemyInSight( Object *obj )
A dozer and a harvester are left alone: both have a job of their own that earns more than the
crate does. An aircraft is left alone too, because a crate cannot be claimed from the air, and
so is anything that dies when it fires - a terrorist is worth more than every crate on the map. */
-static void salvageCrateTick( void )
+static void salvageCrateCall( Object *crate )
{
- const UnsignedInt now = TheGameLogic->getFrame();
- if( now % LOGICFRAMES_PER_SECOND != 0 )
+ const Real SALVAGE_CALL_RADIUS = 150.0f;
+
+ if( !crate->isSalvageCrate() || crate->isDestroyed() )
return;
- const Real SALVAGE_CALL_RADIUS = 150.0f;
+ PartitionFilterAlive alive;
+ PartitionFilterSameMapStatus sameMap( crate );
+ PartitionFilter *filters[] = { &alive, &sameMap, NULL };
+
+ SimpleObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( crate, SALVAGE_CALL_RADIUS,
+ FROM_CENTER_2D, filters, ITER_SORTED_NEAR_TO_FAR );
+ MemoryPoolObjectHolder hold( iter );
- for( Object *crate = TheGameLogic->getFirstObject(); crate != NULL; crate = crate->getNextObject() )
+ Object *collector = NULL;
+ Bool collectorUpgrades = FALSE;
+ Bool collectorIsIdle = FALSE;
+ for( Object *them = iter->first(); them != NULL; them = iter->next() )
{
- if( !crate->isSalvageCrate() || crate->isDestroyed() )
+ if( them->isKindOf( KINDOF_STRUCTURE ) || them->isKindOf( KINDOF_AIRCRAFT ) )
+ continue;
+ if( them->isKindOf( KINDOF_DOZER ) || them->isKindOf( KINDOF_HARVESTER ) )
+ continue;
+ if( them->isContained() || them->isEffectivelyDead() || them->isNeutralControlled() )
+ continue;
+ AIUpdateInterface *ai = them->getAI();
+ if( ai == NULL )
+ continue;
+ const Bool idle = ai->isIdle();
+ if( !idle && !detoursForACrate( ai ) )
+ continue;
+ if( diesUsingItsOwnWeapon( them ) )
continue;
- PartitionFilterAlive alive;
- PartitionFilterSameMapStatus sameMap( crate );
- PartitionFilter *filters[] = { &alive, &sameMap, NULL };
-
- SimpleObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( crate, SALVAGE_CALL_RADIUS,
- FROM_CENTER_2D, filters, ITER_SORTED_NEAR_TO_FAR );
- MemoryPoolObjectHolder hold( iter );
+ const Player *owner = them->getControllingPlayer();
+ if( owner == NULL || crate->getShroudedStatus( owner->getPlayerIndex() ) >= OBJECTSHROUD_FOGGED )
+ continue;
+ // a human's units go where the human sends them; only the computer's are sent for salvage,
+ // and only on an official or random map: in a mission, a Challenge or on a player's own map
+ // the computer plays EA's game, which never went for a crate on its own
+ if( !owner->isForkMapComputer() )
+ continue;
- Object *collector = NULL;
- Bool collectorUpgrades = FALSE;
- Bool collectorIsIdle = FALSE;
- for( Object *them = iter->first(); them != NULL; them = iter->next() )
+ const Bool upgrades = wantsSalvageUpgrade( them );
+ if( collector == NULL || ( upgrades && !collectorUpgrades ) )
{
- if( them->isKindOf( KINDOF_STRUCTURE ) || them->isKindOf( KINDOF_AIRCRAFT ) )
- continue;
- if( them->isKindOf( KINDOF_DOZER ) || them->isKindOf( KINDOF_HARVESTER ) )
- continue;
- if( them->isContained() || them->isEffectivelyDead() || them->isNeutralControlled() )
- continue;
- AIUpdateInterface *ai = them->getAI();
- if( ai == NULL )
- continue;
- const Bool idle = ai->isIdle();
- if( !idle && !detoursForACrate( ai ) )
- continue;
- if( diesUsingItsOwnWeapon( them ) )
- continue;
+ collector = them;
+ collectorUpgrades = upgrades;
+ collectorIsIdle = idle;
+ }
- const Player *owner = them->getControllingPlayer();
- if( owner == NULL || crate->getShroudedStatus( owner->getPlayerIndex() ) >= OBJECTSHROUD_FOGGED )
- continue;
- // a human's units go where the human sends them; only the computer's are sent for salvage,
- // and only on an official or random map: in a mission, a Challenge or on a player's own map
- // the computer plays EA's game, which never went for a crate on its own
- if( !owner->isForkMapComputer() )
- continue;
+ // the iterator runs near to far, so the first one that can be upgraded is the best answer
+ if( collectorUpgrades )
+ break;
+ }
- const Bool upgrades = wantsSalvageUpgrade( them );
- if( collector == NULL || ( upgrades && !collectorUpgrades ) )
- {
- collector = them;
- collectorUpgrades = upgrades;
- collectorIsIdle = idle;
- }
+ if( collector == NULL )
+ return;
- // the iterator runs near to far, so the first one that can be upgraded is the best answer
- if( collectorUpgrades )
- break;
- }
+ if( !collectorIsIdle )
+ {
+ // its own machine picks the moment and puts it back on the order it had
+ collector->getAI()->notifyCrate( crate->getID() );
+ return;
+ }
- if( collector == NULL )
- continue;
+ if( hasEnemyInSight( collector ) )
+ return;
- if( !collectorIsIdle )
- {
- // its own machine picks the moment and puts it back on the order it had
- collector->getAI()->notifyCrate( crate->getID() );
- continue;
- }
+ const Coord3D post = *collector->getPosition();
+ collector->getAI()->aiMoveToPosition( crate->getPosition(), CMD_FROM_AI );
+ collector->getAI()->friend_setSalvageReturnPosition( &post );
+}
- if( hasEnemyInSight( collector ) )
- continue;
+/* The once-a-second work, one object at a time. An object's turn is the frame of the second its ID
+ falls on, never all of them on the frame that divides by sixty: with this pass on one frame, a
+ frame of the second was ten times as likely to run past 13 ms as any other. The count of turns a
+ frame comes out of the object list and nothing else, so every machine and every replay takes the
+ same turns on the same frames. */
+static void oncePerSecondTurn( Object *obj )
+{
+ rankAuraTake( obj );
+ rankAuraGive( obj );
- const Coord3D post = *collector->getPosition();
- collector->getAI()->aiMoveToPosition( crate->getPosition(), CMD_FROM_AI );
- collector->getAI()->friend_setSalvageReturnPosition( &post );
+ // Faction veterancy's self-repair (GLA): a ranked unit that has gone unhurt for the Veterancy
+ // block's SelfRepairDelay heals its side's share of its max health. Healing itself earns it
+ // nothing (Object::scoreTheHeal).
+ // A grade's MEND perk is the same heal at its own rate. A leader's mend aura heals at once, hurt
+ // recently or not, and a unit takes the larger of the two.
+ const UnsignedInt now = TheGameLogic->getFrame();
+ const Real self = MAX( TheGlobalData->getRankStat( obj->getTemplate(), obj->getRankGrade(), RANK_STAT_SELF_REPAIR ),
+ obj->getRankPerk( RANK_PERK_MEND ) );
+ const Real aura = obj->getRankAura( RANK_AURA_MEND );
+ if( ( self > 0.0f || aura > 0.0f ) && !obj->isEffectivelyDead() )
+ {
+ const BodyModuleInterface *body = obj->getBodyModule();
+ const UnsignedInt lastHurt = body->getLastDamageTimestamp();
+ const Bool resting = !( lastHurt <= now && now - lastHurt < TheGlobalData->m_veterancySelfRepairDelay );
+ const Real share = MAX( aura, resting ? self : 0.0f );
+ if( share > 0.0f && body->getHealth() < body->getMaxHealth() )
+ obj->attemptHealing( body->getMaxHealth() * share, obj );
}
+
+ neutralBuildingRepair( obj );
+ salvageCrateCall( obj );
}
/* Tech building respawn, asked for in GitHub #23. In the retail game an oil derrick blown up in
@@ -5039,12 +5054,6 @@ void GameLogic::update( void )
// a vote kick that ran out of time
expireKickVote();
- // and the buildings nobody repairs
- neutralBuildingRepairTick();
-
- // ... and the salvage nobody collects
- salvageCrateTick();
-
// ... and the tech buildings the lobby wants back
techRespawnTick();
@@ -5313,44 +5322,18 @@ void GameLogic::update( void )
{
//Handle disabled statii (and re-enable objects once frame matches)
+ const UnsignedInt turn = m_frame % LOGICFRAMES_PER_SECOND;
for( Object *obj = m_objList; obj; obj = obj->getNextObject() )
{
if( obj->isDisabled() )
{
obj->checkDisabledStatus();
}
+ if( (UnsignedInt)obj->getID() % LOGICFRAMES_PER_SECOND == turn )
+ oncePerSecondTurn( obj );
}
}
- // Faction veterancy's self-repair (GLA): once a second a ranked unit that has gone unhurt for
- // the Veterancy block's SelfRepairDelay heals its side's share of its max health. Healing itself earns it
- // nothing (Object::scoreTheHeal).
- // A grade's MEND perk is the same heal at its own rate. A leader's mend aura heals at once, hurt
- // recently or not, and a unit takes the larger of the two.
- if( m_frame % LOGICFRAMES_PER_SECOND == 0 )
- {
- updateRankAuras( m_objList );
- for( Object *obj = m_objList; obj; obj = obj->getNextObject() )
- {
- const Real self = MAX( TheGlobalData->getRankStat( obj->getTemplate(), obj->getRankGrade(), RANK_STAT_SELF_REPAIR ),
- obj->getRankPerk( RANK_PERK_MEND ) );
- const Real aura = obj->getRankAura( RANK_AURA_MEND );
- if( ( self <= 0.0f && aura <= 0.0f ) || obj->isEffectivelyDead() )
- continue;
- const BodyModuleInterface *body = obj->getBodyModule();
- const UnsignedInt lastHurt = body->getLastDamageTimestamp();
- const Bool resting = !( lastHurt <= m_frame && m_frame - lastHurt < TheGlobalData->m_veterancySelfRepairDelay );
- const Real share = MAX( aura, resting ? self : 0.0f );
- if( share <= 0.0f || body->getHealth() >= body->getMaxHealth() )
- continue;
- obj->attemptHealing( body->getMaxHealth() * share, obj );
- }
- }
-
-
-
-
-
// how long did that take? only a frame that ran over budget is worth a line in the log
tFrameEnd = Clock_Ticks();
{
@@ -6841,9 +6824,11 @@ void GameLogic::loadPostProcess( void )
// climbing higher and higher due to us allocating objects during load (even though
// those objects have their ids overwritten with data from the file. To prevent the
// m_nextObjID from getting un-necessarily high we will set it to the next available
- // id from the objects that are now in the world and actually in use
+ // id from the objects that are now in the world and actually in use, or to the counter
+ // the save held if that is higher: an ID picks the frames an object takes its turns on,
+ // so a loaded game has to hand a new object the ID the game it was saved from would
//
- m_nextObjID = INVALID_ID;
+ m_nextObjID = m_nextObjIDFromSave;
Object *obj;
for( obj = getFirstObject(); obj; obj = obj->getNextObject() )
if( obj->getID() >= m_nextObjID )