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
feat(gameengine): each mod faction keeps its own art, strings and bar
Olcay Seygan3a834ecdf0bd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 629f18fa7..34023cdc9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -27,7 +27,7 @@ found and fixed — EA's own, not port damage.**- Reforged stays on top of every mod. This build's balance, its fixes to EA's data, its AI and its menus load after the mod and win where they touch the same unit, weapon or button, so a mod plays with Reforged's rules. A change that names something the mod renamed or removed is passed over instead of stopping the game, which is how ShockWave starts and plays. A mod's own copy of a file Reforged ships, the skirmish setup screen among them, is ignored, and so are any upscaled art archives it carries. The one exception is the skirmish AI's scripts: a mod's are written for its own generals, so they replace Reforged's, and Reforged's smarter AI plays them.- A `mod.json` in the folder names the mod and its version. The names stand beside the version number in the options menu, in the order the mods were given, and go into every replay you record, so a replay made with mods says which ones, and the replay list marks it as another version when the game is running without them.- Joining a LAN game that runs different mods used to end in a box about a mismatch and nothing else. It names the host's mods now, or tells you the host plays without any.-- Two total conversions in one match. Add `-modfactions` to the mods you give, and each mod's armies join Zero Hour's own instead of replacing them: the faction list reads "ShockWave - USA" and "The End of Days - USA" under plain "USA", and a ShockWave army can fight an End of Days one. Each side builds from its own mod's units, weapons, upgrades and generals' powers. What every side shares still comes from the mod named last: the models and textures two mods both replace, the unit names and voices, the menus and the skirmish AI, which does not know how to play a mod's faction yet.+- Two total conversions in one match. Add `-modfactions` to the mods you give, and each mod's armies join Zero Hour's own instead of replacing them: the faction list reads "ShockWave - USA" and "The End of Days - USA" under plain "USA", and a ShockWave army can fight an End of Days one. Each side builds from its own mod's units, weapons, upgrades and generals' powers, and each looks and sounds like its own mod: a ShockWave tank wears ShockWave's model and textures even where The End of Days replaces the same file, and speaks with ShockWave's voice. Playing a mod's faction, your command bar, build pictures, unit names and tooltips are that mod's; on one of Zero Hour's own you keep our bar. The End of Days' Russia is in the list under its own name. Menus, lobby and colours stay ours whatever mods you load. The skirmish AI lays out a mod's base from the mod's own buildings, but it still trains the army it knows from Zero Hour.## The command bar moves to the middlediff --git a/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFileSystem.h b/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFileSystem.hindex 09c77336b..573e707a3 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFileSystem.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/ArchiveFileSystem.h@@ -175,23 +175,28 @@ class ArchiveFileSystem : public SubsystemInterfaceAsciiString getArchiveFilenameForFile(const AsciiString& filename) const;void loadMods( void );- /// FileSystem::setFocus: FILE_FOCUS_ALL is the merged tree, FILE_FOCUS_RETAIL the tree as it was- /// before any -mod, a -mod index that mod's archives alone. Only -modfactions keeps the apart trees.+ /// FileSystem::setFocus: a -mod index sees that mod's archives alone. FILE_FOCUS_ALL is the merged+ /// tree, which -modfactions leaves as retail's and FILE_FOCUS_RETAIL always is.void setFocus( Int focus ) { m_focus = focus; }+ /// -modfactions: mod's own copy of filename, whatever the focus (FileSystem::splitModName)+ File* openModFile( Int mod, const AsciiString& filename, Int access );+ Bool doesModFileExist( Int mod, const AsciiString& filename ) const;+ Bool getModFileInfo( Int mod, const AsciiString& filename, FileInfo *fileInfo ) const;+protected:virtual void loadIntoDirectoryTree(const ArchiveFile *archiveFile, const AsciiString& archiveFilename, Bool overwrite = FALSE ); ///< load the archive file's header information and apply it to the global archive directory tree.void addToTree(ArchivedDirectoryInfo &root, const ArchiveFile *archiveFile, const AsciiString& archiveFilename, Bool overwrite);void prioritizeLargerFiles(const AsciiString& directory, const char *inferiorArchive, const char *superiorArchive); ///< where two archives claim the same file in this directory, keep the bigger copy.- void keepModsApart( size_t modCount ); ///< snapshot the retail tree and start one empty tree per -mod- void addModArchive( Int mod, ArchiveFile *archiveFile, const AsciiString& archiveFilename ); ///< over the merged tree, and into the mod's own when kept apart+ void keepModsApart( size_t modCount ); ///< one tree per -mod, and the merged one left as retail's+ void addModArchive( Int mod, ArchiveFile *archiveFile, const AsciiString& archiveFilename ); ///< over the merged tree, or into the mod's own when kept apartconst ArchivedDirectoryInfo & focusedRoot( void ) const;+ static AsciiString archiveInTree( const ArchivedDirectoryInfo &root, const AsciiString& filename );Bool inFocus( const AsciiString& archiveFilename ) const;ArchiveFileMap m_archiveFileMap;ArchivedDirectoryInfo m_rootDirectory;- ArchivedDirectoryInfo m_retailRoot; ///< -modfactions: the tree before any -modstd::vector<ArchivedDirectoryInfo> m_modRoots; ///< -modfactions: each -mod's archives alone, in its own orderstd::map<AsciiString, Int> m_archiveMod; ///< -modfactions: archive -> -mod index; retail's are not in itInt m_focus;diff --git a/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.h b/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.hindex 5966a74a6..6227395a1 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.h@@ -155,6 +155,11 @@ public:void setFocus(Int focus);Int getFocus() const { return s_focus; }+ /// -modfactions: a file name starting "M<n>~" ("Art\W3D\M2~AVRanger.w3d") is mod n's copy and nothing+ /// else; the art code falls back to the plain name itself. TRUE for such a name, with *mod the -mod+ /// index and *bare the path without the prefix.+ static Bool splitModName(const AsciiString& filename, Int *mod, AsciiString *bare);+Bool createDirectory(AsciiString directory); ///< create a directory of the given name./// language when Data\<language>\Language.ini is loose or in an archive, otherwise the first@@ -167,6 +172,7 @@ public:void unloadMusicFilesFromCD();protected:AsciiString focusedLooseFile(const AsciiString& filename) const; ///< the loose copy the focus sees, else empty+ AsciiString modFolderFile(Int mod, const AsciiString& filename) const; ///< "<mod folder><filename>" when it is there, else emptymutable std::map<unsigned,bool> m_fileExist;// static: GlobalData's constructor reads files through a TheFileSystem that a few engine tests leave// NULL, and openFile has always answered NULL there without touching the objectdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/INI.h b/GeneralsMD/Code/GameEngine/Include/Common/INI.hindex 81de1847f..2c3b3fec6 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/INI.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/INI.h@@ -177,7 +177,8 @@ enum ModNameType{MODNAME_OBJECT, MODNAME_WEAPON, MODNAME_ARMOR, MODNAME_DAMAGEFX, MODNAME_UPGRADE, MODNAME_SCIENCE,MODNAME_SPECIALPOWER, MODNAME_COMMANDSET, MODNAME_COMMANDBUTTON, MODNAME_FXLIST, MODNAME_OCL,- MODNAME_PARTICLESYSTEM, MODNAME_LOCOMOTOR, MODNAME_PLAYERTEMPLATE,+ MODNAME_PARTICLESYSTEM, MODNAME_LOCOMOTOR, MODNAME_PLAYERTEMPLATE, MODNAME_MAPPEDIMAGE,+ MODNAME_CONTROLBARSCHEME, MODNAME_AUDIOEVENT,MODNAME_COUNT};@@ -189,13 +190,19 @@ public:void scanMods( void ); ///< every -mod's faction files, each under its own FileSystem focusvoid scanLine( Int mod, const char *line ); ///< a block header names one of the mod's own; "Side = X" keeps X outvoid finishScan( Int mod ); ///< drop the side names, which the engine compares as text+ /// a file the mod ships under Art\W3D, Art\Textures or Data\Audio; a word naming it gets the prefix too,+ /// and the FileSystem and WW3D then serve the mod's own copy+ void addAsset( Int mod, const char *fileName );void setActive( Int mod ) { m_active = mod; } ///< -1: nothing is rewrittenInt getActive( void ) const { return m_active; }Int getNameCount( Int mod ) const { return (Int)m_mods[ mod ].all.size(); }- /// rewrite the active mod's names in a comment-free line in place, every word but the first;- /// FALSE when the result would not fit capacity bytes+ /// rewrite the active mod's names, and in a file field the files it ships, in a comment-free line in+ /// place, every word but the first; FALSE when the result would not fit capacity bytesBool rewriteLine( char *line, size_t capacity ) const;+ /// the same for the labels in the mod's own string table. This runs after the INI checksum: the table+ /// is the player's language, and two installs in different languages must still agree.+ Bool rewriteLabels( char *line, size_t capacity ) const;/// "M<n>~X" where mod n has no `type` called X is a reference to retail's X: TRUE and *retailName/// set. Finders ask this on a miss, so a definition of the mod's own X never falls through to retail's.Bool findRetailName( const AsciiString &name, ModNameType type, AsciiString *retailName ) const;@@ -209,7 +216,14 @@ private:std::set<std::string> all;std::set<std::string> byType[ MODNAME_COUNT ];std::set<std::string> sides;+ std::set<std::string> assets; ///< lowercase: w3d and audio by base name, textures by file name};+ static Bool isAsset( const Names &names, const std::string &word );+ static Bool isAssetField( const std::string &field ); ///< a field whose value names a model, animation, texture or sound file+ typedef Bool (ModNamespace::*WordTest)( const std::string &word, Bool assetField ) const;+ Bool isNameOrAsset( const std::string &word, Bool assetField ) const;+ Bool isModLabel( const std::string &word, Bool assetField ) const;+ Bool prefixWords( char *line, size_t capacity, WordTest test ) const;std::vector<Names> m_mods;Int m_active;};diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBarScheme.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBarScheme.hindex 194839bc4..19ad3455b 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBarScheme.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBarScheme.h@@ -276,6 +276,13 @@ public:* is really showing. Empty when nothing else shares it. */AsciiString getCurrentArtTwinSide( void ) const;+ /// -modfactions: the mod (0-based) whose own bar ("M<n>~" scheme) is on screen, -1 for ours;+ /// a mod's bar brings its own painting+ Int getCurrentSchemeMod( void ) const;+ Bool isCurrentSchemeMod( void ) const { return getCurrentSchemeMod() >= 0; }+ /// a mod scheme's painting, cut at the panel seams and each piece drawn where its panel stands+ void drawModPainting( ICoord2D offset, Bool foreground );+// parse Functions for the INI fileconst FieldParse *getFieldParse() const { return m_controlBarSchemeFieldParseTable; } ///< returns the parsing fields@@ -290,7 +297,8 @@ public:void preloadAssets( TimeOfDay timeOfDay ); ///< preload the assetsprivate:- ControlBarScheme *findSchemeForSide( const AsciiString& side ) const; ///< the widest of that side's schemes the screen can wear+ ControlBarScheme *findSchemeForSide( const AsciiString& side, Int mod ) const; ///< the widest of that side's schemes from mod (-1 ours) the screen can wear+ ControlBarScheme *findSchemeForFaction( const AsciiString& side, Int mod ) const; ///< a mod faction's own scheme, else oursControlBarScheme *m_currentScheme; ///< the current scheme that everythign usesCoord2D m_multiplyer;diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/GameText.h b/GeneralsMD/Code/GameEngine/Include/GameClient/GameText.hindex ff17f2896..018ba3560 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/GameText.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/GameText.h@@ -88,6 +88,14 @@ class GameTextInterface : public SubsystemInterface/// the letter after '&' in the English text of this label (the game's own table and Patch.str,/// before any translation), or 0: Classic's command keys are the English ones in every languagevirtual WideChar fetchEnglishHotKey( const AsciiString& label ) { return 0; }++ /// -modfactions: read mod's own string file (its CSF and its Generals.str, the STR winning a+ /// label both carry) into a table of its own, with TheFileSystem focused on that mod. mod is+ /// the index into TheGlobalData->m_mods; a label "M<mod+1>~LABEL" fetches from that table first+ /// and falls back to the bare LABEL in ours.+ virtual void loadModStrings( Int mod ) {}+ /// TRUE when mod's own table carries label, compared without case like ours+ virtual Bool hasModLabel( Int mod, const char *label ) const { return FALSE; }};diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cppindex 41292df97..dceff2c81 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp@@ -237,6 +237,12 @@ void AudioManager::init()ini.load( AsciiString( "Data\\INI\\Default\\Voice.ini" ), INI_LOAD_OVERWRITE, NULL );ini.load( AsciiString( "Data\\INI\\Voice.ini" ), INI_LOAD_OVERWRITE, NULL );+ // -modfactions: each mod's own events under "M<n>~" names; AudioSettings and MiscAudio stay ours+ INI::loadModPasses( "Data\\INI\\Music.ini", NULL );+ INI::loadModPasses( "Data\\INI\\SoundEffects.ini", NULL );+ INI::loadModPasses( "Data\\INI\\Speech.ini", NULL );+ INI::loadModPasses( "Data\\INI\\Voice.ini", NULL );+// do the miscellaneous sound files last so that we find the audioeventrts associated with the events.ini.load( AsciiString( "Data\\INI\\MiscAudio.ini" ), INI_LOAD_OVERWRITE, NULL);@@ -904,7 +910,8 @@ AudioEventInfo *AudioManager::findAudioEventInfo( AsciiString eventName ) constAudioEventInfoHash::const_iterator it;it = m_allAudioEventInfo.find(eventName);if (it == m_allAudioEventInfo.end()) {- return NULL;+ AsciiString retailName;+ return TheModNamespace.findRetailName(eventName, MODNAME_AUDIOEVENT, &retailName) ? findAudioEventInfo(retailName) : NULL;}return (*it).second;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex e1ef27466..d6fad83b6 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -199,36 +199,18 @@ void initSubsystem(SUBSYSTEM*& sysref, AsciiString name, SUBSYSTEM* sys, Xfer *p}//--------------------------------------------------------------------------------------------------/** A store a faction is made of. With -modfactions retail's own files load alone, and then each- * mod's under that mod's names (INI::loadModPasses); a mod's Default\ file never loads. Without it- * this is initSubsystem. */+/** A store a faction is made of. With -modfactions the plain load sees retail's files only, and+ * then each mod's load under that mod's names (INI::loadModPasses); a mod's Default\ file never+ * loads. Without it this is initSubsystem. *///-------------------------------------------------------------------------------------------------template<class SUBSYSTEM>void initFactionSubsystem(SUBSYSTEM*& sysref, AsciiString name, SUBSYSTEM* sys, Xfer *pXfer, const char* path1,const char* path2, const char* dirpath = NULL){- const Bool apart = TheGlobalData->m_modFactions;- if (apart)- TheFileSystem->setFocus(FILE_FOCUS_RETAIL);initSubsystem(sysref, name, sys, pXfer, path1, path2, dirpath);- if (apart)- TheFileSystem->setFocus(FILE_FOCUS_ALL);INI::loadModPasses(dirpath != NULL ? dirpath : path2, pXfer, dirpath != NULL);}-/** A store that names faction parts without being one (crates, the AI's build lists, the ranks):- * with -modfactions retail's copy, since a mod's names its own parts as they are only under its prefix. */-template<class SUBSYSTEM>-void initRetailSubsystem(SUBSYSTEM*& sysref, AsciiString name, SUBSYSTEM* sys, Xfer *pXfer, const char* path1, const char* path2)-{- const Bool apart = TheGlobalData->m_modFactions;- if (apart)- TheFileSystem->setFocus(FILE_FOCUS_RETAIL);- initSubsystem(sysref, name, sys, pXfer, path1, path2);- if (apart)- TheFileSystem->setFocus(FILE_FOCUS_ALL);-}-//-------------------------------------------------------------------------------------------------#if defined(_WIN32)extern HINSTANCE ApplicationHInstance; ///< our application instance@@ -251,24 +233,18 @@ static void checksumFileContents( XferCRC &xferCRC, const char *path )delete [] contents;}-/** The same for a file a faction is made of: with -modfactions retail's copy, then each mod's that- * has one (modsToo), as ControlBar::init loads them. */-static void checksumFactionFile( XferCRC &xferCRC, const char *path, Bool modsToo )+/** The same for the command buttons and sets: with -modfactions each mod's copy after retail's, as+ * ControlBar::init loads them. */+static void checksumFactionFile( XferCRC &xferCRC, const char *path ){- if (!TheGlobalData->m_modFactions)- {- checksumFileContents( xferCRC, path );- return;- }- TheFileSystem->setFocus( FILE_FOCUS_RETAIL );checksumFileContents( xferCRC, path );- for (Int mod = 0; modsToo && mod < (Int)TheGlobalData->m_mods.size(); ++mod)+ for (Int mod = 0; TheGlobalData->m_modFactions && mod < (Int)TheGlobalData->m_mods.size(); ++mod){TheFileSystem->setFocus( mod );if (TheFileSystem->doesFileExist( path ))checksumFileContents( xferCRC, path );+ TheFileSystem->setFocus( FILE_FOCUS_ALL );}- TheFileSystem->setFocus( FILE_FOCUS_ALL );}//-------------------------------------------------------------------------------------------------@@ -1172,7 +1148,7 @@ void GameEngine::init( int argc, char *argv[] )initSubsystem(TheMessageStream,"TheMessageStream", createMessageStream(), NULL);initSubsystem(TheSidesList,"TheSidesList", MSGNEW("GameEngineSubsystem") SidesList(), NULL);initSubsystem(TheCaveSystem,"TheCaveSystem", MSGNEW("GameEngineSubsystem") CaveSystem(), NULL);- initRetailSubsystem(TheRankInfoStore,"TheRankInfoStore", MSGNEW("GameEngineSubsystem") RankInfoStore(), &xferCRC, NULL, "Data\\INI\\Rank.ini");+ initSubsystem(TheRankInfoStore,"TheRankInfoStore", MSGNEW("GameEngineSubsystem") RankInfoStore(), &xferCRC, NULL, "Data\\INI\\Rank.ini");initFactionSubsystem(ThePlayerTemplateStore,"ThePlayerTemplateStore", MSGNEW("GameEngineSubsystem") PlayerTemplateStore(), &xferCRC, "Data\\INI\\Default\\PlayerTemplate.ini", "Data\\INI\\PlayerTemplate.ini");initSubsystem(TheParticleSystemManager,"TheParticleSystemManager", createParticleSystemManager(), NULL);@@ -1246,10 +1222,10 @@ void GameEngine::init( int argc, char *argv[] )#endif/////////////////////////////////////////////////////////////////////////////////////////////- initRetailSubsystem(TheAI,"TheAI", MSGNEW("GameEngineSubsystem") AI(), &xferCRC, "Data\\INI\\Default\\AIData.ini", "Data\\INI\\AIData.ini");+ initSubsystem(TheAI,"TheAI", MSGNEW("GameEngineSubsystem") AI(), &xferCRC, "Data\\INI\\Default\\AIData.ini", "Data\\INI\\AIData.ini");initSubsystem(TheGameLogic,"TheGameLogic", createGameLogic(), NULL);initSubsystem(TheTeamFactory,"TheTeamFactory", MSGNEW("GameEngineSubsystem") TeamFactory(), NULL);- initRetailSubsystem(TheCrateSystem,"TheCrateSystem", MSGNEW("GameEngineSubsystem") CrateSystem(), &xferCRC, "Data\\INI\\Default\\Crate.ini", "Data\\INI\\Crate.ini");+ initSubsystem(TheCrateSystem,"TheCrateSystem", MSGNEW("GameEngineSubsystem") CrateSystem(), &xferCRC, "Data\\INI\\Default\\Crate.ini", "Data\\INI\\Crate.ini");initSubsystem(ThePlayerList,"ThePlayerList", MSGNEW("GameEngineSubsystem") PlayerList(), NULL);initSubsystem(TheRecorder,"TheRecorder", createRecorder(), NULL);initSubsystem(TheRadar,"TheRadar", createRadar(), NULL);@@ -1297,9 +1273,9 @@ void GameEngine::init( int argc, char *argv[] )// the control bar parses these without the checksum, and the AI builds and hunts from them- checksumFactionFile( xferCRC, "Data\\INI\\Default\\CommandButton.ini", FALSE );- checksumFactionFile( xferCRC, "Data\\INI\\CommandButton.ini", TRUE );- checksumFactionFile( xferCRC, "Data\\INI\\CommandSet.ini", TRUE );+ checksumFileContents( xferCRC, "Data\\INI\\Default\\CommandButton.ini" );+ checksumFactionFile( xferCRC, "Data\\INI\\CommandButton.ini" );+ checksumFactionFile( xferCRC, "Data\\INI\\CommandSet.ini" );checksumFileContents( xferCRC, "Data\\INI\\CommandSetReforged.ini" );checksumModels( xferCRC );diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cppindex 471ccf1d4..3bbec462a 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp@@ -470,9 +470,14 @@ const char *const ModNamespace::FactionFiles[] ="Data\\INI\\ObjectCreationList.ini", "Data\\INI\\Locomotor.ini", "Data\\INI\\SpecialPower.ini","Data\\INI\\DamageFX.ini", "Data\\INI\\Armor.ini", "Data\\INI\\Object", "Data\\INI\\Upgrade.ini","Data\\INI\\CommandButton.ini", "Data\\INI\\CommandSet.ini", "Data\\INI\\ParticleSystem.ini",+ "Data\\INI\\MappedImages", "Data\\INI\\ControlBarScheme.ini", "Data\\INI\\Music.ini",+ "Data\\INI\\SoundEffects.ini", "Data\\INI\\Speech.ini", "Data\\INI\\Voice.ini",NULL};+/// where a mod's art and sound sit; a word in its INI that names one of these files is read as the mod's copy+static const char *const ModAssetFolders[] = { "Art\\W3D\\", "Art\\Textures\\", "Data\\Audio\\" };+/// the block keywords whose second word is a name the mod definesstatic const struct { const char *keyword; ModNameType type; } ModBlockTypes[] ={@@ -482,6 +487,8 @@ static const struct { const char *keyword; ModNameType type; } ModBlockTypes[] ={ "CommandSet", MODNAME_COMMANDSET }, { "CommandButton", MODNAME_COMMANDBUTTON }, { "FXList", MODNAME_FXLIST },{ "ObjectCreationList", MODNAME_OCL }, { "ParticleSystem", MODNAME_PARTICLESYSTEM },{ "Locomotor", MODNAME_LOCOMOTOR }, { "PlayerTemplate", MODNAME_PLAYERTEMPLATE },+ { "MappedImage", MODNAME_MAPPEDIMAGE }, { "ControlBarScheme", MODNAME_CONTROLBARSCHEME },+ { "AudioEvent", MODNAME_AUDIOEVENT }, { "DialogEvent", MODNAME_AUDIOEVENT }, { "MusicTrack", MODNAME_AUDIOEVENT },};void ModNamespace::scanMods( void )@@ -521,14 +528,22 @@ void ModNamespace::scanMods( void )}}finishScan( mod );++ FilenameList assetFiles;+ for (size_t folder = 0; folder < ARRAY_SIZE( ModAssetFolders ); ++folder)+ TheFileSystem->getFileListInDirectory( AsciiString( ModAssetFolders[ folder ] ), "*.*", assetFiles, TRUE );+ for (FilenameListIter it = assetFiles.begin(); it != assetFiles.end(); ++it)+ addAsset( mod, it->str() );+ TheGameText->loadModStrings( mod );TheFileSystem->setFocus( FILE_FOCUS_ALL );const Names &names = m_mods[ mod ];- DEBUG_LOG(( "MODNS M%d~ is '%s': %d names from %d files, %d objects, %d weapons, %d upgrades, %d sciences, %d player templates\n",+ DEBUG_LOG(( "MODNS M%d~ is '%s': %d names from %d files, %d objects, %d weapons, %d upgrades, %d sciences, %d player templates, %d images, %d audio events, %d asset names\n",mod + 1, TheGlobalData->m_modNames[ mod ].str(), (Int)names.all.size(), (Int)files.size(),(Int)names.byType[ MODNAME_OBJECT ].size(), (Int)names.byType[ MODNAME_WEAPON ].size(),(Int)names.byType[ MODNAME_UPGRADE ].size(), (Int)names.byType[ MODNAME_SCIENCE ].size(),- (Int)names.byType[ MODNAME_PLAYERTEMPLATE ].size() ));+ (Int)names.byType[ MODNAME_PLAYERTEMPLATE ].size(), (Int)names.byType[ MODNAME_MAPPEDIMAGE ].size(),+ (Int)names.byType[ MODNAME_AUDIOEVENT ].size(), (Int)names.assets.size() ));}}@@ -587,15 +602,103 @@ void ModNamespace::finishScan( Int mod )names.all.erase( *it );}-Bool ModNamespace::rewriteLine( char *line, size_t capacity ) const+/// A-Z only: the result goes into the INI checksum, so no locale may decide it+static std::string foldAscii( const std::string &text )+{+ std::string folded( text );+ for (size_t i = 0; i < folded.size(); ++i)+ {+ if (folded[ i ] >= 'A' && folded[ i ] <= 'Z')+ folded[ i ] = (char)(folded[ i ] - 'A' + 'a');+ }+ return folded;+}++void ModNamespace::addAsset( Int mod, const char *fileName )+{+ const char *slash = strrchr( fileName, '\\' );+ const std::string name = foldAscii( slash != NULL ? slash + 1 : fileName );+ const size_t dot = name.rfind( '.' );+ if (dot == std::string::npos)+ return;+ const std::string base = name.substr( 0, dot );+ const std::string extension = name.substr( dot + 1 );+ if ((Int)m_mods.size() <= mod)+ m_mods.resize( mod + 1 );+ std::set<std::string> &assets = m_mods[ mod ].assets;+ // INI names a model or a sound without its extension, and a texture as .tga when the file is a .dds+ if (extension == "w3d" || extension == "wav" || extension == "mp3")+ assets.insert( base );+ else if (extension == "dds" || extension == "tga")+ {+ assets.insert( base + ".tga" );+ assets.insert( base + ".dds" );+ }+ else+ assets.insert( name );+}++Bool ModNamespace::isAsset( const Names &names, const std::string &word )+{+ const std::string name = foldAscii( word );+ if (names.assets.count( name ) != 0)+ return TRUE;+ // an animation is "<hierarchy>.<animation>", and the file is the animation's+ const size_t dot = name.find( '.' );+ return dot != std::string::npos && names.assets.count( name.substr( dot + 1 ) ) != 0;+}++Bool ModNamespace::isAssetField( const std::string &field )+{+ // what a mod pass reads that names a file: draw modules, trees and props, debris, beams, particles,+ // shadows, mapped images and audio. ShowSubObject and the bone fields stay out, their words are+ // names inside a model and can match a file+ static const char *const AssetFields[] =+ {+ "Model", "Animation", "IdleAnimation", "ModelName", "ModelNames", "AnimationSet", "TextureName",+ "Texture", "ParticleName", "TrackMarks", "ShadowTexture",+ "Sounds", "SoundsMorning", "SoundsEvening", "SoundsNight", "Attack", "Decay", "Filename",+ };+ for (size_t i = 0; i < ARRAY_SIZE( AssetFields ); ++i)+ {+ if (stricmp( field.c_str(), AssetFields[ i ] ) == 0)+ return TRUE;+ }+ return FALSE;+}++Bool ModNamespace::isNameOrAsset( const std::string &word, Bool assetField ) const{const Names &names = m_mods[ m_active ];+ return names.all.count( word ) != 0 || (assetField && isAsset( names, word ));+}++Bool ModNamespace::isModLabel( const std::string &word, Bool ) const+{+ // the engine tests read mod INI with no GameText up+ return word.find( ':' ) != std::string::npos && TheGameText != NULL+ && TheGameText->hasModLabel( m_active, word.c_str() );+}++Bool ModNamespace::rewriteLine( char *line, size_t capacity ) const+{+ return prefixWords( line, capacity, &ModNamespace::isNameOrAsset );+}++Bool ModNamespace::rewriteLabels( char *line, size_t capacity ) const+{+ return prefixWords( line, capacity, &ModNamespace::isModLabel );+}++Bool ModNamespace::prefixWords( char *line, size_t capacity, WordTest test ) const+{char prefix[ 16 ];snprintf( prefix, sizeof( prefix ), "M%d~", m_active + 1 );// INI's own separators; readLine has already turned every other control character into a spacestd::string out;Bool first = TRUE;+ Bool assetField = FALSE;for (const char *p = line; *p != 0; ){if (*p == ' ' || *p == '=')@@ -607,10 +710,17 @@ Bool ModNamespace::rewriteLine( char *line, size_t capacity ) constwhile (*p != 0 && *p != ' ' && *p != '=')++p;const std::string word( start, p - start );- if (!first && names.all.count( word ) != 0)+ if (first)+ {+ // only a field that names a file: a bone or sub-object can share a model's name+ assetField = isAssetField( word );+ out += word;+ first = FALSE;+ continue;+ }+ if ((this->*test)( word, assetField ))out += prefix;out += word;- first = FALSE;}if (out.size() >= capacity)return FALSE;@@ -621,7 +731,8 @@ Bool ModNamespace::rewriteLine( char *line, size_t capacity ) constBool ModNamespace::findRetailName( const AsciiString &name, ModNameType type, AsciiString *retailName ) const{const char *text = name.str();- if (m_mods.empty() || text[ 0 ] != 'M')+ // image and sound names may have been lowercased on the way here+ if (m_mods.empty() || (text[ 0 ] != 'M' && text[ 0 ] != 'm'))return FALSE;char *tilde = NULL;const long mod = strtol( text + 1, &tilde, 10 );@@ -721,6 +832,13 @@ void INI::readLine( void )//DEBUG_LOG(("Xfer val is now 0x%8.8X in %s, line %s\n", ((XferCRC *)s_xfer)->getCRC(),//m_filename.str(), m_buffer));}++ if (TheModNamespace.getActive() >= 0 && !TheModNamespace.rewriteLabels(m_buffer, sizeof(m_buffer)))+ {+ g_LastErrorDump.format("INI::readLine: line %d of '%s' is too long once its mod labels are prefixed\n", m_lineNum, m_filename.str());+ DEBUG_LOG(("%s", g_LastErrorDump.str()));+ throw INI_BUFFER_TOO_SMALL;+ }}//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cppindex 6ace26dd2..2f9d329ef 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp@@ -248,35 +248,35 @@ void ArchiveFileSystem::loadMods() {void ArchiveFileSystem::keepModsApart(size_t modCount){- m_retailRoot = m_rootDirectory;m_modRoots.assign(modCount, ArchivedDirectoryInfo());}void ArchiveFileSystem::addModArchive(Int mod, ArchiveFile *archiveFile, const AsciiString& archiveFilename){- loadIntoDirectoryTree(archiveFile, archiveFilename, TRUE);m_archiveFileMap[archiveFilename] = archiveFile;- if (m_modRoots.empty())+ // kept apart, a mod's files are reached only through its own focus or an "M<n>~" name: the merged+ // view stays retail's, so the menus, the lobby and every file a faction does not name are ours+ if (!m_modRoots.empty())+ {+ addToTree(m_modRoots[mod], archiveFile, archiveFilename, TRUE);+ m_archiveMod[archiveFilename] = mod;return;- addToTree(m_modRoots[mod], archiveFile, archiveFilename, TRUE);- m_archiveMod[archiveFilename] = mod;+ }+ loadIntoDirectoryTree(archiveFile, archiveFilename, TRUE);}const ArchivedDirectoryInfo &ArchiveFileSystem::focusedRoot() const{- if (m_focus == FILE_FOCUS_ALL)- return m_rootDirectory;- if (m_focus == FILE_FOCUS_RETAIL)- return m_retailRoot;- return m_modRoots[m_focus];+ return m_focus < 0 ? m_rootDirectory : m_modRoots[m_focus];}Bool ArchiveFileSystem::inFocus(const AsciiString& archiveFilename) const{- if (m_focus == FILE_FOCUS_ALL)+ if (m_focus == FILE_FOCUS_ALL && m_modRoots.empty())return TRUE;std::map<AsciiString, Int>::const_iterator it = m_archiveMod.find(archiveFilename);- return (it == m_archiveMod.end() ? FILE_FOCUS_RETAIL : it->second) == m_focus;+ const Int owner = it == m_archiveMod.end() ? FILE_FOCUS_RETAIL : it->second;+ return m_focus < 0 ? owner < 0 : owner == m_focus;}Bool ArchiveFileSystem::doesFileExist(const Char *filename) const@@ -411,6 +411,28 @@ void ArchiveFileSystem::prioritizeLargerFiles(const AsciiString& directory, cons}AsciiString ArchiveFileSystem::getArchiveFilenameForFile(const AsciiString& filename) const+{+ return archiveInTree(focusedRoot(), filename);+}++File *ArchiveFileSystem::openModFile(Int mod, const AsciiString& filename, Int access)+{+ const AsciiString archive = archiveInTree(m_modRoots[mod], filename);+ return archive.isEmpty() ? NULL : m_archiveFileMap[archive]->openFile(filename.str(), access);+}++Bool ArchiveFileSystem::doesModFileExist(Int mod, const AsciiString& filename) const+{+ return archiveInTree(m_modRoots[mod], filename).isNotEmpty();+}++Bool ArchiveFileSystem::getModFileInfo(Int mod, const AsciiString& filename, FileInfo *fileInfo) const+{+ ArchiveFileMap::const_iterator it = m_archiveFileMap.find(archiveInTree(m_modRoots[mod], filename));+ return it != m_archiveFileMap.end() && it->second->getFileInfo(filename, fileInfo);+}++AsciiString ArchiveFileSystem::archiveInTree(const ArchivedDirectoryInfo &root, const AsciiString& filename){AsciiString path;path = filename;@@ -418,7 +440,7 @@ AsciiString ArchiveFileSystem::getArchiveFilenameForFile(const AsciiString& fileAsciiString token;AsciiString debugpath;- const ArchivedDirectoryInfo *dirInfo = &focusedRoot();+ const ArchivedDirectoryInfo *dirInfo = &root;path.nextToken(&token, "\\/");diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cppindex 1f9e23298..0fb2be862 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/FileSystem.cpp@@ -162,14 +162,46 @@ AsciiString FileSystem::focusedLooseFile( const AsciiString& filename ) constif (s_focus == FILE_FOCUS_RETAIL)return TheLocalFileSystem->doesFileExist( filename.str() ) ? filename : AsciiString();- const AsciiString &mod = TheGlobalData->m_mods[ s_focus ];- if (!mod.endsWith( "\\" ) && !mod.endsWith( "/" ))+ return modFolderFile( s_focus, filename );+}++AsciiString FileSystem::modFolderFile( Int mod, const AsciiString& filename ) const+{+ const AsciiString &modPath = TheGlobalData->m_mods[ mod ];+ if (!modPath.endsWith( "\\" ) && !modPath.endsWith( "/" ))return AsciiString();- AsciiString path = mod;+ AsciiString path = modPath;path.concat( filename );return TheLocalFileSystem->doesFileExist( path.str() ) ? path : AsciiString();}+//============================================================================+// FileSystem::splitModName+//============================================================================++Bool FileSystem::splitModName( const AsciiString& filename, Int *mod, AsciiString *bare )+{+ if (TheGlobalData == NULL || !TheGlobalData->m_modFactions)+ return FALSE;+ const char *path = filename.str();+ const char *name = path;+ for (const char *p = path; *p != 0; ++p)+ {+ if (*p == '\\' || *p == '/')+ name = p + 1;+ }+ if ((name[ 0 ] != 'M' && name[ 0 ] != 'm') || name[ 1 ] < '0' || name[ 1 ] > '9')+ return FALSE;+ char *tilde = NULL;+ const long n = strtol( name + 1, &tilde, 10 );+ if (*tilde != '~' || n < 1 || n > (long)TheGlobalData->m_mods.size())+ return FALSE;+ *mod = (Int)n - 1;+ *bare = std::string( path, name - path ).c_str();+ bare->concat( tilde + 1 );+ return TRUE;+}+//============================================================================// FileSystem::~FileSystem//============================================================================@@ -249,6 +281,15 @@ File* FileSystem::openFile( const Char *filename, Int access )}const Bool readOnly = (access & (File::WRITE | File::CREATE | File::APPEND | File::TRUNCATE)) == 0;+ Int mod;+ AsciiString bare;+ if ( readOnly && splitModName( AsciiString( filename ), &mod, &bare ) )+ {+ AsciiString loose = modFolderFile( mod, bare );+ if ( loose.isNotEmpty() )+ return TheLocalFileSystem->openFile( loose.str(), access );+ return TheArchiveFileSystem->openModFile( mod, bare, access );+ }if ( readOnly && s_focus != FILE_FOCUS_ALL ){AsciiString loose = focusedLooseFile( AsciiString( filename ) );@@ -308,6 +349,11 @@ Bool FileSystem::doesFileExist(const Char *filename) constif (isGeneratedMapPath( AsciiString( filename ) ))return TRUE;+ Int mod;+ AsciiString bare;+ if (splitModName( AsciiString( filename ), &mod, &bare ))+ return modFolderFile( mod, bare ).isNotEmpty() || TheArchiveFileSystem->doesModFileExist( mod, bare );+// the cache is the merged view's; a focus asks its own files every time (setFocus)if (s_focus != FILE_FOCUS_ALL)return focusedLooseFile( AsciiString( filename ) ).isNotEmpty() || TheArchiveFileSystem->doesFileExist( filename );@@ -347,7 +393,9 @@ void FileSystem::getFileListInDirectory(const AsciiString& directory, const Asci// a mod's loose files listed under their game path, so a file it replaces is loaded once, from the mod (openFile)// TheGlobalData is not there yet while GameData.ini itself loads, and there is no -mod before it is- if (TheGlobalData == NULL || isAbsolutePath(directory) || s_focus == FILE_FOCUS_RETAIL)+ // -modfactions' merged view is retail's+ if (TheGlobalData == NULL || isAbsolutePath(directory) || s_focus == FILE_FOCUS_RETAIL ||+ (s_focus == FILE_FOCUS_ALL && TheGlobalData->m_modFactions)){return;}@@ -383,7 +431,8 @@ AsciiString FileSystem::modLooseFile(const AsciiString& filename, Bool *inModArc*inModArchive = FALSE;}// a folder is not a file: "" or "Maps\" would otherwise find the mod folder itself, which exists- if (TheGlobalData == NULL || TheGlobalData->m_mods.empty() || isAbsolutePath(filename) ||+ // -modfactions reaches a mod's files only by its focus or its "M<n>~" names+ if (TheGlobalData == NULL || TheGlobalData->m_mods.empty() || TheGlobalData->m_modFactions || isAbsolutePath(filename) ||filename.isEmpty() || filename.endsWith("\\") || filename.endsWith("/")){return AsciiString();@@ -486,6 +535,16 @@ Bool FileSystem::getFileInfo(const AsciiString& filename, FileInfo *fileInfo) coreturn TRUE;}+ Int mod;+ AsciiString bare;+ if (splitModName(filename, &mod, &bare)) {+ AsciiString loose = modFolderFile(mod, bare);+ if (loose.isNotEmpty()) {+ return TheLocalFileSystem->getFileInfo(loose, fileInfo);+ }+ return TheArchiveFileSystem->getModFileInfo(mod, bare, fileInfo);+ }+if (s_focus != FILE_FOCUS_ALL) {AsciiString loose = focusedLooseFile(filename);if (loose.isNotEmpty()) {diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cppindex 20c60458a..5f98fc6c3 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp@@ -664,11 +664,13 @@ void ControlBar::watchPlayer( Player *player )const PlayerTemplate *wear = player ? player->getPlayerTemplate(): ThePlayerList->getLocalPlayer()->getPlayerTemplate();- if( m_controlBarSchemeManager && wear && wear->getSide().compare( m_watchedSide ) != 0 )+ // by template name rather than side: under -modfactions a mod's America and ours share the side+ // and not the bar+ if( m_controlBarSchemeManager && wear && wear->getName().compare( m_watchedSide ) != 0 ){// a scheme lays the whole bar out again, so it is set when the side really changes and not// on every click- m_watchedSide = wear->getSide();+ m_watchedSide = wear->getName();m_controlBarSchemeManager->setControlBarSchemeByPlayerTemplate( wear );restoreStageAfterScheme();}@@ -2008,6 +2010,12 @@ const ControlBarPlate *ControlBarPlateForSide( const AsciiString& side, Int paneif( side.isEmpty() || panel < 0 || panel >= ControlBar::CB_PANEL_COUNT )return NULL;+ // -modfactions: a mod's bar wears the mod's own painting (drawModPainting), never our plates,+ // so nothing shifts its windows off the mod's layout or masks its clicks with our art+ if( TheControlBar && TheControlBar->getControlBarSchemeManager() &&+ TheControlBar->getControlBarSchemeManager()->isCurrentSchemeMod() )+ return NULL;+// the boss bar is Chinese and the observer bar is American - EA built each out of that artif( side.startsWithNoCase( "Boss" ) )return &thePlateSets[ 1 ].plate[ panel ];@@ -2836,18 +2844,13 @@ void ControlBar::init( void ){INI ini;m_sideSelectAnimateDown = FALSE;- // -modfactions: retail's own buttons and sets first, then each mod's under its names- const Bool apart = TheGlobalData != NULL && TheGlobalData->m_modFactions;- if (apart)- TheFileSystem->setFocus( FILE_FOCUS_RETAIL );// load the command buttonsini.load( AsciiString( "Data\\INI\\Default\\CommandButton.ini" ), INI_LOAD_OVERWRITE, NULL );ini.load( AsciiString( "Data\\INI\\CommandButton.ini" ), INI_LOAD_OVERWRITE, NULL );// load the command setsini.load( AsciiString( "Data\\INI\\CommandSet.ini" ), INI_LOAD_OVERWRITE, NULL );- if (apart)- TheFileSystem->setFocus( FILE_FOCUS_ALL );+ // -modfactions: each mod's buttons and sets after retail's, under its namesINI::loadModPasses( "Data\\INI\\CommandButton.ini", NULL );INI::loadModPasses( "Data\\INI\\CommandSet.ini", NULL );@@ -4504,10 +4507,12 @@ const PlayerTemplate *ControlBar::templateForSide( AsciiString side )for( Int c = 0; c < 5; c++ )side.removeLastChar();+ // -modfactions: a mod's bar wears that mod's tray, ours ours, though the side is spelt the same+ const Int mod = m_controlBarSchemeManager ? m_controlBarSchemeManager->getCurrentSchemeMod() : -1;for( Int t = 0; t < ThePlayerTemplateStore->getPlayerTemplateCount(); t++ ){const PlayerTemplate *pt = ThePlayerTemplateStore->getNthPlayerTemplate( t );- if( pt && pt->getSide().compareNoCase( side ) == 0+ if( pt && pt->getSide().compareNoCase( side ) == 0 && pt->getModIndex() == mod&& !pt->getSpecialPowerShortcutWinName().isEmpty() )return pt;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cppindex 2335fe56b..789ddbd25 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp@@ -968,6 +968,8 @@ void ControlBarSchemeManager::init( void )ini.load( AsciiString( "Data\\INI\\ControlBarScheme.ini" ), INI_LOAD_OVERWRITE, NULL );// the fork's edits to EA's schemes, each block naming only what it changesini.load( AsciiString( "Data\\INI\\ControlBarSchemeReforged.ini" ), INI_LOAD_MULTIFILE, NULL );+ // -modfactions: each mod's own bars, "M<n>~" names, worn only by that mod's factions+ INI::loadModPasses( "Data\\INI\\ControlBarScheme.ini", NULL );// //Load the user modified control bar schemes// WIN32_FIND_DATA findData;@@ -1076,13 +1078,24 @@ AsciiString ControlBarSchemeManager::getCurrentArtTwinSide( void ) const/** The side's widest scheme, as EA picked. Neither interface draws a scheme's painting; the plates* stand in for it (ControlBarPlateForSide), and the scheme only places the bar's own windows. *///------------------------------------------------------------------------------ControlBarScheme *ControlBarSchemeManager::findSchemeForSide( const AsciiString& side ) const+/// -modfactions: the mod (0-based) a scheme's "M<n>~" name says it came from, -1 for ours+static Int schemeModIndex( const AsciiString& name )+{+ const char *text = name.str();+ if( text[ 0 ] != 'M' && text[ 0 ] != 'm' )+ return -1;+ char *tilde = NULL;+ const long mod = strtol( text + 1, &tilde, 10 );+ return ( tilde != text + 1 && *tilde == '~' && mod >= 1 ) ? (Int)mod - 1 : -1;+}++ControlBarScheme *ControlBarSchemeManager::findSchemeForSide( const AsciiString& side, Int mod ) const{ControlBarScheme *best = NULL;for( ControlBarSchemeList::const_iterator it = m_schemeList.begin(); it != m_schemeList.end(); ++it ){ControlBarScheme *scheme = *it;- if( scheme->m_side.compareNoCase( side ) != 0 )+ if( scheme->m_side.compareNoCase( side ) != 0 || schemeModIndex( scheme->m_name ) != mod )continue;if( best == NULL || scheme->m_ScreenCreationRes.x > best->m_ScreenCreationRes.x )best = scheme;@@ -1090,6 +1103,77 @@ ControlBarScheme *ControlBarSchemeManager::findSchemeForSide( const AsciiString&return best;}+/// a mod faction wears its mod's bar for the side, ours where the mod has none; ours never a mod's+ControlBarScheme *ControlBarSchemeManager::findSchemeForFaction( const AsciiString& side, Int mod ) const+{+ ControlBarScheme *scheme = mod >= 0 ? findSchemeForSide( side, mod ) : NULL;+ return scheme ? scheme : findSchemeForSide( side, -1 );+}++Int ControlBarSchemeManager::getCurrentSchemeMod( void ) const+{+ return m_currentScheme ? schemeModIndex( m_currentScheme->m_name ) : -1;+}++//-----------------------------------------------------------------------------+/** A mod's bar is one painting authored for 800x600 (or its ScreenCreationRes) and our bar stands in+ * three panels at one scale, so the painting is cut where the panels meet and each piece is drawn+ * through its own panel's placement, the way the windows above it are placed. Classic and Reforged+ * alike: the windows are laid out the same way in both. */+//-----------------------------------------------------------------------------+void ControlBarSchemeManager::drawModPainting( ICoord2D offset, Bool foreground )+{+ // where the left and centre, and the centre and right panels meet, in 800x600 design units+ static const Int seams[ ControlBar::CB_PANEL_COUNT + 1 ] = { 0, 182, 616, 800 };++ const Real toDesignX = 800.0f / m_currentScheme->m_ScreenCreationRes.x;+ const Real toDesignY = 600.0f / m_currentScheme->m_ScreenCreationRes.y;+ const Int first = foreground ? 0 : CONTROL_BAR_SCHEME_FOREGROUND_IMAGE_LAYERS;+ const Int last = foreground ? CONTROL_BAR_SCHEME_FOREGROUND_IMAGE_LAYERS : MAX_CONTROL_BAR_SCHEME_IMAGE_LAYERS;+ const Int width = TheDisplay->getWidth();+ const Int height = TheDisplay->getHeight();++ for( Int p = 0; p < ControlBar::CB_PANEL_COUNT; p++ )+ {+ if( TheControlBar->isPanelHidden( p ) )+ continue;+ const Int slide = TheControlBar->getPanelSlideOffset( p );++ IRegion2D band, clip;+ band.lo.x = seams[ p ];+ band.hi.x = seams[ p + 1 ];+ band.lo.y = 0;+ band.hi.y = 600;+ ControlBarPanelDesignToScreen( p, &band, width, height, &clip );+ clip.lo.x += offset.x;+ clip.hi.x += offset.x;+ clip.lo.y += offset.y + slide;+ clip.hi.y += offset.y + slide;+ TheDisplay->setClipRegion( &clip );+ TheDisplay->enableClipping( TRUE );++ for( Int layer = last - 1; layer >= first; layer-- )+ {+ for( ControlBarScheme::ControlBarSchemeImageList::const_iterator it = m_currentScheme->m_layer[ layer ].begin();+ it != m_currentScheme->m_layer[ layer ].end(); ++it )+ {+ const ControlBarSchemeImage *schemeImage = *it;+ if( schemeImage->m_image == NULL )+ continue;+ IRegion2D design, rect;+ design.lo.x = REAL_TO_INT_FLOOR( schemeImage->m_position.x * toDesignX );+ design.lo.y = REAL_TO_INT_FLOOR( schemeImage->m_position.y * toDesignY );+ design.hi.x = REAL_TO_INT_CEIL( ( schemeImage->m_position.x + schemeImage->m_size.x ) * toDesignX );+ design.hi.y = REAL_TO_INT_CEIL( ( schemeImage->m_position.y + schemeImage->m_size.y ) * toDesignY );+ ControlBarPanelDesignToScreen( p, &design, width, height, &rect );+ TheDisplay->drawImage( schemeImage->m_image, rect.lo.x + offset.x, rect.lo.y + offset.y + slide,+ rect.hi.x + offset.x, rect.hi.y + offset.y + slide );+ }+ }+ TheDisplay->enableClipping( FALSE );+ }+}+//-----------------------------------------------------------------------------void ControlBarSchemeManager::setControlBarSchemeByPlayerTemplate( const PlayerTemplate *pt, Bool useSmall){@@ -1104,7 +1188,7 @@ void ControlBarSchemeManager::setControlBarSchemeByPlayerTemplate( const PlayerTside.set("Observer");// picked again every time, even for the side on screen: a new resolution can want a different// scheme for it (findSchemeForSide), and the multiplier below is the screen's- ControlBarScheme *tempScheme = findSchemeForSide( side );+ ControlBarScheme *tempScheme = findSchemeForFaction( side, pt->getModIndex() );DEBUG_LOG(("setControlBarSchemeByPlayer used %s as its side\n", side.str()));if(tempScheme)@@ -1145,7 +1229,9 @@ void ControlBarSchemeManager::setControlBarSchemeByPlayer(Player *p)side.set("Observer");// picked again every time, even for the side on screen: a new resolution can want a different// scheme for it (findSchemeForSide), and the multiplier below is the screen's- ControlBarScheme *tempScheme = findSchemeForSide( side );+ // the neutral and civilian players have no template, and wear ours+ const PlayerTemplate *pt = p->getPlayerTemplate();+ ControlBarScheme *tempScheme = findSchemeForFaction( side, pt ? pt->getModIndex() : -1 );DEBUG_LOG(("setControlBarSchemeByPlayer used %s as its side\n", side.str()));if(tempScheme)diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cppindex f719f81e6..65b9ba48b 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp@@ -114,6 +114,14 @@ struct StringLookUpStringInfo *info;};+/// one -modfactions mod's own labels: info owns the strings, lut is sorted by compareLUT+struct ModStringTable+{+ StringInfo *info;+ StringLookUp *lut;+ Int count;+};+//===============================// CSFHeader//===============================@@ -162,9 +170,21 @@ class GameTextManager : public GameTextInterfacevirtual void initMapStringFile( const AsciiString& filename );virtual WideChar fetchEnglishHotKey( const AsciiString& label );+ virtual void loadModStrings( Int mod );+ virtual Bool hasModLabel( Int mod, const char *label ) const;protected:+ /// -modfactions: each mod's own labels (English CSF and STR), by mod index; empty without the switch+ std::vector< ModStringTable > m_modStrings;+ /// each mod's CSF in the player's language, text only: never consulted for the label set+ std::vector< ModStringTable > m_modLangStrings;+ /// the mod index of a "M<n>~" label with a loaded table, or -1+ Int modLabelIndex( const char *label ) const;+ void readModTable( ModStringTable &table, const char *csf, const char *str );+ /// the mod's text for label: its language's CSF first, then its English CSF and STR+ StringLookUp *findModText( Int mod, const char *label ) const;+/// label (lower case) -> its English hotkey letter, filled once the table is readstd::map< std::string, WideChar > m_englishHotKeys;@@ -210,6 +230,15 @@ class GameTextManager : public GameTextInterface};static int _cdecl compareLUT ( const void *, const void*);++static StringLookUp *findModLabel( const ModStringTable &table, const char *label )+{+ AsciiString lb = label;+ StringLookUp key;+ key.info = NULL;+ key.label = &lb;+ return (StringLookUp *) bsearch( &key, (void*) table.lut, table.count, sizeof(StringLookUp), compareLUT );+}//----------------------------------------------------------------------------// Private Data//----------------------------------------------------------------------------@@ -532,6 +561,16 @@ void GameTextManager::deinit( void )m_textCount = 0;+ for ( size_t mod = 0; mod < m_modStrings.size(); ++mod )+ {+ delete [] m_modStrings[ mod ].info;+ delete [] m_modStrings[ mod ].lut;+ delete [] m_modLangStrings[ mod ].info;+ delete [] m_modLangStrings[ mod ].lut;+ }+ m_modStrings.clear();+ m_modLangStrings.clear();+NoString *noString = m_noStringList;DEBUG_LOG(("\n*** Missing strings ***\n"));@@ -1406,6 +1445,23 @@ UnicodeString GameTextManager::fetch( const Char *label, Bool *exists )return m_failed;}+ // -modfactions: "M<n>~LABEL" is mod n-1's own LABEL, and ours when that mod has none+ if ( label[0] == 'M' && !m_modStrings.empty() )+ {+ Int mod = modLabelIndex( label );+ if ( mod >= 0 )+ {+ label += 3;+ StringLookUp *own = findModText( mod, label );+ if ( own )+ {+ if( exists )+ *exists = TRUE;+ return own->info->text;+ }+ }+ }+StringLookUp *lookUp;StringLookUp key;AsciiString lb;@@ -1463,12 +1519,143 @@ UnicodeString GameTextManager::fetch( AsciiString label, Bool *exists )return fetch(label.str(), exists);}+//============================================================================+// GameTextManager::modLabelIndex+//============================================================================++Int GameTextManager::modLabelIndex( const char *label ) const+{+ if ( label[0] != 'M' || label[1] < '1' || label[1] > '9' || label[2] != '~' )+ return -1;+ Int mod = label[1] - '1';+ return mod < (Int)m_modStrings.size() && m_modStrings[ mod ].lut != NULL ? mod : -1;+}++//============================================================================+// GameTextManager::loadModStrings+//============================================================================++void GameTextManager::loadModStrings( Int mod )+{+ if ( (Int)m_modStrings.size() <= mod )+ {+ ModStringTable none = { NULL, NULL, 0 };+ m_modStrings.resize( mod + 1, none );+ m_modLangStrings.resize( mod + 1, none );+ }++ // The label set decides which INI words get "M<n>~", so it may not depend on the player's+ // language: the English CSF and the STR only. The language's CSF is text alone, read first.+ AsciiString csfFile;+ csfFile.format(g_csfFile, "English");+ readModTable( m_modStrings[ mod ], csfFile.str(), g_strFile );+ AsciiString language = GetRegistryLanguage();+ csfFile.format(g_csfFile, language.str());+ readModTable( m_modLangStrings[ mod ], language.compareNoCase( "English" ) ? csfFile.str() : NULL, NULL );++ DEBUG_LOG(("MODNS M%d~ strings: %d labels\n", mod + 1, m_modStrings[ mod ].count));+}++//============================================================================+// GameTextManager::readModTable+//============================================================================++void GameTextManager::readModTable( ModStringTable &table, const char *csf, const char *str )+{+ // getCSFInfo sizes through our own count and language; keep ours+ Int ourCount = m_textCount;+ LanguageID ourLanguage = m_language;+ Int csfCount = csf && getCSFInfo( csf ) ? m_textCount : 0;+ m_textCount = ourCount;+ m_language = ourLanguage;+ Int strCount = 0;+ if ( str )+ getStringCount( str, strCount );++ table.info = NEW StringInfo[ csfCount + strCount ];++ // the parsers fill m_stringInfo from index 0: point it at the mod's table, the STR after the CSF+ StringInfo *ours = m_stringInfo;+ m_stringInfo = table.info;+ if ( csfCount )+ parseCSF( csf );+ m_stringInfo = table.info + csfCount;+ if ( strCount )+ parseStringFile( str );+ m_stringInfo = ours;++ // the STR's padding leaves empty entries behind; they are no label+ table.lut = NEW StringLookUp[ csfCount + strCount ];+ table.count = 0;+ for ( Int i = 0; i < csfCount + strCount; i++ )+ {+ if ( table.info[ i ].label.isEmpty() )+ continue;+ table.lut[ table.count ].info = &table.info[ i ];+ table.lut[ table.count ].label = &table.info[ i ].label;+ table.count++;+ }+ qsort( table.lut, table.count, sizeof(StringLookUp), compareLUT );++ // a label in both files: the entry further along, the STR's, wins, as the overlays do in init+ if ( table.count > 1 )+ {+ Int kept = 1;+ for ( Int i = 1; i < table.count; i++ )+ {+ if ( table.lut[i].label->compareNoCase( table.lut[kept - 1].label->str() ) == 0 )+ {+ if ( table.lut[i].info > table.lut[kept - 1].info )+ table.lut[kept - 1] = table.lut[i];+ continue;+ }+ table.lut[kept] = table.lut[i];+ kept++;+ }+ table.count = kept;+ }+}++//============================================================================+// GameTextManager::findModText+//============================================================================++StringLookUp *GameTextManager::findModText( Int mod, const char *label ) const+{+ StringLookUp *own = findModLabel( m_modLangStrings[ mod ], label );+ return own ? own : findModLabel( m_modStrings[ mod ], label );+}++//============================================================================+// GameTextManager::hasModLabel+//============================================================================++Bool GameTextManager::hasModLabel( Int mod, const char *label ) const+{+ return findModLabel( m_modStrings[ mod ], label ) != NULL;+}+//============================================================================// GameTextManager::fetchEnglishHotKey//============================================================================WideChar GameTextManager::fetchEnglishHotKey( const AsciiString& label ){+ // a mod's own label: the letter after '&' in the mod's text, which is the mod's own key+ Int mod = m_modStrings.empty() ? -1 : modLabelIndex( label.str() );+ if ( mod >= 0 )+ {+ StringLookUp *own = findModText( mod, label.str() + 3 );+ if ( own )+ {+ const WideChar *amp = own->info->text.str();+ while ( *amp && *amp != u'&' )+ amp++;+ return ( *amp && amp[ 1 ] > u' ' ) ? amp[ 1 ] : 0;+ }+ return fetchEnglishHotKey( AsciiString( label.str() + 3 ) );+ }+AsciiString key = label;key.toLower();std::map< std::string, WideChar >::const_iterator it = m_englishHotKeys.find( key.str() );diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cppindex 8fbacc6e4..9d80b0c18 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Image.cpp@@ -255,7 +255,10 @@ void ImageCollection::addImage( Image *image )const Image *ImageCollection::findImageByName( const AsciiString& name ){std::map<unsigned,Image *>::iterator i=m_imageMap.find(TheNameKeyGenerator->nameToLowercaseKey(name));- return i==m_imageMap.end()?NULL:i->second;+ if (i!=m_imageMap.end())+ return i->second;+ AsciiString retailName;+ return TheModNamespace.findRetailName(name, MODNAME_MAPPEDIMAGE, &retailName) ? findImageByName(retailName) : NULL;} // end findImageByName//-------------------------------------------------------------------------------------------------@@ -290,5 +293,9 @@ void ImageCollection::load( Int textureSize )ini.loadDirectory("Data\\INI\\MappedImages\\HandCreated", TRUE, INI_LOAD_OVERWRITE, NULL );+ // -modfactions: each mod's cameos and HUD art under its own "M<n>~" names+ INI::loadModPasses( buffer, NULL, TRUE );+ INI::loadModPasses( "Data\\INI\\MappedImages\\HandCreated", NULL, TRUE );+} // end loaddiff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cppindex 19d6b46d1..79f57b3ca 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp@@ -3507,13 +3507,8 @@ void ParticleSystemManager::init( void ){/// Read INI data and build templatesINI ini;- // -modfactions: retail's own systems first, then each mod's under its names- const Bool apart = TheGlobalData != NULL && TheGlobalData->m_modFactions;- if (apart)- TheFileSystem->setFocus( FILE_FOCUS_RETAIL );ini.load( AsciiString( "Data\\INI\\ParticleSystem.ini" ), INI_LOAD_OVERWRITE, NULL );- if (apart)- TheFileSystem->setFocus( FILE_FOCUS_ALL );+ // -modfactions: each mod's systems after retail's, under its namesINI::loadModPasses( "Data\\INI\\ParticleSystem.ini", NULL );// The fork's own systems, beside EA's 1088 rather than in a loose copy of all of themini.load( AsciiString( "Data\\INI\\ParticleSystemReforged.ini" ), INI_LOAD_OVERWRITE, NULL );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cppindex 6c52a0b31..b64c91fb6 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp@@ -34,7 +34,8 @@#include "Common/GlobalData.h"#include "Common/Player.h"#include "Common/PlayerList.h"-#include "Common/Team.h"+#include "Common/PlayerTemplate.h"+#include "Common/Team.h"#include "Common/ThingFactory.h"#include "Common/BuildAssistant.h"#include "Common/SpecialPower.h"@@ -1238,6 +1239,18 @@ void AISkirmishPlayer::newMap( void )while (build) {if (build->m_side == mySide) {BuildListInfo *buildList = build->m_buildList->duplicate();+ // -modfactions: the build lists are retail's and keyed by side, so a mod's player builds the+ // mod's own building of each name, and retail's where the mod has none. Before this its+ // command center was torn down below and put back as retail's.+ const Int mod = m_player->getPlayerTemplate()->getModIndex();+ for (BuildListInfo *info = buildList; mod >= 0 && info != NULL; info = info->getNext())+ {+ AsciiString modName;+ modName.format("M%d~%s", mod + 1, info->getTemplateName().str());+ const ThingTemplate *modPlan = TheThingFactory->findTemplate( modName );+ if (modPlan != NULL)+ info->setTemplateName( modPlan->getName() );+ }adjustBuildList(buildList); // adjust to our start position.m_player->setBuildList(buildList);computeCenterAndRadiusOfBase(&m_baseCenter, &m_baseRadius);diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cppindex bfffa10a6..8da91ab18 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp@@ -341,7 +341,17 @@ void PopulatePlayerTemplateComboBox(Int comboBox, GameWindow *comboArray[], Game{WideChar modName[128];WideCharFromUtf8(TheGlobalData->m_modNames[fac->getModIndex()].str(), modName, ARRAY_SIZE(modName));- UnicodeString sideLabel = label;+ // the mod's own name for the faction: The End of Days' Russia sits on our China Nuke General's side+ static const WideChar MissingLabel[] = u"MISSING";+ const Int missingLength = ARRAY_SIZE(MissingLabel) - 1;+ UnicodeString sideLabel = fac->getDisplayName();+ if (sideLabel.isEmpty() || (sideLabel.getLength() >= missingLength+ && std::char_traits<WideChar>::compare(sideLabel.str(), MissingLabel, missingLength) == 0))+ {+ AsciiString modSide;+ modSide.format("M%d~%s", fac->getModIndex() + 1, side.str());+ sideLabel = TheGameText->fetch(modSide);+ }label = UnicodeString(modName);label.concat(UnicodeString(u" - "));label.concat(sideLabel);diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.hindex 1dea9298e..324bee8b6 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h@@ -358,6 +358,9 @@ public:/// the draw methodvirtual void doDrawModule(const Matrix3D* transformMtx);++ /// the name the render object was made from; under -modfactions it keeps the "M<n>~" its Get_Name drops+ const AsciiString& getCurrentModelName() const { return m_curState->m_modelName; }/// Hands the frame's lit headlights to the Direct3D 11 frame, nearest the camera first. Once a/// frame, after the smooth motion has placed every model and before anything is drawn.static void lightHeadlights(const Vector3& cameraPosition);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cppindex 522661ece..a5b2df3bc 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp@@ -711,6 +711,13 @@ void W3DCommandBarBackgroundDraw( GameWindow *window, WinInstanceData *instDataoffset.y = now.y - TheControlBar->getPanelOrigin()->y;}+ // -modfactions: a mod faction's bar is the mod's own painting, not our plates or our page+ if( man->isCurrentSchemeMod() )+ {+ man->drawModPainting( offset, FALSE );+ return;+ }+IRegion2D panels[ ControlBar::CB_PANEL_COUNT ];Bool shown[ ControlBar::CB_PANEL_COUNT ];const Image *images[ ControlBar::CB_PANEL_COUNT ];@@ -757,7 +764,23 @@ void W3DCommandBarBackgroundDraw( GameWindow *window, WinInstanceData *instDatavoid W3DCommandBarForegroundDraw( GameWindow *window, WinInstanceData *instData ){- // nothing sits on top of the plates - see W3DCommandBarBackgroundDraw+ // nothing sits on top of the plates - see W3DCommandBarBackgroundDraw. A mod's bar keeps its+ // scheme's foreground layers, moved with the bar the same way+ ControlBarSchemeManager *man = TheControlBar ? TheControlBar->getControlBarSchemeManager() : NULL;+ if( man == NULL || TheDisplay == NULL || !man->isCurrentSchemeMod() )+ return;++ ICoord2D offset;+ offset.x = offset.y = 0;+ GameWindow *frame = window ? window->winGetParent() : NULL;+ if( frame )+ {+ ICoord2D now;+ frame->winGetScreenPosition( &now.x, &now.y );+ offset.x = now.x - TheControlBar->getPanelOrigin()->x;+ offset.y = now.y - TheControlBar->getPanelOrigin()->y;+ }+ man->drawModPainting( offset, TRUE );}void W3DNoDraw( GameWindow *window, WinInstanceData *instData )diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cppindex 4d79a021b..b6912fe25 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp@@ -91,6 +91,9 @@ const float H_epsilon(1.0f);const float S_epsilon(0.01f);const float V_epsilon(0.01f);+// A texture name past a mod's "M<n>~" prefix, for the checks that read the retail naming ("ZHC...").+static inline const char *Mod_Bare_Name(const char *name) { return name + WW3D_Mod_Prefix_Length(name); }+//---------------------------------------------------------------------// Externs defined somewhere in W3D.//---------------------------------------------------------------------@@ -185,7 +188,7 @@ TextureClass * W3DAssetManager::Get_Texture//Just call the base implementation after adjusting reduction to deal//with our special types.- if (filename && *filename && strncasecmp(filename,"ZHC",3) == 0)+ if (filename && *filename && strncasecmp(Mod_Bare_Name(filename),"ZHC",3) == 0)allow_reduction = false; //don't allow reduction on our infantry textures.return WW3DAssetManager::Get_Texture( filename,@@ -700,10 +703,11 @@ TextureClass * W3DAssetManager::Recolor_Texture_One_Time(TextureClass *texture,newsurf=NEW_REF(SurfaceClass,(desc.Width,desc.Height,desc.Format));newsurf->Copy(0,0,0,0,desc.Width,desc.Height,oldsurf);- if (*(name+3) == 'D' || *(name+3) == 'd')+ const char *kind = Mod_Bare_Name(name) + 3; // the letter after "ZHC"+ if (*kind == 'D' || *kind == 'd')Remap_Palette(newsurf,color, true, false ); //texture only contains a palette stored in top row.else- if (*(name+3) == 'A' || *(name+3) == 'a')+ if (*kind == 'A' || *kind == 'a')Remap_Palette(newsurf,color, false, true ); //texture only contains a palette stored in top row.TextureClass * newtex=NEW_REF(TextureClass,(newsurf,(MipCountType)texture->Get_Mip_Level_Count()));@@ -805,12 +809,20 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj(WWPROFILE( "WW3DAssetManager::Create_Render_Obj" );WWMEMLOG(MEM_GEOMETRY);- // Try to find a prototype- PrototypeClass * proto = Find_Prototype(name);-+ // Try to find a prototype: a mod's own first, then the bare name as retail. The request stays+ // the mod's to the end, so the texture swap and recolour below find the mod's textures too.+ WW3DModRequest mod(name);Set_WW3D_Load_On_Demand(true); // Auto Load.- if (WW3D_Load_On_Demand && proto == NULL)- {+ PrototypeClass * proto = mod.Active() ? Find_Mod_Prototype(mod.Bare) : NULL;+ Bool modProto = proto != NULL;+ if (proto == NULL)+ {+ name = mod.Bare;+ proto = Find_Prototype(name);+ }++ if (WW3D_Load_On_Demand && proto == NULL)+ {// If we didn't find one, try to load on demandchar filename [MAX_PATH];const char *mesh_name = ::strchr (name, '.');@@ -880,7 +892,13 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj(if (reallytexture){- TextureClass *oldTex = Get_Texture(oldTexture);+ // A retail model drawn for a mod carries retail textures, so the one it replaces is+ // looked up as retail, or it would not match the mesh's texture.+ TextureClass *oldTex;+ {+ WW3DModPrefixScope retail(modProto ? WW3D_Mod_Prefix : "");+ oldTex = Get_Texture(modProto ? oldTexture : Mod_Bare_Name(oldTexture));+ }TextureClass *newTex = Get_Texture(newTexture);replaceAssetTexture(rendobj,oldTex,newTex);REF_PTR_RELEASE(newTex);@@ -956,7 +974,7 @@ int W3DAssetManager::Recolor_Mesh(RenderObjClass *robj, const int color)for (i=0; i<material->Texture_Count(); i++){oldtex=material->Peek_Texture(i);- if (strncasecmp(oldtex->Get_Texture_Name(),"ZHC", 3) == 0)+ if (strncasecmp(Mod_Bare_Name(oldtex->Get_Texture_Name()),"ZHC", 3) == 0){ //This texture needs to be adjusted for housecolornewtex=Recolor_Texture(oldtex,color);if (newtex)@@ -1223,7 +1241,7 @@ static Bool getMeshColorMethods(MeshClass *mesh, Bool &vertexColor, Bool &texturMaterialInfoClass *material = mesh->Get_Material_Info();if (material){ for (int j=0; j<material->Texture_Count(); j++)- if (strncasecmp(material->Peek_Texture(j)->Get_Texture_Name(),"ZHC",3) == 0)+ if (strncasecmp(Mod_Bare_Name(material->Peek_Texture(j)->Get_Texture_Name()),"ZHC",3) == 0){ textureColor = true;break;}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cppindex a54fd8add..162c426fa 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp@@ -50,6 +50,7 @@#include "WW3D2/hlod.h"#include "WW3D2/scene.h"#include "WW3D2/matinfo.h"+#include "WW3D2/proto.h"#ifdef _INTERNAL@@ -78,9 +79,18 @@ protected:const char *m_robjName; ///<debug pointer so we know what this is a snapshot of.#endifRenderObjClass *m_robj; ///<render object representing state at time of snapshot+ char m_modPrefix[8] = ""; ///<"M<n>~" the model was asked for under, "" for retail; the robj's own name drops itW3DRenderObjectSnapshot *m_next; ///<snapshot of next render object belonging to same drawable};+// Copies the "M<n>~" a model name starts with, or "" when it has none.+static void copyModPrefix(char *prefix, const char *name)+{+ Int len = WW3D_Mod_Prefix_Length(name);+ memcpy(prefix, name, len);+ prefix[len] = 0;+}+//Dummy material override which we assign to all ghost objects to disable their//texture animation.static RenderObjClass::Material_Override animationDisableOverride;@@ -368,6 +378,9 @@ void W3DGhostObject::snapShot(int playerIndex)elsem_parentSnapshots[playerIndex]->update(robj, &m_drawableInfo);+ // the model name keeps the mod prefix the robj's name drops, so a save reloads the mod's art+ copyModPrefix(snap->m_modPrefix, w3dDraw->getCurrentModelName().str());+//Adding and removing render objects to the scene is expensive//so only do it for the real player watching the screen. There is//also no point in displaying the other player's ghost objects to@@ -683,7 +696,7 @@ void W3DGhostObject::xfer( Xfer *xfer ){// write name from render object- name.set( objectSnapshot->m_robj->Get_Name() );+ name.format( "%s%s", objectSnapshot->m_modPrefix, objectSnapshot->m_robj->Get_Name() );xfer->xferAsciiString( &name );// write scale from render object@@ -726,6 +739,7 @@ void W3DGhostObject::xfer( Xfer *xfer )// we're loading, allocate new snapshotobjectSnapshot = NEW W3DRenderObjectSnapshot( renderObject, &m_drawableInfo, FALSE );+ copyModPrefix( objectSnapshot->m_modPrefix, name.str() );// attach to listif( prevObjectSnapshot )diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.cppindex 6a78d13bf..feff06d80 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.cpp@@ -356,7 +356,16 @@ AggregateDefClass::Load_Assets (const char *passet_name)// Param OK?if (passet_name != NULL) {-++ // Under a mod the mod's own file comes first, as for any other name a mod model uses.+ if (WW3D_Mod_Prefix[0]) {+ char mod_file[MAX_PATH];+ snprintf(mod_file, sizeof(mod_file), "%s%s.w3d", WW3D_Mod_Prefix, passet_name);+ if (WW3D_Mod_Ships(mod_file)) {+ return WW3DAssetManager::Get_Instance()->Load_3D_Assets(mod_file);+ }+ }+// Determine what the current working directory ischar path[MAX_PATH];#if defined(_WIN32)diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cppindex db9dde3e1..0a9764cd2 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp@@ -141,6 +141,84 @@ WW3DAssetManager * WW3DAssetManager::TheInstance = NULL;*/static NullPrototypeClass _NullPrototype;+thread_local char WW3D_Mod_Prefix[8] = "";++int WW3D_Mod_Prefix_Length(const char * name)+{+ if (name[0] != 'M' && name[0] != 'm') return 0;+ int i = 1;+ while (name[i] >= '0' && name[i] <= '9') i++;+ return (i > 1 && i < 7 && name[i] == '~') ? i + 1 : 0;+}++bool WW3D_Mod_Ships(const char * file)+{+ // Mod files do not change while the game runs, so a miss is remembered: a retail model under a+ // mod would otherwise ask the file system again for every sub-object, tree and texture it uses.+ // One set per thread, so no lock is needed whichever thread asks.+ static thread_local HashTemplateClass<StringClass,bool> missing;+ StringClass key(file,true);+ _strlwr(key.Peek_Buffer());+ if (missing.Exists(key)) return false;++ FileClass * f = _TheFileFactory->Get_File(file);+ bool ships = f->Is_Available();+ _TheFileFactory->Return_File(f);+ if (!ships) missing.Insert(key,true);+ return ships;+}++WW3DModRequest::WW3DModRequest(const char * name) : Bare(name), Own(false)+{+ int len = WW3D_Mod_Prefix_Length(name);+ if (len != 0) {+ Own = true;+ strcpy(Saved, WW3D_Mod_Prefix);+ memcpy(WW3D_Mod_Prefix, name, len);+ WW3D_Mod_Prefix[len] = 0;+ Bare = name + len;+ }+}++// The texture loader takes a .dds in place of a .tga, so either one counts as the mod's texture.+static bool Mod_Texture_Ships(const char * name)+{+ if (WW3D_Mod_Ships(name)) return true;+ size_t len = strlen(name);+ if (len < 4 || strcasecmp(name + len - 4, ".tga") != 0) return false;+ char dds[MAX_PATH];+ snprintf(dds, sizeof(dds), "%.*sdds", (int)(len - 3), name);+ return WW3D_Mod_Ships(dds);+}++/*+** A prototype read from a mod's file. It is filed under the mod's prefix and the inner name, so a+** retail or other mod's prototype of the same name stays apart, and it creates its object with the+** mod current, so the sub-objects and tree that object names come from the same mod.+*/+class ModPrototypeClass : public PrototypeClass+{+public:+ ModPrototypeClass(PrototypeClass * inner) : Inner(inner)+ {+ strcpy(Prefix, WW3D_Mod_Prefix);+ snprintf(Name, sizeof(Name), "%s%s", Prefix, inner->Get_Name());+ }++ virtual const char * Get_Name(void) const { return Name; }+ virtual int Get_Class_ID(void) const { return Inner->Get_Class_ID(); }+ virtual RenderObjClass * Create(void) { WW3DModPrefixScope mod(Prefix); return Inner->Create(); }+ virtual void DeleteSelf() { Inner->DeleteSelf(); delete this; }++protected:+ virtual ~ModPrototypeClass(void) {}++private:+ PrototypeClass * Inner;+ char Prefix[8];+ char Name[256];+};+/*** Iterator for the Render Objects in the asset manager*/@@ -657,6 +735,16 @@ bool WW3DAssetManager::Load_3D_Assets( const char * filename )} timer(filename);#endif+ // A prefixed file the mod does not ship is the retail file; that goes back through the virtual+ // entry so a file already loaded is not read again. Whatever file is read, the current mod is+ // the file's own for the read, so a retail file never takes in a mod's names.+ WW3DModRequest mod(filename);+ if (mod.Own && !WW3D_Mod_Ships(filename)) {+ WW3DModPrefixScope retail("");+ return Load_3D_Assets(mod.Bare);+ }+ WW3DModPrefixScope read(mod.Own ? WW3D_Mod_Prefix : "");+FileClass * file = _TheFileFactory->Get_File( filename );if ( file ) {if ( file->Is_Available() ) {@@ -773,6 +861,10 @@ bool WW3DAssetManager::Load_Prototype(ChunkLoadClass & cload)*/if (newproto != NULL) {+ if (WW3D_Mod_Prefix[0]) {+ newproto = W3DNEW ModPrototypeClass(newproto);+ }+if (!Render_Obj_Exists(newproto->Get_Name())) {/*@@ -826,6 +918,16 @@ RenderObjClass * WW3DAssetManager::Create_Render_Obj(const char * name)WWPROFILE( "WW3DAssetManager::Create_Render_Obj" );WWMEMLOG(MEM_GEOMETRY);+ // A mod's own model first; without one the bare name goes on as retail, the mod still current.+ WW3DModRequest mod(name);+ if (mod.Active()) {+ PrototypeClass * mod_proto = Find_Mod_Prototype(mod.Bare);+ if (mod_proto != NULL) {+ return mod_proto->Create();+ }+ name = mod.Bare;+ }+// Try to find a prototypePrototypeClass * proto = Find_Prototype(name);@@ -1004,6 +1106,31 @@ HAnimClass * WW3DAssetManager::Get_HAnim(const char * name){WWPROFILE( "WW3DAssetManager::Get_HAnim" );+ // A mod's own animation first. A miss is put on the missing list under the prefixed name either+ // way, so the next request for it does not ask the file system again before going to retail.+ WW3DModRequest mod(name);+ if (mod.Active()) {+ char full[MAX_PATH];+ snprintf(full, sizeof(full), "%s%s", WW3D_Mod_Prefix, mod.Bare);+ HAnimClass * mod_anim = HAnimManager.Get_Anim(full);+ const char * animname = strchr(mod.Bare, '.');+ if (WW3D_Load_On_Demand && mod_anim == NULL && animname != NULL && !HAnimManager.Is_Missing(full)) {+ char filename[MAX_PATH];+ snprintf(filename, sizeof(filename), "%s%s.w3d", WW3D_Mod_Prefix, animname + 1);+ if (WW3D_Mod_Ships(filename)) {+ Load_3D_Assets(filename);+ mod_anim = HAnimManager.Get_Anim(full);+ }+ if (mod_anim == NULL) {+ HAnimManager.Register_Missing(full);+ }+ }+ if (mod_anim != NULL) {+ return mod_anim;+ }+ name = mod.Bare;+ }+// Try to find the hanimHAnimClass * anim = HAnimManager.Get_Anim(name);@@ -1058,6 +1185,26 @@ HTreeClass * WW3DAssetManager::Get_HTree(const char * name){WWPROFILE( "WW3DAssetManager::Get_HTree" );+ // A mod's own tree first, then the retail one with the mod still current.+ WW3DModRequest mod(name);+ if (mod.Active()) {+ char full[MAX_PATH];+ snprintf(full, sizeof(full), "%s%s", WW3D_Mod_Prefix, mod.Bare);+ HTreeClass * mod_tree = HTreeManager.Get_Tree(full);+ if (WW3D_Load_On_Demand && mod_tree == NULL) {+ char filename[MAX_PATH];+ snprintf(filename, sizeof(filename), "%s.w3d", full);+ if (WW3D_Mod_Ships(filename)) {+ Load_3D_Assets(filename);+ mod_tree = HTreeManager.Get_Tree(full);+ }+ }+ if (mod_tree != NULL) {+ return mod_tree;+ }+ name = mod.Bare;+ }+// Try to find the htreeHTreeClass * htree = HTreeManager.Get_Tree(name);@@ -1125,6 +1272,16 @@ TextureClass * WW3DAssetManager::Get_Texturereturn NULL;}+ // A mod's own texture is filed under its prefixed name, which is also the path the loader+ // opens; when the mod does not ship the file the request is the retail texture.+ WW3DModRequest mod(filename);+ char mod_name[MAX_PATH];+ if (mod.Active()) {+ snprintf(mod_name, sizeof(mod_name), "%s%s", WW3D_Mod_Prefix, mod.Bare);+ _strlwr(mod_name);+ filename = (TextureHash.Get(StringClass(mod_name)) != NULL || Mod_Texture_Ships(mod_name)) ? mod_name : mod.Bare;+ }+StringClass lower_case_name(filename,true);_strlwr(lower_case_name.Peek_Buffer());@@ -1714,6 +1871,27 @@ PrototypeClass * WW3DAssetManager::Find_Prototype(const char * name)return NULL;}+PrototypeClass * WW3DAssetManager::Find_Mod_Prototype(const char * bare)+{+ char full[MAX_PATH];+ snprintf(full, sizeof(full), "%s%s", WW3D_Mod_Prefix, bare);+ PrototypeClass * proto = Find_Prototype(full);++ if (proto == NULL && WW3D_Load_On_Demand) {+ // The file is named by the text before the first '.', as for a retail name.+ char filename[MAX_PATH];+ strcpy(filename, full);+ char * dot = strchr(filename, '.');+ if (dot != NULL) *dot = 0;+ strcat(filename, ".w3d");+ if (WW3D_Mod_Ships(filename)) {+ Load_3D_Assets(filename);+ proto = Find_Prototype(full);+ }+ }+ return proto;+}+/*** Iterator Implementations.** =====================================================================diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.hindex 0060e378a..c89bb4411 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.h@@ -312,6 +312,10 @@ public:void Remove_Prototype(const char *name);PrototypeClass * Find_Prototype(const char * name);+ // The current mod's own prototype for bare, read from the mod's file when it ships one; NULL+ // when the mod has none, and the caller goes on with bare as a retail name.+ PrototypeClass * Find_Mod_Prototype(const char * bare);+/*** Load on Demand*/diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanim.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanim.hindex 63994221b..9fef1d693 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanim.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanim.h@@ -53,6 +53,7 @@#include <refcount.h>#include <slist.h>#include <Vector.H>+#include "wwstring.h"struct NodeMotionStruct;class MotionChannelClass;@@ -90,7 +91,11 @@ public:virtual const char * Get_Name(void) const = 0;virtual const char * Get_HName(void) const = 0;- virtual const char * Get_Key( void ) { return Get_Name(); }+ virtual const char * Get_Key( void ) { return ModKey.Is_Empty() ? Get_Name() : (const char *)ModKey; }++ // An animation read from a mod's file is filed under the mod's prefix and its name, so it and a+ // retail animation of the same name stay apart. Get_Name stays as it is: the hierarchy matches it.+ void Set_Mod_Prefix(const char * prefix) { ModKey = prefix; ModKey += Get_Name(); }virtual int Get_Num_Frames(void) = 0;virtual float Get_Frame_Rate() = 0;@@ -123,7 +128,8 @@ public:virtual int Get_Embedded_Sound_Bone_Index() {return EmbeddedSoundBoneIndex;}protected:- int EmbeddedSoundBoneIndex;+ int EmbeddedSoundBoneIndex;+ StringClass ModKey;};diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanimmgr.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanimmgr.cppindex b6f267d31..7577c8aba 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanimmgr.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanimmgr.cpp@@ -57,6 +57,17 @@#include "wwmemlog.h"#include "w3dexclusionlist.h"#include "animatedsoundmgr.h"+#include "proto.h"++// The key a freshly read animation is filed under: its name, or the mod's prefix and its name when+// the file being read is a mod's.+static const char * Load_Key(HAnimClass * anim)+{+ if (WW3D_Mod_Prefix[0]) {+ anim->Set_Mod_Prefix(WW3D_Mod_Prefix);+ }+ return anim->Get_Key();+}/***********************************************************************************************@@ -166,7 +177,7 @@ int HAnimManagerClass::Load_Morph_Anim(ChunkLoadClass & cload)// load failed!newanim->Release_Ref();goto Error;- } else if (Peek_Anim(newanim->Get_Name()) != NULL) {+ } else if (Peek_Anim(Load_Key(newanim)) != NULL) {// duplicate exists!newanim->Release_Ref(); // Release the one we just loadedgoto Error;@@ -209,7 +220,7 @@ int HAnimManagerClass::Load_Raw_Anim(ChunkLoadClass & cload)// load failed!newanim->Release_Ref();goto Error;- } else if (Peek_Anim(newanim->Get_Name()) != NULL) {+ } else if (Peek_Anim(Load_Key(newanim)) != NULL) {// duplicate exists!newanim->Release_Ref(); // Release the one we just loadedgoto Error;@@ -252,7 +263,7 @@ int HAnimManagerClass::Load_Compressed_Anim(ChunkLoadClass & cload)// load failed!newanim->Release_Ref();goto Error;- } else if (Peek_Anim(newanim->Get_Name()) != NULL) {+ } else if (Peek_Anim(Load_Key(newanim)) != NULL) {// duplicate exists!newanim->Release_Ref(); // Release the one we just loadedgoto Error;diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htreemgr.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htreemgr.cppindex 9c4acf68f..25c504123 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htreemgr.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htreemgr.cpp@@ -52,6 +52,7 @@#include "chunkio.h"#include "wwmemlog.h"#include "w3dexclusionlist.h"+#include "proto.h"/***********************************************************************************************@@ -151,6 +152,19 @@ void HTreeManagerClass::Free_All_Trees_With_Exclusion_List(const W3DExclusionLis// or copying it to the new tail index if it is excluded.int new_tail = 0;+ // The kept trees go back into the hash under the keys they had, taken before anything is+ // deleted: a mod's tree is filed under the mod's prefix and its name, which the name alone+ // does not give back.+ DynamicVectorClass<StringClass> kept_keys;+ DynamicVectorClass<HTreeClass *> kept_trees;+ HashTemplateIterator<StringClass,HTreeClass*> ite(TreeHash);+ for (ite.First(); !ite.Is_Done(); ite.Next()) {+ if (exclusion_list.Is_Excluded(ite.Peek_Value())) {+ kept_keys.Add(ite.Peek_Key());+ kept_trees.Add(ite.Peek_Value());+ }+ }+int treeidx;for (treeidx =0; treeidx < MAX_TREES; treeidx++) {if (TreePtr[treeidx] != NULL) {@@ -175,12 +189,9 @@ void HTreeManagerClass::Free_All_Trees_With_Exclusion_List(const W3DExclusionLisTreeHash.Remove_All();// Add back any trees that were not deleted- for (treeidx=0; treeidx < new_tail; treeidx++)+ for (int i = 0; i < kept_trees.Count(); i++){- // Insert to hash table for fast name based search- StringClass lower_case_name(TreePtr[treeidx]->Get_Name(),true);- _strlwr(lower_case_name.Peek_Buffer());- TreeHash.Insert(lower_case_name,TreePtr[treeidx]);+ TreeHash.Insert(kept_keys[i],kept_trees[i]);}}@@ -211,9 +222,12 @@ int HTreeManagerClass::Load_Tree(ChunkLoadClass & cload)delete newtree;goto Error;- } else if (Get_Tree_ID(newtree->Get_Name()) != -1) {-- // tree with this name already exists, reject it!+ } else if (Get_Tree(StringClass(WW3D_Mod_Prefix,true) + newtree->Get_Name()) != NULL) {++ // tree with this name already exists, reject it! A tree read from a mod's file is filed+ // under the mod's prefix and its name, so only the same mod's copy counts here. The check+ // goes by key, not Get_Tree_ID: a mod's tree carries the bare name too, and a scan by name+ // would turn the retail tree away.delete newtree;goto Error;@@ -224,7 +238,8 @@ int HTreeManagerClass::Load_Tree(ChunkLoadClass & cload)NumTrees++;// Insert to hash table for fast name based search- StringClass lower_case_name(newtree->Get_Name(),true);+ StringClass lower_case_name(WW3D_Mod_Prefix,true);+ lower_case_name += newtree->Get_Name();_strlwr(lower_case_name.Peek_Buffer());TreeHash.Insert(lower_case_name,newtree);}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/proto.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/proto.hindex 85e12a84a..41df4433f 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/proto.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/proto.h@@ -44,11 +44,59 @@#include "always.h"#include <stdlib.h>+#include <string.h>#include "w3d_file.h"class RenderObjClass;class ChunkLoadClass;+/*+** Mod art. With -modfactions a name from mod n's INI text reads "M<n>~name", and the file system+** opens such a file only if mod n ships it. WW3D_Mod_Prefix is the mod the current request belongs+** to ("" is retail): a prefixed request sets it for its own duration, so the names a mod model uses+** inside itself (sub-objects, its tree, its textures) look in that mod first. While a file is read+** it holds the prefix of that file, and whatever the file brings in is keyed under it.+*/+extern thread_local char WW3D_Mod_Prefix[8];++// Length of a leading "M<n>~" on name, 0 when there is none.+int WW3D_Mod_Prefix_Length(const char * name);++// True when the mod named by the prefix on file ships that file.+bool WW3D_Mod_Ships(const char * file);++// Sets WW3D_Mod_Prefix for one scope and puts the old one back after.+class WW3DModPrefixScope+{+public:+ WW3DModPrefixScope(const char * prefix) : Changed(strcmp(WW3D_Mod_Prefix, prefix) != 0)+ {+ if (Changed) { strcpy(Saved, WW3D_Mod_Prefix); strcpy(WW3D_Mod_Prefix, prefix); }+ }+ ~WW3DModPrefixScope(void) { if (Changed) strcpy(WW3D_Mod_Prefix, Saved); }++private:+ bool Changed;+ char Saved[8];+};++// Splits a request name into its bare part and, if it carries a prefix of its own, makes that the+// current mod for the request's duration. Active() then says whether a mod applies at all.+class WW3DModRequest+{+public:+ WW3DModRequest(const char * name);+ ~WW3DModRequest(void) { if (Own) strcpy(WW3D_Mod_Prefix, Saved); }++ bool Active(void) const { return WW3D_Mod_Prefix[0] != 0; }++ const char * Bare;+ bool Own;++private:+ char Saved[8];+};+/*** W3D Prototype system**diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 5c92c3c59..bd1e67e0e 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -17281,7 +17281,7 @@ TEST(modfactions_focus_sees_one_set_of_archives)archives.addModArchive( 1, two, AsciiString( "Mods\\Two\\!two.big" ) );const AsciiString weapon( "Data\\INI\\Weapon.ini" );- CHECK_STR( archives.getArchiveFilenameForFile( weapon ).str(), "Mods\\One\\!one.big" ); // merged: the mod wins+ CHECK_STR( archives.getArchiveFilenameForFile( weapon ).str(), "INIZH.big" ); // the default view is retail'sarchives.setFocus( FILE_FOCUS_RETAIL );CHECK_STR( archives.getArchiveFilenameForFile( weapon ).str(), "INIZH.big" );archives.setFocus( 0 );@@ -17301,7 +17301,74 @@ TEST(modfactions_focus_sees_one_set_of_archives)listed.clear();archives.setFocus( FILE_FOCUS_ALL );archives.getFileListInDirectory( AsciiString( "" ), AsciiString( "Data\\INI\\Object\\" ), AsciiString( "*.ini" ), listed, TRUE );- CHECK_EQ( (Int)listed.size(), 3 );+ CHECK_EQ( (Int)listed.size(), 1 );+ CHECK( listed.begin()->endsWithNoCase( "a.ini" ) );++ // a mod's own copy by index, whatever the focus: what an "M<n>~" file name asks for+ archives.setFocus( 1 );+ CHECK( archives.doesModFileExist( 0, weapon ) );+ CHECK( !archives.doesModFileExist( 1, weapon ) );+ CHECK( archives.doesModFileExist( 1, AsciiString( "Data\\INI\\Object\\c.ini" ) ) );+ CHECK( !archives.doesModFileExist( 0, AsciiString( "Data\\INI\\Object\\a.ini" ) ) );+ archives.setFocus( FILE_FOCUS_ALL );+}++// -modfactions: "M<n>~" on a file name's last part names mod n's copy, only with the switch and a mod n+TEST(modfactions_split_a_mod_file_name)+{+ GlobalData *saved = TheWritableGlobalData;+ TheWritableGlobalData = NEW GlobalData;+ TheWritableGlobalData->m_mods.assign( 2, AsciiString( "Mods\\X" ) );+ Int mod = -1;+ AsciiString bare;+ TheWritableGlobalData->m_modFactions = FALSE;+ CHECK( !FileSystem::splitModName( AsciiString( "Art\\W3D\\M1~AVRanger.w3d" ), &mod, &bare ) );+ TheWritableGlobalData->m_modFactions = TRUE;+ CHECK( FileSystem::splitModName( AsciiString( "Art\\W3D\\M1~AVRanger.w3d" ), &mod, &bare ) );+ CHECK_EQ( mod, 0 );+ CHECK_STR( bare.str(), "Art\\W3D\\AVRanger.w3d" );+ CHECK( FileSystem::splitModName( AsciiString( "m2~exsmoke.tga" ), &mod, &bare ) );+ CHECK_EQ( mod, 1 );+ CHECK_STR( bare.str(), "exsmoke.tga" );+ CHECK( !FileSystem::splitModName( AsciiString( "Art\\W3D\\M3~AVRanger.w3d" ), &mod, &bare ) ); // no third mod+ CHECK( !FileSystem::splitModName( AsciiString( "M1~Art\\W3D\\AVRanger.w3d" ), &mod, &bare ) ); // not the last part+ CHECK( !FileSystem::splitModName( AsciiString( "Art\\W3D\\Mx~AVRanger.w3d" ), &mod, &bare ) );+ delete TheWritableGlobalData;+ TheWritableGlobalData = saved;+}++// -modfactions: a word naming a model, texture or sound the mod ships gets its prefix, so WW3D and the+// FileSystem serve the mod's copy; art it does not ship stays retail's+TEST(modfactions_prefix_the_mods_own_art)+{+ bootOnce();+ ModNamespace names;+ names.addAsset( 0, "Art\\W3D\\AVRanger.W3D" );+ names.addAsset( 0, "Art\\W3D\\AVRanger_STND.w3d" );+ names.addAsset( 0, "Art\\Textures\\exsmoke.dds" );+ names.addAsset( 0, "Data\\Audio\\Sounds\\vrange01a.wav" );+ names.finishScan( 0 );+ names.setActive( 0 );++ char line[ 96 ];+ strcpy( line, " Model = avranger" );+ CHECK( names.rewriteLine( line, sizeof( line ) ) );+ CHECK_STR( line, " Model = M1~avranger" );+ strcpy( line, " Animation = AVRanger_SKL.AVRanger_STND" );+ CHECK( names.rewriteLine( line, sizeof( line ) ) );+ CHECK_STR( line, " Animation = M1~AVRanger_SKL.AVRanger_STND" );+ strcpy( line, " ParticleName = EXSmoke.tga" ); // INI says .tga, the mod ships the .dds+ CHECK( names.rewriteLine( line, sizeof( line ) ) );+ CHECK_STR( line, " ParticleName = M1~EXSmoke.tga" );+ strcpy( line, " Sounds = vrange01a vrange01b" );+ CHECK( names.rewriteLine( line, sizeof( line ) ) );+ CHECK_STR( line, " Sounds = M1~vrange01a vrange01b" );+ strcpy( line, " Model = AVHumvee" );+ CHECK( names.rewriteLine( line, sizeof( line ) ) );+ CHECK_STR( line, " Model = AVHumvee" );+ strcpy( line, " ShowSubObject = AVRanger" ); // a sub-object, not a file+ CHECK( names.rewriteLine( line, sizeof( line ) ) );+ CHECK_STR( line, " ShowSubObject = AVRanger" );}#include "test_minimap_input.inc"