Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
fix(gameengine): write the debug log on its own thread, no disk stall
Olcay Seygan3a1cd322a610
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a7a9624d0..c7ef84c6d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -264,6 +264,7 @@ found and fixed — EA's own, not port damage.**- A long match costs less late in the game. Four Hard computer players on Twilight Flame, well into the match, went from 111.6 to 136.2 frames a second, and the step that works out the battle from 5.59ms to 4.78ms. The computer left every group it had made and never filled in a list the game went through on every step until the match ended, and that list is cleared now. A unit looking for something to shoot passes over ground that holds nobody it could shoot at, sight is worked out with fewer lookups, and the smoke and fire are gone through once per step instead of once for every picture. Eight views over five maps came out the same as before.- Every moving unit's skeleton was worked out three times a picture, once for its shadow, once for the scene and once more for the outline drawn when it stands behind a building. It is worked out once now, and late in the same match the animation costs 60% less. With the rules step finding the next unit due for an update a little faster, minutes 24 to 26 went from 119.8 to 123.7 frames a second, and the match still ends on the same checksum.- Late in a match the picture caught less often. Every ten seconds each computer player looked over its economy, its spending and the enemy army all in one step, 8 to 10ms of work landing on a single picture. Those three now run a fifth of a second apart. With four Hard computer players on Twilight Flame at minutes 24 and 25, pictures slower than 16.7ms went from 29 a minute to 22, and the slowest one in a hundred from 14.7ms to 14.0ms. Two more hitches got smaller in the same match. The map of where units can drive is rebuilt whenever a building goes up or comes down, and that rebuild went from 9.9ms to 7.4ms, with the ones over 8ms halved (90 to 43). A Hard computer steering its Particle Cannon beam now weighs the ground around it in 0.9ms instead of 2.6ms. Neither changes a single move: the match ends on the same checksum.+- The game no longer freezes for seconds when your hard drive is busy. It writes a log of the match as it plays, and once a second the battle itself stopped to push that log to disk. On a drive already busy with something else, Windows can hold such a write back for seconds, and the whole game stood still behind it: a 2v2 against the computer froze for 7.8 seconds on a single step. The log is written on the side now and the battle never waits for it. Three matches played while another program kept the drive busy froze for 6.2 seconds in two of them before; with the change, the slowest step in all three took 48ms.- Every animation runs on a clock instead of counting frames.- Tanks and trucks move the same at any frame rate. Their treads scrolled a fixed step every picture, so at 120 frames a second they ran four times too fast, and a tank turning on the spot rolled both treads forward as if it were driving. Each tread now covers exactly the ground under it. In a tight turn the two run against each other, and backing up runs them backwards. Wheels spin with the distance driven the same way. The hull's springs used to settle four times too fast as well, and every start or stop threw the chassis to its full tilt in a single picture. Now a tank squats as it pulls away and dips its nose when it brakes, easing in over a tenth of a second and settling within half a second. In a corner it leans out, a Crusader up to two and a half degrees. The Humvee, which never moved on its springs at all, rocks too. A run drawing one picture per game tick and one drawing fourteen put every tank in the same pose, to the last digit, for as long as neither skipped a tick.- A scroll that starts after the camera has stood still no longer lurches. The first frame of the move was timed from the last time the camera moved, so after a few seconds of looking at one spot it was worth three frames of scrolling at once. The clock runs while the camera is still now, and the first frame moves one frame's worth.diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cppindex 9bbfdadf1..32a15ace5 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp@@ -83,6 +83,13 @@ extern HWND ApplicationHWnd;#endif#include <thread> // the main thread's id off Windows (Windows uses GetCurrentThreadId); GameDataGone's yield#include <atomic> // GameDataGone's state, set from whichever thread's read failed+#include <chrono>+#include <condition_variable>+#include <mutex>+#include <new>+#if !defined(_WIN32)+#include <pthread.h>+#endifextern char *gAppPrefix; /// So WB can have a different log file name.@@ -119,6 +126,138 @@ extern char *gAppPrefix; /// So WB can have a different log file name.// ----------------------------------------------------------------------------#ifdef DEBUG_LOGGINGstatic FILE *theLogFile = NULL;++/* The log file is written by a thread of its own, never by the thread that logs. Flushing once a+ second from the logging thread still put a disk write inside whichever logic frame came due, and+ D: here is a spinning disk: with other copies of the game, a build and a video dump writing to it,+ Windows holds a writer back for seconds, and one 2v2 skirmish logged a 7.8 s logic frame with all+ of it in the AI, the phase that logs the most. A line goes into theLogQueue under a lock held for+ a copy; the writer takes the queue once a second and writes it with that lock released.+ fileLock keeps the writer and a crash path's flushLogQueue from reordering two batches.+ The log opens during static initialisation, from inside the first operator new, before this+ file's statics are constructed and before the memory manager exists. So the queue is built in+ place in static storage when the file opens, and its text is malloc'd, never operator new. */+struct LogQueue+{+ std::mutex queueLock;+ std::recursive_mutex fileLock; // recursive: a crash on the writer thread flushes from inside a flush+ std::condition_variable wake;+ char *text;+ size_t used;+ size_t size;+ // a platform thread, not std::thread, whose start is an operator new before the memory manager exists+#if defined(_WIN32)+ HANDLE writer;+#else+ pthread_t writer;+#endif+ bool running;+ bool quit;+};+alignas(LogQueue) static unsigned char theLogQueueStorage[ sizeof(LogQueue) ];+static LogQueue *theLogQueue = NULL;++static void queueLogOutput(const char *text)+{+ const size_t length = strlen(text);+ std::lock_guard<std::mutex> lock(theLogQueue->queueLock);+ if (theLogQueue->used + length > theLogQueue->size)+ {+ theLogQueue->size = 2 * (theLogQueue->used + length);+ theLogQueue->text = (char *)realloc(theLogQueue->text, theLogQueue->size);+ }+ memcpy(theLogQueue->text + theLogQueue->used, text, length);+ theLogQueue->used += length;+}++/// Everything queued so far into the file and flushed, on the caller's thread. Crash paths and shutdown.+static void flushLogQueue(void)+{+ if (theLogQueue == NULL)+ return; // a crash before the log opened+ std::lock_guard<std::recursive_mutex> fileLock(theLogQueue->fileLock);+ // the writer's own buffer, swapped with the queue's so a line queued meanwhile goes on the next batch+ static char *batch = NULL;+ static size_t batchSize = 0;+ size_t batchUsed;+ {+ std::lock_guard<std::mutex> lock(theLogQueue->queueLock);+ std::swap(batch, theLogQueue->text);+ std::swap(batchSize, theLogQueue->size);+ batchUsed = theLogQueue->used;+ theLogQueue->used = 0;+ }+ if (theLogFile == NULL || batchUsed == 0)+ return;+ fwrite(batch, 1, batchUsed, theLogFile);+ fflush(theLogFile);+}++static void logWriterMain(void)+{+ std::unique_lock<std::mutex> lock(theLogQueue->queueLock);+ while (!theLogQueue->quit)+ {+ theLogQueue->wake.wait_for(lock, std::chrono::seconds(1));+ lock.unlock();+ flushLogQueue();+ lock.lock();+ }+}++#if defined(_WIN32)+static DWORD WINAPI logWriterThread(LPVOID)+{+ logWriterMain();+ return 0;+}+#else+static void *logWriterThread(void *)+{+ logWriterMain();+ return NULL;+}+#endif++static void startLogWriter(void)+{+ if (theLogQueue == NULL)+ {+ theLogQueue = new (theLogQueueStorage) LogQueue;+ theLogQueue->text = NULL;+ theLogQueue->used = 0;+ theLogQueue->size = 0;+ }+ theLogQueue->quit = false;+#if defined(_WIN32)+ theLogQueue->writer = CreateThread(NULL, 0, logWriterThread, NULL, 0, NULL);+ theLogQueue->running = theLogQueue->writer != NULL;+#else+ theLogQueue->running = pthread_create(&theLogQueue->writer, NULL, logWriterThread, NULL) == 0;+#endif+}++static void stopLogWriter(void)+{+ if (theLogQueue == NULL)+ return;+ if (theLogQueue->running)+ {+ {+ std::lock_guard<std::mutex> lock(theLogQueue->queueLock);+ theLogQueue->quit = true;+ }+ theLogQueue->wake.notify_one();+#if defined(_WIN32)+ WaitForSingleObject(theLogQueue->writer, INFINITE);+ CloseHandle(theLogQueue->writer);+#else+ pthread_join(theLogQueue->writer, NULL);+#endif+ theLogQueue->running = false;+ }+ flushLogQueue();+}#endif#define LARGE_BUFFER 8192static char theBuffer[ LARGE_BUFFER ]; // make it big to avoid weird overflow bugs in debug mode@@ -238,7 +377,12 @@ int MessageBoxWrapper( const char *lpText, const char *lpCaption, unsigned int ufprintf(stderr, "%s%s%s\n", lpCaption, (lpCaption && lpCaption[0]) ? ": " : "", lpText);#ifdef DEBUG_LOGGINGif (theLogFile)- fprintf(theLogFile, "[message box] %s%s%s\n", lpCaption, (lpCaption && lpCaption[0]) ? ": " : "", lpText);+ {+ char line[ 4096 ]; // no operator new here: this can run before the memory manager exists+ snprintf(line, sizeof(line), "[message box] %s%s%s\n", lpCaption, (lpCaption && lpCaption[0]) ? ": " : "", lpText);+ queueLogOutput(line);+ flushLogQueue(); // a box is often the last thing before an _exit, and its reason must reach the file+ }#endifreturn (uType & MSGBOX_ABORTRETRYIGNORE)?MSGBOX_ID_IGNORE:MSGBOX_ID_YES;#endif@@ -302,20 +446,8 @@ static const char *prepBuffer(const char* format, char *buffer, size_t bufferSiz/* The log used to be flushed after every line, which made each DEBUG_LOG inside a logic frame asynchronous write to disk. Single units in big fights logged update times of 60 to 145ms withnothing in the pathfinder, always beside a log line, and did not repeat on a rerun of the same- seed. The file is flushed at most once a second now, and in full on every crash path before the- process exits, so the last lines before a crash still reach it. */-static const UnsignedInt LOG_FLUSH_INTERVAL_MS = 1000;-static UnsignedInt theLastLogFlushMS = 0;--static void flushLogFileAtMostOnceASecond(void)-{- const UnsignedInt nowMS = Clock_Milliseconds_Coarse();- if (nowMS - theLastLogFlushMS < LOG_FLUSH_INTERVAL_MS)- return;- theLastLogFlushMS = nowMS;- fflush(theLogFile);-}-+ seed. The lines go to the writer thread now (theLogQueue), which writes them once a second, and+ every crash path writes the queue out itself before the process exits. */static void doLogOutput(const char *buffer){/* DebugLog already holds this lock around its static buffer; DebugCrash and the stack dump reach@@ -329,10 +461,7 @@ static void doLogOutput(const char *buffer)if (theDebugFlags & DEBUG_FLAG_LOG_TO_FILE){if (theLogFile)- {- fprintf(theLogFile, "%s", buffer); // note, no \n (should be there already)- flushLogFileAtMostOnceASecond();- }+ queueLogOutput(buffer); // note, no \n (should be there already)}// log message to dev studio output window@@ -372,8 +501,7 @@ static int doCrashBox(const char *buffer, Bool logResult)#ifdef DEBUG_LOGGINGif (logResult)DebugLog("[Abort]\n");- if (theLogFile)- fflush(theLogFile);+ flushLogQueue();#endif_exit(1);break;@@ -456,8 +584,7 @@ static int __cdecl unattendedCrtReport( int, char *message, int *returnValue )#ifdef DEBUG_STACKTRACEdoStackDump();#endif- if (theLogFile != NULL)- fflush(theLogFile);+ flushLogQueue();#endifif (returnValue != NULL)*returnValue = 0; // no debugger@@ -531,6 +658,8 @@ void DebugInit(int flags)#endifif (theLogFile != NULL){+ startLogWriter();+ atexit(stopLogWriter); // exit() from anywhere still gets the last second of linesDebugLog("Log %s opened: %s\n", curbuf, getCurrentTimeString());if (hadPreviousLog && rotated != 0)DebugLog("Could not rotate the previous log to %s: it holds an older run than this one.\n", prevbuf);@@ -676,6 +805,7 @@ void DebugShutdown()if (theLogFile){DebugLog("Log closed: %s\n", getCurrentTimeString());+ stopLogWriter();#if !defined(_WIN32)setCrashLogDescriptor(-1);#endif@@ -859,9 +989,12 @@ double SimpleProfiler::getAverageTime()void ReleaseCrash(const char *reason){#ifdef DEBUG_LOGGING- // the debug log is flushed on a timer, and this function ends in _exit, which skips the CRT's own flush- if (theLogFile)- fflush(theLogFile);+ // the debug log is written by its own thread once a second, and this function ends in _exit+ flushLogQueue();+ // From here to _exit the file is this thread's alone, so the writer cannot cut into the report+ // with other threads' lines. Never released; what is queued meanwhile goes out before each _exit.+ if (theLogQueue != NULL)+ theLogQueue->fileLock.lock();#endifreleaseCrashToLog(reason);@@ -919,6 +1052,9 @@ void ReleaseCrash(const char *reason)fclose(theReleaseCrashLogFile);theReleaseCrashLogFile = NULL;}+#ifdef DEBUG_LOGGING+ flushLogQueue(); // the "could not write" line above, if there was one+#endifhideFullScreenWindowForMessage();// the log is written by now; a run nobody is watching should die rather than wait for a click@@ -998,8 +1134,7 @@ static void gameDataGoneExit( void )DEBUG_LOG(( "GAME DATA GONE: %s\n", text ));#ifdef DEBUG_LOGGING- if (theLogFile)- fflush( theLogFile ); // flushed on a timer otherwise, and _exit below skips the CRT's flush+ flushLogQueue(); // written once a second otherwise, and _exit below skips the CRT's flush#endiffprintf( stderr, "GAME DATA GONE: %s\n", text );fflush( stderr );@@ -1033,9 +1168,10 @@ void GameDataGoneCheck( void )void ReleaseCrashLocalized(const AsciiString& p, const AsciiString& m){#ifdef DEBUG_LOGGING- // see ReleaseCrash: the log is flushed on a timer and _exit below skips the CRT's flush- if (theLogFile)- fflush(theLogFile);+ // see ReleaseCrash: the log is written once a second and _exit below skips the CRT's flush+ flushLogQueue();+ if (theLogQueue != NULL)+ theLogQueue->fileLock.lock(); // the report uninterrupted, as in ReleaseCrash#endifif (!TheGameText) {ReleaseCrash(m.str());@@ -1114,6 +1250,9 @@ void ReleaseCrashLocalized(const AsciiString& p, const AsciiString& m)fclose(theReleaseCrashLogFile);theReleaseCrashLogFile = NULL;}+#ifdef DEBUG_LOGGING+ flushLogQueue();+#endif_exit(1);}