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
test(gamenetwork): build the synthetic latency and loss switch in every config
Olcay Seygan05ac324c3046
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex eddfaa70d..dbd51013b 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -475,6 +475,16 @@ public:Bool m_specialPowerUsesDelay ;#endifBool m_TiVOFastMode; ///< When true, the client speeds up the framerate... set by HOTKEY!++ /* Synthetic link conditions - the transport can hold incoming packets back and throw some of+ them away, so a slow or lossy line can be reproduced on one machine. These lived in the+ debug-only block below, and this fork only ever ships Release, so the switch they drive did+ not exist in any build anyone could run. All five default to off. */+ Int m_latencyAverage; ///< Average latency to insert, in milliseconds+ Int m_latencyAmplitude; ///< Amplitude of the sinusoidal modulation of that latency, in milliseconds+ Int m_latencyPeriod; ///< Period of that modulation, in milliseconds; 0 means no modulation+ Int m_latencyNoise; ///< Max amplitude of the jitter thrown on top, in milliseconds+ Int m_packetLoss; ///< Percent of incoming packets to drop@@ -520,11 +530,6 @@ public:Bool m_useLocalMOTD;AsciiString m_baseStatsDir;AsciiString m_MOTDPath;- Int m_latencyAverage; ///< Average latency to insert- Int m_latencyAmplitude; ///< Amplitude of sinusoidal modulation of latency- Int m_latencyPeriod; ///< Period of sinusoidal modulation of latency- Int m_latencyNoise; ///< Max amplitude of jitter to throw in- Int m_packetLoss; ///< Percent of packets to dropBool m_extraLogging; ///< More expensive debug logging to catch crashes.#endifdiff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/LinkSimulation.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/LinkSimulation.hnew file mode 100644index 000000000..719024e06--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/LinkSimulation.h@@ -0,0 +1,87 @@+/*+** Command & Conquer Generals Zero Hour(tm)+** Copyright 2025 Electronic Arts Inc.+**+** This program is free software: you can redistribute it and/or modify+** it under the terms of the GNU General Public License as published by+** the Free Software Foundation, either version 3 of the License, or+** (at your option) any later version.+**+** This program is distributed in the hope that it will be useful,+** but WITHOUT ANY WARRANTY; without even the implied warranty of+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+** GNU General Public License for more details.+**+** You should have received a copy of the GNU General Public License+** along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++// FILE: LinkSimulation.h ///////////////////////////////////////////////////////////////////////+//+// The two decisions the synthetic link simulator makes, as pure functions: whether an arriving+// packet is thrown away, and how long one that is kept is held back before the game sees it.+// The transport calls both from Transport::doRecv.+//+// They live here rather than inline in the transport for the same reason StallJudgement and+// KeepAliveSchedule do: a decision that can be called without a socket can be tested without one,+// and every number in it can be pinned.+//+// Neither of these may ever be made to depend on anything the simulation reads. The rolls handed+// in come from the client random stream, which is per-machine on purpose, and holding a packet+// back only delays the frame the lockstep protocol was already waiting for - it never changes what+// that frame contains.+//+///////////////////////////////////////////////////////////////////////////////////////////////++#pragma once++#ifndef _LINK_SIMULATION_H_+#define _LINK_SIMULATION_H_++#include <math.h>+#include "Lib/BaseType.h"++/**+ * TRUE when an incoming packet should be thrown away.+ *+ * `roll` is a GameClientRandomValue(1, 100). EA rolled (0, 100) - 101 outcomes - against the same+ * `>=`, so every percentage was one point too lossy and a setting of 0 still threw away one packet+ * in a hundred. Over [1, 100] the count of losing rolls is the percentage itself.+ */+inline Bool linkSimPacketIsLost( Int lossPercent, Int roll )+{+ return lossPercent >= roll;+}++/**+ * The time at which a packet received at `now` should be handed to the game.+ *+ * The delay is a constant average, plus a sine wave of `amplitude` over `period` milliseconds, plus+ * the jitter already rolled by the caller. EA's own line was `sin(now * m_latencyPeriod)`, which+ * makes the "period" a radians-per-millisecond multiplier: at any usable setting the argument moves+ * by whole radians every millisecond, so the term is not a slow modulation at all but a second,+ * bigger noise source - and `now * period` overflows an UnsignedInt after a minute of uptime. Read+ * as the field documents itself instead: a period in milliseconds, and 0 for no modulation.+ *+ * A delay that comes out negative means "hand it over at once"; nothing may be delivered before it+ * arrived.+ */+inline UnsignedInt linkSimDeliveryTime( UnsignedInt now, Int average, Int amplitude, Int period, Int noiseRoll )+{+ Int delay = average + noiseRoll;++ if (period != 0)+ {+ const double twoPi = 6.283185307179586476925286766559;+ const UnsignedInt ms = (UnsignedInt)(period < 0 ? -period : period);+ double phase = twoPi * (double)(now % ms) / (double)ms;+ delay += (Int)(amplitude * sin( phase ));+ }++ if (delay < 0)+ delay = 0;++ return now + (UnsignedInt)delay;+}++#endif // _LINK_SIMULATION_H_diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkDefs.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkDefs.hindex 79fb7fce9..ee6cb0972 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkDefs.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkDefs.h@@ -99,7 +99,10 @@ struct TransportMessage};#pragma pack(pop)-#if defined(_DEBUG) || defined(_INTERNAL)+/**+ * A received packet the transport is holding back, to reproduce a slow link on one machine.+ * Built in every configuration - it used to be debug-only, and this fork only ever ships Release.+ */#pragma pack(push, 1)struct DelayedTransportMessage{@@ -107,7 +110,6 @@ struct DelayedTransportMessageTransportMessage message;};#pragma pack(pop)-#endif/*** Message typesdiff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/Transport.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Transport.hindex b61e38142..e829ad13e 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/Transport.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Transport.h@@ -76,9 +76,7 @@ public:TransportMessage m_outBuffer[MAX_MESSAGES];TransportMessage m_inBuffer[MAX_MESSAGES];-#if defined(_DEBUG) || defined(_INTERNAL)- DelayedTransportMessage m_delayedInBuffer[MAX_MESSAGES];-#endif+ DelayedTransportMessage m_delayedInBuffer[MAX_MESSAGES]; // only used when latency simulation is onUnsignedShort m_port;private:diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex 587616ebb..99f42235a 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -413,7 +413,9 @@ Int parseYRes(char *args[], int num)return 1;}-#if defined(_DEBUG) || defined(_INTERNAL)+/* The five synthetic link conditions below used to be debug-build-only, and this fork only ever+ ships Release, so the switch they drive did not exist in any build anyone could run. They are+ the cheapest way to reproduce a lossy or slow link without a second machine on a bad line. *///=============================================================================//=============================================================================Int parseLatencyAverage(char *args[], int num)@@ -469,6 +471,7 @@ Int parsePacketLoss(char *args[], int num)return 2;}+#if defined(_DEBUG) || defined(_INTERNAL)//=============================================================================//=============================================================================Int parseLowDetail(char *args[], int num)@@ -1160,6 +1163,12 @@ static CommandLineParam params[] ={ "-particlebounce", parseParticleBounce },{ "-quickstart", parseQuickStart },+ { "-packetloss", parsePacketLoss },+ { "-latAvg", parseLatencyAverage },+ { "-latAmp", parseLatencyAmplitude },+ { "-latPeriod", parseLatencyPeriod },+ { "-latNoise", parseLatencyNoise },+#if (defined(_DEBUG) || defined(_INTERNAL)){ "-noaudio", parseNoAudio },{ "-map", parseMapName },@@ -1191,11 +1200,6 @@ static CommandLineParam params[] ={ "-nofade", parseNoFade },{ "-nomovecamera", parseNoMoveCamera },{ "-nocinematic", parseNoCinematic },- { "-packetloss", parsePacketLoss },- { "-latAvg", parseLatencyAverage },- { "-latAmp", parseLatencyAmplitude },- { "-latPeriod", parseLatencyPeriod },- { "-latNoise", parseLatencyNoise },{ "-noViewLimit", parseNoViewLimit },{ "-lowDetail", parseLowDetail },{ "-noDynamicLOD", parseNoDynamicLOD },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex 0bb22d67f..6633e5767 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -380,13 +380,14 @@ GlobalData* GlobalData::m_theOriginal = NULL;{ "AutoAflameParticleSystem", INI::parseAsciiString, NULL, offsetof( GlobalData, m_autoAflameParticleSystem ) },{ "AutoAflameParticleMax", INI::parseInt, NULL, offsetof( GlobalData, m_autoAflameParticleMax ) },-/* These are internal use only, they do not need file definitons+ // Synthetic link conditions, for reproducing a slow or lossy line on one machine. EA had these+ // commented out as "internal use only"; they are no more dangerous than the command-line options+ // that set the same fields, and an INI is the only way to set them for a run the launcher starts.{ "LatencyAverage", INI::parseInt, NULL, offsetof( GlobalData, m_latencyAverage ) },{ "LatencyAmplitude", INI::parseInt, NULL, offsetof( GlobalData, m_latencyAmplitude ) },{ "LatencyPeriod", INI::parseInt, NULL, offsetof( GlobalData, m_latencyPeriod ) },{ "LatencyNoise", INI::parseInt, NULL, offsetof( GlobalData, m_latencyNoise ) },{ "PacketLoss", INI::parseInt, NULL, offsetof( GlobalData, m_packetLoss ) },-*/{ "BuildSpeed", INI::parseReal, NULL, offsetof( GlobalData, m_BuildSpeed ) },{ "MinDistFromEdgeOfMapForBuild", INI::parseReal, NULL, offsetof( GlobalData, m_MinDistFromEdgeOfMapForBuild ) },@@ -569,6 +570,12 @@ GlobalData::GlobalData()#endifm_TiVOFastMode = FALSE;+ m_latencyAverage = 0;+ m_latencyAmplitude = 0;+ m_latencyPeriod = 0;+ m_latencyNoise = 0;+ m_packetLoss = 0;+#if defined(_DEBUG) || defined(_INTERNAL)m_wireframe = 0;m_stateMachineDebug = FALSE;@@ -603,11 +610,6 @@ GlobalData::GlobalData()m_disableCameraFade = false;m_disableScriptedInputDisabling = false;m_disableMilitaryCaption = false;- m_latencyAverage = 0;- m_latencyAmplitude = 0;- m_latencyPeriod = 0;- m_latencyNoise = 0;- m_packetLoss = 0;m_saveStats = FALSE;m_saveAllStats = FALSE;m_useLocalMOTD = FALSE;diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Transport.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Transport.cppindex faed62ff4..c08f8e44a 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Transport.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Transport.cpp@@ -26,6 +26,7 @@#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine#include "Common/CRC.h"+#include "GameNetwork/LinkSimulation.h"#include "GameNetwork/Transport.h"#include "GameNetwork/NetworkInterface.h"@@ -76,6 +77,11 @@ Transport::Transport(void){m_winsockInit = false;m_udpsock = NULL;+ // EA never initialized these two. It did not bite because everything that read them was+ // compiled out of the shipping build; now that the simulator is built in every configuration,+ // a Transport that is used before init() would have run on whatever was on the heap.+ m_useLatency = false;+ m_usePacketLoss = false;}Transport::~Transport(void)@@ -137,9 +143,7 @@ Bool Transport::init( UnsignedInt ip, UnsignedShort port ){m_outBuffer[i].length = 0;m_inBuffer[i].length = 0;-#if defined(_DEBUG) || defined(_INTERNAL)m_delayedInBuffer[i].message.length = 0;-#endif}for (i=0; i<MAX_TRANSPORT_STATISTICS_SECONDS; ++i){@@ -155,13 +159,16 @@ Bool Transport::init( UnsignedInt ip, UnsignedShort port )m_port = port;-#if defined(_DEBUG) || defined(_INTERNAL)- if (TheGlobalData->m_latencyAverage > 0 || TheGlobalData->m_latencyNoise)- m_useLatency = true;+ /* Synthetic link conditions, off unless asked for. Assigned rather than only ever set true:+ EA's version could not turn either switch back off, so a second game in the same process+ inherited the first one's settings. */+ m_useLatency = (TheGlobalData->m_latencyAverage > 0 || TheGlobalData->m_latencyNoise != 0);+ m_usePacketLoss = (TheGlobalData->m_packetLoss != 0);- if (TheGlobalData->m_packetLoss)- m_usePacketLoss = true;-#endif+ DEBUG_ASSERTLOG(!m_useLatency && !m_usePacketLoss,+ ("Transport: simulating a link with %d ms latency (amp %d, period %d, noise %d) and %d%% packet loss\n",+ TheGlobalData->m_latencyAverage, TheGlobalData->m_latencyAmplitude,+ TheGlobalData->m_latencyPeriod, TheGlobalData->m_latencyNoise, TheGlobalData->m_packetLoss));return true;}@@ -250,7 +257,6 @@ Bool Transport::doSend() {}} // for (i=0; i<MAX_MESSAGES; ++i)-#if defined(_DEBUG) || defined(_INTERNAL)// Latency simulation - deliver anything we're holding on to that is readyif (m_useLatency){@@ -271,7 +277,6 @@ Bool Transport::doSend() {}}}-#endifreturn retval;}@@ -287,9 +292,7 @@ Bool Transport::doRecv()// Read in anything on our socketsockaddr_in from;-#if defined(_DEBUG) || defined(_INTERNAL)UnsignedInt now = timeGetTime();-#endifTransportMessage incomingMessage;unsigned char *buf = (unsigned char *)&incomingMessage;@@ -297,16 +300,14 @@ Bool Transport::doRecv()// DEBUG_LOG(("Transport::doRecv - checking\n"));while ( (len=m_udpsock->Read(buf, MAX_MESSAGE_LEN, &from)) > 0 ){-#if defined(_DEBUG) || defined(_INTERNAL)// Packet loss simulationif (m_usePacketLoss){- if ( TheGlobalData->m_packetLoss >= GameClientRandomValue(0, 100) )+ if ( linkSimPacketIsLost( TheGlobalData->m_packetLoss, GameClientRandomValue(1, 100) ) ){continue;}}-#endif// DEBUG_LOG(("Transport::doRecv - Got something! len = %d\n", len));// Decrypt the packet@@ -333,17 +334,16 @@ Bool Transport::doRecv()for (int i=0; i<MAX_MESSAGES; ++i){-#if defined(_DEBUG) || defined(_INTERNAL)// Latency simulationif (m_useLatency){if (m_delayedInBuffer[i].message.length == 0){// Empty slot; use it- m_delayedInBuffer[i].deliveryTime =- now + TheGlobalData->m_latencyAverage +- (Int)(TheGlobalData->m_latencyAmplitude * sin(now * TheGlobalData->m_latencyPeriod)) +- GameClientRandomValue(-TheGlobalData->m_latencyNoise, TheGlobalData->m_latencyNoise);+ m_delayedInBuffer[i].deliveryTime = linkSimDeliveryTime( now,+ TheGlobalData->m_latencyAverage, TheGlobalData->m_latencyAmplitude,+ TheGlobalData->m_latencyPeriod,+ GameClientRandomValue(-TheGlobalData->m_latencyNoise, TheGlobalData->m_latencyNoise) );m_delayedInBuffer[i].message.length = incomingMessage.length;m_delayedInBuffer[i].message.addr = ntohl(from.sin_addr.S_un.S_addr);m_delayedInBuffer[i].message.port = ntohs(from.sin_port);@@ -353,7 +353,6 @@ Bool Transport::doRecv()}else{-#endifif (m_inBuffer[i].length == 0){// Empty slot; use it@@ -363,9 +362,7 @@ Bool Transport::doRecv()memcpy(&m_inBuffer[i], buf, len);break;}-#if defined(_DEBUG) || defined(_INTERNAL)}-#endif}//DEBUG_ASSERTCRASH(i<MAX_MESSAGES, ("Message lost!"));}diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex e62445a47..92d46e9d2 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -34,6 +34,7 @@#include "GameNetwork/StallJudgement.h"#include "GameNetwork/KeepAliveSchedule.h"#include "GameNetwork/CushionMetrics.h"+#include "GameNetwork/LinkSimulation.h"#include <float.h>#include "GameClient/Water.h"#include "GameLogic/Module/PhysicsUpdate.h"@@ -2527,6 +2528,83 @@ TEST(keepalive_every_player_gets_one_within_the_round)CHECK( roundMS <= 15000 ); // under the shortest NAT UDP timeouts seen in the wild}+// ---------------------------------------------------------------------------------------------+// The synthetic link simulator (MULTIPLAYER 6). The transport can hold packets back and throw+// some away, so a lossy or slow line can be reproduced without a second machine. Both decisions+// are pure, so both can be pinned here - including the two things EA got wrong in them, which+// nobody could have noticed because the whole facility was compiled out of the shipping build.+// ---------------------------------------------------------------------------------------------++TEST(linksim_packet_loss_percentage_is_the_percentage)+{+ // the count of losing rolls over the hundred a GameClientRandomValue(1, 100) can produce is+ // the percentage itself. EA rolled (0, 100) - a hundred and one outcomes - against the same+ // comparison, so every setting was one point too lossy...+ Int pct;+ for( pct = 0; pct <= 100; pct++ )+ {+ Int lost = 0;+ for( Int roll = 1; roll <= 100; roll++ )+ if (linkSimPacketIsLost( pct, roll ))+ lost++;+ CHECK_EQ( lost, pct );+ }++ // ...and the setting that says "do not drop anything" dropped one packet in a hundred and one+ CHECK( !linkSimPacketIsLost( 0, 1 ) );+ CHECK( linkSimPacketIsLost( 100, 100 ) );+ CHECK( linkSimPacketIsLost( 1, 1 ) );+ CHECK( !linkSimPacketIsLost( 1, 2 ) );+}++TEST(linksim_delivery_is_the_average_plus_the_jitter)+{+ // no modulation asked for: the delay is exactly what was asked for+ CHECK_EQ( linkSimDeliveryTime( 1000, 40, 0, 0, 0 ), 1040u );+ CHECK_EQ( linkSimDeliveryTime( 1000, 40, 0, 0, 15 ), 1055u );+ CHECK_EQ( linkSimDeliveryTime( 1000, 40, 0, 0, -15 ), 1025u );++ // an amplitude with no period is not a modulation, and must not become one+ CHECK_EQ( linkSimDeliveryTime( 1000, 40, 500, 0, 0 ), 1040u );++ // nothing is ever delivered before it arrived, however the jitter falls+ CHECK_EQ( linkSimDeliveryTime( 1000, 40, 0, 0, -400 ), 1000u );+ CHECK_EQ( linkSimDeliveryTime( 0, 0, 0, 0, -400 ), 0u );+}++TEST(linksim_the_modulation_has_the_period_it_says_it_has)+{+ // a period in milliseconds, read the way the field documents itself: zero phase at the start of+ // every period, the peak a quarter of the way in, the trough three quarters in.+ const Int period = 8000;+ const Int amp = 100;++ CHECK_EQ( linkSimDeliveryTime( 0, 200, amp, period, 0 ), 200u ); // sin 0+ CHECK_EQ( linkSimDeliveryTime( period/4, 200, amp, period, 0 ), (UnsignedInt)(period/4 + 300) ); // sin pi/2+ CHECK_EQ( linkSimDeliveryTime( period/2, 200, amp, period, 0 ), (UnsignedInt)(period/2 + 200) ); // sin pi+ CHECK_EQ( linkSimDeliveryTime( 3*period/4, 200, amp, period, 0 ), (UnsignedInt)(3*period/4 + 100) ); // sin 3pi/2++ // and it repeats: the same point of the next period gives the same delay+ CHECK_EQ( linkSimDeliveryTime( period, 200, amp, period, 0 ) - period, 200u );+ CHECK_EQ( linkSimDeliveryTime( period + period/4, 200, amp, period, 0 ) - (period + period/4), 300u );++ /* EA's own line was sin(now * period), which at any usable setting moves the argument by whole+ radians every millisecond - a second noise source, not a modulation - and overflows an+ UnsignedInt after a minute of uptime. The property that pins the difference: over one+ period the delay is a single smooth hump, so consecutive milliseconds differ by almost+ nothing. Under EA's reading they differ by the whole amplitude. */+ UnsignedInt a = linkSimDeliveryTime( 1000000, 200, amp, period, 0 ) - 1000000;+ UnsignedInt b = linkSimDeliveryTime( 1000001, 200, amp, period, 0 ) - 1000001;+ CHECK( (a > b ? a - b : b - a) <= 1u );++ // still true where EA's version wrapped: uptimes past the point now * period overflows+ UnsignedInt late = 0xFFFFF000u;+ UnsignedInt c = linkSimDeliveryTime( late, 200, amp, period, 0 ) - late;+ UnsignedInt d = linkSimDeliveryTime( late + 1, 200, amp, period, 0 ) - (late + 1);+ CHECK( c >= 100u && c <= 300u );+ CHECK( (c > d ? c - d : d - c) <= 1u );+}+// ---------------------------------------------------------------------------------------------// The cushion, and the self-slug it drives (MULTIPLAYER 3.3). Two type defects met in the// middle here: an unsigned frame subtraction that could wrap, and an Int sentinel returned