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
fix(gameengine): close the races between the logic tick and the render
Olcay Seygan243b346cb941
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h b/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.hindex 9a3e6790b..42c64ad7a 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h@@ -40,8 +40,9 @@ class Player;/*** `-logicthread 0`, the default since v3.3.0's crash reports, runs the tick on the main thread.- * `-logicthread 1` hands every tick to a dedicated thread; outside a network game- * the render draws beside it (phases 3 and 4), reading only the copies taken at the sync point.+ * `-logicthread 1` hands every tick to a dedicated thread; outside a network game the render draws+ * beside it (phases 3 and 4), reading only the copies taken at the sync point, and in one the main+ * thread waits for it (phase 5).* `-logicthread 2` adds jitter to the tick to shake out races.** The census counts calls into the client made from the logic thread, one count per channel@@ -79,6 +80,8 @@ namespace LogicThreadCENSUS_AUDIO_READ, ///< a logic read of the audio device: sound lengths, a track done, a handle still playing (hazard 4, M7)CENSUS_CLIENT_READ, ///< a logic read of other client state: selection, input enabled, camera (hazard 4, M7)CENSUS_ASSET_LOAD, ///< the W3D asset manager loading a model or an animation for a cache logic reads (hazards 5 and 22, M7)+ CENSUS_ASSET_LOAD_IN_WINDOW, ///< the CENSUS_ASSET_LOAD calls made while the render's window is open; noteCensus counts it, never place it+ CENSUS_LIVE_MODEL_LOCK, ///< TickReachesLiveModels: the tick taking g_liveModelLockCENSUS_COUNT};@@ -114,6 +117,8 @@ namespace LogicThreadWINDOW_RADAR_OBJECT, ///< RadarObject::friend_getObject, the radar's list of ObjectsWINDOW_DRAWABLE_FIELD, ///< a drawable's model condition or status bits, which the tick sets beside the render (step 3b); the look is LookForDraw'sWINDOW_PLAYER_STATE, ///< a player's energy, radar, rank or defeat, which the tick changes (step 3b)+ WINDOW_PARTITION_ITERATE, ///< PartitionManager's iterate core (projected shadow receivers), whose iteration flags the tick's scans share+ WINDOW_AUDIO_HANDLE, ///< AudioManager::allocateNewHandle, the truck draws' sounds: a pool the tick draws fromWINDOW_COUNT};@@ -159,16 +164,18 @@ namespace LogicThread* reaches a live model through Drawable::getDrawModulesFlushed, which can set a model's state or* pose its bones. Neither side waits for the other while holding it, so neither can deadlock, and* a bone read lands at the same pose either side of the fork: posing is a function of the model- * and the frame's sync time alone. Recursive, because those reaches nest. */+ * and the frame's sync time alone. Recursive, because those reaches nest. TickReachesLiveModels+ * parks the render (parkRender) before it takes this, so the tick never waits while holding it. */extern std::recursive_mutex g_liveModelLock;- /** The tick's half of g_liveModelLock; nothing on any other thread, where the tick is not running- * beside a fork. */+ /** The tick's half of g_liveModelLock, after parkRender: the flush behind a reach builds render+ * objects, adds them to the scene and loads assets, none of which may run beside the render.+ * Nothing on any other thread, where the tick is not running beside a fork. */class TickReachesLiveModels{public:- TickReachesLiveModels( void ) : m_locked( t_isLogicThread ) { if( m_locked ) g_liveModelLock.lock(); }- ~TickReachesLiveModels( void ) { if( m_locked ) g_liveModelLock.unlock(); }+ TickReachesLiveModels( void );+ ~TickReachesLiveModels( void );private:TickReachesLiveModels( const TickReachesLiveModels & );TickReachesLiveModels &operator=( const TickReachesLiveModels & );@@ -180,6 +187,13 @@ namespace LogicThread* pacer there in a single-player match, whether the pass's first tick is due. */void prepareOverlap( void );+ /** R3, on the logic thread before the tick fills a template's bone caches from the W3D asset manager,+ * whose hash tables and reference counts the render uses unlocked, or reaches a live model+ * (TickReachesLiveModels): a tick running beside the render+ * asks it to close its window and waits until it has, so the rest of the tick runs with the main+ * thread waiting for it (one picture's hitch, once per state). Anywhere else it returns at once. */+ void parkRender( void );+/** W3DDisplay::draw, after the render's own restore (smooth motion): the tick that ran beside the* render is flushed here, as runTick flushes one, and an exception it threw is thrown again. */void flushOverlap( void );@@ -193,10 +207,6 @@ namespace LogicThread/** Read -logicthread and start the thread if it asks for one. Called once, from GameEngine::init. */void init( void );- /** TRUE once init started the thread (-logicthread 1 or 2). Smooth motion stays off then, so the- * render may overlap the tick (W3DDisplay::draw). */- Bool isEnabled( void );-/** Join the thread. Safe without an init(). */void shutdown( void );diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.hindex a12dae2fe..e95a54207 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h@@ -545,8 +545,11 @@ public:UnsignedInt tintStatus;Vector3 tintColor;Vector3 selectionColor;+ Coord3D position;};void takeLookForDraw( void );+ /** Where it stood at the sync point, for the draw's own walks of the drawables: the Thing's cache moves with the tick. */+ const Coord3D *getPositionForDraw( void ) const { return &m_lookForDraw.position; }void colorFlash( const RGBColor *color, UnsignedInt decayFrames = DEF_DECAY_FRAMES, UnsignedInt attackFrames = 0, UnsignedInt sustainAtPeak = FALSE ); ///< flash a drawable in the color specified for a short timevoid colorTint( const RGBColor *color ); ///< tint this drawable the color specifieddiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.hindex c03a00239..e27fd812d 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h@@ -187,6 +187,7 @@ public:Object *findObjectByID( ObjectID id ); ///< Given an ObjectID, return a pointer to the object.Object *getFirstObject( void ); ///< Returns the "first" object in the world. When used with the object method "getNextObject()", all objects in the world can be iterated.ObjectID allocateObjectID( void ); ///< Returns a new unique object id+ void growObjectLookupForTick( void ); ///< LogicThread's sync point: room for the next tick's objects, so it never reallocates the lookup beside the render// super hackvoid startNewGame( Bool loadSaveGame );diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cppindex 73dba6da2..b8c32895b 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp@@ -1429,6 +1429,8 @@ Bool AudioManager::shouldPlayLocally(const AudioEventRTS *audioEvent)//-------------------------------------------------------------------------------------------------AudioHandle AudioManager::allocateNewHandle( void ){+ // the tick mints handles too (addAudioEvent), so a sound the render starts beside it shares the pool+ LOGIC_WINDOW_READ( WINDOW_AUDIO_HANDLE );// note, intenionally a post increment rather than a pre increment.return theAudioHandlePool++;}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cppindex 0550dad8f..18de08f73 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp@@ -76,6 +76,11 @@ namespaceBool s_quitting = FALSE;std::exception_ptr s_error;Real s_tickMS = 0.0f; ///< the tick as the logic thread timed it+ /* R3's park, under s_lock too: the render inside the window beside a tick (set as startOverlap hands+ the tick over, cleared as waitOverlap starts to wait), and the tick asking it to close (parkRender). */+ std::condition_variable s_parkCv;+ Bool s_renderBeside = FALSE;+ Bool s_parkWanted = FALSE;// Written by the logic thread only, read by the main thread after a handoff has published them.Int64 s_census[ LogicThread::CENSUS_COUNT ] = { 0 };@@ -95,7 +100,7 @@ namespaceconst char *const WINDOW_NAMES[ LogicThread::WINDOW_COUNT ] ={"drawableobject", "findobject", "objectlist", "logicframe", "thing", "shroud", "partition",- "terrain", "player", "radarobject", "drawablefield", "playerstate"+ "terrain", "player", "radarobject", "drawablefield", "playerstate", "partitioniterate", "audiohandle"};// step 3b, main thread only: the pass's first tick due and allowed beside the render (prepareOverlap),@@ -131,7 +136,8 @@ namespace"drawable", "modelcondition", "audio", "ingameui", "controlbar", "tacticalview", "radar","fxlist", "terrainvisual", "particles", "gameclient", "eva", "newdrawable", "clientrandom","ghost", "messagestream", "display", "jobs", "ondemandflush", "observerlookat",- "drawablepush", "destroydrawable", "audioread", "clientread", "assetload"+ "drawablepush", "destroydrawable", "audioread", "clientread", "assetload", "assetloadinwindow",+ "livemodellock"};// M5: what the tick asked of the audio, the FX lists and the particle systems, in call order.@@ -283,6 +289,10 @@ namespacevoid LogicThread::noteCensus( Channel channel ){++s_census[ channel ];+ // R3: a load beside the render touches the asset manager and the reference counts the render uses;+ // one with the window closed has the main thread waiting. A stale relaxed read only counts too many.+ if( channel == CENSUS_ASSET_LOAD && g_windowOpen.load( std::memory_order_relaxed ) )+ ++s_census[ CENSUS_ASSET_LOAD_IN_WINDOW ];}//-------------------------------------------------------------------------------------------------@@ -291,6 +301,47 @@ void LogicThread::noteWindow( WindowRead read )s_windowReads[ read ].fetch_add( 1, std::memory_order_relaxed );}+//-------------------------------------------------------------------------------------------------+/* The handshake runs under s_lock, never on g_windowOpen's relaxed stores: the main thread clears+ s_renderBeside in waitOverlap after its last render call, so the lock's release and acquire publish+ everything the render did before the tick goes on, and the main thread then waits for the tick.++ No deadlock. The tick waits only for the main thread to reach waitOverlap, which it does when the+ picture it is drawing ends (closeOrDrawAgain sees s_parkWanted and closes) or at once between+ pictures. Inside the window the main thread waits on nothing of the tick's but g_liveModelLock (the+ shadow pass's pose fork, W3DVolumetricShadow.cpp), released before End_Render, and the tick parks+ before it takes that lock (TickReachesLiveModels), never while it holds it. */+void LogicThread::parkRender( void )+{+ if( !t_isLogicThread )+ return;+ std::unique_lock<std::mutex> lock( s_lock );+ if( !s_renderBeside )+ return;+ s_parkWanted = TRUE;+ s_parkCv.wait( lock, []{ return !s_renderBeside; } );+}++//-------------------------------------------------------------------------------------------------+LogicThread::TickReachesLiveModels::TickReachesLiveModels( void ) : m_locked( t_isLogicThread )+{+ if( !m_locked )+ return;+ noteCensus( CENSUS_LIVE_MODEL_LOCK );+ // the flush behind the reach can build render objects, add them to the scene and load from the asset+ // manager, and the bone read poses the live model: none of it beside the render+ parkRender();+ g_liveModelLock.lock();+}++//-------------------------------------------------------------------------------------------------+LogicThread::TickReachesLiveModels::~TickReachesLiveModels( void )+{+ if( !m_locked )+ return;+ g_liveModelLock.unlock();+}+//-------------------------------------------------------------------------------------------------/* Step 3b: the pass's first tick to the logic thread, at the sync point's end. Everything the renderreads of logic was taken before this (takeReadsForRender), and the client block the tick reads is@@ -301,6 +352,7 @@ static void startOverlap( void )return;captureClientBlock();TheGameClient->setFrame( TheGameLogic->getFrame() );+ TheGameLogic->growObjectLookupForTick();jitter();s_overlapStart = LogicClock::now();// open before the tick wakes, so nothing the main thread does beside it reads as outside the window@@ -308,6 +360,7 @@ static void startOverlap( void ){std::lock_guard<std::mutex> lock( s_lock );s_tickPending = TRUE;+ s_renderBeside = TRUE;}s_wakeCv.notify_one();s_overlapRunning = TRUE;@@ -321,6 +374,10 @@ static void waitOverlap( void )Real tickMS;{std::unique_lock<std::mutex> lock( s_lock );+ // the render is done with the window: a tick parked in parkRender goes on with this thread waiting+ s_renderBeside = FALSE;+ s_parkWanted = FALSE;+ s_parkCv.notify_one();s_doneCv.wait( lock, []{ return s_tickDone; } );s_tickDone = FALSE;error = s_error;@@ -364,7 +421,8 @@ Bool LogicThread::OverlapWindow::closeOrDrawAgain( Real pictureMS )Bool running;{std::lock_guard<std::mutex> lock( s_lock );- running = !s_tickDone;+ // a tick parked in parkRender waits for this window to close+ running = !s_tickDone && !s_parkWanted;}// the plan's rule, wait only once the next tick is due, with the next picture's length taken off// so a picture never holds the next tick up; the last picture stands in for the next one@@ -452,12 +510,6 @@ void LogicThread::init( void )DEBUG_LOG(( "LOGICTHREAD: the tick runs on its own thread, the main thread waiting for it\n" ));}-//--------------------------------------------------------------------------------------------------Bool LogicThread::isEnabled( void )-{- return s_enabled;-}-//-------------------------------------------------------------------------------------------------void LogicThread::shutdown( void ){diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cppindex dd073902a..92acec280 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp@@ -590,6 +590,7 @@ void Drawable::takeLookForDraw( void )look.hasSelectionColor = selection != NULL;if( selection )look.selectionColor = *selection;+ look.position = *getPosition();}//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/PlayerColorScheme.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/PlayerColorScheme.cppindex 6dd0d92f4..9c77ef5ff 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/PlayerColorScheme.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/PlayerColorScheme.cpp@@ -25,6 +25,7 @@#include "Common/GameCommon.h"#include "Common/GlobalData.h"+#include "Common/LogicThread.h"#include "Common/Player.h"#include "Common/PlayerList.h"#include "Common/Team.h"@@ -358,6 +359,12 @@ static void rebuildTable( void )// ------------------------------------------------------------------------------------------------static void ensureTable( void ){+ // only the main thread outside the window builds the table, every pass (GameClient::update) before+ // the draw: the tick reads it beside the render, and a rebuild walks the players' relationships the+ // tick may be changing, so a change the tick made shows one pass later+ if( LogicThread::t_isLogicThread || LogicThread::isInsideWindow() )+ return;+if( TheGlobalData == NULL )return;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cppindex 2f2568016..9121d0dcb 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp@@ -3440,6 +3440,9 @@ Object *PartitionManager::getClosestObjects(){//USE_PERF_TIMER(getClosestObjects)+ // theIterFlag and each module's done flag below are shared by every scan; one from the render+ // beside a tick lets the tick's own scan skip an object, so a different target and a desync+ LOGIC_WINDOW_READ( WINDOW_PARTITION_ITERATE );#ifdef DUMP_PERF_STATSif (TheGameLogic->getFrame() != s_gcoPerfFrame)diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cppindex 4b3f670a6..0e75ea30b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp@@ -5433,6 +5433,18 @@ void GameLogic::addObjectToLookupTable( Object *obj )} // end addObjectToLookupTable+// ------------------------------------------------------------------------------------------------+/** A tick beside the render (LogicThread's startOverlap) makes its objects in room grown here, at the+ sync point, so addObjectToLookupTable does not reallocate m_objVector under a reader on the main+ thread. Nothing observes the size past findObjectByID's bound, where a missing slot and a NULL one+ answer alike. ponytail: a tick making more than 4096 objects still grows it in place. */+// ------------------------------------------------------------------------------------------------+void GameLogic::growObjectLookupForTick( void )+{+ while( (UnsignedInt)m_nextObjID + 4096 >= m_objVector.size() )+ m_objVector.resize( m_objVector.size() * 2, NULL );+}+// ------------------------------------------------------------------------------------------------/** Remove object from the ID lookup table */// ------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cppindex 4e3c0cf32..f7e9ca0b2 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cpp@@ -62,11 +62,12 @@//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")#endif-#if defined(DEBUG_CRC)-Int NET_CRC_INTERVAL = 1;-#else-Int NET_CRC_INTERVAL = 100;-#endif+/* How many logic frames apart a network game checks the world CRC; the host's value travels in the+ lobby string, so the room runs on the host's. Release has DEBUG_CRC on, where EA's 1 meant a full+ getCRC every frame, about 1.6 ms of a late-game tick. At 10 a split is still caught within a sixth+ of a second, and the 32-slot CRCSnapshotRing then reaches 320 frames back, past any+ run-ahead. -NetCRCInterval 1 for a desync hunt. */+Int NET_CRC_INTERVAL = 10;// DEFINES ////////////////////////////////////////////////////////////////////diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.hindex 5bf29ff17..e42c66efd 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h@@ -201,6 +201,7 @@ public:Bool updateTreePosition(DrawableID id, Coord3D location, Real angle);void stepTrees(void); ///< W3DTreeBuffer::stepTrees, at the render's sync pointvoid takeWaypointsForRender(void); ///< W3DWaypointBuffer::takeReadsForRender, at the render's sync point+ void takePropShroudForRender(void); ///< W3DPropBuffer::takeShroudForRender, at the render's sync pointvoid renderTrees(CameraClass * camera); ///< renders the tree buffer.Int renderTreeShadowCasters(RenderInfoClass &sunInfo, CameraClass *sceneCamera, const SunShadowCasterCull &cull); ///< the trees drawn into the sun's map, counteddiff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.hindex e43fb9a75..f4459f66f 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.h@@ -111,6 +111,7 @@ public:Bool updatePropPosition(Int id, const Coord3D &location, Real angle, Real scale);/// Let us know that the shroud has changed.void notifyShroudChanged(void);+ void takeShroudForRender(void); ///< the render's sync pointvoid removePropsForConstruction(const Coord3D* pos,diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cppindex baad9ed6e..0eb2d2479 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp@@ -2106,6 +2106,11 @@ void BaseHeightMapRenderObjClass::takeWaypointsForRender(void)m_waypointBuffer->takeReadsForRender();}+void BaseHeightMapRenderObjClass::takePropShroudForRender(void)+{+ m_propBuffer->takeShroudForRender();+}+//=============================================================================Bool BaseHeightMapRenderObjClass::updateTreePosition(DrawableID id, Coord3D location, Real angle){diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cppindex 543f8d94b..bbbee4e28 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp@@ -390,6 +390,8 @@ HAnimClass* W3DAnimationInfo::getAnimHandle() constm_handle->Add_Ref();return m_handle;#else+ LogicThread::parkRender();+ LOGIC_CENSUS( CENSUS_ASSET_LOAD );HAnimClass* handle = W3DDisplay::m_assetManager->Get_HAnim(m_name.str());DEBUG_ASSERTCRASH(handle, ("*** ASSET ERROR: animation %s not found\n",m_name.str()));if (handle != NULL && m_naturalDurationInMsec < 0)@@ -622,13 +624,14 @@ void ModelConditionInfo::validateCachedBones(RenderObjClass* robj, Real scale) cif (m_validStuff & PRISTINE_BONES_VALID)return;+ // the render's call leaves the cache alone: the flag is already clear, so the map is not read, and+ // beside a tick clearing it here raced the tick's fillif (!isValidTimeToCalcLogicStuff())- {- m_pristineBones.clear();- m_validStuff &= ~PRISTINE_BONES_VALID;return;- }+ // R3: this cache and the asset manager below are the render's too, so a tick beside it parks it+ // before it writes either+ LogicThread::parkRender();setFPMode();BONEPOS_LOG(("Validating bones for %s: %s", m_modelName.str(), getDescription().str()));@@ -756,6 +759,8 @@ void ModelConditionInfo::validateWeaponBarrelInfo() constreturn;}+ // R3: a state the render switches to inside the window reads these+ LogicThread::parkRender();setFPMode();for (int wslot = 0; wslot < WEAPONSLOT_COUNT; ++wslot)@@ -900,12 +905,19 @@ void ModelConditionInfo::validateTurretInfo() constif (m_validStuff & TURRETS_VALID)return;+ // the render's call leaves the bones alone: they are 0 until the flag is set, and beside a tick+ // zeroing them here wiped the bones the tick had just found+ if (!isValidTimeToCalcLogicStuff())+ return;++ // R3: as validateWeaponBarrelInfo+ LogicThread::parkRender();setFPMode();for (int tslot = 0; tslot < MAX_TURRETS; ++tslot){TurretInfo& tur = m_turrets[tslot];- if (!isValidTimeToCalcLogicStuff() || m_modelName.isEmpty())+ if (m_modelName.isEmpty()){tur.m_turretAngleBone = 0;tur.m_turretPitchBone = 0;@@ -939,11 +951,8 @@ void ModelConditionInfo::validateTurretInfo() const}}- if (isValidTimeToCalcLogicStuff())- {- m_validStuff |= TURRETS_VALID;- }-}+ m_validStuff |= TURRETS_VALID;+}//-------------------------------------------------------------------------------------------------const Matrix3D* ModelConditionInfo::findPristineBone(NameKeyType boneName, Int* boneIndex) const@@ -3475,7 +3484,7 @@ void W3DModelDraw::lightHeadlights(const Vector3& cameraPosition)for (size_t i = 0; i < s_headlightQueue.size(); ++i){W3DModelDraw* draw = s_headlightQueue[i];- const Coord3D* pos = draw->getDrawable()->getPosition();+ const Coord3D* pos = draw->getDrawable()->getPositionForDraw();const Real dx = pos->x - cameraPosition.X, dy = pos->y - cameraPosition.Y, dz = pos->z - cameraPosition.Z;nearest.push_back(std::make_pair(dx * dx + dy * dy + dz * dz, draw));}@@ -3700,6 +3709,7 @@ void W3DModelDraw::setModelState(const ModelConditionInfo* newState){const W3DModelDrawModuleData* data = getW3DModelDrawModuleData();Bool swapsTexture = !data->m_replaceTextureOld.isEmpty();+ LOGIC_CENSUS( CENSUS_ASSET_LOAD );m_renderObject = W3DDisplay::m_assetManager->Create_Render_Obj(newState->m_modelName.str(), draw->getScale(), m_hexColor,swapsTexture ? data->m_replaceTextureOld.str() : NULL, swapsTexture ? data->m_replaceTextureNew.str() : NULL);DEBUG_ASSERTCRASH(m_renderObject, ("*** ASSET ERROR: Model %s not found!\n",newState->m_modelName.str()));diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cppindex 16f46b3db..7b54a91b3 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp@@ -50,6 +50,7 @@#include "W3DDevice/GameClient/HeightMap.h"#include "d3dx9math.h"#include "Common/GlobalData.h"+#include "Common/LogicThread.h"#include "W3DDevice/GameClient/W3DProjectedShadow.h"#include "WW3D2/statistics.h"#include "Common/Debug.h"@@ -1552,6 +1553,15 @@ Int W3DProjectedShadowManager::renderShadows(RenderInfoClass & rinfo)projectionCount++;projector->Peek_Material_Pass()->UnInstall_Materials();+ /* The objects the shadow falls on come from the partition, whose scans share iteration flags+ with the tick's (a desync) and whose modules the tick frees beside the render. The window+ is open for every picture at every -logicthread setting, so the shadow falls on the+ terrain alone and every setting draws the same picture.+ ponytail: receivers lost for mods with SHADOW_PROJECTION (the fork's INI has none); the+ upgrade is the receivers gathered at W3DDisplay's takeReadsForRender. */+ if (LogicThread::isInsideWindow())+ continue;+SimpleObjectIterator *iter;Object *obj;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex e4275aed7..38ac4068a 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -2206,9 +2206,13 @@ extern UnsignedInt TheSceneDrawCalls;// R1, smooth motion (W3DSmoothMotion.h). Three steps around the scene's render, and only the picture:// smoothMotionBegin before updateViews: the blend's alpha, and on a new tick each drawable's position// (the camera's lock follows the blended one)-// smoothMotionApply after the particles, before the render targets and the scene: on a new tick each-// model's transform is captured, then every model is shown blended+// smoothMotionApply after the particles and the sync point, before the overlap window opens: on a new+// tick each model's transform is captured, then every model is shown blended// smoothMotionRestore after the render loop: the logic transforms go back before picking and the logic+// A tick reads live bones (ParticleUplinkCannonUpdate), so it never runs beside a blend: a picture that holds+// one keeps its tick serial. A picture with a tick beside it shows the state before that tick, which was due+// when it was handed over, so it is a whole tick behind and blends nothing anyway; the pictures drawn again+// beside it (phase 4) show the logic transforms as they stand.//=============================================================================bool TheSmoothMotionActive = false;float TheSmoothMotionAlpha = 1.0f;@@ -2216,6 +2220,8 @@ static UnsignedInt s_smoothPositionFrame = 0xFFFFFFFFu;static UnsignedInt s_smoothModelFrame = 0xFFFFFFFFu;static Bool s_smoothApplied = FALSE;static Bool s_smoothBehind = FALSE; // this picture is a whole tick or more behind: nothing captured or blended+static Bool s_pacingNoted = FALSE; // ZH_SMOOTH_MOTION_STATS samples this pass's pictures, of s_pacingFrame+static UnsignedInt s_pacingFrame = 0;/* Smooth motion's default: a blend only on a display that refreshes faster than the logic ticks. At 60 Hzevery refresh shows a new tick already, and the blend would only draw each one a tick late. The@@ -2290,13 +2296,12 @@ static void notePacing(UnsignedInt frame)static void smoothMotionBegin(){- // on a display faster than the logic, unless -nosmoothmotion says no or the logic thread wants the- // render beside its tick; -recordfps's pictures between two logic frames always blend, from the frame- // before the first so that one is captured+ // on a display faster than the logic, unless -nosmoothmotion says no, at every -logicthread setting;+ // -recordfps's pictures between two logic frames always blend, from the frame before the first so that+ // one is capturedconst Bool video = GameEngine_videoBlends();TheSmoothMotionActive = !TheGlobalData->m_headless- && ((TheGlobalData->m_smoothMotion && !LogicThread::isEnabled()- && (TheGlobalData->m_smoothMotionAnyDisplay || displayOutpacesLogic()))+ && ((TheGlobalData->m_smoothMotion && (TheGlobalData->m_smoothMotionAnyDisplay || displayOutpacesLogic()))|| video);TheSmoothMotionAlpha = TheSmoothMotionActive ? GameEngine_logicTickFraction() : 1.0f;// A picture a whole tick or more behind the battle shows every model at its logic transform, so it@@ -2306,8 +2311,10 @@ static void smoothMotionBegin()// an alpha of 1, and the frame before the first blended one has to be captured.s_smoothBehind = TheSmoothMotionAlpha >= 1.0f && !video;static const Bool stats = getenv("ZH_SMOOTH_MOTION_STATS") != NULL;- if (stats && TheGameLogic->isInGame() && !TheGameLogic->isInShellGame() && !TheGameLogic->isGamePaused())- notePacing(TheGameClient->getFrame());+ s_pacingNoted = stats && TheGameLogic->isInGame() && !TheGameLogic->isInShellGame() && !TheGameLogic->isGamePaused();+ s_pacingFrame = TheGameClient->getFrame();+ if (s_pacingNoted)+ notePacing(s_pacingFrame);if (!TheSmoothMotionActive || s_smoothBehind)return;const UnsignedInt frame = TheGameClient->getFrame();@@ -2375,6 +2382,18 @@ static void smoothMotionApply()s_smoothPassTicks += Clock_Ticks() - passStart;}+/* Phase 4's picture drawn again beside the tick. Only a pass with no blend held hands its tick over, so+ this picture, like the pass's first, is a whole tick behind and shows the logic transforms; it touches+ no drawable and no logic, and is only counted, for the cost and pacing figures. */+static void smoothMotionDrawAgain()+{+ DEBUG_ASSERTCRASH(!s_smoothApplied, ("smooth motion: a blend held beside a tick"));+ if (s_pacingNoted)+ notePacing(s_pacingFrame);+ if (TheSmoothMotionActive)+ ++s_smoothPasses;+}+static void smoothMotionRestore(){if (!s_smoothApplied)@@ -2442,6 +2461,10 @@ static void takeReadsForRender( Bool renders )static_cast<W3DView *>( view )->recordPostDraw();TheInGameUI->recordDraw();TheTerrainRenderObject->takeWaypointsForRender();+ // never the load screen's: no tick runs beside it, and with the shroud off nothing wipes what it would+ // read before the partition's first update+ if( !TheGlobalData->m_loadScreenRender )+ TheTerrainRenderObject->takePropShroudForRender();TheTerrainRenderObject->stepTrees(); // before the particles: a falling tree's FX makes systems#if ZH_MODERN_WATERif (TheWaterRenderObj) TheWaterRenderObj->takeReadsForRender();@@ -2722,6 +2745,7 @@ AGAIN:now = Clock_Milliseconds(); // the letterbox's fade runs on itTheLookAtTranslator->scrollView();primaryW3DView->updateCameraBesideTick();+ smoothMotionDrawAgain();#ifdef DEBUG_LOGGINGtOverlapStart = Clock_Ticks();#endif@@ -2749,6 +2773,9 @@ AGAIN:TheParticleUpdateMS = w3dElapsedMS( tParticleStart, tParticleEnd );#endiftakeReadsForRender( rendersThisPass() );+ // R1: after the particles read the logic bones (Lorenzen's note above) and the sync point+ // flushed the models' conditions, before anything renders and before a tick may start+ smoothMotionApply();pictureStart = Clock_Ticks();#ifdef DEBUG_LOGGINGtOverlapStart = Clock_Ticks();@@ -2756,11 +2783,13 @@ AGAIN:// a draw from inside a tick (the load screen the map start paints) is the tick's own. The// tick runs beside a render that reads logic only through the sync point's copies, which// rules out the scripted camera's loop of renders, the debug overlays and displays that walk- // the objects live, -cinema's own interface, smooth motion's restore and the load screen.+ // the objects live, -cinema's own interface, a blend on the models (the tick reads live+ // bones) and the load screen.if( !TheGameLogic->isInGameLogicUpdate() ){- Bool mayOverlap = !loopForCameraMovement && rendersThisPass() && !TheSmoothMotionActive+ Bool mayOverlap = !loopForCameraMovement && rendersThisPass() && !s_smoothApplied&& m_debugDisplayCallback == NULL && !TheGlobalData->m_loadScreenRender+ && !TheGlobalData->m_breakTheMovie && !TheGlobalData->m_disableRender // takeReadsForRender took nothing&& !TheGlobalData->m_showLanes && !CinemaDirector_hidesHud()&& TheObserverCamera.getDrawnPaneCount() <= 1;#if defined(_DEBUG) || defined(_INTERNAL)@@ -2773,9 +2802,6 @@ AGAIN:}}- // R1: after the particles read the logic bones (Lorenzen's note above), before anything renders.- smoothMotionApply();-// After the smooth motion, so a lamp's light sits where its model is drawn this frame.if (primaryW3DView && primaryW3DView->get3DCamera())W3DModelDraw::lightHeadlights(primaryW3DView->get3DCamera()->Get_Position());diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DGameClient.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DGameClient.cppindex 180033c68..256c67114 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DGameClient.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DGameClient.cpp@@ -49,6 +49,8 @@#include "GameClient/GameClient.h"#include "GameClient/ParticleSys.h"#include "GameClient/RayEffect.h"+#include "GameLogic/GameLogic.h"+#include "GameLogic/Object.h"#include "W3DDevice/GameClient/W3DAssetManager.h"#include "W3DDevice/GameClient/W3DGameClient.h"#include "W3DDevice/GameClient/W3DStatusCircle.h"@@ -229,6 +231,14 @@ void W3DGameClient::adjustLOD( Int adj )//-------------------------------------------------------------------------------------------------void W3DGameClient::notifyTerrainObjectMoved(Object *obj){+ // LOGIC-THREAD.md: drawTrees reads the trees beside the tick, so a push or a topple waits for its+ // end and takes the unit as it stands then. A unit the tick destroyed pushes nothing.+ const ObjectID id = obj->getID();+ LOGIC_AFTER_TICK( [this, id]() {+ Object *mover = TheGameLogic->findObjectByID( id );+ if( mover )+ notifyTerrainObjectMoved( mover );+ } );if (TheTerrainRenderObject) {TheTerrainRenderObject->unitMoved(obj);}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cppindex b07cbb485..c1b9cf7ae 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp@@ -47,6 +47,7 @@#include "WW3D2/dx11runtime.h"#include "Platform/SunShadow.h"#include "Common/JobSystem.h"+#include "Common/LogicThread.h"#include "GameLogic/GameLogic.h"#include "GameLogic/Object.h"#include "GameLogic/Module/LifetimeUpdate.h"@@ -1878,13 +1879,15 @@ void W3DParticleSystemManager::takeReadsForRender( void )/** The systems a pass draws from, walked again only when a particle update or anything else that* adds or takes away a system or a particle has run since the last walk. A system with no- * particles draws nothing and one the local player cannot see is skipped, so neither is kept. */+ * particles draws nothing and one the local player cannot see is skipped, so neither is kept.+ * Inside the window a new id means no walk: a system made there is filed when the window closes,+ * so the walk would find what the sync point found, by way of the objects the tick is deleting. */void W3DParticleSystemManager::refreshFrameView( void ){const UnsignedInt logicFrame = TheGameLogic->getFrame();if (m_frameViewValid && m_frameViewLogicFrame == logicFrame && m_frameViewFrame == m_lastLogicFrameUpdate&& m_frameViewParticles == m_particleCount && m_frameViewSystems == m_particleSystemCount- && m_frameViewNextID == m_uniqueSystemID)+ && (m_frameViewNextID == m_uniqueSystemID || LogicThread::isInsideWindow()))return;m_frameView.clear();diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cppindex 02ce5683a..cc69a2e4c 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp@@ -326,6 +326,17 @@ void W3DPropBuffer::notifyShroudChanged()}}+/** LOGIC-THREAD.md phase 3: what the shroud change wiped is read again at the sync point, since a+ * pass inside the window finds the cells being written by the tick beside it. */+void W3DPropBuffer::takeShroudForRender()+{+ const Int localPlayerIndex = TheObserverCamera.getShroudPlayerIndex();+ for (Int i=0; i<m_numProps; i++) {+ if (m_props[i].ss == OBJECTSHROUD_INVALID)+ m_props[i].ss = ThePartitionManager->getPropShroudStatusForPlayer(localPlayerIndex, &m_props[i].location);+ }+}+DECLARE_PERF_TIMER(Prop_Render)