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
refactor(gameclient): play a tick's sounds, fx and particle systems after it
Olcay Seyganbe495bc0d7cf
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h b/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.hindex a04806aa6..6a0603806 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h@@ -332,7 +332,15 @@ class AudioManager : public SubsystemInterfacevirtual void removeLevelSpecificAudioEventInfos( void );void removeAllAudioRequests( void );-++ /** What addAudioEvent and removeAudioEvent do on the main thread. A sound a tick plays gets its+ * handle at the call and comes here after the tick with it (LOGIC-THREAD.md M5); 0 mints one. */+ AudioHandle addAudioEventNow( const AudioEventRTS *eventToAdd, AudioHandle handle );+ void removeAudioEventNow( AudioHandle audioEvent );++ /// a handle a tick minted for a sound still waiting for the end of the tick counts as playing+ Bool isQueuedFromTick( AudioHandle handle ) const;+protected:AudioSettings *m_audioSettings;MiscAudio *m_miscAudio;@@ -346,6 +354,7 @@ class AudioManager : public SubsystemInterfaceAudioEventInfoHash m_allAudioEventInfo;std::vector< std::pair<AudioEventInfo *, AudioEventInfo *> > m_beforeMapOverrides; ///< live event, its copy from before the mapAudioHandle theAudioHandlePool;+ std::vector<AudioHandle> m_handlesQueuedFromTick; ///< minted by addAudioEvent inside a tick, not yet addedstd::list<std::pair<AsciiString, Real> > m_adjustedVolumes;Real m_musicVolume;diff --git a/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h b/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.hindex 1f3bb9f53..737304aa1 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h@@ -29,6 +29,8 @@#include "Lib/BaseType.h"+#include <functional>+/*** `-logicthread 0` (the default) runs the tick on the main thread, as it always ran.* `-logicthread 1` hands every tick to a dedicated thread and waits for it: nothing overlaps@@ -66,6 +68,7 @@ namespace LogicThreadCENSUS_OBSERVER_LOOKAT, ///< ControlBar::getObserverLookAtPlayer, a logic read of client state (M7)CENSUS_DRAWABLE_PUSH, ///< Drawable::doClientWork run inside the tick: hidden, colour, decal, shadows, sub-objects, ambient sound, captionCENSUS_DESTROY_DRAWABLE, ///< a drawable deleted: draw modules, render objects, shadows (M4: after the tick for one logic destroyed)+ CENSUS_AUDIO_READ, ///< a logic read of the audio device: sound lengths, a track done, a handle still playing (hazard 4, M7)CENSUS_COUNT};@@ -97,6 +100,19 @@ namespace LogicThread/** The census and the handoff cost, as HEADLESS LOGICTHREAD lines. */void report( void );+ /** LOGIC-THREAD.md phase 2, M5. The effects a tick asks of the client (sounds, FX lists, particle+ * systems) wait in one queue, in the order the tick asked for them, and runTick runs them on the+ * main thread after the drawables' deferred work, so every drawable they attach to has its render+ * objects. Keyed on isInGameLogicUpdate past the map load, like the drawables, so -logicthread 0+ * and 1 run one path. */+ Bool defersEffects( void );++ /** Inside a tick, queue `call` for after it; anywhere else, run it now. */+ void callAfterTick( const std::function<void()>& call );++ /** The tick cleared the game: what it queued has no game left to play in. GameEngine::reset. */+ void discardEffects( void );+} // namespace LogicThread#define LOGIC_CENSUS( channel ) LogicThread::census( LogicThread::channel )diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/FXList.h b/GeneralsMD/Code/GameEngine/Include/GameClient/FXList.hindex 8fa18983c..deea7b96a 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/FXList.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/FXList.h@@ -34,16 +34,39 @@// INCLUDES ///////////////////////////////////////////////////////////////////////////////////////#include "Common/GameMemory.h"+#include "Common/GameType.h"#include "Common/NameKeyGenerator.h"#include "Common/STLTypedefs.h"+#include "WWMath/matrix3d.h"// FORWARD REFERENCES /////////////////////////////////////////////////////////////////////////////+class Drawable;class FXNugget;class FXList;class FXListStore;class INI;class Object;-class Matrix3D;++//-------------------------------------------------------------------------------------------------+/**+ What an FX nugget reads of an object, taken when the FX was asked for. An FX logic plays inside+ a tick runs after the tick (LOGIC-THREAD.md phase 2, M5), when the object may have moved on or+ been destroyed; it plays where and as the object stood at the call.+*/+struct FXObjectView+{+ ObjectID id;+ Coord3D position;+ Matrix3D transform;+ Int playerIndex; ///< of the controlling player, -1 without one+ Real boundingCircleRadius;+ /// the object answers clear for every player: always visible, or out of the partition (garrisoned)+ Bool alwaysClear;+ /// for the bones an FX reads; a drawable the tick destroyed is deleted only after the tick's FX ran+ const Drawable *drawable;++ void take( const Object *obj );+};//-------------------------------------------------------------------------------------------------/**@@ -88,11 +111,11 @@ public:the object-based version... by default, just call the location-based implementation.Note that primary and/or secondary can be null, so you must check for this.*/- virtual void doFXObj(const Object* primary, const Object* secondary = NULL) const;+ virtual void doFXObj(const FXObjectView* primary, const FXObjectView* secondary = NULL) const;private:-};+};EMPTY_DTOR(FXNugget)//-------------------------------------------------------------------------------------------------@@ -185,6 +208,10 @@ protected:private:+ /// what the two above do, at once outside a tick and after it for one a tick asked for+ void doFXPosNow(const Coord3D *primary, const Matrix3D* primaryMtx, const Real primarySpeed, const Coord3D *secondary, const Real overrideRadius) const;+ void doFXObjNow(const FXObjectView* primary, const FXObjectView* secondary, const Object* primaryObject) const;+typedef std::list< FXNugget* > FXNuggetList;FXNuggetList m_nuggets;diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.hindex 2115afc1f..f14c20256 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h@@ -44,6 +44,7 @@#include "WWMath/matrix3d.h" ///< @todo Replace with our own matrix library#include "Common/STLTypedefs.h"+#include <functional>#include <vector>@@ -684,6 +685,14 @@ public:void attachToDrawable( const Drawable *draw ); ///< attach this particle system to a Drawablevoid attachToObject( const Object *obj ); ///< attach this particle system to an Object+ void attachToObjectID( ObjectID id ) { m_attachedToObjectID = id; } ///< the same, for an object that may be gone already++ /** LOGIC-THREAD.md phase 2, M5. A system made inside a tick is a shell until the end of the tick:+ * its ID and everything copied from the template, so logic can place it, attach it, stop it and+ * keep its ID. The client stream's draws, the slave, the manager's list and the DebrisTrails+ * option wait for this, which the constructor runs at once outside a tick. */+ void buildClientPart( Bool createSlaves );+ Bool isShell( void ) const { return m_isShell; }virtual Bool update( Int localPlayerIndex ); ///< update this particle system, return false if dead@@ -717,7 +726,7 @@ public:/// Force a burst of particles to be emitted immediately.void trigger (void) { m_burstDelayLeft = 0; m_delayLeft = 0;}- void setInitialDelay( UnsignedInt delay ) { m_delayLeft = delay; }+ void setInitialDelay( UnsignedInt delay ) { m_delayLeft = delay; m_initialDelaySet = TRUE; }/// the name of the particles; a reference, as the renderer asks it of every system several times/// a frame and a copy is an atomic increment and decrement each@@ -887,6 +896,8 @@ protected:Bool m_isFirstPos; ///< true if this system hasn't been drawn before.Bool m_isSaveable; ///< true if this system should be saved/loadedBool m_skipParentXfrm; ///< true if this system is already in world space.+ Bool m_isShell; ///< made inside a tick and not yet built (buildClientPart)+ Bool m_initialDelaySet; ///< setInitialDelay was called, so the build keeps it over the template's// the actual particle system data is inherited from ParticleSystemInfo@@ -943,6 +954,10 @@ public:/// destroy the particle system with the given id (if it still exists)void destroyParticleSystemByID(ParticleSystemID id);+ /** Run work on the system with this id if it exists: at once outside a tick, after it for a call+ * from one (LOGIC-THREAD.md M5), where logic may not reach a live system. */+ void withSystem( ParticleSystemID id, const std::function<void( ParticleSystem * )> &work );+/// return iterators to the particle system templateTemplateMap::iterator beginParticleSystemTemplate() { return m_templateMap.begin(); }TemplateMap::iterator endParticleSystemTemplate() { return m_templateMap.end(); }@@ -977,6 +992,8 @@ public:// A restored system reads its saved id after the constructor has already filed it under the// fresh one, so it tells the manager to re-file it.void friend_renumberParticleSystem( ParticleSystem *particleSystem, ParticleSystemID oldID );+ /// a system a tick made waits here for its build after the tick (ParticleSystem::buildClientPart)+ void friend_addShell( ParticleSystem *shell, Bool createSlaves );protected:@@ -1001,6 +1018,7 @@ protected:UnsignedInt m_lastLogicFrameUpdate;Int m_localPlayerIndex; ///<used to tell particle systems which particles can be skipped due to player shroud statusstd::vector<ParticleSystem *> m_independentUpdates; ///< this update's systems whose particles go to the job pool; kept so it does not reallocate+ std::vector<ParticleSystem *> m_shells; ///< made inside this tick, built after it; reset() deletes any a cleared game leftprivate:TemplateMap m_templateMap; ///< a hash map of all particle system templatesdiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/LogicRandomValue.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/LogicRandomValue.hindex 26430b0e0..2305a2b9e 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/LogicRandomValue.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/LogicRandomValue.h@@ -46,6 +46,11 @@ extern Real GetGameLogicRandomValueReal( Real lo, Real hi, char *file, int lineextern Int GetGameLogicRandomValueUnchanged( int lo, int hi );extern Real GetGameLogicRandomValueRealUnchanged( Real lo, Real hi );+// A copy of the logic seed, and a copy the two reads above use instead of the live seed until it is+// unpinned with NULL. For a sound a tick plays and the main thread builds after it (LOGIC-THREAD.md M5).+extern void CopyGameLogicSeed( UnsignedInt seed[6] );+extern void PinGameLogicSeedForUnchanged( const UnsignedInt *seed );+// use these macros to access the random value functions#define GameLogicRandomValue( lo, hi ) GetGameLogicRandomValue( lo, hi, __FILE__, __LINE__ )#define GameLogicRandomValueReal( lo, hi ) GetGameLogicRandomValueReal( lo, hi, __FILE__, __LINE__ )diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cppindex d463c3854..6293a2d70 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp@@ -58,6 +58,10 @@#include "Common/FileSystem.h"#include "Common/GameEngine.h"#include "Common/GameMusic.h"+#include "GameLogic/LogicRandomValue.h"++#include <algorithm>+#include <array>#include "Common/GameSounds.h"#include "Common/GlobalData.h"#include "Common/MiscAudio.h"@@ -323,6 +327,7 @@ void AudioManager::reset()m_speechVolume = m_systemSpeechVolume;m_disallowSpeech = FALSE;+ m_handlesQueuedFromTick.clear();}//-------------------------------------------------------------------------------------------------@@ -429,11 +434,71 @@ void AudioManager::getInfoForAudioEvent( const AudioEventRTS *eventToFindAndFill//-------------------------------------------------------------------------------------------------AudioHandle AudioManager::addAudioEvent(const AudioEventRTS *eventToAdd){- LOGIC_CENSUS( CENSUS_AUDIO );if (eventToAdd->getEventName().isEmpty() || eventToAdd->getEventName() == AsciiString("NoSound")) {return AHSV_NoSound;}+ if (!LogicThread::defersEffects()) {+ return addAudioEventNow(eventToAdd, 0);+ }++ /* LOGIC-THREAD.md phase 2, M5. Inside a tick the sound gets its handle here, so logic can keep it+ and stop the sound later, and everything else waits for the end of the tick: the options, the+ local player, the request list and the audio stream's draws, which then come in the order the+ tick played its sounds. The handle is minted whether or not this machine will play the sound;+ which handles exist was never the same on two machines, so nothing logic keeps depends on it. */+ if (!eventToAdd->getAudioEventInfo()) {+ getInfoForAudioEvent(eventToAdd);+ if (!eventToAdd->getAudioEventInfo()) {+ DEBUG_CRASH(("No info for requested audio event '%s'\n", eventToAdd->getEventName().str()));+ return AHSV_Error;+ }+ }++ const AudioHandle handle = allocateNewHandle();+ m_handlesQueuedFromTick.push_back(handle);+ AudioEventRTS copy(*eventToAdd);++ // A list played in order steps on from the index the caller's event holds; the build writes the+ // step into its own copy, so the caller's event takes it here. A random list remembers its last+ // pick to avoid playing it twice running, and that pick is made after the tick, too late for the+ // caller's event: a looping random sound logic restarts can repeat a variant now.+ const AudioEventInfo *info = eventToAdd->getAudioEventInfo();+ if (info->m_soundType != AT_Music && info->m_soundType != AT_Streaming+ && !info->m_sounds.empty() && !BitTest(info->m_control, AC_RANDOM)) {+ AudioEventRTS *caller = const_cast<AudioEventRTS*>(eventToAdd);+ caller->setPlayingAudioIndex(caller->getPlayingAudioIndex() + 1);+ }++ // A scripted sound picks its file from the logic seed without moving it; pin the seed it would+ // have read at this call.+ const Bool logical = eventToAdd->getIsLogicalAudio();+ std::array<UnsignedInt, 6> seed = {};+ if (logical) {+ CopyGameLogicSeed(seed.data());+ }++ LogicThread::callAfterTick([this, copy, handle, logical, seed]() mutable {+ std::vector<AudioHandle>::iterator queued = std::find(m_handlesQueuedFromTick.begin(), m_handlesQueuedFromTick.end(), handle);+ if (queued != m_handlesQueuedFromTick.end()) {+ m_handlesQueuedFromTick.erase(queued);+ }+ if (logical) {+ PinGameLogicSeedForUnchanged(seed.data());+ }+ addAudioEventNow(©, handle);+ if (logical) {+ PinGameLogicSeedForUnchanged(NULL);+ }+ });+ return handle;+}++//-------------------------------------------------------------------------------------------------+AudioHandle AudioManager::addAudioEventNow(const AudioEventRTS *eventToAdd, AudioHandle handle)+{+ LOGIC_CENSUS( CENSUS_AUDIO );+#ifdef INTENSIVE_AUDIO_DEBUGDEBUG_LOG(("AUDIO (%d): Received addAudioEvent('%s')", TheGameLogic->getFrame(), eventToAdd->getEventName().str()));#endif@@ -476,7 +541,7 @@ AudioHandle AudioManager::addAudioEvent(const AudioEventRTS *eventToAdd)}AudioEventRTS *audioEvent = MSGNEW("AudioEventRTS") AudioEventRTS(*eventToAdd); // poolify- audioEvent->setPlayingHandle( allocateNewHandle() );+ audioEvent->setPlayingHandle( handle ? handle : allocateNewHandle() );audioEvent->generateFilename(); // which file are we actually going to play?((AudioEventRTS*)eventToAdd)->setPlayingAudioIndex( audioEvent->getPlayingAudioIndex() );audioEvent->generatePlayInfo(); // generate pitch shift and volume shift now as well@@ -597,6 +662,13 @@ AsciiString AudioManager::prevTrackName(const AsciiString& currentTrack )//-------------------------------------------------------------------------------------------------void AudioManager::removeAudioEvent(AudioHandle audioEvent)+{+ // in order with the tick's adds, so a sound it starts and stops is started first+ LogicThread::callAfterTick([this, audioEvent]() { removeAudioEventNow(audioEvent); });+}++//-------------------------------------------------------------------------------------------------+void AudioManager::removeAudioEventNow(AudioHandle audioEvent){LOGIC_CENSUS( CENSUS_AUDIO );if (audioEvent == AHSV_StopTheMusic || audioEvent == AHSV_StopTheMusicFade) {@@ -657,8 +729,16 @@ void AudioManager::setAudioEventVolumeOverride( AsciiString eventToAffect, Real//-------------------------------------------------------------------------------------------------void AudioManager::removeAudioEvent( AsciiString eventToRemove ){- LOGIC_CENSUS( CENSUS_AUDIO );- removePlayingAudio( eventToRemove );+ LogicThread::callAfterTick( [this, eventToRemove]() {+ LOGIC_CENSUS( CENSUS_AUDIO );+ removePlayingAudio( eventToRemove );+ } );+}++//-------------------------------------------------------------------------------------------------+Bool AudioManager::isQueuedFromTick( AudioHandle handle ) const+{+ return std::find( m_handlesQueuedFromTick.begin(), m_handlesQueuedFromTick.end(), handle ) != m_handlesQueuedFromTick.end();}//-------------------------------------------------------------------------------------------------@@ -1090,6 +1170,7 @@ Real AudioManager::getWaveFileLengthMS( AsciiString strToLoad ) const//-------------------------------------------------------------------------------------------------Real AudioManager::getAudioLengthMS( const AudioEventRTS *event ){+ LOGIC_CENSUS( CENSUS_AUDIO_READ );if (!event->getAudioEventInfo()) {getInfoForAudioEvent(event);if (!event->getAudioEventInfo()) {diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex c0cb0dcb1..a13da3ac0 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -1565,7 +1565,11 @@ void GameEngine::reset( void )if (TheGameLogic->isInMultiplayerGame())deleteNetwork = true;+ // the clear-game tick resets from inside the tick; its sounds and effects have no game to play in+ LogicThread::discardEffects();TheSubsystemList->resetAll();+ // and what the objects' teardown asked for, GameLogic resetting last+ LogicThread::discardEffects();if (deleteNetwork){diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cppindex 6f54062df..d4131d803 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cpp@@ -255,6 +255,22 @@ DEBUG_LOG(( "%d: GetGameLogicRandomValue = %d (%d - %d), %s line %d\n",// all stays in step. That is what client-side effects need: they are allowed to want a number// that everybody agrees on without being allowed to decide how the simulation unfolds.//+// LOGIC-THREAD.md phase 2, M5: a sound logic plays inside a tick is built after the tick, when the+// seed has moved on. The tick copies the seed at the call and the build pins that copy, so the+// unchanged reads pick the file they would have picked at the call.+static const UnsignedInt *thePinnedLogicSeed = NULL;++void CopyGameLogicSeed( UnsignedInt seed[6] )+{+ for (int i = 0; i < 6; ++i)+ seed[i] = theGameLogicSeed[i];+}++void PinGameLogicSeedForUnchanged( const UnsignedInt *seed )+{+ thePinnedLogicSeed = seed;+}+Int GetGameLogicRandomValueUnchanged( int lo, int hi ){UnsignedInt delta = hi - lo + 1;@@ -262,9 +278,10 @@ Int GetGameLogicRandomValueUnchanged( int lo, int hi )if (delta == 0)return hi;+ const UnsignedInt *seed = thePinnedLogicSeed ? thePinnedLogicSeed : theGameLogicSeed;UnsignedInt seedCopy[6];for (int i = 0; i < 6; ++i)- seedCopy[i] = theGameLogicSeed[i];+ seedCopy[i] = seed[i];return ((Int)(randomValue(seedCopy) % delta)) + lo;}@@ -279,9 +296,10 @@ Real GetGameLogicRandomValueRealUnchanged( Real lo, Real hi )if (delta <= 0.0f)return hi;+ const UnsignedInt *seed = thePinnedLogicSeed ? thePinnedLogicSeed : theGameLogicSeed;UnsignedInt seedCopy[6];for (int i = 0; i < 6; ++i)- seedCopy[i] = theGameLogicSeed[i];+ seedCopy[i] = seed[i];return ((Real)(randomValue(seedCopy)) * theMultFactor ) * delta + lo;}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cppindex b611d3d3e..8cfa17901 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp@@ -27,6 +27,7 @@#include "Common/MessageStream.h"#include "GameClient/ControlBar.h"#include "GameClient/Drawable.h"+#include "GameClient/GameClient.h"#include "GameLogic/FPUControl.h"#include "GameLogic/GameLogic.h"@@ -35,6 +36,7 @@#include <exception>#include <mutex>#include <thread>+#include <vector>#if defined(_WIN32)#include <eh.h>#endif@@ -80,9 +82,28 @@ namespace"drawable", "modelcondition", "audio", "ingameui", "controlbar", "tacticalview", "radar","fxlist", "terrainvisual", "particles", "gameclient", "eva", "newdrawable", "clientrandom","ghost", "messagestream", "display", "jobs", "ondemandflush", "observerlookat",- "drawablepush", "destroydrawable"+ "drawablepush", "destroydrawable", "audioread"};+ // M5: what the tick asked of the audio, the FX lists and the particle systems, in call order.+ // Filled inside the tick, run and emptied by flushAfterTick; one thread touches it at a time.+ std::vector< std::function<void()> > s_effects;++ /* Everything a tick left for the main thread, in the order it has to run: the drawables' work first+ (M1, M3, M4 builds the render objects of the drawables the tick made), then the effects, which+ attach to those drawables and read their bones, then the deletion of the drawables the tick+ destroyed, whose bones a death effect may still have read, then the control bar (M2). */+ void flushAfterTick( void )+ {+ Drawable::flushPendingClientWork();+ // an effect queues nothing more: none of them runs inside a tick+ for( size_t i = 0; i < s_effects.size(); ++i )+ s_effects[ i ]();+ s_effects.clear();+ TheGameClient->flushDestroyedDrawables();+ ControlBar::flushLogicCalls();+ }+Real elapsedMS( LogicClock::time_point a, LogicClock::time_point b ){return std::chrono::duration<Real, std::milli>( b - a ).count();@@ -208,8 +229,7 @@ void LogicThread::runTick( void ){++s_inlineTicks;TheGameLogic->UPDATE();- Drawable::flushPendingClientWork();- ControlBar::flushLogicCalls();+ flushAfterTick();return;}@@ -251,10 +271,30 @@ void LogicThread::runTick( void )if( error )std::rethrow_exception( error );- // What the tick deferred on the drawables (phase 2, M1) and on the control bar (M2), here on the- // main thread at both settings.- Drawable::flushPendingClientWork();- ControlBar::flushLogicCalls();+ // What the tick deferred on the drawables (phase 2, M1), the effects (M5) and the control bar (M2),+ // here on the main thread at both settings.+ flushAfterTick();+}++//-------------------------------------------------------------------------------------------------+Bool LogicThread::defersEffects( void )+{+ return TheGameLogic != NULL && TheGameLogic->isInGameLogicUpdate() && !TheGameLogic->isLoadingMap();+}++//-------------------------------------------------------------------------------------------------+void LogicThread::callAfterTick( const std::function<void()>& call )+{+ if( defersEffects() )+ s_effects.push_back( call );+ else+ call();+}++//-------------------------------------------------------------------------------------------------+void LogicThread::discardEffects( void )+{+ s_effects.clear();}//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cppindex ad0f8ef3d..2869e693e 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp@@ -5380,8 +5380,8 @@ void Drawable::flushPendingClientWork()draw->doPendingClientWork( FALSE );}s_clientWorkQueue.clear();- // last, so a work above that holds a drawable the tick destroyed runs before it is deleted- TheGameClient->flushDestroyedDrawables();+ // LogicThread's flushAfterTick deletes the drawables the tick destroyed after this and the+ // tick's effects, so a work above or an effect that holds one runs before it is deleted}//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cppindex 3ffabf4fa..8ace68083 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cpp@@ -87,12 +87,25 @@ static void adjustVector(Coord3D *vec, const Matrix3D* mtx)/////////////////////////////////////////////////////////////////////////////////////////////////////--------------------------------------------------------------------------------------------------void FXNugget::doFXObj(const Object* primary, const Object* secondary) const+void FXObjectView::take( const Object *obj ){- const Coord3D* p = primary ? primary->getPosition() : NULL;- const Matrix3D* mtx = primary ? primary->getTransformMatrix() : NULL;+ id = obj->getID();+ position = *obj->getPosition();+ transform = *obj->getTransformMatrix();+ const Player *player = obj->getControllingPlayer();+ playerIndex = player ? player->getPlayerIndex() : -1;+ boundingCircleRadius = obj->getGeometryInfo().getBoundingCircleRadius();+ alwaysClear = obj->isKindOf(KINDOF_ALWAYS_VISIBLE) || obj->friend_getPartitionData() == NULL;+ drawable = obj->getDrawable();+}++//-------------------------------------------------------------------------------------------------+void FXNugget::doFXObj(const FXObjectView* primary, const FXObjectView* secondary) const+{+ const Coord3D* p = primary ? &primary->position : NULL;+ const Matrix3D* mtx = primary ? &primary->transform : NULL;const Real speed = 0.0f; // yes, that's right -- NOT the object's speed.- const Coord3D* s = secondary ? secondary->getPosition() : NULL;+ const Coord3D* s = secondary ? &secondary->position : NULL;doFXPos(p, mtx, speed, s);}@@ -115,13 +128,13 @@ public:TheAudio->addAudioEvent(&sound);}- virtual void doFXObj(const Object* primary, const Object* secondary = NULL) const+ virtual void doFXObj(const FXObjectView* primary, const FXObjectView* secondary = NULL) const{AudioEventRTS sound(m_soundName);if (primary){- sound.setPlayerIndex(primary->getControllingPlayer()->getPlayerIndex());- sound.setPosition(primary->getPosition());+ sound.setPlayerIndex(primary->playerIndex);+ sound.setPosition(&primary->position);}TheAudio->addAudioEvent(&sound);@@ -328,16 +341,16 @@ public:m_color.red = m_color.green = m_color.blue = 0;}- virtual void doFXObj(const Object* primary, const Object* /*secondary*/) const+ virtual void doFXObj(const FXObjectView* primary, const FXObjectView* /*secondary*/) const{if (primary){Real radius = m_radius;if (m_boundingCirclePct > 0)- radius = (primary->getGeometryInfo().getBoundingCircleRadius() * m_boundingCirclePct);+ radius = (primary->boundingCircleRadius * m_boundingCirclePct);- TheDisplay->createLightPulse(primary->getPosition(), &m_color, 1, radius, m_increaseFrames, m_decreaseFrames);+ TheDisplay->createLightPulse(&primary->position, &m_color, 1, radius, m_increaseFrames, m_decreaseFrames);}else{@@ -585,11 +598,11 @@ public:if (m_atTarget){DEBUG_ASSERTCRASH(secondary, ("ParticleSystem %s is AtTarget but the FX has no target\n", m_name.str()));- reallyDoFX(secondary, NULL, NULL, overrideRadius);+ reallyDoFX(secondary, NULL, INVALID_ID, overrideRadius);}else if (primary){- reallyDoFX(primary, primaryMtx, NULL, overrideRadius);+ reallyDoFX(primary, primaryMtx, INVALID_ID, overrideRadius);}else{@@ -597,7 +610,7 @@ public:}}- virtual void doFXObj(const Object* primary, const Object* secondary) const+ virtual void doFXObj(const FXObjectView* primary, const FXObjectView* secondary) const{if (primary){@@ -606,18 +619,18 @@ public:{// HERE WE MUST BUILD A MATRIX WHICH WILL ORIENT THE NEW PARTICLE SYSTEM TO FACE AWAY FROM THE SECONDARY OBJECT// THE RESULT SHOULD LOOK LIKE THE DIRECTION OF THE "ATTACK" IS CARRIED THROUGH LIKE A RICOCHET- Real deltaX = primary->getPosition()->x - secondary->getPosition()->x;- Real deltaY = primary->getPosition()->y - secondary->getPosition()->y;+ Real deltaX = primary->position.x - secondary->position.x;+ Real deltaY = primary->position.y - secondary->position.y;Real aimingAngle = atan2(deltaY, deltaX);Matrix3D aimingMatrix(1);aimingMatrix.Rotate_Z( aimingAngle );- reallyDoFX(primary->getPosition(), &aimingMatrix, primary, 0.0f);+ reallyDoFX(&primary->position, &aimingMatrix, primary->id, 0.0f);}else// if we have an object, then adjust the offset and direction by the object's transformation// matrix, so that (say) an offset of +10 in the z axis "follows" the orientation of the object.- reallyDoFX(primary->getPosition(), primary->getTransformMatrix(), primary, 0.0f);+ reallyDoFX(&primary->position, &primary->transform, primary->id, 0.0f);}else{@@ -654,7 +667,7 @@ public:protected:- void reallyDoFX(const Coord3D *primary, const Matrix3D* mtx, const Object* thingToAttachTo, Real overrideRadius ) const+ void reallyDoFX(const Coord3D *primary, const Matrix3D* mtx, ObjectID thingToAttachTo, Real overrideRadius ) const{Coord3D offset = m_offset;if (mtx)@@ -702,8 +715,10 @@ protected:if (m_rotateZ != 0.0f)sys->rotateLocalTransformZ(m_rotateZ);- if (m_attachToObject && thingToAttachTo)- sys->attachToObject(thingToAttachTo);+ // by ID: an object the tick destroyed after asking for this is gone now, and the+ // system lets go of it on its first update as it did of a dying one+ if (m_attachToObject && thingToAttachTo != INVALID_ID)+ sys->attachToObjectID(thingToAttachTo);elsesys->setPosition( &newPos );@@ -764,7 +779,7 @@ public:DEBUG_CRASH(("You must use the object form for this effect"));}- virtual void doFXObj(const Object* primary, const Object* /*secondary*/) const+ virtual void doFXObj(const FXObjectView* primary, const FXObjectView* /*secondary*/) const{if (primary){@@ -797,21 +812,27 @@ public:protected:- void doFxAtBones(const Object* obj, Int start) const+ void doFxAtBones(const FXObjectView* obj, Int start) const{Coord3D bonePos[MAX_BONE_POINTS];Matrix3D boneMtx[MAX_BONE_POINTS];- Drawable* draw = obj->getDrawable();+ const Drawable* draw = obj->drawable;if (draw){// yes, BONEPOS_CURRENT_CLIENT_ONLY -- this is client-only, so should be safe to do.Int count = draw->getCurrentClientBonePositions(m_boneName.str(), start, bonePos, boneMtx, MAX_BONE_POINTS);for (Int i = 0; i < count; ++i){+ // Thing::convertBonePosToWorldPos, on the transform the object had at the callCoord3D p;Matrix3D m;- obj->convertBonePosToWorldPos(&bonePos[i], &boneMtx[i], &p, &m);+ m.mul(obj->transform, boneMtx[i]);+ Vector3 v(bonePos[i].x, bonePos[i].y, bonePos[i].z);+ Matrix3D::Transform_Vector(obj->transform, v, &v);+ p.x = v.X;+ p.y = v.Y;+ p.z = v.Z;FXList::doFXPos(m_fx, &p, &m, 0.0f, NULL, 0.0f);}}@@ -870,6 +891,27 @@ void FXList::clear()//-------------------------------------------------------------------------------------------------void FXList::doFXPos(const Coord3D *primary, const Matrix3D* primaryMtx, const Real primarySpeed, const Coord3D *secondary, const Real overrideRadius ) const+{+ if (!LogicThread::defersEffects())+ {+ doFXPosNow(primary, primaryMtx, primarySpeed, secondary, overrideRadius);+ return;+ }++ // LOGIC-THREAD.md phase 2, M5: after the tick, in order with its other effects, at the points the+ // call named. Every nugget dereferences the primary, so it is always there.+ const Coord3D p = *primary;+ const Bool hasMtx = primaryMtx != NULL;+ const Matrix3D mtx = hasMtx ? *primaryMtx : Matrix3D(1);+ const Bool hasSecondary = secondary != NULL;+ const Coord3D s = hasSecondary ? *secondary : p;+ LogicThread::callAfterTick( [this, p, hasMtx, mtx, primarySpeed, hasSecondary, s, overrideRadius]() {+ doFXPosNow(&p, hasMtx ? &mtx : NULL, primarySpeed, hasSecondary ? &s : NULL, overrideRadius);+ } );+}++//-------------------------------------------------------------------------------------------------+void FXList::doFXPosNow(const Coord3D *primary, const Matrix3D* primaryMtx, const Real primarySpeed, const Coord3D *secondary, const Real overrideRadius ) const{LOGIC_CENSUS( CENSUS_FXLIST );if (ThePartitionManager->getShroudStatusForPlayer(TheObserverCamera.getShroudPlayerIndex(), primary) != CELLSHROUD_CLEAR)@@ -883,10 +925,53 @@ void FXList::doFXPos(const Coord3D *primary, const Matrix3D* primaryMtx, const R//-------------------------------------------------------------------------------------------------void FXList::doFXObj(const Object* primary, const Object* secondary) const+{+ FXObjectView p = {}, s = {};+ if (primary)+ p.take(primary);+ if (secondary)+ s.take(secondary);++ // LOGIC-THREAD.md phase 2, M5: inside a tick the FX plays after it, as the objects stood here+ if (!LogicThread::defersEffects())+ {+ doFXObjNow(primary ? &p : NULL, secondary ? &s : NULL, primary);+ return;+ }+ const Bool hasPrimary = primary != NULL;+ const Bool hasSecondary = secondary != NULL;+ LogicThread::callAfterTick( [this, p, s, hasPrimary, hasSecondary]() {+ doFXObjNow(hasPrimary ? &p : NULL, hasSecondary ? &s : NULL, hasPrimary ? TheGameLogic->findObjectByID(p.id) : NULL);+ } );+}++//-------------------------------------------------------------------------------------------------+void FXList::doFXObjNow(const FXObjectView* primary, const FXObjectView* secondary, const Object* primaryObject) const{LOGIC_CENSUS( CENSUS_FXLIST );- if (primary && primary->getShroudedStatus(TheObserverCamera.getShroudPlayerIndex()) > OBJECTSHROUD_PARTIAL_CLEAR)- return; //the primary object is fogged or shrouded so don't bother with the effect.+ if (primary)+ {+ // The shroud is asked here and not at the call: the object's answer is a cache that can take a+ // ghost snapshot into the scene. An object the tick destroyed after asking is gone; the cells+ // under its centre and its edge answer instead, any one clear being the object's partial clear.+ const Int shroudPlayer = TheObserverCamera.getShroudPlayerIndex();+ Bool hidden;+ if (primaryObject)+ hidden = primaryObject->getShroudedStatus(shroudPlayer) > OBJECTSHROUD_PARTIAL_CLEAR;+ else if (primary->alwaysClear)+ hidden = FALSE;+ else+ {+ const Real r = primary->boundingCircleRadius;+ const Coord3D &c = primary->position;+ const Coord3D footprint[] = { c, { c.x + r, c.y, c.z }, { c.x - r, c.y, c.z }, { c.x, c.y + r, c.z }, { c.x, c.y - r, c.z } };+ hidden = TRUE;+ for (size_t i = 0; i < ARRAY_SIZE(footprint) && hidden; ++i)+ hidden = ThePartitionManager->getShroudStatusForPlayer(shroudPlayer, &footprint[i]) != CELLSHROUD_CLEAR;+ }+ if (hidden)+ return; //the primary object is fogged or shrouded so don't bother with the effect.+ }for (FXNuggetList::const_iterator it = m_nuggets.begin(); it != m_nuggets.end(); ++it){diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cppindex 0b003aaaf..37db3bd02 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp@@ -32,6 +32,8 @@#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine#include "Common/LogicThread.h"+#include <algorithm>+#define DEFINE_PARTICLE_SYSTEM_NAMES#include "Common/FileSystem.h"@@ -1479,9 +1481,11 @@ ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate,m_isOneShot = sysTemplate->m_isOneShot;- m_delayLeft = particleTimerFrames( sysTemplate->m_initialDelay.getValue() );+ m_delayLeft = 0; // buildClientPart+ m_initialDelaySet = FALSE;+ m_isShell = FALSE;- m_startTimestamp = TheGameClient->getFrame();+ m_startTimestamp = 0; // buildClientPartm_systemLifetimeLeft = sysTemplate->m_systemLifetime;if (sysTemplate->m_systemLifetime)m_isForever = false;@@ -1518,10 +1522,10 @@ ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate,m_windMotionEndAngleMin = sysTemplate->m_windMotionEndAngleMin;m_windMotionEndAngleMax = sysTemplate->m_windMotionEndAngleMax;m_windMotionMovingToEndAngle = sysTemplate->m_windMotionMovingToEndAngle;- m_windMotionStartAngle = GameClientRandomValueReal( m_windMotionStartAngleMin, m_windMotionStartAngleMax );- m_windMotionEndAngle = GameClientRandomValueReal( m_windMotionEndAngleMin, m_windMotionEndAngleMax );- m_windAngle = GameClientRandomValueReal( m_windMotionStartAngle, m_windMotionEndAngle );-+ m_windMotionStartAngle = 0.0f; // buildClientPart+ m_windMotionEndAngle = 0.0f;+ m_windAngle = 0.0f;+m_shaderType = sysTemplate->m_shaderType;m_particleType = sysTemplate->m_particleType;@@ -1534,6 +1538,48 @@ ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate,m_slaveSystemID = INVALID_PARTICLE_SYSTEM_ID;m_masterSystem = NULL;m_slaveSystem = NULL;++ m_attachedSystemName = sysTemplate->m_attachedSystemName;+ m_particleCount = 0;+ m_personalityStore = 0;+ m_controlParticle = NULL;+ m_groundShadow = NULL;+ m_inSunMap = FALSE;++ // A system logic makes inside a tick is built after it (LOGIC-THREAD.md M5). The load path's+ // systems have no id yet and are never made in a tick.+ if (m_systemID != INVALID_PARTICLE_SYSTEM_ID && LogicThread::defersEffects())+ {+ m_isShell = TRUE;+ TheParticleSystemManager->friend_addShell(this, createSlaves);+ }+ else+ buildClientPart(createSlaves);++ //DEBUG_ASSERTLOG(!(m_totalParticleSystemCount % 10 == 0), ( "TotalParticleSystemCount = %d\n", m_totalParticleSystemCount ));+}++// ------------------------------------------------------------------------------------------------+/** The constructor's client half, in the order the constructor always ran it: the client stream's+ * draws, the slave, the manager's list, the DebrisTrails option. */+// ------------------------------------------------------------------------------------------------+void ParticleSystem::buildClientPart( Bool createSlaves )+{+ LOGIC_CENSUS( CENSUS_PARTICLES );+ m_isShell = FALSE;+ const ParticleSystemTemplate *sysTemplate = m_template;++ // drawn whether or not the tick set its own delay, as the constructor drew it before the call+ const UnsignedInt delay = particleTimerFrames( sysTemplate->m_initialDelay.getValue() );+ if (!m_initialDelaySet)+ m_delayLeft = delay;++ m_startTimestamp = TheGameClient->getFrame();++ m_windMotionStartAngle = GameClientRandomValueReal( m_windMotionStartAngleMin, m_windMotionStartAngleMax );+ m_windMotionEndAngle = GameClientRandomValueReal( m_windMotionEndAngleMin, m_windMotionEndAngleMax );+ m_windAngle = GameClientRandomValueReal( m_windMotionStartAngle, m_windMotionEndAngle );+if( createSlaves ){ParticleSystem *slaveSystem = sysTemplate->createSlaveSystem();@@ -1544,17 +1590,16 @@ ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate,setSlave( slaveSystem );m_slaveSystem->setMaster( this );+ // what the tick did to the shell that a built system passes to its slave+ if( !m_isSaveable )+ m_slaveSystem->setSaveable( FALSE );+ if( m_isDestroyed )+ m_slaveSystem->destroy();+} // end if} // end if- m_attachedSystemName = sysTemplate->m_attachedSystemName;- m_particleCount = 0;- m_personalityStore = 0;- m_controlParticle = NULL;- m_groundShadow = NULL;- m_inSunMap = FALSE;-// A system built without an id yet - the load path does that, so it can restore the saved id// first - registers itself once it has one, rather than here where the manager would file it// under nothing and every later lookup by id would miss it.@@ -1566,8 +1611,6 @@ ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate,// list and every caller holding the pointer go on exactly as they do with the option on.if (sysTemplate->m_explosionDebrisTrail && !TheGlobalData->m_explosionDebrisTrails)destroy();-- //DEBUG_ASSERTLOG(!(m_totalParticleSystemCount % 10 == 0), ( "TotalParticleSystemCount = %d\n", m_totalParticleSystemCount ));}// ------------------------------------------------------------------------------------------------@@ -1613,7 +1656,8 @@ ParticleSystem::~ParticleSystem()m_controlParticle = NULL;- if (m_systemID != INVALID_PARTICLE_SYSTEM_ID)+ // a shell a cleared game left was never filed+ if (m_systemID != INVALID_PARTICLE_SYSTEM_ID && !m_isShell)TheParticleSystemManager->friend_removeParticleSystem(this);//DEBUG_ASSERTLOG(!(m_totalParticleSystemCount % 10 == 0), ( "TotalParticleSystemCount = %d\n", m_totalParticleSystemCount ));}@@ -3683,6 +3727,11 @@ void ParticleSystemManager::init( void )// ------------------------------------------------------------------------------------------------void ParticleSystemManager::reset( void ){+ // systems a tick made in a game it then cleared, never built+ for (size_t i = 0; i < m_shells.size(); ++i)+ m_shells[ i ]->deleteInstance();+ m_shells.clear();+while (getParticleSystemCount()) {if (m_allParticleSystemList.front()) {m_allParticleSystemList.front()->deleteInstance();@@ -3838,7 +3887,6 @@ void ParticleSystemManager::setOnScreenParticleCount(int count)// ------------------------------------------------------------------------------------------------ParticleSystem *ParticleSystemManager::createParticleSystem( const ParticleSystemTemplate *sysTemplate, Bool createSlaves ){- LOGIC_CENSUS( CENSUS_PARTICLES );// sanityif (sysTemplate == NULL)return NULL;@@ -3867,10 +3915,15 @@ ParticleSystemID ParticleSystemManager::createAttachedParticleSystemID(// ------------------------------------------------------------------------------------------------ParticleSystem *ParticleSystemManager::findParticleSystem( ParticleSystemID id ){- LOGIC_CENSUS( CENSUS_PARTICLES );if (id == INVALID_PARTICLE_SYSTEM_ID)return NULL; // my, that was easy+ // a system this tick made is the tick's own until it is built+ for (size_t i = 0; i < m_shells.size(); ++i)+ if (m_shells[ i ]->getSystemID() == id)+ return m_shells[ i ];++ LOGIC_CENSUS( CENSUS_PARTICLES );ParticleSystemIDMap::const_iterator it = m_allParticleSystemMap.find( id );return (it != m_allParticleSystemMap.end()) ? it->second : NULL;@@ -3881,9 +3934,36 @@ ParticleSystem *ParticleSystemManager::findParticleSystem( ParticleSystemID id )// ------------------------------------------------------------------------------------------------void ParticleSystemManager::destroyParticleSystemByID(ParticleSystemID id){- ParticleSystem* pSystem = findParticleSystem(id);- if( pSystem )- pSystem->destroy();+ withSystem( id, []( ParticleSystem *pSystem ) { pSystem->destroy(); } );+}++// ------------------------------------------------------------------------------------------------+void ParticleSystemManager::withSystem( ParticleSystemID id, const std::function<void( ParticleSystem * )> &work )+{+ if( id == INVALID_PARTICLE_SYSTEM_ID )+ return;++ // after the tick, in order with the systems it built (LOGIC-THREAD.md M5)+ LogicThread::callAfterTick( [this, id, work]() {+ ParticleSystem* pSystem = findParticleSystem(id);+ if( pSystem )+ work( pSystem );+ } );+}++// ------------------------------------------------------------------------------------------------+void ParticleSystemManager::friend_addShell( ParticleSystem *shell, Bool createSlaves )+{+ m_shells.push_back( shell );+ const ParticleSystemID id = shell->getSystemID();+ LogicThread::callAfterTick( [this, shell, id, createSlaves]() {+ // gone if a reset inside the tick deleted it; by the ID, as a new shell can take its address+ std::vector<ParticleSystem *>::iterator it = std::find( m_shells.begin(), m_shells.end(), shell );+ if( it == m_shells.end() || shell->getSystemID() != id )+ return;+ m_shells.erase( it );+ shell->buildClientPart( createSlaves );+ } );}// ------------------------------------------------------------------------------------------------@@ -3957,22 +4037,28 @@ void ParticleSystemManager::destroyAttachedSystems( Object *obj )if( obj == NULL )return;- // iterate through all systems- ParticleSystem *system = NULL;+ // after the tick, so the systems it attached to the object are built and among them (M5)+ const ObjectID objID = obj->getID();+ LogicThread::callAfterTick( [this, objID]() {+ LOGIC_CENSUS( CENSUS_PARTICLES );- for( ParticleSystemListIt it = m_allParticleSystemList.begin();- it != m_allParticleSystemList.end();- ++it )- {+ // iterate through all systems+ ParticleSystem *system = NULL;- system = *it;- if( system == NULL )- continue;-- if( system->getAttachedObject() == obj->getID() )- system->destroy();+ for( ParticleSystemListIt it = m_allParticleSystemList.begin();+ it != m_allParticleSystemList.end();+ ++it )+ {- }+ system = *it;+ if( system == NULL )+ continue;++ if( system->getAttachedObject() == objID )+ system->destroy();++ }+ } );}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cppindex 2d176d889..c932bad97 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cpp@@ -1174,15 +1174,12 @@ void ActiveBody::createParticleSystems( const AsciiString &boneBaseName,void ActiveBody::deleteAllParticleSystems( void ){BodyParticleSystem *nextBodySystem;- ParticleSystem *particleSystem;while( m_particleSystems ){- // get this particle system- particleSystem = TheParticleSystemManager->findParticleSystem( m_particleSystems->m_particleSystemID );- if( particleSystem )- particleSystem->destroy();+ // this particle system, after the tick (LOGIC-THREAD.md M5)+ TheParticleSystemManager->destroyParticleSystemByID( m_particleSystems->m_particleSystemID );// get next system in the bodynextBodySystem = m_particleSystems->m_next;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cppindex 3f80bf55f..1b867ca3f 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp@@ -962,20 +962,25 @@ protected:if (!m_nameAreObjects){- for (DrawModule** dm = obj->getDrawable()->getDrawModules(); *dm; ++dm)- {- DebrisDrawInterface* di = (*dm)->getDebrisDrawInterface();- if (di)+ // the model and its animation only reach the draw module: after the tick for debris a tick+ // throws (LOGIC-THREAD.md M5), with the client stream's draw that picks the animation+ Drawable *draw = obj->getDrawable();+ const Color color = m_okToChangeModelColor ? obj->getIndicatorColor() : 0;+ draw->doClientWork( [this, draw, modelName, color]() {+ for (DrawModule** dm = draw->getDrawModules(); *dm; ++dm){- di->setModelName(modelName, m_okToChangeModelColor ? obj->getIndicatorColor() : 0, m_shadowType);- if (m_animSets.size() > 0)+ DebrisDrawInterface* di = (*dm)->getDebrisDrawInterface();+ if (di){- // the animation names only reach the draw module, so the client stream- Int which = GameClientRandomValue(0, m_animSets.size()-1);- di->setAnimNames(m_animSets[which].m_animInitial, m_animSets[which].m_animFlying, m_animSets[which].m_animFinal, m_fxFinal);+ di->setModelName(modelName, color, m_shadowType);+ if (m_animSets.size() > 0)+ {+ Int which = GameClientRandomValue(0, m_animSets.size()-1);+ di->setAnimNames(m_animSets[which].m_animInitial, m_animSets[which].m_animFlying, m_animSets[which].m_animFinal, m_fxFinal);+ }}}- }+ }, Drawable::WORK_AFTER_FLUSH );}Coord3D offset = m_offset;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cppindex 715eaa87a..84aba7672 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BoneFXUpdate.cpp@@ -459,16 +459,8 @@ void BoneFXUpdate::doParticleSystemAtBone(const ParticleSystemTemplate *particleParticleSystem *psys = TheParticleSystemManager->createParticleSystem(particleSystemTemplate);if (psys != NULL){- // drop the systems that have already died: a repeating emitter otherwise grows this list for- // the whole match, and its saved count is only an UnsignedShort- std::vector<ParticleSystemID>::iterator live = m_particleSystemIDs.begin();- while (live != m_particleSystemIDs.end())- {- if (TheParticleSystemManager->findParticleSystem(*live) == NULL)- live = m_particleSystemIDs.erase(live);- else- ++live;- }+ // The dead ones are dropped when the game is saved, outside the tick: logic may not ask the client+ // which systems still live inside one (LOGIC-THREAD.md M5).m_particleSystemIDs.push_back(psys->getSystemID());psys->setPosition(bonePosition);psys->attachToObject(building);@@ -506,11 +498,7 @@ void BoneFXUpdate::computeNextLogicFXTime(const BaseBoneListInfo *info, Int &nex//-------------------------------------------------------------------------------------------------void BoneFXUpdate::killRunningParticleSystems() {for (std::vector<ParticleSystemID>::iterator it = m_particleSystemIDs.begin(); it != m_particleSystemIDs.end(); ++it)- {- ParticleSystem *sys = TheParticleSystemManager->findParticleSystem(*it);- if( sys )- sys->destroy();- }+ TheParticleSystemManager->destroyParticleSystemByID(*it);m_particleSystemIDs.clear();}@@ -599,6 +587,19 @@ void BoneFXUpdate::xfer( Xfer *xfer )// extend base classUpdateModule::xfer( xfer );+ // a repeating emitter grows the list for the whole body state, and the saved count is only an UnsignedShort+ if( xfer->getXferMode() == XFER_SAVE )+ {+ std::vector<ParticleSystemID>::iterator live = m_particleSystemIDs.begin();+ while( live != m_particleSystemIDs.end() )+ {+ if( TheParticleSystemManager->findParticleSystem( *live ) == NULL )+ live = m_particleSystemIDs.erase( live );+ else+ ++live;+ }+ }+// particle system vector count and dataUnsignedShort particleSystemCount = m_particleSystemIDs.size();xfer->xferUnsignedShort( &particleSystemCount );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cppindex 617d96fb0..725f3a52e 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp@@ -36,6 +36,7 @@#include "Common/Thing.h"#include "Common/ThingTemplate.h"#include "Common/INI.h"+#include "Common/LogicThread.h"#include "Common/RandomValue.h"#include "Common/Player.h"#include "GameLogic/GameLogic.h"@@ -325,39 +326,46 @@ void EMPUpdate::doDisableAttack( void )Real victimVolume = victimFootprintArea * MIN(victimHeight, 10.0f);UnsignedInt emitterCount = MAX(15, REAL_TO_INT_CEIL(data->m_sparksPerCubicFoot * victimVolume));-- for (Int e = 0 ; e < emitterCount; ++e)- {- ParticleSystem *sys = TheParticleSystemManager->createParticleSystem(tmp);-- if (sys)+ // The sparks are made after the tick with the client stream's draws that place them+ // (LOGIC-THREAD.md M5); nothing logic keeps refers to them.+ const GeometryInfo geometry = curVictim->getGeometryInfo();+ const ObjectID victimID = curVictim->getID();+ const UnsignedInt lifetime = MAX(0, data->m_disabledDuration - LOGICFRAMES_PER_SECOND);+ LogicThread::callAfterTick( [tmp, geometry, victimID, victimHeight, emitterCount, lifetime]() {+ for (Int e = 0 ; e < emitterCount; ++e){- Coord3D offs = {0,0,0};- // Where a spark sits inside the victim is a thing only this machine ever looks- // at, so it comes off the client stream. Nothing in the simulation reads it.- curVictim->getGeometryInfo().makeRandomOffsetWithinFootprint( offs, TRUE );- offs.z = GameClientRandomValue(3, victimHeight);-- //This puts all the sparks within a quadrahemicycloid (rectangular dome) volume- //The same shape as a four cornered camping dome tent, for those with less Greek- if (offs.length() > victimHeight)++ ParticleSystem *sys = TheParticleSystemManager->createParticleSystem(tmp);++ if (sys){- Real resoreX = offs.x;- Real resoreY = offs.y;- offs.normalize();- offs.z *= victimHeight;- offs.x = resoreX;- offs.y = resoreY;+ Coord3D offs = {0,0,0};+ // Where a spark sits inside the victim is a thing only this machine ever looks+ // at, so it comes off the client stream. Nothing in the simulation reads it.+ geometry.makeRandomOffsetWithinFootprint( offs, TRUE );+ offs.z = GameClientRandomValue(3, victimHeight);++ //This puts all the sparks within a quadrahemicycloid (rectangular dome) volume+ //The same shape as a four cornered camping dome tent, for those with less Greek+ if (offs.length() > victimHeight)+ {+ Real resoreX = offs.x;+ Real resoreY = offs.y;+ offs.normalize();+ offs.z *= victimHeight;+ offs.x = resoreX;+ offs.y = resoreY;+ }++ sys->attachToObjectID(victimID);+ sys->setPosition( &offs );+ sys->setSystemLifetime(lifetime);+ // Client stream too: this line runs only where the drawable and the particle system exist.+ sys->setInitialDelay(GameClientRandomValue(1,ConvertRetailFrames(100)));}-- sys->attachToObject(curVictim);- sys->setPosition( &offs );- sys->setSystemLifetime(MAX(0, data->m_disabledDuration - LOGICFRAMES_PER_SECOND));- // Client stream too: this line runs only where the drawable and the particle system exist.- sys->setInitialDelay(GameClientRandomValue(1,ConvertRetailFrames(100)));}- }+ } );}}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FirestormDynamicGeometryInfoUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FirestormDynamicGeometryInfoUpdate.cppindex ee02157bd..e28bf2c60 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FirestormDynamicGeometryInfoUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FirestormDynamicGeometryInfoUpdate.cpp@@ -178,25 +178,17 @@ UpdateSleepTime FirestormDynamicGeometryInfoUpdate::update( void )if( m_myParticleSystemID[ i ] ){- ParticleSystem *sys = TheParticleSystemManager->findParticleSystem( m_myParticleSystemID[ i ] );-- if( sys )- {+ // after the tick, a system that died having nothing to do (LOGIC-THREAD.md M5); it used to+ // forget the ID of one it could not find, which logic may not ask the client inside a tick+ const Real radius = getObject()->getGeometryInfo().getMajorRadius();+ TheParticleSystemManager->withSystem( m_myParticleSystemID[ i ], [radius]( ParticleSystem *sys ) {ParticleSystemInfo::EmissionVolumeType type = sys->getEmisionVolumeType();if( type == ParticleSystemInfo::EmissionVolumeType::SPHERE )- sys->setEmissionVolumeSphereRadius( getObject()->getGeometryInfo().getMajorRadius() );+ sys->setEmissionVolumeSphereRadius( radius );else if( type == ParticleSystemInfo::EmissionVolumeType::CYLINDER )- sys->setEmissionVolumeCylinderRadius( getObject()->getGeometryInfo().getMajorRadius() );-- } // end if- else- {-- // this system not found (it probably died)... stop trying to find it in the future- m_myParticleSystemID[ i ] = INVALID_PARTICLE_SYSTEM_ID;-- } // end else+ sys->setEmissionVolumeCylinderRadius( radius );+ } );} // end ifdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cppindex b3e1f03a8..d5556d218 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WaveGuideUpdate.cpp@@ -383,34 +383,28 @@ void WaveGuideUpdate::doShapeEffects( void )// just above the ground//Int i, j;- ParticleSystem *particleSys;- Coord3D pos;for( i = 0; i < m_shapePointCount; i++ ){+ //+ // we have the height of the terrain at this shape point in the transformed shape+ // point array ... just set the LOCAL position for the particle system to reflect+ // this Z *IF* that Z will not take us above the target water height+ //+ if( m_transformedShapePoints[ i ].z >= modData->m_preferredHeight )+ continue;+ const Real z = m_transformedShapePoints[ i ].z;+for( j = 0; j < MAX_SHAPE_EFFECTS; j++ ){- // get the particle system here- particleSys = TheParticleSystemManager->findParticleSystem( m_shapeEffects[ i ][ j ] );- if( particleSys )- {-- //- // we have the height of the terrain at this shape point in the transformed shape- // point array ... just set the LOCAL position for the particle system to reflect- // this Z *IF* that Z will not take us above the target water height- //- if( m_transformedShapePoints[ i ].z < modData->m_preferredHeight )- {-- particleSys->getPosition( &pos );- pos.z = m_transformedShapePoints[ i ].z;- particleSys->setPosition( &pos );-- } // end if-- } // end if+ // the particle system, after the tick (LOGIC-THREAD.md M5)+ TheParticleSystemManager->withSystem( m_shapeEffects[ i ][ j ], [z]( ParticleSystem *particleSys ) {+ Coord3D pos;+ particleSys->getPosition( &pos );+ pos.z = z;+ particleSys->setPosition( &pos );+ } );} // end for jdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cppindex 868afb44a..d7f4c95c8 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp@@ -38,6 +38,7 @@#include "Common/AudioHandleSpecialValues.h"#include "Common/GameAudio.h"#include "Common/GameEngine.h"+#include "Common/LogicThread.h"#include "Common/MapObject.h" // For MAP_XY_FACTOR#include "Common/PartitionSolver.h"#include "Common/Player.h"@@ -3336,7 +3337,8 @@ void ScriptActions::doResumeSupplyTruckingForIdleUnits(const AsciiString& player//-------------------------------------------------------------------------------------------------void ScriptActions::doAmbientSoundsPause(Bool pausing) // if true, then pause, if false then resume.{- TheAudio->pauseAmbient(pausing);+ // the audio state calls go after the tick in order with its sounds (LOGIC-THREAD.md M5)+ LogicThread::callAfterTick( [pausing]{ TheAudio->pauseAmbient(pausing); } );}//-------------------------------------------------------------------------------------------------@@ -4027,7 +4029,7 @@ void ScriptActions::doAudioSetVolume(AudioAffect whichToAffect, Real newVolumeLenewVolumeLevel = 1.0f;}- TheAudio->setVolume(newVolumeLevel, whichToAffect);+ LogicThread::callAfterTick( [newVolumeLevel, whichToAffect]{ TheAudio->setVolume(newVolumeLevel, whichToAffect); } );}//-------------------------------------------------------------------------------------------------@@ -5173,13 +5175,13 @@ void ScriptActions::doSetWarehouseValue( const AsciiString& warehouseName, Int c//-------------------------------------------------------------------------------------------------void ScriptActions::doSoundEnableType( const AsciiString& soundEventName, Bool enable ){- TheAudio->setAudioEventEnabled(soundEventName, enable);+ LogicThread::callAfterTick( [soundEventName, enable]{ TheAudio->setAudioEventEnabled(soundEventName, enable); } );}//-------------------------------------------------------------------------------------------------void ScriptActions::doSoundRemoveAllDisabled(){- TheAudio->removeDisabledEvents();+ LogicThread::callAfterTick( []{ TheAudio->removeDisabledEvents(); } );}//-------------------------------------------------------------------------------------------------@@ -5193,7 +5195,7 @@ void ScriptActions::doSoundRemoveType( const AsciiString& soundEventName )//-------------------------------------------------------------------------------------------------void ScriptActions::doSoundOverrideVolume( const AsciiString& soundEventName, Real newVolume ){- TheAudio->setAudioEventVolumeOverride(soundEventName, newVolume / 100.0f);+ LogicThread::callAfterTick( [soundEventName, newVolume]{ TheAudio->setAudioEventVolumeOverride(soundEventName, newVolume / 100.0f); } );}//-------------------------------------------------------------------------------------------------@@ -6605,10 +6607,10 @@ void ScriptActions::executeAction( ScriptAction *pAction )TheTacticalView->setTimeMultiplier(pAction->getParameter(0)->getInt());return;case ScriptAction::SUSPEND_BACKGROUND_SOUNDS:- TheAudio->pauseAudio(AudioAffect_Sound);+ LogicThread::callAfterTick( []{ TheAudio->pauseAudio(AudioAffect_Sound); } );return;- case ScriptAction::RESUME_BACKGROUND_SOUNDS:- TheAudio->resumeAudio(AudioAffect_Sound);+ case ScriptAction::RESUME_BACKGROUND_SOUNDS:+ LogicThread::callAfterTick( []{ TheAudio->resumeAudio(AudioAffect_Sound); } );return;case ScriptAction::PLAY_SOUND_EFFECT_AT:doPlaySoundEffectAt(pAction->getParameter(0)->getString(), pAction->getParameter(1)->getString());diff --git a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cppindex 59a3a67d5..072d33881 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp@@ -58,6 +58,7 @@#include "Common/GameSounds.h"#include "Common/CRCDebug.h"#include "Common/GlobalData.h"+#include "Common/LogicThread.h"#include "Common/ScopedMutex.h"#include "GameClient/DebugDisplay.h"@@ -1649,6 +1650,7 @@ Bool MilesAudioManager::isMusicPlaying( void ) const//-------------------------------------------------------------------------------------------------Bool MilesAudioManager::hasMusicTrackCompleted( const AsciiString& trackName, Int numberOfTimes ) const{+ LOGIC_CENSUS( CENSUS_AUDIO_READ );std::list<PlayingAudio *>::const_iterator it;PlayingAudio *playing;for (it = m_playingStreams.begin(); it != m_playingStreams.end(); ++it) {@@ -1751,6 +1753,7 @@ void MilesAudioManager::closeDevice( void )//-------------------------------------------------------------------------------------------------Bool MilesAudioManager::isCurrentlyPlaying( AudioHandle handle ){+ LOGIC_CENSUS( CENSUS_AUDIO_READ );std::list<PlayingAudio *>::iterator it;PlayingAudio *playing;@@ -1785,7 +1788,8 @@ Bool MilesAudioManager::isCurrentlyPlaying( AudioHandle handle )}}- return false;+ // and so is a sound the tick asked for, which waits for the end of the tick to be requested+ return isQueuedFromTick(handle);}//-------------------------------------------------------------------------------------------------