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): refuse damaged maps and undo map.ini after the match
Olcay Seygan1319c799dcd2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 28ca20d1a..4561181aa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1638,6 +1638,8 @@ The whole HUD is on the hardware. Four colours carry it, and they mean the same- Another player can no longer make your game write files the host never announced, rewrite or remove someone else's LAN game, crash you with a malformed network or lobby message, or flood your memory with oversized commands. A command with an invalid weapon slot is refused.- Crash fixes: ordering an upgrade with a Supply Drop Zone, a GLA Hole or a captured Oil Derrick selected, a map that shows a counter it never set, a camera shake at a waypoint that is not there, and closing a menu while it animates. A map message with a percent sign in it shows as written.- Stopped sounds really stop. A destroyed unit's engine loop and a turret's turning loop no longer play on, and the Idle Worker tooltip shows its key.+- A damaged map sends you back to the menu with a box naming it as damaged, instead of closing the game. A map file is whatever its maker handed you, and the reader trusted every count in it: a height map claiming four billion cells, a trigger with a negative number of points or a tile class pointing past its table either crashed the game or read on into the next part of the file, where every machine found different garbage. Each count is checked against what the file can hold now, and a map that fails is left out of the list or refused at the start, the same way on every machine in the match.+- A custom map's rules last for that match only. A map.ini could rewrite a weapon, a sound, a particle effect, an FX list, the water or the snow, and the next match on another map played with the change still in it, so two players who had played different maps before were running different rules. Every store a map may touch puts the game's own values back when the match ends, and a block a map has no business changing (the mouse, the multiplayer colours, the campaigns) is skipped with the rest of the file still loading. A map.ini that raised a unit's price showed it on the button and charged the old one; it charges what the button says now. Values no sane map uses, a build time of a hundred years or a snowstorm a million flakes wide, are refused one line at a time.## Units take corners wide, and drive round a jam instead of into itdiff --git a/GeneralsMD/Code/Data/Patch.str b/GeneralsMD/Code/Data/Patch.strindex f05a90c5c..a58cb11f5 100644--- a/GeneralsMD/Code/Data/Patch.str+++ b/GeneralsMD/Code/Data/Patch.str@@ -1161,6 +1161,10 @@ GUI:SaveFromOlderGame"This save was made by the original game or by an older version of Reforged, and cannot be loaded."END+GUI:MapCorrupt+"The map %ls is damaged and cannot be played."+END+GUI:KickVoteStarted"%ls wants %ls out of the match. Type /yes or /no in chat: every other player has 30 seconds to agree."ENDdiff --git a/GeneralsMD/Code/Data/Turkish/Generals.str b/GeneralsMD/Code/Data/Turkish/Generals.strindex 7de534c3b..ad0a135f7 100644--- a/GeneralsMD/Code/Data/Turkish/Generals.str+++ b/GeneralsMD/Code/Data/Turkish/Generals.str@@ -15577,6 +15577,10 @@ GUI:SaveFromOlderGame"Bu kayıt orijinal oyunla ya da Reforged'ın eski bir sürümüyle yapılmış, yüklenemez."END+GUI:MapCorrupt+"%ls haritası bozuk, oynanamaz."+END+GUI:KickVoteStarted"%ls, %ls oyuncusunun maçtan atılmasını istiyor. Sohbete /yes ya da /no yazın: diğer oyuncuların kabul etmek için 30 saniyesi var."ENDdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/DamageFX.h b/GeneralsMD/Code/GameEngine/Include/Common/DamageFX.hindex 3cdb0689e..680255eba 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/DamageFX.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/DamageFX.h@@ -159,6 +159,7 @@ private:typedef std::hash_map< NameKeyType, DamageFX, rts::hash<NameKeyType>, rts::equal_to<NameKeyType> > DamageFXMap;DamageFXMap m_dfxmap;+ std::vector< std::pair<NameKeyType, DamageFX> > m_beforeMapOverrides; ///< see reset()};diff --git a/GeneralsMD/Code/GameEngine/Include/Common/DataChunk.h b/GeneralsMD/Code/GameEngine/Include/Common/DataChunk.hindex 0ee4f8240..cc84be234 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/DataChunk.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/DataChunk.h@@ -184,6 +184,7 @@ protected:void clearChunkStack( void ); // clear the stackvoid decrementDataLeft( int size ); // update data left in chunk(s)+ void readFromChunk( void *ptr, Int len ); // read len bytes of the current chunk, or throw ERROR_CORRUPT_FILE_FORMATpublic:void *m_currentObject; // user parse routines can use this to allow one chunk@@ -229,6 +230,9 @@ public:UnicodeString readUnicodeString(void);Dict readDict(void);void readArrayOfBytes(char *ptr, Int len);+ /// an Int count of items each at least bytesEach long, refused (ERROR_CORRUPT_FILE_FORMAT) when+ /// negative or when that many could not fit in what is left of the chunk+ Int readCount(Int bytesEach);NameKeyType readNameKey(void);};diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h b/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.hindex 38553fb82..a04806aa6 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h@@ -257,6 +257,8 @@ class AudioManager : public SubsystemInterfacevirtual void processRequestList( void );virtual AudioEventInfo *newAudioEventInfo( AsciiString newEventName );+ /// a map.ini is about to define this event; keep the game's own copy for reset(). TRUE if it existed+ Bool rememberEventBeforeMapINI( AsciiString eventName );virtual void addAudioEventInfo( AudioEventInfo * newEventInfo );virtual AudioEventInfo *findAudioEventInfo( AsciiString eventName ) const;@@ -342,6 +344,7 @@ class AudioManager : public SubsystemInterfacestd::vector<AsciiString> m_musicTracks;AudioEventInfoHash m_allAudioEventInfo;+ std::vector< std::pair<AudioEventInfo *, AudioEventInfo *> > m_beforeMapOverrides; ///< live event, its copy from before the mapAudioHandle theAudioHandlePool;std::list<std::pair<AsciiString, Real> > m_adjustedVolumes;diff --git a/GeneralsMD/Code/GameEngine/Include/Common/INI.h b/GeneralsMD/Code/GameEngine/Include/Common/INI.hindex 09f63b091..a92dee73a 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/INI.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/INI.h@@ -364,6 +364,13 @@ public:static void parseUnsignedInt( INI *ini, void *instance, void *store, const void* userData );static void parseReal( INI *ini, void *instance, void *store, const void* userData );static void parsePositiveNonZeroReal( INI *ini, void *instance, void *store, const void* userData );+ /// userData is a const RealRange*; a value outside it, or NaN, is ignored in a map's rules file+ /// (INI_LOAD_CREATE_OVERRIDES) and throws INI_INVALID_DATA anywhere else+ struct RealRange { Real lo, hi; };+ static void parseRealInRange( INI *ini, void *instance, void *store, const void* userData );+ /// userData is a const IntRange*; out of range (past an Int included) is treated as parseRealInRange does+ struct IntRange { Int lo, hi; };+ static void parseIntInRange( INI *ini, void *instance, void *store, const void* userData );static void parseBool( INI *ini, void *instance, void *store, const void* userData );static void parseBitInInt32( INI *ini, void *instance, void *store, const void* userData );static void parseAsciiString( INI *ini, void *instance, void *store, const void* userData );diff --git a/GeneralsMD/Code/GameEngine/Include/Common/MapReaderWriterInfo.h b/GeneralsMD/Code/GameEngine/Include/Common/MapReaderWriterInfo.hindex 65fe2d7ec..1e3c17ce9 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/MapReaderWriterInfo.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/MapReaderWriterInfo.h@@ -58,6 +58,11 @@#define K_LIGHTING_VERSION_3 3 // Added 2 additional global lights for terrain.#define K_WORLDDICT_VERSION_1 1#define K_MAPPREVIEW_VERSION_1 1++// The widest height map a map file may claim, border included. Retail maps are a few hundred+// cells a side; the bound is only there so that width times height, and the arrays sized from it,+// are a number a corrupt or hostile file cannot overflow or exhaust memory with.+#define K_MAX_HEIGHT_MAP_SIDE 4096/** Virtual helper class, so that we can write map data using FILE* or CFile. */class OutputStream {public:diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.h b/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.hindex 8715a4ec1..9cc4f0534 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.h@@ -611,7 +611,7 @@ public:Real calcMaxHealth( void ) const;/// Used only by Skirmish AI. Everyone else should call calcCostToBuild.- Int friend_getBuildCost() const { return m_buildCost; }+ Int friend_getBuildCost() const { return getBuildCost(); }const AsciiString& getDefaultOwningSide() const { return m_defaultOwningSide; }@@ -654,8 +654,10 @@ protected:// these are NOT publicly available; you should call calcCostToBuild() or calcTimeToBuild()// instead, because they will take player handicaps into account.//- Int getBuildCost() const { return m_buildCost; }- Real getBuildTime() const { return m_buildTime; }+ // Through the final override: a command button and a build list hold the base template, and a+ // map.ini's BuildCost showed in the tooltip and the sell price but was never charged.+ Int getBuildCost() const { return ((const ThingTemplate *)getFinalOverride())->m_buildCost; }+ Real getBuildTime() const { return ((const ThingTemplate *)getFinalOverride())->m_buildTime; }const PerUnitSoundMap* getAllPerUnitSounds( void ) const { return &m_perUnitSounds; }void validateAudio();const AudioEventRTS* getAudio(ThingTemplateAudioType t) const { return m_audioarray.m_audio[t] ? &m_audioarray.m_audio[t]->m_event : &s_audioEventNoSound; }diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/FXList.h b/GeneralsMD/Code/GameEngine/Include/GameClient/FXList.hindex 49f288cb8..8fa18983c 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/FXList.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/FXList.h@@ -141,6 +141,12 @@ public:m_nuggets.push_back(fxn);}+ /// trade contents; the nuggets are owned, so a list cannot be copied+ void swap(FXList &that)+ {+ m_nuggets.swap(that.m_nuggets);+ }+/// inline convenience method to avoid having to check for null.inline static void doFXPos(const FXList* fx, const Coord3D *primary, const Matrix3D* primaryMtx = NULL, const Real primarySpeed = 0.0f, const Coord3D *secondary = NULL, const Real overrideRadius = 0.0f){@@ -198,7 +204,7 @@ public:~FXListStore();void init() { }- void reset() { }+ void reset();void update() { }/**@@ -216,6 +222,9 @@ private:FXListMap m_fxmap;+ FXListMap m_beforeMapOverrides; ///< a map.ini's edited lists, as they were before it+ std::vector<NameKeyType> m_addedByMap; ///< names a map.ini brought+};// EXTERNALS //////////////////////////////////////////////////////////////////////////////////////diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.hindex c17685d41..3750062ec 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h@@ -910,6 +910,8 @@ public:ParticleSystemTemplate *findTemplate( const AsciiString &name ) const;ParticleSystemTemplate *findParentTemplate( const AsciiString &name, int parentNum ) const;ParticleSystemTemplate *newTemplate( const AsciiString &name );+ /// a map.ini is about to write over this template; reset() puts it back+ void rememberTemplateBeforeMapINI( ParticleSystemTemplate *sysTemplate );/// given a template, instantiate a particle systemParticleSystem *createParticleSystem( const ParticleSystemTemplate *sysTemplate,@@ -990,6 +992,7 @@ protected:private:TemplateMap m_templateMap; ///< a hash map of all particle system templates+ std::vector< std::pair<ParticleSystemTemplate *, ParticleSystemInfo> > m_beforeMapOverrides; ///< see reset()};/// The particle system manager singletondiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/CaveSystem.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/CaveSystem.hindex ec66deb26..90de91f2b 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/CaveSystem.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/CaveSystem.h@@ -39,6 +39,11 @@ class TunnelTracker; // The player owns one such object for his Tunnels, so inst#include "Common/Snapshot.h"#include "Common/SubsystemInterface.h"+// The index is a slot in a vector that registerNewCave pads with NULLs up to it, so a map's+// CaveIndex or SET_CAVE_INDEX of a million allocates a million slots, and a negative one never+// stops padding. Retail uses a handful; xfer writes the count as an UnsignedShort.+enum { MAX_CAVE_INDEX_COUNT = 1024 };+/**System responsible for Crates as code objects - ini, new/delete etc*/diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.hindex fef851a9e..dde4e4b48 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h@@ -181,6 +181,7 @@ public:// super hackvoid startNewGame( Bool loadSaveGame );+ void refuseCorruptMap( void ); ///< a start whose map turned out unreadable goes back to the menusvoid loadMapINI( AsciiString mapName );void updateLoadProgress( Int progress );diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CaveContain.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CaveContain.hindex 953b093dd..9bc934d60 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CaveContain.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/CaveContain.h@@ -38,6 +38,7 @@// INCLUDES ///////////////////////////////////////////////////////////////////////////////////////#include "GameLogic/Module/CreateModule.h"#include "GameLogic/Module/OpenContain.h"+#include "GameLogic/CaveSystem.h"struct Sound;class Team;@@ -53,13 +54,15 @@ public:m_caveIndexData = 0;// By default, all Caves will be grouped together as number 0}- static void buildFieldParse(MultiIniFieldParse& p)+ static void buildFieldParse(MultiIniFieldParse& p){OpenContainModuleData::buildFieldParse(p);- static const FieldParse dataFieldParse[] =+ // a map's rules file can redefine a cave, and the index becomes a vector slot+ static const INI::IntRange caveIndexRange = { 0, MAX_CAVE_INDEX_COUNT - 1 };+ static const FieldParse dataFieldParse[] ={- { "CaveIndex", INI::parseInt, NULL, offsetof( CaveContainModuleData, m_caveIndexData ) },+ { "CaveIndex", INI::parseIntInRange, &caveIndexRange, offsetof( CaveContainModuleData, m_caveIndexData ) },{ 0, 0, 0, 0 }};p.add(dataFieldParse);diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.hindex 79399990c..cb5a054fb 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h@@ -1624,7 +1624,20 @@ inline void PartitionManager::worldToCell(Real wx, Real wy, Int *cx, Int *cy)//-----------------------------------------------------------------------------inline Int PartitionManager::worldToCellDist(Real w){- return REAL_TO_INT_CEIL(w * m_cellSizeInv);+ // A map object can carry any vision or shroud range, and a circle a million cells wide is a+ // float-to-int overflow and then a loop over the square of it. Twice the grid's width plus+ // height reaches every cell from a centre well off the map, so a reveal that big touches+ // exactly the cells it touched unclamped. The threat and value falloff divides by the radius+ // and would move, but the one retail object that sees 99999 (ChinaArtilleryCannon) has no+ // shroud range and so never draws one. NaN fails the first test and lands on the limit.+ // Before init the counts are zero and so is m_cellSizeInv.+ const Real limit = (Real)(2 * (m_cellCountX + m_cellCountY));+ Real cells = w * m_cellSizeInv;+ if (!(cells <= limit))+ cells = limit;+ else if (cells < -limit)+ cells = -limit;+ return REAL_TO_INT_CEIL(cells);}//-----------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.hindex ac7850871..7290ffd7d 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h@@ -900,6 +900,7 @@ private:};std::vector<WeaponTemplate*> m_weaponTemplateVector;+ Int m_countBeforeMapOverrides; ///< templates before a map.ini added its own, -1 if it added none// Looking a weapon up by name walked that whole vector. The same templates are indexed here// by name key; the vector stays because load order is what iterates it.diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cppindex dceff2c81..493d53a5b 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp@@ -294,6 +294,18 @@ void AudioManager::postProcessLoad()//-------------------------------------------------------------------------------------------------void AudioManager::reset(){+ // Sounds, dialogue and music a map.ini redefined go back to the game's own, in place, because+ // every AudioEventRTS that played one holds the pointer; backwards, so map.ini then solo.ini on+ // the same event ends at the first. A voice line's length is what a script waiting on it counts,+ // so this is not only what the next match sounds like. An event the map added stays: the next+ // definition starts again from the default event, as a new one would.+ for (Int i = (Int)m_beforeMapOverrides.size() - 1; i >= 0; --i)+ {+ *m_beforeMapOverrides[i].first = *m_beforeMapOverrides[i].second;+ m_beforeMapOverrides[i].second->deleteInstance();+ }+ m_beforeMapOverrides.clear();+// clear out any adjusted volumes we might have set.m_adjustedVolumes.clear();@@ -887,6 +899,20 @@ AudioEventInfo *AudioManager::newAudioEventInfo( AsciiString audioName )return m_allAudioEventInfo[audioName];}+//-------------------------------------------------------------------------------------------------+Bool AudioManager::rememberEventBeforeMapINI( AsciiString eventName )+{+ // the same lookup newAudioEventInfo makes, so this keeps the event the parse will write over+ AudioEventInfo *live = findAudioEventInfo(eventName);+ if (live == NULL)+ return FALSE;++ AudioEventInfo *copy = newInstance(AudioEventInfo);+ *copy = *live;+ m_beforeMapOverrides.push_back(std::make_pair(live, copy));+ return TRUE;+}+//-------------------------------------------------------------------------------------------------// Add an AudioEventInfo structure allocated elsewhere to the audio event listvoid AudioManager::addAudioEventInfo( AudioEventInfo * newEvent )diff --git a/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cpp b/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cppindex 1f869505e..e20a78463 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/DamageFX.cpp@@ -295,9 +295,15 @@ void DamageFXStore::init()}//-------------------------------------------------------------------------------------------------+/** Puts back what a map.ini changed, as ArmorStore::reset does: backwards, so a DamageFX both map.ini+ * and solo.ini changed goes back to the first state, and in place, because body modules hold a+ * pointer to it. A name the map brought stays; a later definition clears it first anyway. */void DamageFXStore::reset(){-}+ for (Int i = (Int)m_beforeMapOverrides.size() - 1; i >= 0; --i)+ m_dfxmap[m_beforeMapOverrides[i].first] = m_beforeMapOverrides[i].second;+ m_beforeMapOverrides.clear();+}//-------------------------------------------------------------------------------------------------void DamageFXStore::update()@@ -310,6 +316,9 @@ void DamageFXStore::update()const char *c = ini->getNextToken();NameKeyType key = TheNameKeyGenerator->nameToKey(c);+ DamageFXMap::const_iterator existing = TheDamageFXStore->m_dfxmap.find(key);+ if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES && existing != TheDamageFXStore->m_dfxmap.end())+ TheDamageFXStore->m_beforeMapOverrides.push_back(std::make_pair(key, existing->second));DamageFX& dfx = TheDamageFXStore->m_dfxmap[key];dfx.clear();ini->initFromINI(&dfx, dfx.getFieldParse());diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex 7bb2d7eda..7a69aca91 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -78,6 +78,10 @@ static void parseIgnoredField( INI *, void *, void *, const void * ){}+// A map's map.ini can carry a GameData block. Retail is 40; a tiny cell makes the partition grid+// millions of cells on a large map, a huge one leaves the whole map in a handful of cells.+static const INI::RealRange PARTITION_CELL_SIZE_RANGE = { 20.0f, 400.0f };+///////////////////////////////////////////////////////////////////////////////////////////////////// PRIVATE DATA //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////@@ -230,7 +234,7 @@ static void parseIgnoredField( INI *, void *, void *, const void * ){ "StealthFriendlyOpacity", INI::parsePercentToReal, NULL, offsetof( GlobalData, m_stealthFriendlyOpacity ) },{ "DefaultOcclusionDelay", INI::parseDurationUnsignedInt, NULL, offsetof( GlobalData, m_defaultOcclusionDelay ) },- { "PartitionCellSize", INI::parseReal, NULL, offsetof( GlobalData, m_partitionCellSize ) },+ { "PartitionCellSize", INI::parseRealInRange, &PARTITION_CELL_SIZE_RANGE, offsetof( GlobalData, m_partitionCellSize ) },{ "AmmoPipScaleFactor", INI::parseReal, NULL, offsetof( GlobalData, m_ammoPipScaleFactor ) },{ "ContainerPipScaleFactor", INI::parseReal, NULL, offsetof( GlobalData, m_containerPipScaleFactor ) },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cppindex 6f1c92366..9543770a0 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp@@ -322,6 +322,34 @@ void INI::unPrepFile()s_xfer = NULL;}+//-------------------------------------------------------------------------------------------------+/** The blocks a map's rules file (map.ini, solo.ini, read INI_LOAD_CREATE_OVERRIDES) may hold: the+ * ones whose stores put the map's edits back at the end of the match. Every other block in the+ * table either wrote over the game's own data for good (the mouse, the in-game UI, multiplayer+ * colours, terrain types, campaigns, videos) or refused a name an earlier map had added (roads,+ * bridges, animations, EVA events), so the same map read differently on a machine that had played+ * another first. No shipped map uses one; one in a custom map is skipped and the rest of the file+ * still loads, on every machine alike. MappedImage stays: an image is drawn, never read by+ * the simulation, and custom maps bring their own cameos with it. */+//-------------------------------------------------------------------------------------------------+static Bool isMapINIBlock(const char* token)+{+ static const char *const MapINIBlocks[] =+ {+ "AIData", "Armor", "AudioEvent", "CommandButton", "CommandSet", "CrateData", "DamageFX",+ "DialogEvent", "FXList", "GameData", "Locomotor", "MappedImage", "MusicTrack", "Object",+ "ObjectCreationList", "ObjectReskin", "ParticleSystem", "PlayerTemplate", "Rank", "Science",+ "SpecialPower", "Upgrade", "WaterSet", "WaterTransparency", "Weather", "Weapon",+ NULL+ };+ for (const char *const *name = MapINIBlocks; *name; ++name)+ {+ if (strcmp(*name, token) == 0)+ return TRUE;+ }+ return FALSE;+}+//-------------------------------------------------------------------------------------------------static INIBlockParse findBlockParse(const char* token){@@ -390,6 +418,31 @@ void INI::load( AsciiString filename, INILoadType loadType, Xfer *pXfer )if( token ){INIBlockParse parse = findBlockParse(token);+ if (parse && m_loadType == INI_LOAD_CREATE_OVERRIDES && !isMapINIBlock(token))+ {+ /* Read past it and go on with the file. Nothing parses it, so its End is found by+ counting: an End closes, a line with no '=' opens a sub-block (Mission, SideSounds,+ a radius cursor), every other line is a field. The count is the same on every+ machine, so is what follows.+ ponytail: a field written without its '=' counts as an opening and the skip runs+ on past the block; a real parse of each refused type if a map ever needs it. */+ DEBUG_LOG(("[LINE: %d - FILE: '%s'] a map's rules file may not hold a '%s' block, skipped\n",+ getLineNum(), getFilename().str(), token));+ Int depth = 1;+ while( depth > 0 && m_endOfFile == FALSE )+ {+ readLine();+ const Bool isField = strchr( m_buffer, '=' ) != NULL;+ const char *word = strtok( m_buffer, m_seps );+ if( word == NULL )+ continue;+ if( strcasecmp( word, m_blockEndToken ) == 0 )+ --depth;+ else if( !isField )+ ++depth;+ }+ continue;+ }if (parse){#if defined(_DEBUG) || defined(_INTERNAL)@@ -920,7 +973,18 @@ void INI::parseShort( INI* ini, void * /*instance*/, void *store, const void* /*void INI::parseUnsignedShort( INI* ini, void * /*instance*/, void *store, const void* /*userData*/ ){const char *token = ini->getNextToken();- Int value = scanInt(token);+ /* sscanf's %d on a number past Int is undefined, and the CRTs disagree: a map's BuildCost of+ 99999999999 came out in range on one machine and was refused on another. strtoll is defined+ there (it saturates), and reads every in-range token the way %d did. */+ char *end;+ long long value = strtoll(token, &end, 10);+ if (end == token)+ throw INI_INVALID_DATA;+ if ((value < 0 || value > 65535) && ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES)+ {+ DEBUG_LOG(("[LINE: %d in '%s'] %s does not fit 0..65535, the line is ignored\n", ini->getLineNum(), ini->getFilename().str(), token));+ return;+ }if (value < 0 || value > 65535){DEBUG_CRASH(("Bad value INI::parseUnsignedShort"));@@ -974,6 +1038,52 @@ void INI::parsePositiveNonZeroReal( INI* ini, void * /*instance*/, void *store,}+//-------------------------------------------------------------------------------------------------+/** A real that a map's rules file can set to something the game cannot live with: a build time+ * that overflows the frame count, a snow box that divides by zero. Refused before it is stored,+ * and NaN with it, since a NaN fails both comparisons. In a map's rules file only the line goes:+ * the value stays what it was and the rest of the file loads. The game's own data stops. */+//-------------------------------------------------------------------------------------------------+static void refuseOutOfRange( INI *ini, const char *what )+{+ DEBUG_LOG(("[LINE: %d in '%s'] %s is out of range, refused\n", ini->getLineNum(), ini->getFilename().str(), what));+ if (ini->getLoadType() != INI_LOAD_CREATE_OVERRIDES)+ throw INI_INVALID_DATA;+}++void INI::parseRealInRange( INI* ini, void * /*instance*/, void *store, const void* userData )+{+ const RealRange *range = (const RealRange *)userData;+ const char *token = ini->getNextToken();+ Real value = scanReal(token);+ if (!(value >= range->lo && value <= range->hi))+ {+ refuseOutOfRange(ini, token);+ return;+ }+ *(Real *)store = value;+}++//-------------------------------------------------------------------------------------------------+/** The integer twin. strtoll rather than sscanf's %d, whose answer for a number past Int is+ * undefined and differs between the CRTs (see parseUnsignedShort). */+//-------------------------------------------------------------------------------------------------+void INI::parseIntInRange( INI* ini, void * /*instance*/, void *store, const void* userData )+{+ const IntRange *range = (const IntRange *)userData;+ const char *token = ini->getNextToken();+ char *end;+ long long value = strtoll(token, &end, 10);+ if (end == token)+ throw INI_INVALID_DATA;+ if (value < range->lo || value > range->hi)+ {+ refuseOutOfRange(ini, token);+ return;+ }+ *(Int *)store = (Int)value;+}+//-------------------------------------------------------------------------------------------------/** Parse a degree value (0 to 360) and store the radian value of that degree* in a Real */diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAudioEventInfo.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAudioEventInfo.cppindex 162772875..202d69f18 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAudioEventInfo.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIAudioEventInfo.cpp@@ -48,7 +48,12 @@ void INI::parseMusicTrackDefinition( INI* ini )// read the nameconst char* c = ini->getNextToken();- name.set( c );+ name.set( c );++ // a map's music track is put back after the match; listed again it would play twice as often+ Bool existed = FALSE;+ if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES)+ existed = TheAudio->rememberEventBeforeMapINI( name );track = TheAudio->newAudioEventInfo( name );if (!track) {@@ -58,7 +63,8 @@ void INI::parseMusicTrackDefinition( INI* ini )AudioEventInfo *defaultInfo = TheAudio->findAudioEventInfo("DefaultMusicTrack");if (defaultInfo) {(*track) = (*defaultInfo);- TheAudio->addTrackName( name );+ if (!existed)+ TheAudio->addTrackName( name );}track->m_audioName = name;@@ -76,7 +82,10 @@ void INI::parseAudioEventDefinition( INI* ini )// read the nameconst char* c = ini->getNextToken();- name.set( c );+ name.set( c );++ if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES)+ TheAudio->rememberEventBeforeMapINI( name );track = TheAudio->newAudioEventInfo( name );if (!track) {@@ -103,7 +112,10 @@ void INI::parseDialogDefinition( INI* ini )// read the nameconst char* c = ini->getNextToken();- name.set( c );+ name.set( c );++ if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES)+ TheAudio->rememberEventBeforeMapINI( name );track = TheAudio->newAudioEventInfo( name );if (!track) {diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIParticleSys.cppindex 915f9949f..ef940abb3 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIParticleSys.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIParticleSys.cpp@@ -52,6 +52,10 @@ void INI::parseParticleSystemDefinition( INI* ini )sysTemplate = TheParticleSystemManager->newTemplate( name );}+ // a map's rules file edits the template every system of that name is made from+ if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES)+ TheParticleSystemManager->rememberTemplateBeforeMapINI( sysTemplate );+// parse the ini definitionini->initFromINI( sysTemplate, sysTemplate->getFieldParse() );}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cppindex 2e4553b8c..e14172b99 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp@@ -390,4 +390,10 @@ void SpecialPowerStore::reset( void )++it;}}++ // A power a map adds takes the next id, and the id is what a special power command carries. The+ // counter went on climbing over the powers deleted above, so the same map's power got a different+ // id on a machine that had played another custom map first. The survivors are the game's own, in+ // the order they were numbered.+ m_nextSpecialPowerID = m_specialPowerTemplates.empty() ? 0 : m_specialPowerTemplates.back()->getID();} // end resetdiff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cppindex 51ef9ccee..3ae711c2b 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/DataChunk.cpp@@ -548,6 +548,11 @@ void DataChunkTableOfContents::read( ChunkInputStream &s)for( i=0; i<count; i++ ){+ // the count is the file's word; a table that runs off the end of the file leaves the+ // header unopened below either way, so stop instead of allocating up to two billion names+ if (s.eof())+ break;+// allocate new id mappingm = newInstance(Mapping);@@ -751,6 +756,10 @@ AsciiString DataChunkInput::openDataChunk(DataChunkVersionType *ver )if (this->atEndOfFile()) {return (AsciiString(""));}+ // A chunk is nested whole inside its parent. One that claims more than the parent has left, or+ // a negative size, would have every read past it land in the parent's next chunk.+ if (c->dataSize < 0 || (c->next && c->next->dataLeft < c->dataSize))+ throw ERROR_CORRUPT_FILE_FORMAT;return m_contents.getName( c->id );}@@ -858,38 +867,53 @@ void DataChunkInput::decrementDataLeft( Int size )// The sizes of the parent chunks on the stack are adjusted in closeDataChunk.}-Real DataChunkInput::readReal(void)-{+// A map is a file anyone can hand the game. EA only asserted here, so a release build read on past+// the chunk into the next one, or past the end of the file, where the read copies nothing and the+// value is whatever the stack held: a different number on every machine. A field the chunk does+// not have, or a file that stops short, is corrupt in every build.+void DataChunkInput::readFromChunk( void *ptr, Int len )+{+ if (len < 0 || m_chunkStack->dataLeft < len)+ throw ERROR_CORRUPT_FILE_FORMAT;+ if (m_file->read( ptr, len ) != len)+ throw ERROR_CORRUPT_FILE_FORMAT;+ decrementDataLeft( len );+}++Real DataChunkInput::readReal(void)+{Real r;- DEBUG_ASSERTCRASH(m_chunkStack->dataLeft>=sizeof(Real), ("Read past end of chunk."));- m_file->read( (char *)&r, sizeof(Real) );- decrementDataLeft( sizeof(Real) );- return r;+ readFromChunk( &r, sizeof(Real) );+ return r;}-Int DataChunkInput::readInt(void)-{+Int DataChunkInput::readInt(void)+{Int i;- DEBUG_ASSERTCRASH(m_chunkStack->dataLeft>=sizeof(Int), ("Read past end of chunk."));- m_file->read( (char *)&i, sizeof(Int) );- decrementDataLeft( sizeof(Int) );- return i;+ readFromChunk( &i, sizeof(Int) );+ return i;}-Byte DataChunkInput::readByte(void)-{+Byte DataChunkInput::readByte(void)+{Byte b;- DEBUG_ASSERTCRASH(m_chunkStack->dataLeft>=sizeof(Byte), ("Read past end of chunk."));- m_file->read( (char *)&b, sizeof(Byte) );- decrementDataLeft( sizeof(Byte) );- return b;+ readFromChunk( &b, sizeof(Byte) );+ return b;}-void DataChunkInput::readArrayOfBytes(char *ptr, Int len)-{- DEBUG_ASSERTCRASH(m_chunkStack->dataLeft>=len, ("Read past end of chunk."));- m_file->read( ptr, len );- decrementDataLeft( len );+void DataChunkInput::readArrayOfBytes(char *ptr, Int len)+{+ readFromChunk( ptr, len );+}++// A count is what a parser sizes an allocation from before it reads the items, so a count the+// chunk cannot hold is refused before anything is allocated for it.+Int DataChunkInput::readCount(Int bytesEach)+{+ Int count = readInt();+ if (count < 0 || count > m_chunkStack->dataLeft / bytesEach)+ throw ERROR_CORRUPT_FILE_FORMAT;+ return count;}NameKeyType DataChunkInput::readNameKey(void)@@ -908,11 +932,8 @@ NameKeyType DataChunkInput::readNameKey(void)Dict DataChunkInput::readDict(){- UnsignedShort len;- DEBUG_ASSERTCRASH(m_chunkStack->dataLeft>=sizeof(UnsignedShort), ("Read past end of chunk."));- m_file->read( &len, sizeof(UnsignedShort) );- decrementDataLeft( sizeof(UnsignedShort) );- DEBUG_ASSERTCRASH(m_chunkStack->dataLeft>=len, ("Read past end of chunk."));+ UnsignedShort len;+ readFromChunk( &len, sizeof(UnsignedShort) );Dict d(len);@@ -953,16 +974,12 @@ Dict DataChunkInput::readDict()AsciiString DataChunkInput::readAsciiString(void){- UnsignedShort len;- DEBUG_ASSERTCRASH(m_chunkStack->dataLeft>=sizeof(UnsignedShort), ("Read past end of chunk."));- m_file->read( &len, sizeof(UnsignedShort) );- decrementDataLeft( sizeof(UnsignedShort) );- DEBUG_ASSERTCRASH(m_chunkStack->dataLeft>=len, ("Read past end of chunk."));+ UnsignedShort len;+ readFromChunk( &len, sizeof(UnsignedShort) );AsciiString theString;if (len>0) {char *str = theString.getBufferForRead(len);- m_file->read( str, len );- decrementDataLeft( len );+ readFromChunk( str, len );// add null delimiter to string. Note that getBufferForRead allocates space for terminating null.str[len] = '\000';}@@ -972,16 +989,12 @@ AsciiString DataChunkInput::readAsciiString(void)UnicodeString DataChunkInput::readUnicodeString(void){- UnsignedShort len;- DEBUG_ASSERTCRASH(m_chunkStack->dataLeft>=sizeof(UnsignedShort), ("Read past end of chunk."));- m_file->read( &len, sizeof(UnsignedShort) );- decrementDataLeft( sizeof(UnsignedShort) );- DEBUG_ASSERTCRASH(m_chunkStack->dataLeft>=len, ("Read past end of chunk."));+ UnsignedShort len;+ readFromChunk( &len, sizeof(UnsignedShort) );UnicodeString theString;if (len>0) {WideChar *str = theString.getBufferForRead(len);- m_file->read( (char*)str, len*sizeof(WideChar) );- decrementDataLeft( len*sizeof(WideChar) );+ readFromChunk( str, len*sizeof(WideChar) );// add null delimiter to string. Note that getBufferForRead allocates space for terminating null.str[len] = '\000';}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cppindex fefc09e47..643bbc385 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp@@ -111,15 +111,21 @@ void Upgrade::loadPostProcess( void )// UPGRADE TEMPLATE //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+// A map's rules file can set these. A time past an Int of frames was a float-to-int conversion the+// platforms answer differently (see ThingTemplate's BuildTimeRange), and a cost past an Int was+// sscanf's undefined overflow. Both are refused, the same way on every machine.+static const INI::RealRange UpgradeBuildTimeRange = { 0.0f, 86400.0f };+static const INI::IntRange UpgradeBuildCostRange = { 0, 1000000 };+//-------------------------------------------------------------------------------------------------//--------------------------------------------------------------------------------------------------const FieldParse UpgradeTemplate::m_upgradeFieldParseTable[] =+const FieldParse UpgradeTemplate::m_upgradeFieldParseTable[] ={{ "DisplayName", INI::parseAsciiString, NULL, offsetof( UpgradeTemplate, m_displayNameLabel ) },{ "Type", INI::parseIndexList, TheUpgradeTypeNames, offsetof( UpgradeTemplate, m_type ) },- { "BuildTime", INI::parseReal, NULL, offsetof( UpgradeTemplate, m_buildTime ) },- { "BuildCost", INI::parseInt, NULL, offsetof( UpgradeTemplate, m_cost ) },+ { "BuildTime", INI::parseRealInRange, &UpgradeBuildTimeRange, offsetof( UpgradeTemplate, m_buildTime ) },+ { "BuildCost", INI::parseIntInRange, &UpgradeBuildCostRange, offsetof( UpgradeTemplate, m_cost ) },{ "ButtonImage", INI::parseAsciiString, NULL, offsetof( UpgradeTemplate, m_buttonImageName ) },{ "ResearchSound", INI::parseAudioEventRTS, NULL, offsetof( UpgradeTemplate, m_researchSound ) },{ "UnitSpecificSound", INI::parseAudioEventRTS, NULL, offsetof( UpgradeTemplate, m_unitSpecificSound ) },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cppindex 676157791..cd32713e5 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp@@ -113,8 +113,15 @@ AudioEventRTS ThingTemplate::s_audioEventNoSound;*/+/* calcTimeToBuild turns seconds into an Int frame count and multiplies it by the handicap, the+ faction modifier and up to 100 for low power. A map's rules file with a BuildTime past that, or+ below zero, or not a number, went through a float-to-int conversion the platforms answer+ differently (x64 a large negative, ARM64 saturated), and Windows and Mac players built at+ different speeds in the same match. A day is far past any real object and safe in the Int. */+static const INI::RealRange BuildTimeRange = { 0.0f, 86400.0f };+// NOTE NOTE NOTE -- s_objectFieldParseTable and s_objectReskinFieldParseTable must be updated in tandem -- see comment above-const FieldParse ThingTemplate::s_objectFieldParseTable[] =+const FieldParse ThingTemplate::s_objectFieldParseTable[] ={{ "DisplayName", INI::parseAndTranslateLabel, NULL, offsetof( ThingTemplate, m_displayName ) },{ "RadarPriority", INI::parseByteSizedIndexList, RadarPriorityNames, offsetof( ThingTemplate, m_radarPriority ) },@@ -146,7 +153,7 @@ const FieldParse ThingTemplate::s_objectFieldParseTable[] ={ "Prerequisites", ThingTemplate::parsePrerequisites, 0, 0 },{ "Buildable", INI::parseByteSizedIndexList, BuildableStatusNames, offsetof( ThingTemplate, m_buildable) },{ "BuildCost", INI::parseUnsignedShort, NULL, offsetof( ThingTemplate, m_buildCost ) },- { "BuildTime", INI::parseReal, NULL, offsetof( ThingTemplate, m_buildTime ) },+ { "BuildTime", INI::parseRealInRange, &BuildTimeRange, offsetof( ThingTemplate, m_buildTime ) },{ "RefundValue", INI::parseUnsignedShort, NULL, offsetof( ThingTemplate, m_refundValue ) },{ "BuildCompletion", INI::parseByteSizedIndexList, BuildCompletionNames, offsetof( ThingTemplate, m_buildCompletion ) },{ "EnergyProduction", INI::parseInt, NULL, offsetof( ThingTemplate, m_energyProduction ) },diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cppindex 2ee957f0d..b0104553c 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cpp@@ -931,11 +931,41 @@ const FXList *FXListStore::findFXList(const char* name) const// read the FXList nameconst char *c = ini->getNextToken();NameKeyType key = TheNameKeyGenerator->nameToKey(c);+ if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES)+ {+ FXListStore *store = TheFXListStore;+ if (store->m_fxmap.find(key) == store->m_fxmap.end())+ store->m_addedByMap.push_back(key);+ else if (store->m_beforeMapOverrides.find(key) == store->m_beforeMapOverrides.end()+ && std::find(store->m_addedByMap.begin(), store->m_addedByMap.end(), key) == store->m_addedByMap.end())+ store->m_beforeMapOverrides[key].swap(store->m_fxmap[key]); // the game's own list, kept whole+ }FXList& fxl = TheFXListStore->m_fxmap[key];fxl.clear();ini->initFromINI(&fxl, TheFXListFieldParse);}+//-------------------------------------------------------------------------------------------------+/** A map.ini rewrote FXLists in place and the next match played with them. The game's own lists+ * go back. A list the map brought is emptied rather than removed: a weapon whose effect name+ * found nothing at startup was pointed at it when the map loaded (WeaponStore::postProcessLoad),+ * and an empty list draws what the missing one did, nothing. */+//-------------------------------------------------------------------------------------------------+void FXListStore::reset()+{+ for (FXListMap::iterator it = m_beforeMapOverrides.begin(); it != m_beforeMapOverrides.end(); ++it)+ {+ FXList &live = m_fxmap[it->first];+ live.clear();+ live.swap(it->second);+ }+ m_beforeMapOverrides.clear();++ for (size_t i = 0; i < m_addedByMap.size(); ++i)+ m_fxmap[m_addedByMap[i]].clear();+ m_addedByMap.clear();+}+//-------------------------------------------------------------------------------------------------/*static*/ void INI::parseFXListDefinition(INI *ini){diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cppindex 7992098dd..c05cfc5b8 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp@@ -3738,6 +3738,13 @@ CommandSet *ControlBar::newCommandSetOverride( CommandSet *setToOverride )return NULL;}+ /* Hang the override off the end of the chain. findNonConstCommandSet hands back the base set (the+ button lookup hands back the final override), so a set map.ini and solo.ini both edit, or one+ file edits twice, copied the base, next-override pointer and all, and hung the copy off the+ base: the chain ran base, second, first, the final override was the first edit and the second+ never showed. */+ setToOverride = (CommandSet *)setToOverride->friend_getFinalOverride();+// allocate a new setCommandSet* set = newInstance(CommandSet)(setToOverride->getName());diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cppindex eeaea0865..dac56a3a6 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp@@ -226,6 +226,10 @@ static Bool ParseSizeOnly(DataChunkInput &file, DataChunkInfo *info, void *userD{m_width = file.readInt();m_height = file.readInt();+ // the game's own reader refuses these (WorldHeightMapData::ParseHeightMapData), so the list does too+ if (m_width < 1 || m_width > K_MAX_HEIGHT_MAP_SIDE || m_height < 1 || m_height > K_MAX_HEIGHT_MAP_SIDE) {+ throw ERROR_CORRUPT_FILE_FORMAT;+ }if (info->version >= K_HEIGHT_MAP_VERSION_3) {m_borderSize = file.readInt();} else {@@ -233,7 +237,7 @@ static Bool ParseSizeOnly(DataChunkInput &file, DataChunkInfo *info, void *userD}if (info->version >= K_HEIGHT_MAP_VERSION_4) {- Int numBorders = file.readInt();+ Int numBorders = file.readCount(2 * sizeof(Int));m_boundaries.resize(numBorders);for (int i = 0; i < numBorders; ++i) {m_boundaries[i].x = file.readInt();diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Snow.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Snow.cppindex c0296dec0..701e28235 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Snow.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Snow.cpp@@ -104,6 +104,14 @@ SnowManager::~SnowManager()OVERRIDE<WeatherSetting> TheWeatherSetting = NULL;+/* A map's rules file can carry a Weather block. A box under one unit made updateIniSettings take+ rand() modulo zero, a zero density or velocity divided by zero, and the snow drawn each frame is+ about (box * density) squared flakes, so a big box or density hung the frame. Shipped data uses+ boxes of 100 and 200, density 1 to 4 and velocity 2.5 to 25; the limits leave room around that. */+static const INI::RealRange SnowBoxRange = { 1.0f, 400.0f };+static const INI::RealRange SnowDensityRange = { 0.05f, 4.0f };+static const INI::RealRange SnowVelocityRange = { 0.1f, 500.0f };+// PRIVATE DATA ///////////////////////////////////////////////////////////////////////////////////const FieldParse WeatherSetting::m_weatherSettingFieldParseTable[] ={@@ -115,9 +123,9 @@ const FieldParse WeatherSetting::m_weatherSettingFieldParseTable[] ={ "SnowMaxPointSize", INI::parseReal,NULL, offsetof( WeatherSetting, m_snowMaxPointSize ) },{ "SnowMinPointSize", INI::parseReal,NULL, offsetof( WeatherSetting, m_snowMinPointSize ) },{ "SnowQuadSize", INI::parseReal,NULL, offsetof( WeatherSetting, m_snowQuadSize ) },- { "SnowBoxDimensions", INI::parseReal,NULL, offsetof( WeatherSetting, m_snowBoxDimensions ) },- { "SnowBoxDensity", INI::parseReal,NULL, offsetof( WeatherSetting, m_snowBoxDensity ) },- { "SnowVelocity", INI::parseReal,NULL, offsetof( WeatherSetting, m_snowVelocity ) },+ { "SnowBoxDimensions", INI::parseRealInRange,&SnowBoxRange, offsetof( WeatherSetting, m_snowBoxDimensions ) },+ { "SnowBoxDensity", INI::parseRealInRange,&SnowDensityRange, offsetof( WeatherSetting, m_snowBoxDensity ) },+ { "SnowVelocity", INI::parseRealInRange,&SnowVelocityRange, offsetof( WeatherSetting, m_snowVelocity ) },{ "SnowPointSprites", INI::parseBool,NULL, offsetof( WeatherSetting, m_usePointSprites ) },{ "SnowEnabled", INI::parseBool,NULL, offsetof( WeatherSetting, m_snowEnabled ) },{ 0, 0, 0, 0 },diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cppindex 79d99605f..f4d37e606 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp@@ -3656,7 +3656,24 @@ void ParticleSystemManager::reset( void )m_uniqueSystemID = INVALID_PARTICLE_SYSTEM_ID;m_lastLogicFrameUpdate = -1;- // leave templates as-is++ // Templates stay, but not as a map.ini left them: each one it wrote over gets its state from+ // before back, backwards so map.ini and solo.ini on the same system end at the first. A system the+ // map made from nothing goes back to a fresh template's defaults rather than away, since an FXList+ // that named it may hold it. The slave is looked up again from the restored name.+ for( Int i = (Int)m_beforeMapOverrides.size() - 1; i >= 0; --i )+ {+ ParticleSystemTemplate *sysTemplate = m_beforeMapOverrides[ i ].first;+ (ParticleSystemInfo &)*sysTemplate = m_beforeMapOverrides[ i ].second;+ sysTemplate->m_slaveTemplate = NULL;+ }+ m_beforeMapOverrides.clear();+}++// ------------------------------------------------------------------------------------------------+void ParticleSystemManager::rememberTemplateBeforeMapINI( ParticleSystemTemplate *sysTemplate )+{+ m_beforeMapOverrides.push_back( std::make_pair( sysTemplate, (const ParticleSystemInfo &)*sysTemplate ) );}// ------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cppindex bef9a11bf..242cc05ef 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp@@ -168,7 +168,8 @@ Bool PolygonTrigger::ParsePolygonTriggersDataChunk(DataChunkInput &file, DataChuriverStart = file.readInt();}- numPoints = file.readInt();+ // the points are allocated from this count before they are read, three Ints each+ numPoints = file.readCount(3 * sizeof(Int));PolygonTrigger *pTrig = newInstance(PolygonTrigger)(numPoints+1);pTrig->setTriggerName(triggerName);if (info->version >= K_TRIGGERS_VERSION_4) {diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/WorldHeightMapData.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/WorldHeightMapData.cppindex d6ed79d47..9b8b1c77e 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/WorldHeightMapData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/WorldHeightMapData.cpp@@ -173,6 +173,10 @@ Bool WorldHeightMapData::ParseHeightMapData(DataChunkInput &file, DataChunkInfo{m_width = file.readInt();m_height = file.readInt();+ // everything below is sized from these, so a map file's word for them is checked first+ if (m_width < 1 || m_width > K_MAX_HEIGHT_MAP_SIDE || m_height < 1 || m_height > K_MAX_HEIGHT_MAP_SIDE) {+ throw ERROR_CORRUPT_FILE_FORMAT;+ }if (info->version >= K_HEIGHT_MAP_VERSION_3) {m_borderSize = file.readInt();} else {@@ -180,7 +184,7 @@ Bool WorldHeightMapData::ParseHeightMapData(DataChunkInput &file, DataChunkInfo}if (info->version >= K_HEIGHT_MAP_VERSION_4) {- Int numBorders = file.readInt();+ Int numBorders = file.readCount(2 * sizeof(Int));m_boundaries.resize(numBorders);for (int i = 0; i < numBorders; ++i) {m_boundaries[i].x = file.readInt();@@ -193,10 +197,10 @@ Bool WorldHeightMapData::ParseHeightMapData(DataChunkInput &file, DataChunkInfo}m_dataSize = file.readInt();- m_data = MSGNEW("WorldHeightMap_ParseHeightMapData") UnsignedByte[m_dataSize];- if (m_dataSize <= 0 || (m_dataSize != (m_width*m_height))) {+ if (m_dataSize != m_width*m_height) {throw ERROR_CORRUPT_FILE_FORMAT ;}+ m_data = MSGNEW("WorldHeightMap_ParseHeightMapData") UnsignedByte[m_dataSize];Int numBytesX = (m_width+7)/8; //how many bytes to fit all bitflagsInt numBytesY = m_height;@@ -234,6 +238,10 @@ Bool WorldHeightMapData::ParseSizeOnly(DataChunkInput &file, DataChunkInfo *info{m_width = file.readInt();m_height = file.readInt();+ // as in ParseHeightMapData+ if (m_width < 1 || m_width > K_MAX_HEIGHT_MAP_SIDE || m_height < 1 || m_height > K_MAX_HEIGHT_MAP_SIDE) {+ throw ERROR_CORRUPT_FILE_FORMAT;+ }if (info->version >= K_HEIGHT_MAP_VERSION_3) {m_borderSize = file.readInt();} else {@@ -241,7 +249,7 @@ Bool WorldHeightMapData::ParseSizeOnly(DataChunkInput &file, DataChunkInfo *info}if (info->version >= K_HEIGHT_MAP_VERSION_4) {- Int numBorders = file.readInt();+ Int numBorders = file.readCount(2 * sizeof(Int));m_boundaries.resize(numBorders);for (int i = 0; i < numBorders; ++i) {m_boundaries[i].x = file.readInt();@@ -254,10 +262,10 @@ Bool WorldHeightMapData::ParseSizeOnly(DataChunkInput &file, DataChunkInfo *info}m_dataSize = file.readInt();- m_data = MSGNEW("WorldHeightMap_ParseSizeOnly") UnsignedByte[m_dataSize];- if (m_dataSize <= 0 || (m_dataSize != (m_width*m_height))) {+ if (m_dataSize != m_width*m_height) {throw ERROR_CORRUPT_FILE_FORMAT ;}+ m_data = MSGNEW("WorldHeightMap_ParseSizeOnly") UnsignedByte[m_dataSize];file.readArrayOfBytes((char *)m_data, m_dataSize);// Resize me.if (info->version == K_HEIGHT_MAP_VERSION_1) {@@ -551,8 +559,22 @@ Bool WorldHeightMapData::parseLogicalMap(ChunkInputStream *pStrm)PolygonTrigger::deleteTriggers(); // just in case.TheSidesList->emptySides();file.registerParser(AsciiString("SidesList"), AsciiString::TheEmptyString, SidesList::ParseSidesDataChunk );- if (!file.parse(this))+ // a map that fails halfway leaves the globals empty rather than half filled, as WorldHeightMap's does+ Bool parsed;+ try {+ parsed = file.parse(this);+ } catch (...) {+ freeListOfMapObjects();+ PolygonTrigger::deleteTriggers();+ TheSidesList->emptySides();+ throw;+ }+ if (!parsed) {+ freeListOfMapObjects();+ PolygonTrigger::deleteTriggers();+ TheSidesList->emptySides();return FALSE;+ }TheSidesList->validateSides();return TRUE;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/CaveContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/CaveContain.cppindex dfc12024d..2bea5942c 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/CaveContain.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/CaveContain.cpp@@ -272,6 +272,11 @@ void CaveContain::onBuildComplete( void )//-------------------------------------------------------------------------------------------------void CaveContain::tryToSetCaveIndex( Int newIndex ){+ // The index comes from a map script, so one the cave system cannot hold is a failed try,+ // the same as switching into a cave that has someone in it.+ if( newIndex < 0 || newIndex >= MAX_CAVE_INDEX_COUNT )+ return;+if( TheCaveSystem->canSwitchIndexToIndex( m_caveIndex, newIndex ) ){TunnelTracker *myOldTracker = TheCaveSystem->getTunnelTrackerForCaveIndex( m_caveIndex );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cppindex 095c566ac..7a0282258 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp@@ -1579,9 +1579,9 @@ void WeaponTemplate::dealDamageInternal(ObjectID sourceID, ObjectID victimID, co//-------------------------------------------------------------------------------------------------//-------------------------------------------------------------------------------------------------//--------------------------------------------------------------------------------------------------WeaponStore::WeaponStore()+WeaponStore::WeaponStore() : m_countBeforeMapOverrides(-1){-}+}//-------------------------------------------------------------------------------------------------WeaponStore::~WeaponStore()@@ -1765,6 +1765,21 @@ void WeaponStore::reset()}}+ /* A weapon the map made from nothing goes too. Left in the store, the next map that defined the+ same name edited this one, from the old map's values instead of a new weapon's defaults, and+ a machine that had not played the old map built a different weapon. The templates that held+ it were the map's own and went with ThingFactory::reset. */+ if (m_countBeforeMapOverrides >= 0)+ {+ for (size_t i = m_countBeforeMapOverrides; i < m_weaponTemplateVector.size(); ++i)+ {+ m_weaponTemplateHashMap.erase(m_weaponTemplateVector[i]->m_nameKey);+ m_weaponTemplateVector[i]->deleteInstance();+ }+ m_weaponTemplateVector.resize(m_countBeforeMapOverrides);+ m_countBeforeMapOverrides = -1;+ }+deleteAllDelayedDamage();deleteWeaponsNow();resetWeaponTemplates();@@ -1958,6 +1973,8 @@ void WeaponStore::postProcessLoad()else{// no item is present, create a new one+ if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES && TheWeaponStore->m_countBeforeMapOverrides < 0)+ TheWeaponStore->m_countBeforeMapOverrides = (Int)TheWeaponStore->m_weaponTemplateVector.size();weapon = TheWeaponStore->newWeaponTemplate(name);}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cppindex 0842252e0..1156ce056 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp@@ -76,6 +76,7 @@#include "GameClient/InGameUI.h"#include "GameClient/LoadScreen.h"#include "GameClient/MapUtil.h"+#include "GameClient/MessageBox.h"#include "GameClient/Mouse.h"#include "GameClient/ParticleSys.h"#include "GameClient/TerrainVisual.h"@@ -429,6 +430,10 @@ void GameLogic::init( void )m_rankPointsToAddAtGameStart = 0;}+// the water table as it was before a map.ini's WaterSet blocks, put back by reset()+static WaterSetting s_waterSettingsBeforeMapINI[ TIME_OF_DAY_COUNT ];+static Bool s_waterSettingsSaved = FALSE;+//-------------------------------------------------------------------------------------------------/** Reset the game logic systems *///-------------------------------------------------------------------------------------------------@@ -500,6 +505,17 @@ void GameLogic::reset( void )// Clean up any weather overrides that were generated for this map.WeatherSetting *ws = (WeatherSetting*) TheWeatherSetting.getNonOverloadedPointer();TheWeatherSetting = (WeatherSetting*) ws->deleteOverrides();+ // the snow manager copied the map's numbers when the Weather block was read+ if (TheSnowManager)+ TheSnowManager->updateIniSettings();++ // WaterSet has no override chain: the block writes straight into the time-of-day table+ if (s_waterSettingsSaved)+ {+ for (Int i = 0; i < TIME_OF_DAY_COUNT; ++i)+ WaterSettings[ i ] = s_waterSettingsBeforeMapINI[ i ];+ s_waterSettingsSaved = FALSE;+ }m_rankPointsToAddAtGameStart = 0;} // end reset@@ -1113,6 +1129,34 @@ void GameLogic::deleteLoadScreen( void )} // end deleteLoadScreen+// ------------------------------------------------------------------------------------------------+/** startNewGame threw ERROR_CORRUPT_FILE_FORMAT part-way through the map. Take down what the start+ * had put up, as a failed save load does, and say why on the menu it was started from. */+// ------------------------------------------------------------------------------------------------+void GameLogic::refuseCorruptMap( void )+{+ DEBUG_LOG(("GameLogic::refuseCorruptMap - '%s' does not load, back to the menus\n", TheGlobalData->m_mapName.str()));++ UnicodeString mapName;+ mapName.translate( TheGlobalData->m_mapName );++ deleteLoadScreen();+ TheWritableGlobalData->m_loadScreenRender = FALSE;+ setLoadingMap( FALSE );+ TheMouse->setVisibility( TRUE );++ if( TheRecorder->getMode() == RECORDERMODETYPE_RECORD )+ TheRecorder->stopRecording();++ clearGameData( FALSE );+ TheShell->showShell( TRUE );++ UnicodeString msg;+ msg.format( TheGameText->fetch( "GUI:MapCorrupt" ), mapName.str() );+ MessageBoxOk( TheGameText->fetch( "GUI:Error" ), msg, NULL );++} // end refuseCorruptMap+// ------------------------------------------------------------------------------------------------/** Entry point for starting a new game, the engine is already in clean state at this* point and ready to load up with all the data */@@ -2563,6 +2607,18 @@ void GameLogic::loadMapINI( AsciiString mapName )// Keep what parsed up to the bad line and play on: every machine in a match has the same file,// the map CRC sees to that, so each stops at the same line and the rules still agree.//+ //+ // Everything below is undone when the match ends: each store a map's rules file may write to+ // keeps what it overwrote and its reset() puts it back (INI.cpp's isMapINIBlock names them), so+ // the next match plays the game's own rules whatever map came before, on every machine alike.+ //+ if (!s_waterSettingsSaved)+ {+ for (Int i = 0; i < TIME_OF_DAY_COUNT; ++i)+ s_waterSettingsBeforeMapINI[ i ] = WaterSettings[ i ];+ s_waterSettingsSaved = TRUE;+ }+snprintf(fullFledgeFilename, _MAX_PATH, "%s\\map.ini", filename); fullFledgeFilename[_MAX_PATH-1] = 0;if (TheFileSystem->doesFileExist(fullFledgeFilename)) {DEBUG_LOG(("Loading map.ini\n"));@@ -4595,7 +4651,22 @@ void GameLogic::update( void )#ifdef _PROFILEProfile::StartRange("map_load");#endif- startNewGame( FALSE );+ /* The map cache reads only a map's size, world info and objects, so a map damaged in its+ sides, triggers or blend tiles is listed, picked and sent, and first fails here. Every+ machine in the match has the same bytes, the map CRC sees to that, so each one fails on the+ same chunk and each goes back to the menus the same way, instead of ending the program. */+ try+ {+ startNewGame( FALSE );+ }+ catch (ErrorCode ec)+ {+ if (ec != ERROR_CORRUPT_FILE_FORMAT)+ throw;+ m_startNewGame = FALSE;+ refuseCorruptMap();+ return;+ }#ifdef _PROFILEProfile::StopRange("map_load");#endifdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cppindex 6b48e7a64..24b8e513e 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp@@ -219,11 +219,22 @@ WorldHeightMap::WorldHeightMap(ChunkInputStream *pStrm, Bool logicalDataOnly):#endiffile.registerParser( AsciiString("GlobalLighting"), AsciiString::TheEmptyString, ParseLightingDataChunk );}- if (!file.parse(this)) {-- throw(ERROR_CORRUPT_FILE_FORMAT);+ // A map that turns out corrupt halfway has already put its first objects, triggers and sides+ // into the globals the logical branch fills. Leave them empty rather than half a map for+ // whatever loads next.+ try {+ if (!file.parse(this)) {+ throw(ERROR_CORRUPT_FILE_FORMAT);+ }+ } catch (...) {+ if (logicalDataOnly) {+ freeListOfMapObjects();+ PolygonTrigger::deleteTriggers();+ TheSidesList->emptySides();+ }+ throw;}- // patch bad maps.+ // patch bad maps.if (!logicalDataOnly) {for(i=0; i<m_dataSize; i++) {if (m_cliffInfoNdxes[i]<0 || m_cliffInfoNdxes[i]>= m_numCliffInfo) {@@ -576,6 +587,16 @@ void WorldHeightMap::readTexClass(TXTextureClass *texClass, TileData **tileData)* Input: DataChunkInput**/+/** readTexClass writes up to ten by ten tiles of a class from its firstTile on into a+ NUM_SOURCE_TILES array, both numbers straight from the map file. */+static void checkTexClassTiles(const TXTextureClass &texClass)+{+ const Int tilesWritten = min(texClass.numTiles, 100);+ if (texClass.firstTile < 0 || texClass.numTiles < 0 || texClass.firstTile > NUM_SOURCE_TILES - tilesWritten) {+ throw ERROR_CORRUPT_FILE_FORMAT;+ }+}+Bool WorldHeightMap::ParseBlendTileData(DataChunkInput &file, DataChunkInfo *info, void *userData){// The cells - tile indexes, flip and cliff bits - are the data half's (GameLogic/WorldHeightMapData.cpp),@@ -583,6 +604,8 @@ Bool WorldHeightMap::ParseBlendTileData(DataChunkInput &file, DataChunkInfo *infif (!parseBlendTileCells(file, info))return false;int i; // and no j: the cell loop that used it is parseBlendTileCells' now (MSVC's C4101, W2)+ // Every count below indexes a fixed array of this class, so a map file that claims more than+ // the array holds is corrupt; EA only asserted, and a release build wrote past the array.m_numBitmapTiles = file.readInt();DEBUG_ASSERTCRASH(m_numBitmapTiles>0 && m_numBitmapTiles<2048, ("Unlikely numBitmapTiles."));m_numBlendedTiles = file.readInt();@@ -592,9 +615,17 @@ Bool WorldHeightMap::ParseBlendTileData(DataChunkInput &file, DataChunkInfo *inf} else {m_numCliffInfo = 1; // cliffInfo[0] is the default info.}+ if (m_numBitmapTiles < 0 || m_numBitmapTiles > NUM_SOURCE_TILES+ || m_numBlendedTiles < 1 || m_numBlendedTiles > NUM_BLEND_TILES+ || m_numCliffInfo < 1 || m_numCliffInfo > NUM_CLIFF_INFO) {+ throw ERROR_CORRUPT_FILE_FORMAT;+ }// --> file loading herem_numTextureClasses = file.readInt();DEBUG_ASSERTCRASH(m_numTextureClasses>0 && m_numTextureClasses<200, ("Unlikely m_numTextureClasses."));+ if (m_numTextureClasses < 0 || m_numTextureClasses > NUM_TEXTURE_CLASSES) {+ throw ERROR_CORRUPT_FILE_FORMAT;+ }for (i=0; i<m_numTextureClasses; i++) {m_textureClasses[i].globalTextureClass = -1;m_textureClasses[i].firstTile = file.readInt();@@ -606,6 +637,7 @@ Bool WorldHeightMap::ParseBlendTileData(DataChunkInput &file, DataChunkInfo *inf/* Int legacy = */ file.readInt();m_textureClasses[i].name = file.readAsciiString();+ checkTexClassTiles(m_textureClasses[i]);readTexClass(&m_textureClasses[i], m_sourceTiles);}m_numEdgeTextureClasses = 0;@@ -613,12 +645,17 @@ Bool WorldHeightMap::ParseBlendTileData(DataChunkInput &file, DataChunkInfo *infif (info->version >= K_BLEND_TILE_VERSION_4) {m_numEdgeTiles = file.readInt();m_numEdgeTextureClasses = file.readInt();+ if (m_numEdgeTiles < 0 || m_numEdgeTiles > NUM_SOURCE_TILES+ || m_numEdgeTextureClasses < 0 || m_numEdgeTextureClasses > NUM_TEXTURE_CLASSES) {+ throw ERROR_CORRUPT_FILE_FORMAT;+ }for (i=0; i<m_numEdgeTextureClasses; i++) {m_edgeTextureClasses[i].globalTextureClass = -1;m_edgeTextureClasses[i].firstTile = file.readInt();m_edgeTextureClasses[i].numTiles = file.readInt();m_edgeTextureClasses[i].width = file.readInt();m_edgeTextureClasses[i].name = file.readAsciiString();+ checkTexClassTiles(m_edgeTextureClasses[i]);readTexClass(&m_edgeTextureClasses[i], m_edgeTiles);}}diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 18480b609..90e3299c3 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -17193,3 +17193,5 @@ TEST(modfactions_prefix_the_last_part_of_a_file_path)#include "test_supply_center_save.inc"#include "test_cinema.inc"#include "test_game_results.inc"+#include "test_map_ini_rollback.inc"+#include "test_hostile_map.inc"diff --git a/GeneralsMD/Code/Tests/test_hostile_map.inc b/GeneralsMD/Code/Tests/test_hostile_map.incnew file mode 100644index 000000000..d22152f0d--- /dev/null+++ b/GeneralsMD/Code/Tests/test_hostile_map.inc@@ -0,0 +1,391 @@+// A map file, and the map.ini beside it, come from whoever made the map. These hand the readers+// numbers no editor writes and check each one is refused, rather than allocated, looped over or+// read past. A refused map is ERROR_CORRUPT_FILE_FORMAT out of the chunk reader, which+// MapCache::addMap catches and leaves the map out of the list, or INI_INVALID_DATA out of a+// map.ini field.++#include "GameLogic/WorldHeightMapData.h"+#include "GameLogic/Module/CaveContain.h"++// A CkMp stream written by hand: a table of contents naming each label (label i gets id i + 1),+// then chunk headers and data in whatever order the test puts them.+struct HostileChunkBytes+{+ std::vector<char> bytes;++ void put( const void *p, size_t n ) { bytes.insert( bytes.end(), (const char *)p, (const char *)p + n ); }+ void putInt( Int v ) { put( &v, sizeof( v ) ); }+ void contents( const char *const *labels, Int count )+ {+ put( "CkMp", 4 );+ putInt( count );+ for( Int i = 0; i < count; ++i )+ {+ unsigned char len = (unsigned char)strlen( labels[ i ] );+ put( &len, 1 );+ put( labels[ i ], len );+ UnsignedInt id = i + 1;+ put( &id, sizeof( id ) );+ }+ }+ void chunk( UnsignedInt id, DataChunkVersionType version, Int dataSize )+ {+ put( &id, sizeof( id ) );+ put( &version, sizeof( version ) );+ putInt( dataSize );+ }+};++struct HostileProbe+{+ Int first;+ Int second;+ Bool threw;+};++static Bool hostileReadTwoInts( DataChunkInput &file, DataChunkInfo *, void *userData )+{+ HostileProbe *probe = (HostileProbe *)userData;+ probe->first = file.readInt();+ try+ {+ probe->second = file.readInt();+ }+ catch( ErrorCode ec )+ {+ probe->threw = ( ec == ERROR_CORRUPT_FILE_FORMAT );+ }+ return TRUE;+}++static Bool hostileReadCount( DataChunkInput &file, DataChunkInfo *, void *userData )+{+ HostileProbe *probe = (HostileProbe *)userData;+ try+ {+ probe->first = file.readCount( sizeof( Int ) );+ }+ catch( ErrorCode ec )+ {+ probe->threw = ( ec == ERROR_CORRUPT_FILE_FORMAT );+ }+ return TRUE;+}++static Bool hostileParseInner( DataChunkInput &file, DataChunkInfo *info, void *userData )+{+ file.registerParser( AsciiString( "Inner" ), info->label, hostileReadTwoInts );+ return file.parse( userData );+}++/* EA only asserted on a read past the end of a chunk, so a release build read the next chunk's bytes,+ or past the end of the file, where nothing is copied and the field keeps whatever the stack held. */+TEST(data_chunk_read_past_the_end_of_its_chunk_throws_in_every_build)+{+ CHECK( bootOnce() );+ const char *labels[] = { "Probe" };++ // the chunk holds one Int and the parser asks for two+ {+ HostileChunkBytes f;+ f.contents( labels, 1 );+ f.chunk( 1, 1, sizeof( Int ) );+ f.putInt( 7 );+ f.putInt( 8 ); // the bytes are there, but past the chunk++ HostileProbe probe = { 0, 0, FALSE };+ MemoryChunkInputStream stream( &f.bytes[0], (Int)f.bytes.size() );+ DataChunkInput input( &stream );+ input.registerParser( AsciiString( "Probe" ), AsciiString::TheEmptyString, hostileReadTwoInts );+ CHECK( input.parse( &probe ) );+ CHECK_EQ( probe.first, 7 );+ CHECK( probe.threw );+ CHECK_EQ( probe.second, 0 );+ }++ // the chunk claims two Ints and the file ends after one+ {+ HostileChunkBytes f;+ f.contents( labels, 1 );+ f.chunk( 1, 1, 2 * sizeof( Int ) );+ f.putInt( 7 );++ HostileProbe probe = { 0, 0, FALSE };+ MemoryChunkInputStream stream( &f.bytes[0], (Int)f.bytes.size() );+ DataChunkInput input( &stream );+ input.registerParser( AsciiString( "Probe" ), AsciiString::TheEmptyString, hostileReadTwoInts );+ input.parse( &probe );+ CHECK_EQ( probe.first, 7 );+ CHECK( probe.threw );+ }++ // and a chunk that does hold both reads both, as every real map does+ {+ HostileChunkBytes f;+ f.contents( labels, 1 );+ f.chunk( 1, 1, 2 * sizeof( Int ) );+ f.putInt( 7 );+ f.putInt( 8 );++ HostileProbe probe = { 0, 0, FALSE };+ MemoryChunkInputStream stream( &f.bytes[0], (Int)f.bytes.size() );+ DataChunkInput input( &stream );+ input.registerParser( AsciiString( "Probe" ), AsciiString::TheEmptyString, hostileReadTwoInts );+ CHECK( input.parse( &probe ) );+ CHECK_EQ( probe.second, 8 );+ CHECK( !probe.threw );+ }+}++/* A chunk is nested whole inside its parent; one that claims more than the parent has left is+ refused when it is opened, before any of its reads land in the parent's next chunk. */+TEST(data_chunk_larger_than_its_parent_is_corrupt)+{+ CHECK( bootOnce() );+ const char *labels[] = { "Outer", "Inner" };+ const Int header = sizeof( UnsignedInt ) + sizeof( DataChunkVersionType ) + sizeof( Int );++ HostileChunkBytes f;+ f.contents( labels, 2 );+ f.chunk( 1, 1, header + 2 * sizeof( Int ) );+ f.chunk( 2, 1, 1000 );+ f.putInt( 7 );+ f.putInt( 8 );++ HostileProbe probe = { 0, 0, FALSE };+ MemoryChunkInputStream stream( &f.bytes[0], (Int)f.bytes.size() );+ DataChunkInput input( &stream );+ input.registerParser( AsciiString( "Outer" ), AsciiString::TheEmptyString, hostileParseInner );+ Bool corrupt = FALSE;+ try+ {+ input.parse( &probe );+ }+ catch( ErrorCode ec )+ {+ corrupt = ( ec == ERROR_CORRUPT_FILE_FORMAT );+ }+ CHECK( corrupt );+ CHECK_EQ( probe.first, 0 );+}++/* A count that sizes an allocation is checked against the bytes its items would need. */+TEST(data_chunk_count_the_chunk_cannot_hold_is_refused)+{+ CHECK( bootOnce() );+ const char *labels[] = { "Probe" };++ HostileChunkBytes f;+ f.contents( labels, 1 );+ f.chunk( 1, 1, 3 * sizeof( Int ) );+ f.putInt( 1000000 );+ f.putInt( 0 );+ f.putInt( 0 );++ HostileProbe probe = { -1, 0, FALSE };+ MemoryChunkInputStream stream( &f.bytes[0], (Int)f.bytes.size() );+ DataChunkInput input( &stream );+ input.registerParser( AsciiString( "Probe" ), AsciiString::TheEmptyString, hostileReadCount );+ input.parse( &probe );+ CHECK( probe.threw );++ // two Ints left after the count: a count of two fits, three does not+ HostileChunkBytes g;+ g.contents( labels, 1 );+ g.chunk( 1, 1, 3 * sizeof( Int ) );+ g.putInt( 2 );+ g.putInt( 0 );+ g.putInt( 0 );++ HostileProbe fits = { -1, 0, FALSE };+ MemoryChunkInputStream fitsStream( &g.bytes[0], (Int)g.bytes.size() );+ DataChunkInput fitsInput( &fitsStream );+ fitsInput.registerParser( AsciiString( "Probe" ), AsciiString::TheEmptyString, hostileReadCount );+ fitsInput.parse( &fits );+ CHECK( !fits.threw );+ CHECK_EQ( fits.first, 2 );+}++/* The table of contents' own count used to loop and allocate up to two billion names off the+ end of the file. */+TEST(data_chunk_table_of_contents_longer_than_the_file_stops)+{+ CHECK( bootOnce() );++ HostileChunkBytes f;+ f.put( "CkMp", 4 );+ f.putInt( 0x7fffffff );++ MemoryChunkInputStream stream( &f.bytes[0], (Int)f.bytes.size() );+ DataChunkInput input( &stream );+ CHECK( !input.isValidFileType() );+}++// HeightMapData, version 4: width, height, border, the boundaries, then the heights+static void hostileHeightMap( HostileChunkBytes &f, Int width, Int height, Int numBorders, Int dataSize, Int heightBytes )+{+ const char *labels[] = { "HeightMapData" };+ f.contents( labels, 1 );+ const Int borders = numBorders > 0 && numBorders < 16 ? numBorders : 0;+ f.chunk( 1, K_HEIGHT_MAP_VERSION_4, 5 * sizeof( Int ) + borders * 2 * sizeof( Int ) + heightBytes );+ f.putInt( width );+ f.putInt( height );+ f.putInt( 0 );+ f.putInt( numBorders );+ for( Int i = 0; i < borders; ++i )+ {+ f.putInt( width );+ f.putInt( height );+ }+ f.putInt( dataSize );+ for( Int i = 0; i < heightBytes; ++i )+ f.bytes.push_back( (char)i );+}++static Bool hostileHeightMapRefused( HostileChunkBytes &f )+{+ WorldHeightMapData map;+ MemoryChunkInputStream stream( &f.bytes[0], (Int)f.bytes.size() );+ try+ {+ map.parseHeightsAndCells( &stream );+ }+ catch( ErrorCode ec )+ {+ return ec == ERROR_CORRUPT_FILE_FORMAT;+ }+ return FALSE;+}++/* The heights were allocated from the file's dataSize before it was compared with width times+ height, and the boundary list resized from a count nobody checked. */+TEST(height_map_sizes_a_map_file_cannot_hold_are_refused)+{+ CHECK( bootOnce() );++ // a real one, two by two, reads+ {+ HostileChunkBytes f;+ hostileHeightMap( f, 2, 2, 1, 4, 4 );+ WorldHeightMapData map;+ MemoryChunkInputStream stream( &f.bytes[0], (Int)f.bytes.size() );+ CHECK( map.parseHeightsAndCells( &stream ) );+ CHECK_EQ( map.getXExtent(), 2 );+ CHECK_EQ( map.getYExtent(), 2 );+ CHECK_EQ( (Int)map.getAllBoundaries().size(), 1 );+ }+ {+ HostileChunkBytes f;+ hostileHeightMap( f, K_MAX_HEIGHT_MAP_SIDE + 1, 2, 1, 2 * ( K_MAX_HEIGHT_MAP_SIDE + 1 ), 0 );+ CHECK( hostileHeightMapRefused( f ) );+ }+ {+ // 65537 squared wraps to 131073 in an Int, so this dataSize passed the old check and the+ // heights were then indexed as 65537 a side+ HostileChunkBytes f;+ hostileHeightMap( f, 65537, 65537, 1, 131073, 0 );+ CHECK( hostileHeightMapRefused( f ) );+ }+ {+ HostileChunkBytes f;+ hostileHeightMap( f, 2, 2, 0x10000000, 4, 4 );+ CHECK( hostileHeightMapRefused( f ) );+ }+ {+ HostileChunkBytes f;+ hostileHeightMap( f, 2, 2, -1, 4, 4 );+ CHECK( hostileHeightMapRefused( f ) );+ }+ {+ // a dataSize that is not width times height, refused before the heights are allocated+ HostileChunkBytes f;+ hostileHeightMap( f, 2, 2, 1, 0x7fffffff, 4 );+ CHECK( hostileHeightMapRefused( f ) );+ }+}++/* A map.ini can redefine a cave, and the index is a slot registerNewCave pads a vector up to. */+TEST(cave_index_outside_what_the_cave_system_holds_is_refused)+{+ CHECK( bootOnce() );++ GlobalData *savedGlobals = TheWritableGlobalData;+ if( savedGlobals == NULL )+ TheWritableGlobalData = NEW GlobalData;+ if( TheModuleFactory == NULL )+ {+ TheModuleFactory = NEW ModuleFactory;+ TheModuleFactory->init();+ }+ if( TheThingFactory == NULL )+ TheThingFactory = NEW ThingFactory;++ writeFile( TEST_INI,+ "Object CaveIndexProbe\r\n"+ " Behavior = CaveContain ModuleTag_01\r\n"+ " CaveIndex = 3\r\n"+ " End\r\n"+ "End\r\n" );+ CHECK( loadIni( TEST_INI ) );+ const ThingTemplate *probe = TheThingFactory->findTemplate( "CaveIndexProbe" );+ CHECK( probe != NULL );+ if( probe != NULL )+ {+ const ModuleInfo &modules = probe->getBehaviorModuleInfo();+ CHECK_EQ( modules.getCount(), 1 );+ if( modules.getCount() == 1 )+ CHECK_EQ( ((const CaveContainModuleData *)modules.getNthData( 0 ))->m_caveIndexData, 3 );+ }++ writeFile( TEST_INI,+ "Object CaveIndexProbeHuge\r\n"+ " Behavior = CaveContain ModuleTag_01\r\n"+ " CaveIndex = 1024\r\n"+ " End\r\n"+ "End\r\n" );+ CHECK( loadIni( TEST_INI ) == FALSE );++ writeFile( TEST_INI,+ "Object CaveIndexProbeNegative\r\n"+ " Behavior = CaveContain ModuleTag_01\r\n"+ " CaveIndex = -1\r\n"+ " End\r\n"+ "End\r\n" );+ CHECK( loadIni( TEST_INI ) == FALSE );++ remove( TEST_INI );+ if( savedGlobals == NULL )+ {+ delete TheWritableGlobalData;+ TheWritableGlobalData = NULL;+ }+}++/* PartitionCellSize sizes the partition grid; a map.ini's GameData block asking for a tiny cell+ made it millions of cells. The refusal comes before the field is stored. */+TEST(partition_cell_size_outside_its_range_is_refused)+{+ CHECK( bootOnce() );++ GlobalData *saved = TheWritableGlobalData;+ TheWritableGlobalData = NEW GlobalData;+ const Real before = TheWritableGlobalData->m_partitionCellSize;++ writeFile( TEST_INI,+ "GameData\r\n"+ " PartitionCellSize = 0.01\r\n"+ "End\r\n" );+ CHECK( loadIni( TEST_INI ) == FALSE );+ CHECK( TheWritableGlobalData->m_partitionCellSize == before );++ writeFile( TEST_INI,+ "GameData\r\n"+ " PartitionCellSize = 100000\r\n"+ "End\r\n" );+ CHECK( loadIni( TEST_INI ) == FALSE );+ CHECK( TheWritableGlobalData->m_partitionCellSize == before );++ remove( TEST_INI );+ delete TheWritableGlobalData;+ TheWritableGlobalData = saved;+}diff --git a/GeneralsMD/Code/Tests/test_map_ini_rollback.inc b/GeneralsMD/Code/Tests/test_map_ini_rollback.incnew file mode 100644index 000000000..2679bbaf8--- /dev/null+++ b/GeneralsMD/Code/Tests/test_map_ini_rollback.inc@@ -0,0 +1,298 @@+// A map's rules file (map.ini, solo.ini) is read INI_LOAD_CREATE_OVERRIDES at map load, and every+// store it may write to puts the game's own data back in reset() at the end of the match. These+// play two maps back to back the way GameLogic does: load the first map's file, reset the store,+// load the second's, and check nothing of the first is left - on a machine that never played it,+// the second match would otherwise run on different rules.++#include "Common/DamageFX.h"+#include "GameLogic/Weapon.h"+#include "GameClient/Snow.h"++// GameLogic::loadMapINI's load: unknown fields skipped, any throw stops the file there+static Bool loadMapIni( const char *name )+{+ INI ini;+ ini.setSkipUnknownFields( TRUE );+ try+ {+ ini.load( AsciiString( name ), INI_LOAD_CREATE_OVERRIDES, NULL );+ return TRUE;+ }+ catch( ... )+ {+ }+ return FALSE;+}++/* A block whose store cannot put it back is skipped in a map's rules file, nested sub-block and+ all, and the blocks after it still load. */+TEST(map_ini_refuses_a_block_its_store_cannot_put_back)+{+ CHECK( bootOnce() );++ if( TheArmorStore == NULL )+ TheArmorStore = NEW ArmorStore;++ writeFile( TEST_INI,+ "Armor MapRefuseProbeArmor\r\n"+ " Armor = SMALL_ARMS 50%\r\n"+ "End\r\n"+ "Video MapRefuseProbeVideo\r\n"+ " Filename = Probe\r\n"+ "End\r\n"+ "Campaign MapRefuseProbeCampaign\r\n"+ " CampaignNameLabel = Probe ; a comment with an End in it\r\n"+ " Mission MISSION01\r\n"+ " Map = Probe\r\n"+ " End\r\n"+ "End\r\n"+ "Armor MapRefuseProbeArmorAfter\r\n"+ " Armor = SMALL_ARMS 50%\r\n"+ "End\r\n" );+ CHECK( loadMapIni( TEST_INI ) );+ CHECK( TheArmorStore->findArmorTemplate( "MapRefuseProbeArmor" ) != NULL );+ CHECK( TheArmorStore->findArmorTemplate( "MapRefuseProbeArmorAfter" ) != NULL );++ TheArmorStore->reset();+ remove( TEST_INI );+}++/* A weapon the first map edits goes back to the game's values, and one it made from nothing is gone,+ so the second map that defines the same name builds it from a new weapon's defaults. */+TEST(map_ini_weapons_go_back_after_the_match)+{+ CHECK( bootOnce() );++ if( TheWeaponStore == NULL )+ TheWeaponStore = NEW WeaponStore;++ writeFile( TEST_INI,+ "Weapon MapRollbackProbeGun\r\n"+ " PrimaryDamage = 60.0\r\n"+ " AttackRange = 150.0\r\n"+ "End\r\n" );+ CHECK( loadIni( TEST_INI ) );++ writeFile( TEST_INI,+ "Weapon MapRollbackProbeGun\r\n"+ " PrimaryDamage = 999.0\r\n"+ "End\r\n"+ "Weapon MapOnlyProbeGun\r\n"+ " PrimaryDamage = 5.0\r\n"+ " AttackRange = 300.0\r\n"+ "End\r\n" );+ CHECK( loadMapIni( TEST_INI ) );++ WeaponBonus noBonus;+ const WeaponTemplate *gun = TheWeaponStore->findWeaponTemplate( "MapRollbackProbeGun" );+ CHECK( gun != NULL );+ if( gun == NULL )+ return;+ CHECK_NEAR( gun->getPrimaryDamage( noBonus ), 999.0f, 0.01f );+ CHECK( TheWeaponStore->findWeaponTemplate( "MapOnlyProbeGun" ) != NULL );++ TheWeaponStore->reset();++ CHECK( TheWeaponStore->findWeaponTemplate( "MapRollbackProbeGun" ) == gun );+ CHECK_NEAR( gun->getPrimaryDamage( noBonus ), 60.0f, 0.01f );+ CHECK_NEAR( gun->getUnmodifiedAttackRange(), 150.0f, 0.01f );+ CHECK( TheWeaponStore->findWeaponTemplate( "MapOnlyProbeGun" ) == NULL );++ // the second map names the first map's weapon without its range: a fresh weapon's, not 300+ writeFile( TEST_INI,+ "Weapon MapOnlyProbeGun\r\n"+ " PrimaryDamage = 7.0\r\n"+ "End\r\n" );+ CHECK( loadMapIni( TEST_INI ) );+ const WeaponTemplate *again = TheWeaponStore->findWeaponTemplate( "MapOnlyProbeGun" );+ CHECK( again != NULL );+ if( again != NULL )+ CHECK( again->getUnmodifiedAttackRange() < 299.0f );++ TheWeaponStore->reset();+ CHECK( TheWeaponStore->findWeaponTemplate( "MapOnlyProbeGun" ) == NULL );+ remove( TEST_INI );+}++/* DamageFX was rewritten in place and never put back. */+TEST(map_ini_damage_fx_goes_back_after_the_match)+{+ CHECK( bootOnce() );++ if( TheDamageFXStore == NULL )+ TheDamageFXStore = NEW DamageFXStore;++ writeFile( TEST_INI,+ "DamageFX MapRollbackProbeDFX\r\n"+ " ThrottleTime = Default 100\r\n"+ "End\r\n" );+ CHECK( loadIni( TEST_INI ) );+ const DamageFX *dfx = TheDamageFXStore->findDamageFX( "MapRollbackProbeDFX" );+ CHECK( dfx != NULL );+ if( dfx == NULL )+ return;+ const UnsignedInt before = dfx->getDamageFXThrottleTime( DAMAGE_EXPLOSION, NULL );++ writeFile( TEST_INI,+ "DamageFX MapRollbackProbeDFX\r\n"+ " ThrottleTime = Default 2000\r\n"+ "End\r\n" );+ CHECK( loadMapIni( TEST_INI ) );+ CHECK( dfx->getDamageFXThrottleTime( DAMAGE_EXPLOSION, NULL ) != before );++ TheDamageFXStore->reset();+ CHECK( TheDamageFXStore->findDamageFX( "MapRollbackProbeDFX" ) == dfx );+ CHECK_EQ( dfx->getDamageFXThrottleTime( DAMAGE_EXPLOSION, NULL ), before );+ remove( TEST_INI );+}++/* A map's BuildCost is what the object costs - the base template answers with the override's price -+ and it is the game's price again after the match. BuildTime and BuildCost a platform would read+ differently (out of range, past an Int) are refused. */+TEST(map_ini_build_cost_is_charged_and_goes_back)+{+ CHECK( bootOnce() );++ GlobalData *savedGlobals = TheWritableGlobalData;+ if( savedGlobals == NULL )+ TheWritableGlobalData = NEW GlobalData;+ if( TheModuleFactory == NULL )+ {+ TheModuleFactory = NEW ModuleFactory;+ TheModuleFactory->init();+ }+ if( TheThingFactory == NULL )+ TheThingFactory = NEW ThingFactory;++ writeFile( TEST_INI,+ "Object MapCostProbe\r\n"+ " Behavior = DestroyDie ModuleTag_01\r\n"+ " End\r\n"+ " BuildCost = 100\r\n"+ " BuildTime = 10\r\n"+ "End\r\n" );+ CHECK( loadIni( TEST_INI ) );+ const ThingTemplate *probe = TheThingFactory->findTemplate( "MapCostProbe" );+ CHECK( probe != NULL );+ if( probe == NULL )+ return;+ CHECK_EQ( probe->friend_getBuildCost(), 100 );++ writeFile( TEST_INI,+ "Object MapCostProbe\r\n"+ " BuildCost = 900\r\n"+ "End\r\n" );+ CHECK( loadMapIni( TEST_INI ) );+ CHECK( TheThingFactory->findTemplate( "MapCostProbe" ) == probe );+ CHECK_EQ( probe->friend_getBuildCost(), 900 );++ TheThingFactory->reset();+ CHECK_EQ( probe->friend_getBuildCost(), 100 );++ const char *const refused[] =+ {+ "Object MapCostProbe\r\n BuildTime = 1000000000\r\nEnd\r\n",+ "Object MapCostProbe\r\n BuildTime = -1\r\nEnd\r\n",+ "Object MapCostProbe\r\n BuildCost = 99999999999\r\nEnd\r\n",+ "Object MapCostProbe\r\n BuildCost = 70000\r\nEnd\r\n",+ };+ // only the line is refused: the file loads, the value stays the game's+ for( Int i = 0; i < (Int)ARRAY_SIZE( refused ); ++i )+ {+ writeFile( TEST_INI, refused[ i ] );+ CHECK( loadMapIni( TEST_INI ) );+ CHECK_EQ( probe->friend_getBuildCost(), 100 );+ TheThingFactory->reset();+ }++ // and in the game's own data it still stops the load+ writeFile( TEST_INI, "Object MapCostProbeStrict\r\n BuildTime = -1\r\nEnd\r\n" );+ CHECK( loadIni( TEST_INI ) == FALSE );++ remove( TEST_INI );+ if( savedGlobals == NULL )+ {+ delete TheWritableGlobalData;+ TheWritableGlobalData = NULL;+ }+}++/* A special power a map adds takes the next id, and the id is what a power's command carries: the+ same map gives it the same id whatever map was played before it. */+TEST(map_ini_power_ids_do_not_depend_on_earlier_maps)+{+ CHECK( bootOnce() );++ if( TheSpecialPowerStore == NULL )+ TheSpecialPowerStore = NEW SpecialPowerStore;++ writeFile( TEST_INI,+ "SpecialPower MapIdProbePower\r\n"+ "End\r\n" );+ CHECK( loadMapIni( TEST_INI ) );+ const SpecialPowerTemplate *first = TheSpecialPowerStore->findSpecialPowerTemplate( "MapIdProbePower" );+ CHECK( first != NULL );+ if( first == NULL )+ return;+ const UnsignedInt id = first->getID();+ TheSpecialPowerStore->reset();+ CHECK( TheSpecialPowerStore->findSpecialPowerTemplate( "MapIdProbePower" ) == NULL );++ // another custom map in between, with two powers of its own+ writeFile( TEST_INI,+ "SpecialPower MapIdProbeOtherA\r\n"+ "End\r\n"+ "SpecialPower MapIdProbeOtherB\r\n"+ "End\r\n" );+ CHECK( loadMapIni( TEST_INI ) );+ TheSpecialPowerStore->reset();++ writeFile( TEST_INI,+ "SpecialPower MapIdProbePower\r\n"+ "End\r\n" );+ CHECK( loadMapIni( TEST_INI ) );+ const SpecialPowerTemplate *again = TheSpecialPowerStore->findSpecialPowerTemplate( "MapIdProbePower" );+ CHECK( again != NULL );+ if( again != NULL )+ CHECK_EQ( again->getID(), id );++ TheSpecialPowerStore->reset();+ remove( TEST_INI );+}++/* Snow settings that divided by zero or drew billions of flakes are refused; shipped values pass. */+TEST(map_ini_refuses_extreme_snow)+{+ CHECK( bootOnce() );++ writeFile( TEST_INI,+ "Weather\r\n"+ " SnowBoxDimensions = 150\r\n"+ " SnowBoxDensity = 4\r\n"+ " SnowVelocity = 25\r\n"+ "End\r\n" );+ CHECK( loadMapIni( TEST_INI ) );+ CHECK_NEAR( TheWeatherSetting->m_snowBoxDimensions, 150.0f, 0.001f );++ const char *const refused[] =+ {+ "Weather\r\n SnowBoxDimensions = 0\r\nEnd\r\n",+ "Weather\r\n SnowBoxDimensions = 100000\r\nEnd\r\n",+ "Weather\r\n SnowBoxDensity = 0\r\nEnd\r\n",+ "Weather\r\n SnowBoxDensity = 1000\r\nEnd\r\n",+ "Weather\r\n SnowVelocity = 0\r\nEnd\r\n",+ };+ for( Int i = 0; i < (Int)ARRAY_SIZE( refused ); ++i )+ {+ writeFile( TEST_INI, refused[ i ] );+ CHECK( loadMapIni( TEST_INI ) ); // the line goes, the file loads+ CHECK_NEAR( TheWeatherSetting->m_snowBoxDimensions, 150.0f, 0.001f );+ CHECK( TheWeatherSetting->m_snowBoxDensity > 0.0f && TheWeatherSetting->m_snowBoxDensity <= 4.0f );+ CHECK( TheWeatherSetting->m_snowVelocity > 0.0f );+ }++ // what GameLogic::reset does with the map's weather+ WeatherSetting *ws = (WeatherSetting *)TheWeatherSetting.getNonOverloadedPointer();+ TheWeatherSetting = (WeatherSetting *)ws->deleteOverrides();+ remove( TEST_INI );+}