Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

fix(gameengine): thread races and load-path crashes from the v3.2.0 reports

Olcay Seygan4e2c74a7a46a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index be167e76a..275173f62 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -203,6 +203,8 @@ found and fixed — EA's own, not port damage.**
- A mod whose team colour textures are stored in a format the colour cannot be painted into, a compressed one for instance, no longer crashes the game as such a unit comes out (a player hit it under The Power of the West). The unit keeps the texture's own colours.
- A shortcut button on the powers bar whose power the mod does not have stays off the bar instead of crashing the game while the command bar fills. A mod's own button, or a Reforged button loaded over a mod, can name a power that was never defined.
- A `-mod` path with `.` or `..` in it is refused. An archive counts as your mod's only when it was loaded for that mod. Two mods under `-modfactions` that define a command set with the same name both load now, and the later one wins.
+- A computer player on a mod's Helix no longer crashes the match when it sends the Helix on a bombing raid. The AI picked its raiders by the bomb upgrade on the Helix's buttons, and Contra's Nuke General Helix (under `-modfactions` beside ShockWave) has that upgrade without the napalm bomb the raid drops. A Helix without that bomb now stays with the army.
+- Under `-modfactions` a plain number in a model or sound line stays a number. A mod's own art gets the mod's mark in front of its name, and a mod file named with nothing but a number, a 6.dds say, had an animation's repeat count, the 6 in "0 6", marked as if it named that file, after which it no longer read as a number. That is our best reading of why ShockWave and Project Raptor together stopped while loading Project Raptor's Air Force General; we do not have that mod to check.
## One interface
@@ -1726,7 +1728,17 @@ The whole HUD is on the hardware. Four colours carry it, and they mean the same
## It does not crash
+- The game no longer crashes now and then as a match starts or a new unit comes on the field. Since 3.2.0 the battle runs beside the picture, and both sides ask the game's files whether a model or a texture is there. The answers go into one shared list, and two answers written at once tore it, which took the game down later in some unrelated place. Two reads from the same game archive at once could also hand one of them the other's bytes. Each now waits its turn.
+- Text on the screen, a message line or a unit's label, no longer crashes the game with the Direct3D 11 picture on. Three players met it on 3.2.0 in the same spot. The picture keeps a note of every texture it has copied, and a texture thrown away on the battle's side struck its note off while the picture was writing a new one in. The battle's side now leaves the striking off to the picture, which does it before its next look.
+- A tank or helicopter carrying an add-on on its back, an Overlord's Gattling Cannon or a Helix's bunker, no longer crashes the game now and then. Since 3.2.0 the battle runs beside the picture, and the picture, seating the add-on on its carrier, finished the carrier's waiting model changes while the battle was still adding to that same list. The picture now takes the carrier as the last step between pictures left it.
+- Giving an order no longer crashes an install whose model archive lacks the small marker drawn at the end of an order line, as one repack's does. The marker used to show only on a rally point, so such an install got away with it; now every order draws one. The line is drawn without the marker there.
+- A graphics setup that cannot make a single texture now gets the message that Direct3D could not start, instead of "Uncaught Exception during initialization". One player met the crash three times in a row on the Direct3D 11 picture with a dxgi.dll in the game folder: even the plain stand-in the game shows for a missing texture could not be made, and the first texture loaded fell on it.
- The rings the battle lays on the ground, a nuke's target circle or a Spectre gunship's, no longer crash the game now and then. Since 3.2.0 the battle runs beside the picture, and those rings were laid and lifted from the battle's side while the picture was walking the list of them, so the picture could read a ring that had just been thrown away. They are laid and lifted between pictures now.
+- A save that will not load now says so in a box instead of crashing the game. The load had already put half the units in when it stopped, and clearing them away again went through a list of every unit's timers that the half-done load had left out of step, so the game wrote into memory it did not own.
+- Loading a save from the in-game menu no longer crashes when a paratrooper is still hanging under his chute. Clearing the old match away took the chute first, the soldier "landed" off the map, died, and his death blast tried to build its debris for players that were already gone. A paratrooper cleared away with the match now just goes.
+- Rewinding a replay no longer stops the game with "sleepy update module illegal index". A Cold Fusion plant with Control Rods puts its bonus power back as the rewind finishes loading, and that switched the player's buildings off or on again at a moment when the game was not ready to wake them. A rewind now finishes exactly the way loading a save does, with every building's power as it was saved.
+- A skirmish on a custom map whose maker left out the script list for one side no longer crashes as the match starts. The win and defeat checks go on that side, and there was no list to add them to; it gets an empty one now.
+- A replay that shows the followed player's own pointer no longer swaps that pointer from the battle's side while the picture is drawing it. The swap rebuilds the pointer's picture and its text, and on 3.2.0 it could happen halfway through a frame; it waits for the frame's end now, like everything else the battle hands the screen.
- A graphics driver that stops responding no longer takes the game down through the radar. The battle carries on while the picture is lost, and the radar kept redrawing its unit dots into a texture that had nothing behind it. It skips the redraw until there is something to draw into.
- Your aircraft's ammo pips no longer crash the game. They have shown all the time since the jets learned to fly, and they are lined up with the health bar, so a plane drawn without a health bar took the game down. Such a plane shows no pips.
- Starting a match with the Direct3D 11 picture on took the game down. Both devices were presenting into the same window, the old one lost itself, and the fog texture then locked a surface that was never made.
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFile.h b/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFile.h
index 741cf2c1d..4b7f661dd 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFile.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFile.h
@@ -35,6 +35,8 @@
#include "Common/AsciiString.h"
#include "Common/ArchiveFileSystem.h"
+#include <mutex>
+
class File;
/**
@@ -71,6 +73,12 @@ protected:
const ArchivedFileInfo * getArchivedFileInfo(const AsciiString& filename) const; ///< return the ArchivedFileInfo from the directory tree.
File *m_file; ///< file pointer to the archive file on disk. Kept open so we don't have to continuously open and close the file all the time.
+ /// Held across a seek on m_file and the read after it (RAMFile and StreamingArchiveFile::openFromArchive,
+ /// StreamingArchiveFile::read). The handle has one file position, and the main thread, the logic
+ /// thread's model loads in an overlapped tick and the audio's streams all read archives: a seek from
+ /// one between another's seek and read hands it the wrong bytes. One per archive, so a stream from
+ /// the music archive never waits on a model being read out of another.
+ std::mutex m_readLock;
DetailedArchivedDirectoryInfo m_rootDirectory;
};
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.h b/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.h
index 7649d3392..42a943b6d 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.h
@@ -55,6 +55,8 @@
#include "Common/STLTypedefs.h"
#include "Common/SubsystemInterface.h"
+#include <mutex>
+
//----------------------------------------------------------------------------
// Forward References
//----------------------------------------------------------------------------
@@ -184,6 +186,9 @@ protected:
AsciiString focusedLooseFile(const AsciiString& filename) const; ///< the loose copy the focus sees, else empty
AsciiString modFolderFile(Int mod, const AsciiString& filename) const; ///< "<mod folder><filename>" when it is there, else empty
mutable std::map<unsigned,bool> m_fileExist;
+ /// m_fileExist is asked from the main thread and from the logic thread's model loads in an overlapped
+ /// tick (and the texture loader's, if it ever runs): two inserts at once corrupt the tree and the heap
+ mutable std::mutex m_fileExistLock;
// static: GlobalData's constructor reads files through a TheFileSystem that a few engine tests leave
// NULL, and openFile has always answered NULL there without touching the object
static Int s_focus;
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/RAMFile.h b/GeneralsMD/Code/GameEngine/Include/Common/RAMFile.h
index 1c16c4b3d..c3c9849d7 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/RAMFile.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/RAMFile.h
@@ -56,6 +56,8 @@
#include "Common/file.h"
+#include <mutex>
+
//----------------------------------------------------------------------------
// Forward References
//----------------------------------------------------------------------------
@@ -82,7 +84,7 @@ class RAMFile : public File
Char *m_data; ///< File data in memory
Int m_pos; ///< current read position
Int m_size; ///< size of file in memory
-
+
public:
RAMFile();
@@ -101,7 +103,9 @@ class RAMFile : public File
virtual Bool scanString(AsciiString &newString); ///< return what gets read as a string from the current memory position.
virtual Bool open( File *file ); ///< Open file for fast RAM access
- virtual Bool openFromArchive(File *archiveFile, const AsciiString& filename, Int offset, Int size); ///< copy file data from the given file at the given offset for the given size.
+ /// copy file data from the given file at the given offset for the given size, holding
+ /// archiveLock (the archive's ArchiveFile::m_readLock) across the seek and the read
+ virtual Bool openFromArchive(File *archiveFile, std::mutex &archiveLock, const AsciiString& filename, Int offset, Int size);
virtual Bool openFromMemory(const Char *data, Int size, const AsciiString& filename); ///< read a block somebody else is holding, for a file that was never on a disk
virtual Bool copyDataToFile(File *localFile); ///< write the contents of the RAM file to the given local file. This could be REALLY slow.
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/StreamingArchiveFile.h b/GeneralsMD/Code/GameEngine/Include/Common/StreamingArchiveFile.h
index 8afab6096..dd2ea5f81 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/StreamingArchiveFile.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/StreamingArchiveFile.h
@@ -78,6 +78,7 @@ class StreamingArchiveFile : public RAMFile
protected:
File *m_file; ///< The archive file that I came from
+ std::mutex *m_archiveLock; ///< its ArchiveFile::m_readLock, held across each seek and read
Int m_startingPos; ///< My starting position in the archive
Int m_size; ///< My length
Int m_curPos; ///< My current position.
@@ -101,7 +102,7 @@ class StreamingArchiveFile : public RAMFile
virtual Bool scanString(AsciiString &newString) { DEBUG_CRASH(("Should not call scanString on a streaming file.\n")); return FALSE; }
virtual Bool open( File *file ); ///< Open file for fast RAM access
- virtual Bool openFromArchive(File *archiveFile, const AsciiString& filename, Int offset, Int size); ///< copy file data from the given file at the given offset for the given size.
+ virtual Bool openFromArchive(File *archiveFile, std::mutex &archiveLock, const AsciiString& filename, Int offset, Int size); ///< stream the given file's bytes at the given offset for the given size
virtual Bool copyDataToFile(File *localFile) { DEBUG_CRASH(("Are you sure you meant to copyDataToFile on a streaming file?")); return FALSE; }
virtual char* readEntireAndClose() { DEBUG_CRASH(("Are you sure you meant to readEntireAndClose on a streaming file?")); return NULL; }
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp
index dec07364b..9645f88eb 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp
@@ -747,8 +747,28 @@ Bool ModNamespace::isAssetField( const std::string &field )
return FALSE;
}
+/// "0", "6", "-1.5", "25%": digits with at most a sign, points and a closing percent
+static Bool isNumber( const std::string &word )
+{
+ Bool digit = FALSE;
+ for (size_t i = 0; i < word.size(); ++i)
+ {
+ const char c = word[ i ];
+ if (c >= '0' && c <= '9')
+ digit = TRUE;
+ else if (!(c == '.' || ((c == '-' || c == '+') && i == 0) || (c == '%' && i + 1 == word.size())))
+ return FALSE;
+ }
+ return digit;
+}
+
Bool ModNamespace::isNameOrAsset( const std::string &word, Bool assetField ) const
{
+ // A number is a number. An animation's distance and repeat count sit in a file field, and with a
+ // texture called 6.dds in the mod "IdleAnimation = X.X 0 6" read "M2~6", which is no Int: a parse
+ // error at load under -modfactions.
+ if (isNumber( word ))
+ return FALSE;
const Names &names = m_mods[ m_active ];
return names.all.count( word ) != 0 || (assetField && isAsset( names, word ));
}
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cpp
index 089eb4478..5fcc3536b 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cpp
@@ -241,7 +241,10 @@ FileSystem::~FileSystem()
void FileSystem::init( void )
{
- m_fileExist.clear(); // see reset(): the cache outlives whatever it was an answer about
+ {
+ std::lock_guard<std::mutex> lock( m_fileExistLock );
+ m_fileExist.clear(); // see reset(): the cache outlives whatever it was an answer about
+ }
TheLocalFileSystem->init();
TheArchiveFileSystem->init();
}
@@ -270,7 +273,10 @@ void FileSystem::reset( void )
// mounted, or before Win32BIGFileSystem::init re-loaded the Patch*.big over the plain pass, made
// that file invisible for the rest of the run - and the cache is keyed by name, so nothing else
// would ever ask again.
- m_fileExist.clear();
+ {
+ std::lock_guard<std::mutex> lock( m_fileExistLock );
+ m_fileExist.clear();
+ }
TheLocalFileSystem->reset();
TheArchiveFileSystem->reset();
@@ -350,7 +356,9 @@ File* FileSystem::openFile( const Char *filename, Int access )
map's (upstream #991). */
if ( file != NULL && (access & File::CREATE) )
{
- m_fileExist[ TheNameKeyGenerator->nameToLowercaseKey( filename ) ] = true;
+ const unsigned key = TheNameKeyGenerator->nameToLowercaseKey( filename );
+ std::lock_guard<std::mutex> lock( m_fileExistLock );
+ m_fileExist[ key ] = true;
}
if ( (TheArchiveFileSystem != NULL) && (file == NULL) )
@@ -383,23 +391,21 @@ Bool FileSystem::doesFileExist(const Char *filename) const
return focusedLooseFile( AsciiString( filename ) ).isNotEmpty() || TheArchiveFileSystem->doesFileExist( filename );
unsigned key=TheNameKeyGenerator->nameToLowercaseKey(filename);
- std::map<unsigned,bool>::iterator i=m_fileExist.find(key);
- if (i!=m_fileExist.end())
- return i->second;
-
- if (TheLocalFileSystem->doesFileExist(filename) || modLooseFile(AsciiString(filename)).isNotEmpty())
- {
- m_fileExist[key]=true;
- return TRUE;
- }
- if (TheArchiveFileSystem != NULL && TheArchiveFileSystem->doesFileExist(filename))
- {
- m_fileExist[key]=true;
- return TRUE;
+ {
+ std::lock_guard<std::mutex> lock( m_fileExistLock );
+ std::map<unsigned,bool>::iterator i=m_fileExist.find(key);
+ if (i!=m_fileExist.end())
+ return i->second;
}
- m_fileExist[key]=false;
- return FALSE;
+ // asked unlocked, so a slow disk does not hold the other thread up; two threads asking the same
+ // name both find the same answer and store it twice
+ const Bool exists = TheLocalFileSystem->doesFileExist(filename) || modLooseFile(AsciiString(filename)).isNotEmpty()
+ || (TheArchiveFileSystem != NULL && TheArchiveFileSystem->doesFileExist(filename));
+
+ std::lock_guard<std::mutex> lock( m_fileExistLock );
+ m_fileExist[key]=exists != FALSE;
+ return exists;
}
//============================================================================
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/RAMFile.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/RAMFile.cpp
index b9ae32938..56b5413f1 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/RAMFile.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/RAMFile.cpp
@@ -88,7 +88,7 @@
//----------------------------------------------------------------------------
-// Public Data
+// Public Data
//----------------------------------------------------------------------------
@@ -211,7 +211,7 @@ Bool RAMFile::open( File *file )
//============================================================================
// RAMFile::openFromArchive
//============================================================================
-Bool RAMFile::openFromArchive(File *archiveFile, const AsciiString& filename, Int offset, Int size)
+Bool RAMFile::openFromArchive(File *archiveFile, std::mutex &archiveLock, const AsciiString& filename, Int offset, Int size)
{
//USE_PERF_TIMER(RAMFile)
if (archiveFile == NULL) {
@@ -229,11 +229,14 @@ Bool RAMFile::openFromArchive(File *archiveFile, const AsciiString& filename, In
m_data = MSGNEW("RAMFILE") Char [size]; // pool[]ify
m_size = size;
- if (archiveFile->seek(offset, File::START) != offset) {
- return FALSE;
- }
- if (archiveFile->read(m_data, size) != size) {
- return FALSE;
+ {
+ std::lock_guard<std::mutex> lock( archiveLock );
+ if (archiveFile->seek(offset, File::START) != offset) {
+ return FALSE;
+ }
+ if (archiveFile->read(m_data, size) != size) {
+ return FALSE;
+ }
}
m_nameStr = filename;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp
index b1813e1f8..f971f3637 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp
@@ -756,12 +756,15 @@ void GameState::loadCheckpoint( AsciiString filepath, const std::function< void(
TheGameEngine->reset();
afterReset();
+ // The post-process is part of the load, as it is in loadGame: a Cold Fusion plant's Control Rods
+ // put its power back there, and outside the load that browned the player out or in again and
+ // idled buildings whose update modules were not back on the sleepy heap yet, "sleepy update module
+ // illegal index" on a replay rewind. The save already holds every building's power state.
+ LatchRestore<Bool> inLoadGame( m_isInLoadGame, TRUE );
+
TheGhostObjectManager->saveLockGhostObjects( TRUE );
TheGameLogic->setLoadingWithoutScreen( TRUE );
- {
- LatchRestore<Bool> inLoadGame( m_isInLoadGame, TRUE );
- xferSaveData( &xferLoad, SNAPSHOT_SAVELOAD );
- }
+ xferSaveData( &xferLoad, SNAPSHOT_SAVELOAD );
TheGameLogic->setLoadingWithoutScreen( FALSE );
xferLoad.close();
TheGhostObjectManager->saveLockGhostObjects( FALSE );
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/StreamingArchiveFile.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/StreamingArchiveFile.cpp
index 6936bba46..d71204b82 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/StreamingArchiveFile.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/StreamingArchiveFile.cpp
@@ -107,8 +107,9 @@
//=================================================================
StreamingArchiveFile::StreamingArchiveFile()
-: m_file(NULL),
- m_startingPos(0),
+: m_file(NULL),
+ m_archiveLock(NULL),
+ m_startingPos(0),
m_size(0),
m_curPos(0)
{
@@ -166,7 +167,7 @@ Bool StreamingArchiveFile::open( File *file )
//============================================================================
// StreamingArchiveFile::openFromArchive
//============================================================================
-Bool StreamingArchiveFile::openFromArchive(File *archiveFile, const AsciiString& filename, Int offset, Int size)
+Bool StreamingArchiveFile::openFromArchive(File *archiveFile, std::mutex &archiveLock, const AsciiString& filename, Int offset, Int size)
{
//USE_PERF_TIMER(StreamingArchiveFile)
if (archiveFile == NULL) {
@@ -178,14 +179,17 @@ Bool StreamingArchiveFile::openFromArchive(File *archiveFile, const AsciiString&
}
m_file = archiveFile;
+ m_archiveLock = &archiveLock;
m_startingPos = offset;
m_size = size;
m_curPos = 0;
+ // read() seeks before every read, so the position left here is only the check's
+ std::lock_guard<std::mutex> lock( archiveLock );
if (m_file->seek(offset, File::START) != offset) {
return FALSE;
}
-
+
if (m_file->seek(size) != m_startingPos + size) {
return FALSE;
}
@@ -222,20 +226,25 @@ Int StreamingArchiveFile::read( void *buffer, Int bytes )
return 0;
}
- // There shouldn't be a way that this can fail, because we've already verified that the file
- // contains at least this many bits.
- m_file->seek(m_startingPos + m_curPos, File::START);
-
- if (bytes + m_curPos > m_size)
+ if (bytes + m_curPos > m_size)
bytes = m_size - m_curPos;
- Int bytesRead = m_file->read(buffer, bytes);
+ Int bytesRead;
+ {
+ std::lock_guard<std::mutex> lock( *m_archiveLock );
+ // There shouldn't be a way that this can fail, because we've already verified that the file
+ // contains at least this many bits.
+ m_file->seek(m_startingPos + m_curPos, File::START);
+ bytesRead = m_file->read(buffer, bytes);
+ }
// the archive's drive gone under a stream (music, speech): see Win32BIGFile::openFile. From the audio's
// thread GameDataGone only records it, and the main loop stops the game (GameDataGoneCheck).
if (bytesRead < 0 && m_file->deviceGone())
GameDataGone(m_file->getName());
- m_curPos += bytesRead;
+ // a failed read moved nothing; adding its -1 walked the stream back over bytes already played
+ if (bytesRead > 0)
+ m_curPos += bytesRead;
return bytesRead;
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
index 98a398a62..5b73be3be 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
@@ -5543,10 +5543,16 @@ void Drawable::flushPendingTransform( Bool onDemand )
//-------------------------------------------------------------------------------------------------
/** The draw modules with whatever the tick has deferred applied now. For the callers inside a tick
that act on the render object as it stands (animation timing, weapon fire FX, live bones, ghost
- snapshots): the census counts these on their own channel, the list phase 3 has to resolve. */
+ snapshots): the census counts these on their own channel, the list phase 3 has to resolve.
+ Inside the overlap window the render asks too (a rider's model on its container's bone, an
+ attach-to-bone model, both from doDrawModule), and the tick beside it may be adding steps to this
+ same drawable: flushing there swapped m_pendingSteps out from under the logic thread's push_back,
+ and flushAfterTick then ran a step whose work had been freed. As getDrawModules does, the window
+ reads the render objects as the sync point left them; flushAfterTick applies the rest. */
DrawModule** Drawable::getDrawModulesFlushed()
{
- doPendingClientWork( TRUE );
+ if (!LogicThread::isInsideWindow())
+ doPendingClientWork( TRUE );
return getDrawModulesNonDirty();
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
index 2d0cc2388..625776659 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp
@@ -12207,6 +12207,23 @@ static const UpgradeTemplate *helixUpgradeOn( const ThingTemplate *tmpl, Int kin
return NULL;
}
+/** A Helix of this kind flies the napalm bomb flyRaid drops. A mod's Helix can carry a "Bomb" upgrade
+ * on its buttons and drop something else, or nothing the AI knows: ShockWave's under -modfactions
+ * came out as a raider with no such power and the raid read a null one. */
+static Bool helixCarriesNapalmBomb( const ThingTemplate *tmpl )
+{
+ const ModuleInfo &modules = tmpl->getBehaviorModuleInfo();
+ for( Int m = 0; m < modules.getCount(); ++m )
+ {
+ if( modules.getNthName( m ).compareNoCase( "SpecialAbilityUpdate" ) != 0 )
+ continue;
+ const SpecialPowerTemplate *power = static_cast<const SpecialAbilityUpdateModuleData *>( modules.getNthData( m ) )->m_specialPowerTemplate;
+ if( power && power->getSpecialPowerType() == SPECIAL_HELIX_NAPALM_BOMB )
+ return TRUE;
+ }
+ return FALSE;
+}
+
/** How much a raid wants a building: production, then income, then power; 0 for anything else. */
static Int raidPreference( const Object *obj )
{
@@ -12324,7 +12341,7 @@ Int AIPlayer::helixRoleWanted( const ThingTemplate *tmpl ) const
const Int healersWanted = tallyBase( m_player ).army >= HEALER_THIRD_ARMY ? MAX_HEALERS : MIN_HEALERS;
if( healers < healersWanted && helixUpgradeOn( tmpl, HELIX_TOWER ) )
return HELIX_HEALER;
- if( raiders < MAX_RAIDERS && helixUpgradeOn( tmpl, HELIX_BOMB ) )
+ if( raiders < MAX_RAIDERS && helixUpgradeOn( tmpl, HELIX_BOMB ) && helixCarriesNapalmBomb( tmpl ) )
return HELIX_RAIDER;
return -1;
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp
index e8b311857..d75a075ad 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp
@@ -177,11 +177,11 @@ void UpdateModule::xfer( Xfer *xfer )
}
#endif
- // m_indexInLogic is not saved -- it's restored in gamelogic::postprocess.
- if( xfer->getXferMode() == XFER_LOAD )
- {
- m_indexInLogic = -1;
- }
+ // m_indexInLogic is not saved, and a load leaves it alone: the module was put on the sleepy heap
+ // when newObject made its object, and that is the slot it holds until GameLogic::loadPostProcess
+ // rebuilds the heap. Setting it to -1 here left the heap holding modules that said they were not
+ // on it, and a load that threw part way then destroyed every object through that lie:
+ // eraseSleepyUpdate(-1) wrote through a garbage pointer, a player's crash after a failed Load.
} // end xfer
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index 38c24c130..5a7f08e1f 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -484,8 +484,13 @@ void GameLogic::reset( void )
m_mouseVisibleMemory = TRUE;
setFPMode();
- // destroy all objects
- destroyAllObjectsImmediate();
+ // destroy all objects. This is a clear-out the way clearGameData's is, and a Load from the in-game
+ // menu comes here without passing clearGameData: a paratrooper whose chute went first "landed" off
+ // the map, fired his death weapon, and its debris was built for a player list already emptied.
+ {
+ LatchRestore<Bool> clearing( m_clearingGameData, TRUE );
+ destroyAllObjectsImmediate();
+ }
m_nextObjID = (ObjectID)1;
m_pendingTechBuildings.clear();
@@ -1726,7 +1731,14 @@ void GameLogic::startNewGame( Bool loadingSaveGame )
Int count = ScriptList::getReadScripts(scripts);
if (count)
{
+ // a map can be saved with no script list for a side, the first one these go to included
+ // (a player's custom map, a crash at the start of a skirmish): it gets an empty one
ScriptList *pSL = TheSidesList->getSideInfo(0)->getScriptList();
+ if (pSL == NULL)
+ {
+ pSL = newInstance(ScriptList);
+ TheSidesList->getSideInfo(0)->setScriptList(pSL);
+ }
Script *next = scripts[0]->getScript();
while (next)
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
index 8acef1735..49cb5a40b 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
@@ -2632,17 +2632,25 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, AIGroup *orderedGroup
ViewLocation loc;
const Coord3D &pos = msg->getArgument( 0 )->location;
loc.init( pos.x, pos.y, pos.z, msg->getArgument( 1 )->real, msg->getArgument( 2 )->real, msg->getArgument( 3 )->real );
- TheObserverCamera.notePlayerView( thisPlayer->getPlayerIndex(), loc );
-
- // a replay shows the recorded player's pointer too, while the watcher is not using his own
- if (TheRecorder->getMode() == RECORDERMODETYPE_PLAYBACK && TheObserverCamera.getMode() == OBSERVER_CAMERA_PLAYER
- && TheObserverCamera.getFollowedPlayerIndex() == thisPlayer->getPlayerIndex() && !TheLookAtTranslator->hasMouseMovedRecently())
- {
- TheMouse->setCursor( (Mouse::MouseCursor)(msg->getArgument( 4 )->integer) );
- ICoord2D mousePos = msg->getArgument( 5 )->pixel;
- TheMouse->setPosition( mousePos.x, mousePos.y );
- TheLookAtTranslator->setCurrentPos( mousePos );
- }
+ const Int playerIndex = thisPlayer->getPlayerIndex();
+ const Mouse::MouseCursor cursor = (Mouse::MouseCursor)(msg->getArgument( 4 )->integer);
+ const ICoord2D mousePos = msg->getArgument( 5 )->pixel;
+
+ /* All of it is the watcher's camera and pointer, which the render reads while the tick runs
+ beside it: the cursor change rebuilds the pointer's text and picture, so it waits for the
+ tick's end like every other client call the tick makes. */
+ LogicThread::callAfterTick( [playerIndex, loc, cursor, mousePos]() {
+ TheObserverCamera.notePlayerView( playerIndex, loc );
+
+ // a replay shows the recorded player's pointer too, while the watcher is not using his own
+ if (TheRecorder->getMode() == RECORDERMODETYPE_PLAYBACK && TheObserverCamera.getMode() == OBSERVER_CAMERA_PLAYER
+ && TheObserverCamera.getFollowedPlayerIndex() == playerIndex && !TheLookAtTranslator->hasMouseMovedRecently())
+ {
+ TheMouse->setCursor( cursor );
+ TheMouse->setPosition( mousePos.x, mousePos.y );
+ TheLookAtTranslator->setCurrentPos( mousePos );
+ }
+ } );
break;
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp
index 71cafaaf9..2d8466c44 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp
@@ -217,6 +217,10 @@ void W3DWaypointBuffer::drawWaypoints(RenderInfoClass &rinfo)
switch( it->kind )
{
case DRAW_PUCK:
+ // an install whose W3D archives lack SCMNode.w3d (seen in a third-party repack) has no
+ // puck; retail drew one only for a rally point, every order draws one now
+ if( !m_waypointNodeRobj )
+ break;
m_waypointNodeRobj->Set_Position( points[ 0 ] );
WW3D::Render( *m_waypointNodeRobj, localRinfo ); // the little hockey puck
break;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFile.cpp b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFile.cpp
index f862348c5..65a6efd2d 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFile.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFile.cpp
@@ -73,7 +73,7 @@ File* Win32BIGFile::openFile( const Char *filename, Int access )
ramFile = newInstance( RAMFile );
ramFile->deleteOnClose();
- if (ramFile->openFromArchive(m_file, fileInfo->m_filename, fileInfo->m_offset, fileInfo->m_size) == FALSE) {
+ if (ramFile->openFromArchive(m_file, m_readLock, fileInfo->m_filename, fileInfo->m_offset, fileInfo->m_size) == FALSE) {
ramFile->close();
ramFile = NULL;
// the archive was readable when it was opened: if its drive has gone since, say so and stop
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp
index 432f95542..7247b28d3 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp
@@ -23,10 +23,13 @@
#include <d3d9.h>
#include <d3d11.h>
#include <algorithm>
+#include <atomic>
#include <map>
+#include <mutex>
#include <stdio.h>
#include <string.h>
#include <string>
+#include <thread>
#include <unordered_map>
#include <vector>
@@ -552,8 +555,8 @@ static ID3D11ShaderResourceView * mirror(ID3D11Device * device, ID3D11DeviceCont
// the d3d9.dll time under TextureClass::Apply in the profile (an unnamed export, Ordinal23, is the
// nearest label the sampler has for that code). An entry stands while its texture is alive, has
// not been written by the CPU since (DX11Texture_Mark_Dirty marks it stale) and answers the same
-// level of detail; the view itself is still owned by the texture. Main thread only, like every
-// other call here.
+// level of detail; the view itself is still owned by the texture. Read and written on the thread
+// that binds textures only; see Forget_Answer for the two calls that can come from another.
struct MirrorAnswer
{
ID3D11ShaderResourceView * View;
@@ -565,6 +568,58 @@ typedef std::unordered_map<IDirect3DBaseTexture9 *, MirrorAnswer> MirrorAnswerMa
// after that, and the watch erases from this.
static MirrorAnswerMap & MirrorAnswers = *new MirrorAnswerMap;
+// A texture's last reference does not always go on the thread that binds: the logic thread runs a
+// tick beside the render, whatever drops a texture there releases its watch there, and a CPU write
+// made there marks it dirty from there. Erasing from MirrorAnswers then raced the render's insert into
+// it and broke the table's links, which v3.2.0 players met as a crash inside this insert. Such a
+// call is queued instead, in order, and the binding thread applies the queue before its next
+// lookup. A texture made at a dead one's address can only be bound after its death was queued, so
+// the stale answer is gone first. Never destroyed, for the reason MirrorAnswers is not.
+struct PendingAnswer
+{
+ IDirect3DBaseTexture9 * Texture;
+ bool Erase; ///< the texture died; otherwise it was written and its answer is stale
+};
+static std::atomic<std::thread::id> BindingThread;
+static std::atomic<bool> AnswersPending(false);
+static std::mutex & PendingLock = *new std::mutex;
+static std::vector<PendingAnswer> & PendingAnswers = *new std::vector<PendingAnswer>;
+
+static void Apply_Answer(IDirect3DBaseTexture9 * texture, bool erase)
+{
+ MirrorAnswerMap::iterator answer = MirrorAnswers.find(texture);
+ if (answer == MirrorAnswers.end()) {
+ return;
+ }
+ if (erase) {
+ MirrorAnswers.erase(answer);
+ } else {
+ answer->second.Stale = true;
+ }
+}
+
+static void Apply_Pending_Answers()
+{
+ std::lock_guard<std::mutex> lock(PendingLock);
+ for (size_t i = 0; i < PendingAnswers.size(); ++i) {
+ Apply_Answer(PendingAnswers[i].Texture, PendingAnswers[i].Erase);
+ }
+ PendingAnswers.clear();
+ AnswersPending = false;
+}
+
+static void Forget_Answer(IDirect3DBaseTexture9 * texture, bool erase)
+{
+ if (std::this_thread::get_id() == BindingThread.load(std::memory_order_relaxed)) {
+ Apply_Answer(texture, erase);
+ return;
+ }
+ std::lock_guard<std::mutex> lock(PendingLock);
+ PendingAnswer pending = { texture, erase };
+ PendingAnswers.push_back(pending);
+ AnswersPending = true;
+}
+
// Hung on a texture as private data the first time it is answered for, so that D3D9 releasing its
// private data when the texture goes takes the answer with it before another texture can be made
// at the same address.
@@ -592,7 +647,7 @@ public:
{
const ULONG left = --References;
if (left == 0) {
- MirrorAnswers.erase(Texture);
+ Forget_Answer(Texture, true);
delete this;
}
return left;
@@ -606,6 +661,11 @@ private:
ID3D11ShaderResourceView * DX11Texture_Mirror(ID3D11Device * device, ID3D11DeviceContext * context,
IDirect3DBaseTexture9 * texture)
{
+ // relaxed: every bind comes through here, and no watch exists before the first one has set it
+ BindingThread.store(std::this_thread::get_id(), std::memory_order_relaxed);
+ if (AnswersPending) {
+ Apply_Pending_Answers();
+ }
MirrorAnswerMap::iterator answer = MirrorAnswers.find(texture);
if (answer != MirrorAnswers.end() && !answer->second.Stale
&& answer->second.Lod == texture->GetLOD()) {
@@ -647,10 +707,7 @@ void DX11Texture_Mark_Dirty(IDirect3DSurface9 * surface)
const unsigned char dirty = 1;
texture->SetPrivateData(DX11_TEXTURE_DIRTY, &dirty, sizeof(dirty), 0);
- MirrorAnswerMap::iterator answer = MirrorAnswers.find(texture);
- if (answer != MirrorAnswers.end()) {
- answer->second.Stale = true;
- }
+ Forget_Answer(texture, false);
texture->Release();
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
index 9c001632c..568c29bd5 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
@@ -938,6 +938,18 @@ bool DX8Wrapper::Create_Device(void)
** Initialize all subsystems
*/
Do_Onetime_Device_Dependent_Inits();
+
+ /* A device that cannot make the 128x128 stand-in texture cannot make any texture, and calling it
+ created only moved the fault: every load that fails ends on the stand-in, so the first one
+ (exmask_g.tga in the screen cross fade) released a null texture during startup. Seen three
+ times in a row on one machine in the v3.2.0 reports, Direct3D 11 with a dxgi.dll in the game
+ folder. Refusing the device here gives the player the Direct3D failure message instead. */
+ IDirect3DTexture9 * missing = MissingTexture::_Get_Missing_Texture();
+ if (missing == NULL) {
+ Release_Device();
+ return false;
+ }
+ missing->Release();
return true;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.cpp
index f9797a1df..a69650bc9 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.cpp
@@ -175,7 +175,10 @@ void MissingTexture::_Init()
void MissingTexture::_Deinit()
{
- _MissingTexture->Release();
+ // Null when the device could not make it, which DX8Wrapper::Create_Device refuses and releases.
+ if (_MissingTexture) {
+ _MissingTexture->Release();
+ }
_MissingTexture=0;
}
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 6c545abe9..bc0028bcc 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -18554,6 +18554,12 @@ TEST(modfactions_prefix_the_mods_own_art)
strcpy( line, " ShowSubObject = AVRanger" ); // a sub-object, not a file
CHECK( names.rewriteLine( line, sizeof( line ) ) );
CHECK_STR( line, " ShowSubObject = AVRanger" );
+
+ // a texture named like a number leaves the animation's numbers alone
+ names.addAsset( 0, "Art\\Textures\\6.dds" );
+ strcpy( line, " IdleAnimation = AVRanger_SKL.AVRanger_STND 0 6" );
+ CHECK( names.rewriteLine( line, sizeof( line ) ) );
+ CHECK_STR( line, " IdleAnimation = M1~AVRanger_SKL.AVRanger_STND 0 6" );
}
// -modfactions: the file in a path-shaped word is its last part, past either slash