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(gameclient): army pick screen with a random pool in every lobby
Olcay Seygan66c950944d48
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 617250150..4ac0c115a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,12 @@ found and fixed — EA's own, not port damage.**- In a LAN or online room the other players do not download anything: the map's name carries its recipe, and their own game builds the same map from it and checks it against yours. A room that records stats keeps to the official list.- Random maps used to be reachable only by a hidden command-line switch that added five rows to the skirmish list.+## An army screen in every lobby++- Click a seat's army in the skirmish, LAN or online room and a full screen opens in place of the drop-down list. Every army stands on it under its side's heading, USA, China, GLA and Turkiye, with a large portrait of the one you click, its name across a banner, what it is built to do and what it brings. Confirm takes the army; Back or Escape leaves the seat as it was. The host picks for the computer seats the same way, and nobody can open another player's seat.+- Random gets a pool you choose. Custom Selection puts a tick box on every army, and Random then draws only from the ticked ones: tick China and its three generals and you play Chinese every game, which one is a surprise. With Random focused, the portrait shows every army it can be, lit when it is in the draw and dimmed when it is not. Everyone in the room draws from the same pool, the replay too, so a game never splits over it, and the skirmish room keeps your pool for the next match.+- A plain Random no longer hands you Turkiye. The side is an experiment and a player asking for any army should not get it unasked; tick it into a Custom Selection to have it in the draw. Armies a mod brings in beside ours show on the screen and go into a pool like any other. A replay recorded before this change, with a Random seat in it, plays out differently.+## Music that follows the fight- In a skirmish or an online match the music now answers the battle. While nothing happens one of your side's calmer tracks plays; once guns open up near the camera or on your own forces it crossfades to a harder one, and to the hardest when the fight is big. Six Crusaders against six Scorpions and four Technicals: the first shots brought in a tense track, the battle track followed four seconds later, and twelve seconds after the shooting died down a calm one was back. Two Rangers against three Rebels only gets the middle one.diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex 2734094af..93e39370f 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -187,6 +187,7 @@ Data/INI/ControlBarSchemeReforged.iniData/INI/FXListReforged.iniData/INI/FixesReforged.iniData/INI/MappedImages/HandCreated/ReforgedBarChinaBeacon.ini+Data/INI/MappedImages/HandCreated/ReforgedFactionPicker.iniData/INI/MappedImages/HandCreated/ReforgedForceAttack.iniData/INI/MappedImages/HandCreated/ReforgedHudAmericaCommandBar.iniData/INI/MappedImages/HandCreated/ReforgedHudAmericaPowers.ini@@ -212,12 +213,12 @@ Data/INI/ParticleSystemReforged.iniData/INI/PlayerTemplateReforged.iniData/INI/ScienceReforged.iniData/INI/SpecialPowerReforged.ini-Data/INI/TurkiyeReforged.iniData/INI/SpeechReforged.ini+Data/INI/TurkiyeReforged.iniData/INI/TurkiyeWeaponReforged.iniData/INI/UpgradeReforged.ini-Data/INI/WeaponReforged.iniData/INI/VideoReforged.ini+Data/INI/WeaponReforged.iniData/INI/WindowTransitionsReforged.iniData/Install_Final.bmpData/Patch.str@@ -653,6 +654,7 @@ GameEngine/Include/GameClient/EstablishConnectionsMenu.hGameEngine/Include/GameClient/Eva.hGameEngine/Include/GameClient/ExtendedMessageBox.hGameEngine/Include/GameClient/FXList.h+GameEngine/Include/GameClient/FactionPicker.hGameEngine/Include/GameClient/FontDesc.hGameEngine/Include/GameClient/GUICallbacks.hGameEngine/Include/GameClient/GUICommandTranslator.h@@ -1252,6 +1254,7 @@ GameEngine/Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cppGameEngine/Source/GameClient/GUI/ControlBar/ControlBarUnderConstruction.cppGameEngine/Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cppGameEngine/Source/GameClient/GUI/EstablishConnectionsMenu/EstablishConnectionsMenu.cpp+GameEngine/Source/GameClient/GUI/FactionPicker.cppGameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cppGameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cppGameEngine/Source/GameClient/GUI/GUICallbacks/Diplomacy.cppdiff --git a/GeneralsMD/Code/Data/INI/MappedImages/HandCreated/ReforgedFactionPicker.ini b/GeneralsMD/Code/Data/INI/MappedImages/HandCreated/ReforgedFactionPicker.ininew file mode 100644index 000000000..2221ae9d8--- /dev/null+++ b/GeneralsMD/Code/Data/INI/MappedImages/HandCreated/ReforgedFactionPicker.ini@@ -0,0 +1,12 @@+; The lobby's army screen shows FactionPicker<template name> for an army when it is mapped, in place of+; the template's GeneralImage. Turkiye's is its Maresal insignia (RankTurkiye_21 in+; ReforgedRanksTurkiye.ini), since everywhere else it wears America's eagle. Mapped images are not in+; the multiplayer INI checksum.++MappedImage FactionPickerFactionTurkiye+ Texture = ReforgedRanksTurkiye.tga+ TextureWidth = 512+ TextureHeight = 192+ Coords = Left:327 Top:136 Right:377 Bottom:182+ Status = NONE+Enddiff --git a/GeneralsMD/Code/Data/INI/PlayerTemplateReforged.ini b/GeneralsMD/Code/Data/INI/PlayerTemplateReforged.iniindex 4aabd8db0..9f65a0ce2 100644--- a/GeneralsMD/Code/Data/INI/PlayerTemplateReforged.ini+++ b/GeneralsMD/Code/Data/INI/PlayerTemplateReforged.ini@@ -6,6 +6,7 @@; Turkiye has its own roster (TurkiyeReforged.ini) on American bodies and buys the American general; powers: BaseSide USA, the American sciences on top of its own SCIENCE_Turkiye, and America's load; screen, music and pictures until it has its own. It starts with a Combat Engineer team, not a dozer.+; RandomExcluded keeps it out of a plain Random; a lobby's Custom Selection can still tick it in.PlayerTemplate FactionTurkiyeSide = Turkiye@@ -33,6 +34,7 @@ PlayerTemplate FactionTurkiyeSideIconImage = GameinfoAMRCAGeneralImage = USA_LogoOldFaction = No+ RandomExcluded = YesArmyTooltip = TOOLTIP:BioStrategyLong_TurkiyeFeatures = GUI:BioFeatures_TurkiyeMedallionRegular = USAGeneral_slvrdiff --git a/GeneralsMD/Code/Data/Patch.str b/GeneralsMD/Code/Data/Patch.strindex cc5c1f608..ee18d0f81 100644--- a/GeneralsMD/Code/Data/Patch.str+++ b/GeneralsMD/Code/Data/Patch.str@@ -3341,3 +3341,34 @@ ENDGUI:RandomMapSizeHuge"Extra Large"END++// The staging rooms' army screen, opened from a seat's army box. %s in the Confirm label is the+// army's name, %s in LeftOut the armies a plain Random never draws, and the two %d in Pool are the+// ticked armies and the armies that can be ticked.+GUI:FactionPickTitle+"Select Army"+END++GUI:FactionPickRandomAll+"Random All"+END++GUI:FactionPickCustom+"Custom Selection"+END++GUI:FactionPickConfirm+"Confirm %s"+END++GUI:FactionPickRandom+"Random picks one of these armies for you when the match starts."+END++GUI:FactionPickLeftOut+"Random never draws: %s. Tick it under Custom Selection to add it."+END++GUI:FactionPickPool+"Random picks one of the %d armies ticked on the left, out of %d. Click an army to tick it or take it out."+ENDdiff --git a/GeneralsMD/Code/Data/Turkish/Generals.str b/GeneralsMD/Code/Data/Turkish/Generals.strindex b31a94d5d..f37e1999d 100644--- a/GeneralsMD/Code/Data/Turkish/Generals.str+++ b/GeneralsMD/Code/Data/Turkish/Generals.str@@ -17630,3 +17630,31 @@ ENDGUI:RandomMapSizeHuge"Çok Büyük"END++GUI:FactionPickTitle+"Ordu Seç"+END++GUI:FactionPickRandomAll+"Hepsi Rastgele"+END++GUI:FactionPickCustom+"Özel Seçim"+END++GUI:FactionPickConfirm+"Onayla: %s"+END++GUI:FactionPickRandom+"Rastgele, maç başlarken bu ordulardan birini sizin için seçer."+END++GUI:FactionPickLeftOut+"Rastgele şunları hiç seçmez: %s. Eklemek için Özel Seçim'den işaretleyin."+END++GUI:FactionPickPool+"Rastgele, solda işaretli %d ordudan birini seçer (toplam %d). Bir orduya tıklayarak onu ekleyin ya da çıkarın."+ENDdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/PlayerTemplate.h b/GeneralsMD/Code/GameEngine/Include/Common/PlayerTemplate.hindex d56695fe2..3fa0be7cf 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/PlayerTemplate.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/PlayerTemplate.h@@ -141,6 +141,8 @@ public:AsciiString getScoreScreenMusic() const { return m_scoreScreenMusic; }inline Bool isOldFaction( void ) const { return m_oldFaction; }+ /// a plain Random never draws it; a lobby's own pick of the Random pool may still tick it in+ inline Bool isRandomExcluded( void ) const { return m_randomExcluded; }static const FieldParse* getFieldParse();@@ -181,6 +183,7 @@ private:Bool m_observer;Bool m_playableSide;Bool m_oldFaction; ///< Faction existed in the original Generals+ Bool m_randomExcluded;Int m_intrinsicSPP;diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/FactionPicker.h b/GeneralsMD/Code/GameEngine/Include/GameClient/FactionPicker.hnew file mode 100644index 000000000..e892c7b74--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/FactionPicker.h@@ -0,0 +1,47 @@+/*+** Command & Conquer Generals Zero Hour(tm)+** Copyright 2025 Electronic Arts Inc.+**+** This program is free software: you can redistribute it and/or modify+** it under the terms of the GNU General Public License as published by+** the Free Software Foundation, either version 3 of the License, or+** (at your option) any later version.+**+** This program is distributed in the hope that it will be useful,+** but WITHOUT ANY WARRANTY; without even the implied warranty of+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+** GNU General Public License for more details.+**+** You should have received a copy of the GNU General Public License+** along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++// FILE: FactionPicker.h //////////////////////////////////////////////////////////////////////////+//+// The staging rooms' army screen. A click on a seat's army box opens it instead of the box's own+// list: every army the box lists, grouped under its side, a large portrait and what the army does,+// and a Random whose pool the player can tick by hand. The pick goes back through the box, so each+// room's own handling of a new army (a skirmish seat, a LAN or online request to the host) runs as+// it did for the list.+////////////////////////////////////////////////////////////////////////////////////////////////////++#pragma once++#ifndef _FACTIONPICKER_H_+#define _FACTIONPICKER_H_++#include "Lib/BaseType.h"++class GameWindow;++/// every seat's ComboBoxPlayerTemplate<n> in this room opens the screen when clicked+void FactionPickerAttach( GameWindow *parent, const char *layoutFilename );+/// the room is going away: an open screen goes with it+void FactionPickerDetach( void );+/// the box's Random line carries the seat's own Random, a pool included, so the box shows it and+/// the screen opens on it+void FactionPickerSyncRandom( GameWindow *combo, Int pick );+/// -factionpicker: the next room that attaches opens the screen on its first seat, custom shows the pool+void FactionPickerOpenOnStart( Bool custom );++#endif // _FACTIONPICKER_H_diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/UIStyle.h b/GeneralsMD/Code/GameEngine/Include/GameClient/UIStyle.hindex 2b5cb8010..427ecab55 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/UIStyle.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/UIStyle.h@@ -113,6 +113,8 @@ namespace UIStylevoid wordmark( DisplayString *words[ 2 ], Int right, Int y );/// a screen's title in capitals, as the layouts letter theirsUnicodeString capitals( const UnicodeString &words );+ /// a name in capitals whatever the language, so a map's English name keeps its plain I in Turkish+ UnicodeString nameCapitals( const UnicodeString &name );/// a house colour lifted toward white where it is too dark to read as words on a panelColor readable( Color player );diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/GameInfo.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/GameInfo.hindex 4419f499e..f5af22ba9 100644--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/GameInfo.h+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/GameInfo.h@@ -36,6 +36,7 @@#include "Common/Money.h"#include "GameNetwork/NetworkDefs.h"#include "GameNetwork/FirewallHelper.h"+#include <vector>enum SlotState{@@ -58,6 +59,38 @@ enumPLAYERTEMPLATE_MIN = PLAYERTEMPLATE_OBSERVER};+// A Random the player narrowed to a pool of factions. The pool rides in the seat's faction number+// itself, PLAYERTEMPLATE_RANDOM_POOL - mask, so every slot string, LAN or online request, save and+// replay that carries a pick carries the pool too and every machine draws from the same list. Bit n+// of the mask is the n-th template GetRandomPoolCandidates lists, the store's order, which the INI+// checksum already holds equal across machines.+enum+{+ PLAYERTEMPLATE_RANDOM_POOL = -16,+ RANDOM_POOL_BITS = 30 // ponytail: candidates past the 30th cannot be ticked into a pool; a wider mask needs a field of its own in the slot string+};++inline Bool IsRandomPlayerTemplate( Int pick ) { return pick == PLAYERTEMPLATE_RANDOM || pick < PLAYERTEMPLATE_RANDOM_POOL; }+/// a faction, Random, a Random pool or Observer, whatever the pick came from+Bool IsValidPlayerTemplatePick( Int pick );+/// the pick for a pool; no faction and the default pool are plain Random+Int EncodeRandomPool( UnsignedInt mask );+/// the pool a Random pick draws from; plain Random's is the default one+UnsignedInt DecodeRandomPool( Int pick );+/// the templates a Random may land on, in the store's order: playable, not a locked general+void GetRandomPoolCandidates( std::vector<Int> &candidates );+/// every candidate a template does not mark RandomExcluded+UnsignedInt GetDefaultRandomPool( void );+/// the templates a Random pick draws from in this game; a pool the old-factions rule empties draws as plain Random+void GetRandomDraw( Int pick, Bool oldFactionsOnly, std::vector<Int> &draw );+/// a pick as a preferences file keeps it, a Random pool by its armies' template names: the pool's bits+/// count candidates, and a mod loaded or dropped since the file was written renumbers them+AsciiString PlayerTemplatePreference( Int pick );+Int PlayerTemplateFromPreference( const AsciiString &text );+/// a pick as the slot string carries it: a Random pool as its mask in hex, the room's budget being 400 bytes+AsciiString PlayerTemplateSlotField( Int pick );+Int PlayerTemplateFromSlotField( const AsciiString &field );+// The lobby's income sharing: which earnings are split evenly between a player and every ally// still in the match. The values travel in the options string and in saves, so only append.enum IncomeSharing@@ -98,7 +131,7 @@ public:void setPlayerTemplate( Int playerTemplate ){ m_playerTemplate = playerTemplate;- if (playerTemplate <= PLAYERTEMPLATE_MIN)+ if (playerTemplate == PLAYERTEMPLATE_OBSERVER)m_startPos = -1;}Int getPlayerTemplate( void ) const { return m_playerTemplate; }diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex 60ad48d9f..eea0712c4 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -42,6 +42,7 @@#include "GameClient/GameText.h"#include "GameClient/ChromaKeyboard.h"#include "GameClient/GameConsole.h" // for -freecam+#include "GameClient/FactionPicker.h" // for -factionpicker#include "GameNetwork/GameInfo.h" // for the SlotState -autoskirmish hands the AI slots#include "GameLogic/AI.h" // for aiPersonalityFromName, which -aipersona reads its names with#include "GameNetwork/NetworkUtil.h" // for ResolveIP, which -lanip parses its address with@@ -2525,6 +2526,18 @@ Int parseSkirmishLobby(char *args[], int num)return 1;}+/* -factionpicker [custom] opens the skirmish staging room with the army screen up on the first seat,+ as a click on the seat's army box would, so the screen can be photographed without a click.+ "custom" opens it on Custom Selection with the Random pool's ticks showing. Implies+ -skirmishlobby. */+Int parseFactionPicker(char *args[], int num)+{+ const Bool custom = num > 1 && args[1] && strcasecmp(args[1], "custom") == 0;+ FactionPickerOpenOnStart(custom);+ parseSkirmishLobby(args, num);+ return custom ? 2 : 1;+}+/* -optionsmenu opens the options screen over the main menu at startup, where a click on Optionswould put it. A change to that screen can then be photographed page by page from a script thatonly has to press the tabs, instead of first finding the main menu's buttons. Implies@@ -3007,6 +3020,7 @@ static CommandLineParam params[] ={ "-lanname", parseLanName },{ "-lanlobby", parseLanLobby },{ "-skirmishlobby", parseSkirmishLobby },+ { "-factionpicker", parseFactionPicker },{ "-optionsmenu", parseOptionsMenu },//-allAdvice featurediff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cppindex f288cbd73..d9baeb494 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp@@ -102,6 +102,7 @@{ "SpecialPowerShortcutButtonCount",INI::parseInt, NULL, offsetof( PlayerTemplate, m_specialPowerShortcutButtonCount ) },{ "IsObserver", INI::parseBool, NULL, offsetof( PlayerTemplate, m_observer ) },{ "OldFaction", INI::parseBool, NULL, offsetof( PlayerTemplate, m_oldFaction ) },+ { "RandomExcluded", INI::parseBool, NULL, offsetof( PlayerTemplate, m_randomExcluded ) },{ "IntrinsicSciencePurchasePoints", INI::parseInt, NULL, offsetof( PlayerTemplate, m_intrinsicSPP ) },{ "ScoreScreenImage", INI::parseAsciiString, NULL, offsetof( PlayerTemplate, m_scoreScreenImage ) },{ "LoadScreenImage", INI::parseAsciiString, NULL, offsetof( PlayerTemplate, m_loadScreenImage ) },@@ -201,6 +202,7 @@ PlayerTemplate::PlayerTemplate() :m_observer(false),m_playableSide(false),m_oldFaction(false),+ m_randomExcluded(false),m_intrinsicSPP(0),m_specialPowerShortcutButtonCount(0){diff --git a/GeneralsMD/Code/GameEngine/Source/Common/UserPreferences.cpp b/GeneralsMD/Code/GameEngine/Source/Common/UserPreferences.cppindex 9d262d212..543a4dbf5 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/UserPreferences.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/UserPreferences.cpp@@ -528,8 +528,8 @@ Int CustomMatchPreferences::getPreferredFaction(void)return PLAYERTEMPLATE_RANDOM;}- ret = atoi(it->second.str());- if (ret == PLAYERTEMPLATE_OBSERVER || ret < PLAYERTEMPLATE_MIN || ret >= ThePlayerTemplateStore->getPlayerTemplateCount())+ ret = PlayerTemplateFromPreference(it->second);+ if (ret == PLAYERTEMPLATE_OBSERVER || !IsValidPlayerTemplatePick(ret))ret = PLAYERTEMPLATE_RANDOM;if (ret >= 0)@@ -558,9 +558,7 @@ Int CustomMatchPreferences::getPreferredFaction(void)void CustomMatchPreferences::setPreferredFaction(Int val){- AsciiString s;- s.format("%d", val);- (*this)["PlayerTemplate"] = s;+ (*this)["PlayerTemplate"] = PlayerTemplatePreference(val);}Bool CustomMatchPreferences::usesSystemMapDir(void)diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/FactionPicker.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/FactionPicker.cppnew file mode 100644index 000000000..709aeffb9--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/FactionPicker.cpp@@ -0,0 +1,905 @@+/*+** Command & Conquer Generals Zero Hour(tm)+** Copyright 2025 Electronic Arts Inc.+**+** This program is free software: you can redistribute it and/or modify+** it under the terms of the GNU General Public License as published by+** the Free Software Foundation, either version 3 of the License, or+** (at your option) any later version.+**+** This program is distributed in the hope that it will be useful,+** but WITHOUT ANY WARRANTY; without even the implied warranty of+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+** GNU General Public License for more details.+**+** You should have received a copy of the GNU General Public License+** along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++// FILE: FactionPicker.cpp ////////////////////////////////////////////////////////////////////////+//+// The staging rooms' army screen (FactionPicker.h). One window drawn in code over the whole room,+// modal while it is up, in the front end's look (UIStyle.h): the armies on the left under their+// sides' headings with Random All and Custom Selection over them, the focused army's portrait, name+// and description on the right, Back and Confirm in the room's button row. It reads the armies from+// the seat's own box, so whatever the box lists (the generals, a mod's sides, Observer where the room+// has one) is what the screen offers, and it hands the pick back through the box.+//+// Custom Selection ticks the Random pool. A ticked pool goes into the seat's faction number+// (EncodeRandomPool, GameInfo.h), which every room already sends to the host and the host to every+// player, so the draw at the start of the match sees the same pool on every machine.+////////////////////////////////////////////////////////////////////////////////////////////////////++#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine++#include "Lib/Clock.h"++#include "Common/AudioEventRTS.h"+#include "Common/GameAudio.h"+#include "Common/GlobalData.h"+#include "Common/NameKeyGenerator.h"+#include "Common/PlayerTemplate.h"+#include "GameClient/ChallengeGenerals.h"+#include "GameClient/Display.h"+#include "GameClient/DisplayString.h"+#include "GameClient/DisplayStringManager.h"+#include "GameClient/FactionPicker.h"+#include "GameClient/Gadget.h"+#include "GameClient/GadgetComboBox.h"+#include "GameClient/GadgetListBox.h"+#include "GameClient/GameFont.h"+#include "GameClient/GameText.h"+#include "GameClient/GameWindow.h"+#include "GameClient/GameWindowManager.h"+#include "GameClient/Image.h"+#include "GameClient/KeyDefs.h"+#include "GameClient/Mouse.h"+#include "GameClient/UIStyle.h"+#include "GameNetwork/GameInfo.h"++#include <vector>++// the screen on the 1920x1080 board, inside the staging room's panel+static const Real LEFT = UIStyle::ROOM_INSET;+static const Real RIGHT = 1920.0f - UIStyle::ROOM_INSET;+static const Real GRID_RIGHT = 760.0f;+static const Real DETAIL_LEFT = 792.0f;+static const Real TOP = 168.0f;+static const Real TAB_HEIGHT = 44.0f;+static const Real TAB_GAP = 12.0f;+static const Real GRID_TOP = 232.0f;+static const Real GRID_BOTTOM = 916.0f;+static const Real HEADING_HEIGHT = 34.0f;+static const Real GROUP_GAP = 10.0f;+static const Real CELL = 112.0f;+static const Real CELL_GAP = 12.0f;+static const Real PORTRAIT_BOTTOM = 440.0f;+static const Real BANNER_BOTTOM = 504.0f;+static const Real DESCRIPTION_TOP = 516.0f;+static const Real PAD = 16.0f;+static const Real POOL_ICON = 96.0f;+static const Real MAX_PORTRAIT_SCALE = 4.0f; // a 64 px side logo blown up past this is only blur+static const Int POOL_DIM_ALPHA = 190;+static const char *const PICKER_IMAGE_PREFIX = "FactionPicker"; // a template's own picture here, FactionPickerFactionTurkiye++struct PickerCell+{+ Int pick; ///< the box's item data: a template or PLAYERTEMPLATE_OBSERVER+ Int poolBit; ///< its bit in a Random pool, -1 when it cannot go in one+ UnicodeString name; ///< the box's own line, so a mod's faction reads as the box has it+ const Image *icon;+ const Image *portrait;+ UnicodeString strategy;+ UnicodeString features;+ DisplayString *label; ///< the name in the cell, only for an army with no picture+ IRegion2D box;+};++struct PickerGroup+{+ AsciiString leadSide;+ Int mod;+ DisplayString *heading;+ ICoord2D at;+ std::vector<Int> cells;+};++static Bool s_openOnStart = FALSE;+static Bool s_openOnStartCustom = FALSE;++static GameWindow *s_window = NULL;+static GameWindow *s_combo = NULL;+static GameWindow *s_oldFocus = NULL;+static std::vector<PickerCell> s_cells;+static std::vector<PickerGroup> s_groups;+static Int s_focus = -1; ///< a cell, or -1 for Random+static Bool s_custom = FALSE;+static UnsignedInt s_mask = 0;+static UnicodeString s_leftOut; ///< the listed armies a plain Random never draws+static Int s_lastPressCell = -1;+static UnsignedInt s_lastPressTime = 0;++static DisplayString *s_title = NULL;+static DisplayString *s_tabText[ 2 ] = { NULL, NULL };+static DisplayString *s_backText = NULL;+static DisplayString *s_confirmText = NULL;+static DisplayString *s_nameText = NULL;+static DisplayString *s_strategyText = NULL;+static DisplayString *s_randomMark = NULL;+static std::vector<DisplayString *> s_featureText;++static IRegion2D s_panelBox, s_tabBox[ 2 ], s_backBox, s_confirmBox, s_portraitBox, s_bannerBox, s_descriptionBox;++//-------------------------------------------------------------------------------------------------+static DisplayString *newText( const UnicodeString &text, GameFont *font )+{+ DisplayString *string = TheDisplayStringManager->newDisplayString();+ string->setFont( font );+ string->setText( text );+ return string;+}++static void freeText( DisplayString *&string )+{+ if( string )+ TheDisplayStringManager->freeDisplayString( string );+ string = NULL;+}++static IRegion2D boardBox( Real x0, Real y0, Real x1, Real y1 )+{+ IRegion2D box;+ box.lo.x = UIStyle::boardX( x0 );+ box.lo.y = UIStyle::boardY( y0 );+ box.hi.x = UIStyle::boardX( x1 );+ box.hi.y = UIStyle::boardY( y1 );+ return box;+}++static Bool isInside( const IRegion2D &box, Int x, Int y )+{+ return x >= box.lo.x && x < box.hi.x && y >= box.lo.y && y < box.hi.y;+}++static Int boxWidth( const IRegion2D &box ) { return box.hi.x - box.lo.x; }+static Int boxHeight( const IRegion2D &box ) { return box.hi.y - box.lo.y; }++static void click( void )+{+ AudioEventRTS sound( "GUIClick" );+ TheAudio->addAudioEvent( &sound );+}++static void drawCentred( DisplayString *string, const IRegion2D &box, Color color )+{+ Int width, height;+ string->getSize( &width, &height );+ string->draw( box.lo.x + ( boxWidth( box ) - width ) / 2, box.lo.y + ( boxHeight( box ) - height ) / 2, color, UIStyle::SHADOW );+}++static void drawFitted( const Image *image, const IRegion2D &box, Real maxScale )+{+ const Real scale = min( maxScale, min( (Real)boxWidth( box ) / image->getImageWidth(), (Real)boxHeight( box ) / image->getImageHeight() ) );+ const Int width = REAL_TO_INT( image->getImageWidth() * scale );+ const Int height = REAL_TO_INT( image->getImageHeight() * scale );+ const Int x = box.lo.x + ( boxWidth( box ) - width ) / 2;+ const Int y = box.lo.y + ( boxHeight( box ) - height ) / 2;+ TheDisplay->drawImage( image, x, y, x + width, y + height );+}++/** A Features label lists one thing a line. */+static void splitLines( const UnicodeString &text, std::vector<UnicodeString> &lines )+{+ lines.clear();+ UnicodeString line;+ for( Int each = 0; each <= text.getLength(); each++ )+ {+ const WideChar c = each < text.getLength() ? text.getCharAt( each ) : u'\n';+ // EA's labels carry the break as a real one; a hand-written .str may leave it as the two characters+ const Bool escaped = c == u'\\' && each + 1 < text.getLength() && text.getCharAt( each + 1 ) == u'n';+ if( c != u'\n' && !escaped )+ {+ line.concat( c );+ continue;+ }+ if( escaped )+ each++;+ line.trim();+ if( !line.isEmpty() )+ lines.push_back( line );+ line.clear();+ }+}++static Bool isTicked( const PickerCell &cell )+{+ return cell.poolBit >= 0 && ( s_mask & ( 1u << cell.poolBit ) ) != 0;+}++static Int tickedCount( void )+{+ Int count = 0;+ for( size_t each = 0; each < s_cells.size(); each++ )+ count += isTicked( s_cells[ each ] ) ? 1 : 0;+ return count;+}++static Int tickableCount( void )+{+ Int count = 0;+ for( size_t each = 0; each < s_cells.size(); each++ )+ count += s_cells[ each ].poolBit >= 0 ? 1 : 0;+ return count;+}++/// whether Random, as the screen stands, can land on the army+static Bool isDrawn( const PickerCell &cell )+{+ if( s_custom )+ return isTicked( cell );+ return cell.poolBit >= 0 && !ThePlayerTemplateStore->getNthPlayerTemplate( cell.pick )->isRandomExcluded();+}++/// the pool bits of the armies the box lists; a template it hides keeps a bit nobody can untick+static UnsignedInt listedMask( void )+{+ UnsignedInt mask = 0;+ for( size_t each = 0; each < s_cells.size(); each++ )+ {+ if( s_cells[ each ].poolBit >= 0 )+ mask |= 1u << s_cells[ each ].poolBit;+ }+ return mask;+}++static Int cellAt( Int x, Int y )+{+ for( size_t each = 0; each < s_cells.size(); each++ )+ {+ if( isInside( s_cells[ each ].box, x, y ) )+ return (Int)each;+ }+ return -1;+}++static Bool canConfirm( void )+{+ return s_focus >= 0 || !s_custom || tickedCount() > 0;+}++//-------------------------------------------------------------------------------------------------+/** The armies in the box, each under the first army of its side: a general's Side begins with his+ * side's ("AmericaLaserGeneral" under "America"), so Turkiye, on America's BaseSide but a side of its+ * own, heads its own group, and a mod's sides stay with their mod. */+static void buildCells( void )+{+ std::vector<Int> candidates;+ GetRandomPoolCandidates( candidates );++ GameWindow *listBox = GadgetComboBoxGetListBox( s_combo );+ GameFont *smallFont = UIStyle::font( UIStyle::TEXT_SMALL );+ for( Int line = 0; line < GadgetComboBoxGetLength( s_combo ); line++ )+ {+ const Int pick = (Int)(intptr_t)GadgetComboBoxGetItemData( s_combo, line );+ if( IsRandomPlayerTemplate( pick ) )+ continue;++ PickerCell cell;+ cell.pick = pick;+ cell.poolBit = -1;+ cell.name = GadgetListBoxGetText( listBox, line, 0 );+ cell.icon = NULL;+ cell.portrait = NULL;+ cell.label = NULL;++ AsciiString side = "Observer";+ Int mod = -1;+ if( pick == PLAYERTEMPLATE_OBSERVER )+ {+ cell.icon = cell.portrait = TheMappedImageCollection->findImageByName( "GameinfoOBSRVR" );+ }+ else+ {+ const PlayerTemplate *pt = ThePlayerTemplateStore->getNthPlayerTemplate( pick );+ side = pt->getSide();+ mod = pt->getModIndex();+ for( size_t n = 0; n < candidates.size() && n < RANDOM_POOL_BITS; n++ )+ {+ if( candidates[ n ] == pick )+ cell.poolBit = (Int)n;+ }+ // a retail general has the challenge screen's pictures of him; a side has its logo, unless a+ // picture is mapped for this screen alone (Turkiye borrows America's logo everywhere else)+ const GeneralPersona *persona = TheChallengeGenerals->getGeneralByTemplateName( pt->getName() );+ AsciiString ownImage( PICKER_IMAGE_PREFIX );+ ownImage.concat( pt->getName() );+ const Image *own = TheMappedImageCollection->findImageByName( ownImage );+ const Image *logo = own ? own : ( pt->getGeneralImage() ? pt->getGeneralImage() : pt->getSideIconImage() );+ cell.icon = persona && persona->getBioPortraitSmall() ? persona->getBioPortraitSmall() : logo;+ cell.portrait = persona && persona->getBioPortraitLarge() ? persona->getBioPortraitLarge() : logo;+ if( !pt->getTooltip().isEmpty() )+ cell.strategy = TheGameText->fetch( pt->getTooltip() );+ if( !pt->getGeneralFeatures().isEmpty() )+ cell.features = TheGameText->fetch( pt->getGeneralFeatures() );+ if( pt->isRandomExcluded() )+ {+ if( !s_leftOut.isEmpty() )+ s_leftOut.concat( u", " );+ s_leftOut.concat( cell.name );+ }+ }+ if( !cell.icon )+ {+ cell.label = newText( cell.name, smallFont );+ cell.label->setWordWrapCentered( TRUE );+ }++ size_t group = 0;+ for( ; group < s_groups.size(); group++ )+ {+ if( s_groups[ group ].mod == mod && side.startsWith( s_groups[ group ].leadSide ) )+ break;+ }+ if( group == s_groups.size() )+ {+ PickerGroup lead;+ lead.leadSide = side;+ lead.mod = mod;+ lead.heading = newText( cell.name, UIStyle::font( UIStyle::TEXT_HEADING ) );+ s_groups.push_back( lead );+ }+ s_groups[ group ].cells.push_back( (Int)s_cells.size() );+ s_cells.push_back( cell );+ }+}++/** Places everything; the cells shrink until every group fits above the button row. */+static void layout( void )+{+ s_panelBox = boardBox( UIStyle::ROOM_PANEL_LEFT, UIStyle::ROOM_PANEL_TOP, UIStyle::ROOM_PANEL_RIGHT, UIStyle::ROOM_PANEL_BOTTOM );+ const Real tabWidth = ( GRID_RIGHT - LEFT - TAB_GAP ) / 2;+ s_tabBox[ 0 ] = boardBox( LEFT, TOP, LEFT + tabWidth, TOP + TAB_HEIGHT );+ s_tabBox[ 1 ] = boardBox( GRID_RIGHT - tabWidth, TOP, GRID_RIGHT, TOP + TAB_HEIGHT );++ Real cell = CELL;+ Int columns = 1;+ for( ;; )+ {+ columns = max( 1, (Int)( ( GRID_RIGHT - LEFT + CELL_GAP ) / ( cell + CELL_GAP ) ) );+ Real height = 0;+ for( size_t group = 0; group < s_groups.size(); group++ )+ {+ const Int rows = ( (Int)s_groups[ group ].cells.size() + columns - 1 ) / columns;+ height += HEADING_HEIGHT + rows * ( cell + CELL_GAP ) + GROUP_GAP;+ }+ if( height <= GRID_BOTTOM - GRID_TOP || cell <= 40.0f )+ break;+ cell -= 8.0f;+ }++ Real y = GRID_TOP;+ for( size_t group = 0; group < s_groups.size(); group++ )+ {+ PickerGroup &g = s_groups[ group ];+ g.at.x = UIStyle::boardX( LEFT );+ g.at.y = UIStyle::boardY( y );+ y += HEADING_HEIGHT;+ for( size_t each = 0; each < g.cells.size(); each++ )+ {+ const Real x = LEFT + ( each % columns ) * ( cell + CELL_GAP );+ const Real top = y + ( each / columns ) * ( cell + CELL_GAP );+ PickerCell &c = s_cells[ g.cells[ each ] ];+ c.box = boardBox( x, top, x + cell, top + cell );+ if( c.label )+ c.label->setWordWrap( boxWidth( c.box ) - UIStyle::px( 8 ) );+ }+ y += ( ( (Int)g.cells.size() + columns - 1 ) / columns ) * ( cell + CELL_GAP ) + GROUP_GAP;+ }++ s_portraitBox = boardBox( DETAIL_LEFT, TOP, RIGHT, PORTRAIT_BOTTOM );+ s_bannerBox = boardBox( DETAIL_LEFT, PORTRAIT_BOTTOM + 8.0f, RIGHT, BANNER_BOTTOM );+ s_descriptionBox = boardBox( DETAIL_LEFT, DESCRIPTION_TOP, RIGHT, GRID_BOTTOM );+ s_backBox = boardBox( LEFT, UIStyle::ROOM_BUTTON_TOP, LEFT + UIStyle::ROOM_BUTTON_WIDTH, UIStyle::ROOM_BUTTON_BOTTOM );+ s_confirmBox = boardBox( RIGHT - UIStyle::ROOM_WIDE_BUTTON_WIDTH, UIStyle::ROOM_BUTTON_TOP, RIGHT, UIStyle::ROOM_BUTTON_BOTTOM );+}++/** The name, the description and the Confirm label follow the focus. */+static void refresh( void )+{+ UnicodeString name, strategy, features;+ if( s_focus >= 0 )+ {+ const PickerCell &cell = s_cells[ s_focus ];+ name = cell.name;+ strategy = cell.strategy;+ features = cell.features;+ }+ else+ {+ name = TheGameText->fetch( "GUI:Random" );+ if( s_custom )+ strategy.format( TheGameText->fetch( "GUI:FactionPickPool" ), tickedCount(), tickableCount() );+ else+ {+ strategy = TheGameText->fetch( "GUI:FactionPickRandom" );+ if( !s_leftOut.isEmpty() )+ {+ UnicodeString leftOut;+ leftOut.format( TheGameText->fetch( "GUI:FactionPickLeftOut" ), s_leftOut.str() );+ strategy.concat( u' ' );+ strategy.concat( leftOut );+ }+ }+ // the armies the draw can land on+ for( size_t each = 0; each < s_cells.size(); each++ )+ {+ const PickerCell &cell = s_cells[ each ];+ if( !isDrawn( cell ) )+ continue;+ features.concat( cell.name );+ features.concat( u'\n' );+ }+ }++ s_nameText->setText( UIStyle::capitals( name ) );+ s_strategyText->setText( strategy );++ for( size_t each = 0; each < s_featureText.size(); each++ )+ freeText( s_featureText[ each ] );+ s_featureText.clear();+ std::vector<UnicodeString> lines;+ splitLines( features, lines );+ const Int columnWidth = ( boxWidth( s_descriptionBox ) - UIStyle::px( 3 * PAD ) ) / 2;+ for( size_t each = 0; each < lines.size(); each++ )+ {+ UnicodeString line( u"- " );+ line.concat( lines[ each ] );+ DisplayString *text = newText( line, UIStyle::font( UIStyle::TEXT_BODY ) );+ text->setWordWrap( columnWidth );+ s_featureText.push_back( text );+ }++ UnicodeString confirm;+ confirm.format( TheGameText->fetch( "GUI:FactionPickConfirm" ), name.str() );+ s_confirmText->setText( UIStyle::capitals( confirm ) );+}++//-------------------------------------------------------------------------------------------------+static void drawCellPicture( const PickerCell &cell, const IRegion2D &box )+{+ const Int inset = UIStyle::px( 6 );+ IRegion2D inner = box;+ inner.lo.x += inset;+ inner.lo.y += inset;+ inner.hi.x -= inset;+ inner.hi.y -= inset;+ if( cell.icon )+ drawFitted( cell.icon, inner, 100.0f );+ else+ drawCentred( cell.label, box, UIStyle::INK );+}++/** Random's preview: every army a Random can be, the ones it can land on lit and the rest dimmed. */+static void drawPoolPreview( const IRegion2D &area )+{+ std::vector<Int> shown;+ for( size_t each = 0; each < s_cells.size(); each++ )+ {+ if( s_cells[ each ].poolBit >= 0 )+ shown.push_back( (Int)each );+ }+ if( shown.empty() )+ return;++ const Int gap = UIStyle::px( CELL_GAP );+ const Int count = (Int)shown.size();+ Int size = UIStyle::px( POOL_ICON );+ Int columns = 1;+ Int rows = 1;+ for( ;; )+ {+ columns = max( 1, ( boxWidth( area ) + gap ) / ( size + gap ) );+ rows = ( count + columns - 1 ) / columns;+ if( rows * ( size + gap ) - gap <= boxHeight( area ) || size <= gap )+ break;+ size -= gap;+ }+ columns = min( columns, count );+ const Int left = area.lo.x + ( boxWidth( area ) - ( columns * ( size + gap ) - gap ) ) / 2;+ const Int top = area.lo.y + ( boxHeight( area ) - ( rows * ( size + gap ) - gap ) ) / 2;+ for( Int n = 0; n < count; n++ )+ {+ const PickerCell &cell = s_cells[ shown[ n ] ];+ // a short last row sits centred under the full ones+ const Int inRow = min( columns, count - ( n / columns ) * columns );+ const Int rowShift = ( columns - inRow ) * ( size + gap ) / 2;+ IRegion2D box;+ box.lo.x = left + rowShift + ( n % columns ) * ( size + gap );+ box.lo.y = top + ( n / columns ) * ( size + gap );+ box.hi.x = box.lo.x + size;+ box.hi.y = box.lo.y + size;+ UIStyle::panel( box.lo.x, box.lo.y, size, size, UIStyle::CARD );+ drawCellPicture( cell, box );+ if( !isDrawn( cell ) )+ TheDisplay->drawFillRect( box.lo.x, box.lo.y, size, size, UIStyle::withAlpha( UIStyle::GROUND, POOL_DIM_ALPHA ) );+ }+}++static void drawPicker( GameWindow *window, WinInstanceData *instData )+{+ // the room stays up underneath for its updates, so the screen paints over every pixel of it+ UIStyle::shell();+ UIStyle::panel( s_panelBox.lo.x, s_panelBox.lo.y, boxWidth( s_panelBox ), boxHeight( s_panelBox ), UIStyle::PANEL );++ Int width, height;+ s_title->getSize( &width, &height );+ s_title->draw( UIStyle::boardX( UIStyle::ROOM_TITLE_LEFT ), UIStyle::boardY( UIStyle::ROOM_TITLE_MIDDLE ) - height / 2, UIStyle::INK, UIStyle::SHADOW );+ UIStyle::rule( s_panelBox.lo.x, UIStyle::boardY( UIStyle::ROOM_HEADER_LINE ), boxWidth( s_panelBox ) );++ const Bool tabOn[ 2 ] = { s_focus < 0 && !s_custom, s_custom };+ for( Int tab = 0; tab < 2; tab++ )+ {+ const IRegion2D &box = s_tabBox[ tab ];+ UIStyle::tab( box.lo.x, box.lo.y, boxWidth( box ), boxHeight( box ) );+ drawCentred( s_tabText[ tab ], box, tabOn[ tab ] ? UIStyle::ACTIVE : UIStyle::INK );+ }++ const ICoord2D mouse = TheMouse->getMouseStatus()->pos;+ for( size_t group = 0; group < s_groups.size(); group++ )+ s_groups[ group ].heading->draw( s_groups[ group ].at.x, s_groups[ group ].at.y, UIStyle::ACTIVE, UIStyle::SHADOW );+ for( size_t each = 0; each < s_cells.size(); each++ )+ {+ const PickerCell &cell = s_cells[ each ];+ const IRegion2D &box = cell.box;+ UIStyle::panel( box.lo.x, box.lo.y, boxWidth( box ), boxHeight( box ), UIStyle::CARD );+ drawCellPicture( cell, box );+ const Int inset = UIStyle::px( 6 );++ if( s_custom )+ {+ // out of the pool reads as greyed; an army that cannot go in a pool has no box to tick+ if( !isTicked( cell ) )+ TheDisplay->drawFillRect( box.lo.x, box.lo.y, boxWidth( box ), boxHeight( box ), UIStyle::withAlpha( UIStyle::GROUND, 150 ) );+ if( cell.poolBit >= 0 )+ {+ const Int size = UIStyle::px( 26 );+ const Int x = box.hi.x - size - inset;+ const Int y = box.lo.y + inset;+ UIStyle::panel( x, y, size, size, isTicked( cell ) ? UIStyle::ACTIVE : UIStyle::CARD );+ if( isTicked( cell ) )+ {+ const Real line = (Real)max( 2, UIStyle::px( 3 ) );+ TheDisplay->drawLine( x + size / 5, y + size / 2, x + size * 2 / 5, y + size * 3 / 4, line, UIStyle::GROUND );+ TheDisplay->drawLine( x + size * 2 / 5, y + size * 3 / 4, x + size * 4 / 5, y + size / 4, line, UIStyle::GROUND );+ }+ }+ }+ if( (Int)each == s_focus )+ UIStyle::edge( box.lo.x, box.lo.y, boxWidth( box ), boxHeight( box ) );+ else if( isInside( box, mouse.x, mouse.y ) )+ TheDisplay->drawOpenRect( box.lo.x, box.lo.y, boxWidth( box ), boxHeight( box ), 1.0f, UIStyle::EDGE_LIT );+ }++ UIStyle::panel( s_portraitBox.lo.x, s_portraitBox.lo.y, boxWidth( s_portraitBox ), boxHeight( s_portraitBox ), UIStyle::CARD );+ IRegion2D portraitInner = s_portraitBox;+ const Int portraitInset = UIStyle::px( PAD );+ portraitInner.lo.x += portraitInset;+ portraitInner.lo.y += portraitInset;+ portraitInner.hi.x -= portraitInset;+ portraitInner.hi.y -= portraitInset;+ if( s_focus < 0 )+ drawPoolPreview( portraitInner );+ else if( s_cells[ s_focus ].portrait )+ drawFitted( s_cells[ s_focus ].portrait, portraitInner, MAX_PORTRAIT_SCALE );+ else+ drawCentred( s_randomMark, s_portraitBox, UIStyle::MUTED );++ UIStyle::panel( s_bannerBox.lo.x, s_bannerBox.lo.y, boxWidth( s_bannerBox ), boxHeight( s_bannerBox ), UIStyle::CARD );+ UIStyle::stripe( s_bannerBox.lo.x, s_bannerBox.lo.y, boxHeight( s_bannerBox ), UIStyle::GOLD );+ drawCentred( s_nameText, s_bannerBox, UIStyle::INK );++ const IRegion2D &d = s_descriptionBox;+ UIStyle::panel( d.lo.x, d.lo.y, boxWidth( d ), boxHeight( d ), UIStyle::CARD );+ const Int pad = UIStyle::px( PAD );+ s_strategyText->draw( d.lo.x + pad, d.lo.y + pad, UIStyle::INK, UIStyle::SHADOW );+ s_strategyText->getSize( &width, &height );+ const Int featuresTop = d.lo.y + pad + ( height > 0 ? height + pad : 0 );+ const Int perColumn = ( (Int)s_featureText.size() + 1 ) / 2;+ Int y = featuresTop;+ for( size_t each = 0; each < s_featureText.size(); each++ )+ {+ if( (Int)each == perColumn )+ y = featuresTop;+ const Int x = d.lo.x + pad + ( (Int)each < perColumn ? 0 : ( boxWidth( d ) - pad ) / 2 );+ s_featureText[ each ]->draw( x, y, UIStyle::MUTED, UIStyle::SHADOW );+ s_featureText[ each ]->getSize( &width, &height );+ y += height;+ }++ UIStyle::button( s_backBox.lo.x, s_backBox.lo.y, boxWidth( s_backBox ), boxHeight( s_backBox ) );+ drawCentred( s_backText, s_backBox, UIStyle::INK );+ UIStyle::button( s_confirmBox.lo.x, s_confirmBox.lo.y, boxWidth( s_confirmBox ), boxHeight( s_confirmBox ) );+ drawCentred( s_confirmText, s_confirmBox, canConfirm() ? UIStyle::INK : UIStyle::MUTED );+}++//-------------------------------------------------------------------------------------------------+static void closePicker( Bool restoreFocus )+{+ s_window->winHide( TRUE );+ TheWindowManager->winUnsetModal( s_window );+ TheWindowManager->winDestroy( s_window );+ s_window = NULL;+ if( restoreFocus )+ TheWindowManager->winSetFocus( s_oldFocus );+ s_oldFocus = NULL;++ for( size_t each = 0; each < s_cells.size(); each++ )+ freeText( s_cells[ each ].label );+ for( size_t group = 0; group < s_groups.size(); group++ )+ freeText( s_groups[ group ].heading );+ for( size_t each = 0; each < s_featureText.size(); each++ )+ freeText( s_featureText[ each ] );+ s_cells.clear();+ s_groups.clear();+ s_featureText.clear();+ freeText( s_title );+ freeText( s_tabText[ 0 ] );+ freeText( s_tabText[ 1 ] );+ freeText( s_backText );+ freeText( s_confirmText );+ freeText( s_nameText );+ freeText( s_strategyText );+ freeText( s_randomMark );+ s_leftOut.clear();+}++/** The pick goes in through the box: its line selected and the room told, as a pick from its list+ * was. A Random rides on the box's Random line, whose item data carries the pool. */+static void confirm( void )+{+ if( !canConfirm() )+ return;+ const Int pick = s_focus >= 0 ? s_cells[ s_focus ].pick : ( s_custom ? EncodeRandomPool( s_mask & listedMask() ) : (Int)PLAYERTEMPLATE_RANDOM );+ GameWindow *combo = s_combo;+ closePicker( TRUE );++ // the host may have taken the seat away while the screen was up+ if( !BitTest( combo->winGetStatus(), WIN_STATUS_ENABLED ) )+ return;+ for( Int line = 0; line < GadgetComboBoxGetLength( combo ); line++ )+ {+ const Int data = (Int)(intptr_t)GadgetComboBoxGetItemData( combo, line );+ if( data != pick && !( IsRandomPlayerTemplate( pick ) && IsRandomPlayerTemplate( data ) ) )+ continue;+ GadgetComboBoxSetItemData( combo, line, (void *)(intptr_t)pick );+ GadgetComboBoxSetSelectedPos( combo, line, TRUE );+ // the list only reports a change of line, and Random to a Random pool is none+ TheWindowManager->winSendSystemMsg( combo->winGetOwner(), GCM_SELECTED, (WindowMsgData)combo, 0 );+ return;+ }+}++static void pressAt( Int x, Int y )+{+ if( isInside( s_backBox, x, y ) )+ {+ click();+ closePicker( TRUE );+ return;+ }+ if( isInside( s_confirmBox, x, y ) )+ {+ click();+ confirm();+ return;+ }+ if( isInside( s_tabBox[ 0 ], x, y ) )+ {+ click();+ s_custom = FALSE;+ s_focus = -1;+ refresh();+ return;+ }+ if( isInside( s_tabBox[ 1 ], x, y ) )+ {+ click();+ s_custom = !s_custom;+ s_focus = -1;+ refresh();+ return;+ }+ const Int each = cellAt( x, y );+ if( each < 0 )+ return;+ click();+ if( s_custom && s_cells[ each ].poolBit >= 0 )+ s_mask ^= 1u << s_cells[ each ].poolBit;+ else+ {+ s_custom = FALSE;+ s_focus = each;+ }+ refresh();+}++/** The window manager hands the second press of a double click on as a plain press, so the pair is+ * timed here, on the release: a confirm on the press would leave its release to the room. */+static void releaseAt( Int x, Int y )+{+ const Int cell = cellAt( x, y );+ const UnsignedInt now = Clock_Milliseconds();+ const Bool second = cell >= 0 && cell == s_lastPressCell && now - s_lastPressTime <= TheGlobalData->m_doubleClickTimeMS;+ s_lastPressCell = second ? -1 : cell;+ s_lastPressTime = now;+ if( second && !s_custom )+ {+ s_focus = cell;+ confirm();+ return;+ }+ pressAt( x, y );+}++static WindowMsgHandledType pickerInput( GameWindow *window, UnsignedInt msg, WindowMsgData mData1, WindowMsgData mData2 )+{+ const Int x = (Int)( mData1 & 0xFFFF );+ const Int y = (Int)( ( mData1 >> 16 ) & 0xFFFF );+ switch( msg )+ {+ case GWM_CHAR:+ if( BitTest( mData2, KEY_STATE_UP ) )+ {+ if( mData1 == KEY_ESC )+ closePicker( TRUE );+ else if( mData1 == KEY_ENTER || mData1 == KEY_KPENTER )+ confirm();+ }+ break;+ case GWM_LEFT_UP:+ releaseAt( x, y );+ break;+ }+ // nothing under the screen sees the mouse or the keys while it is up+ return MSG_HANDLED;+}++static WindowMsgHandledType pickerSystem( GameWindow *window, UnsignedInt msg, WindowMsgData mData1, WindowMsgData mData2 )+{+ if( msg == GWM_INPUT_FOCUS )+ {+ if( mData1 == TRUE )+ *(Bool *)mData2 = TRUE;+ return MSG_HANDLED;+ }+ return GameWinDefaultSystem( window, msg, mData1, mData2 );+}++static void openPicker( GameWindow *combo )+{+ if( s_window )+ return;+ s_combo = combo;+ buildCells();++ // the box's Random line remembers the seat's last pool, so a seat on an army keeps it too+ Int current = PLAYERTEMPLATE_RANDOM;+ Int line = 0;+ GadgetComboBoxGetSelectedPos( combo, &line );+ if( line >= 0 )+ current = (Int)(intptr_t)GadgetComboBoxGetItemData( combo, line );+ Int random = PLAYERTEMPLATE_RANDOM;+ for( Int each = 0; each < GadgetComboBoxGetLength( combo ); each++ )+ {+ const Int data = (Int)(intptr_t)GadgetComboBoxGetItemData( combo, each );+ if( IsRandomPlayerTemplate( data ) )+ random = data;+ }+ s_mask = DecodeRandomPool( random );+ s_custom = current < PLAYERTEMPLATE_RANDOM_POOL;+ s_focus = -1;+ s_lastPressCell = -1;+ for( size_t each = 0; each < s_cells.size(); each++ )+ {+ if( s_cells[ each ].pick == current )+ s_focus = (Int)each;+ }++ s_title = newText( UIStyle::capitals( TheGameText->fetch( "GUI:FactionPickTitle" ) ), UIStyle::titleFont( UIStyle::TEXT_TITLE ) );+ s_tabText[ 0 ] = newText( TheGameText->fetch( "GUI:FactionPickRandomAll" ), UIStyle::font( UIStyle::TEXT_BODY ) );+ s_tabText[ 1 ] = newText( TheGameText->fetch( "GUI:FactionPickCustom" ), UIStyle::font( UIStyle::TEXT_BODY ) );+ s_backText = newText( UIStyle::capitals( TheGameText->fetch( "GUI:Back" ) ), UIStyle::titleFont( UIStyle::TEXT_HEADING ) );+ s_confirmText = newText( UnicodeString::TheEmptyString, UIStyle::titleFont( UIStyle::TEXT_HEADING ) );+ s_nameText = newText( UnicodeString::TheEmptyString, UIStyle::titleFont( UIStyle::TEXT_TITLE ) );+ s_strategyText = newText( UnicodeString::TheEmptyString, UIStyle::font( UIStyle::TEXT_STRONG ) );+ s_randomMark = newText( UnicodeString( u"?" ), UIStyle::titleFont( UIStyle::TEXT_DISPLAY ) );+ layout();+ s_strategyText->setWordWrap( boxWidth( s_descriptionBox ) - UIStyle::px( 2 * PAD ) );+ refresh();++ s_window = TheWindowManager->winCreate( NULL, WIN_STATUS_ENABLED | WIN_STATUS_ABOVE, 0, 0,+ TheDisplay->getWidth(), TheDisplay->getHeight(), pickerSystem );+ s_window->winSetDrawFunc( drawPicker );+ s_window->winSetInputFunc( pickerInput );+ s_oldFocus = TheWindowManager->winGetFocus();+ TheWindowManager->winSetModal( s_window );+ TheWindowManager->winSetFocus( s_window );+}++//-------------------------------------------------------------------------------------------------+// the seat's box: a click on it or on its arrow opens the screen instead of the list+static WindowMsgHandledType comboInput( GameWindow *window, UnsignedInt msg, WindowMsgData mData1, WindowMsgData mData2 )+{+ if( msg == GWM_LEFT_UP )+ {+ click();+ openPicker( window );+ return MSG_HANDLED;+ }+ return GadgetComboBoxInput( window, msg, mData1, mData2 );+}++static WindowMsgHandledType comboSystem( GameWindow *window, UnsignedInt msg, WindowMsgData mData1, WindowMsgData mData2 )+{+ if( msg == GBM_SELECTED && (GameWindow *)mData1 == GadgetComboBoxGetDropDownButton( window ) )+ {+ openPicker( window );+ return MSG_HANDLED;+ }+ return GadgetComboBoxSystem( window, msg, mData1, mData2 );+}++void FactionPickerAttach( GameWindow *parent, const char *layoutFilename )+{+ GameWindow *first = NULL;+ for( Int i = 0; i < MAX_SLOTS; ++i )+ {+ AsciiString name;+ name.format( "%s:ComboBoxPlayerTemplate%d", layoutFilename, i );+ GameWindow *combo = TheWindowManager->winGetWindowFromId( parent, NAMEKEY( name ) );+ if( !combo )+ continue; // a mod's layout with fewer seats+ combo->winSetInputFunc( comboInput );+ combo->winSetSystemFunc( comboSystem );+ if( !first )+ first = combo;+ }+ if( s_openOnStart && first )+ {+ s_openOnStart = FALSE;+ openPicker( first );+ if( s_openOnStartCustom )+ {+ s_custom = TRUE;+ s_focus = -1;+ refresh();+ }+ }+}++void FactionPickerDetach( void )+{+ if( s_window )+ closePicker( FALSE );+ s_combo = NULL;+}++void FactionPickerSyncRandom( GameWindow *combo, Int pick )+{+ if( !IsRandomPlayerTemplate( pick ) )+ return;+ for( Int line = 0; line < GadgetComboBoxGetLength( combo ); line++ )+ {+ if( IsRandomPlayerTemplate( (Int)(intptr_t)GadgetComboBoxGetItemData( combo, line ) ) )+ {+ GadgetComboBoxSetItemData( combo, line, (void *)(intptr_t)pick );+ return;+ }+ }+}++void FactionPickerOpenOnStart( Bool custom )+{+ s_openOnStart = TRUE;+ s_openOnStartCustom = custom;+}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cppindex 2195a5aa7..99df2c951 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp@@ -540,6 +540,12 @@ static void handlePlayerTemplateSelection(int index)Int oldTemplate = slot->getPlayerTemplate();slot->setPlayerTemplate(playerTemplate);+ // the host's own pick, or his AI's, gets the budget check a request gets in LANAPI::OnGameOptions+ if (myGame->amIHost() && GameInfoToAsciiString(myGame).isEmpty())+ {+ playerTemplate = PLAYERTEMPLATE_RANDOM;+ slot->setPlayerTemplate(playerTemplate);+ }if (oldTemplate == PLAYERTEMPLATE_OBSERVER){diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cppindex 1e9ef5b17..862c0ac33 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp@@ -132,8 +132,8 @@ Int LANPreferences::getPreferredFaction(void)return PLAYERTEMPLATE_RANDOM;}- ret = atoi(it->second.str());- if (ret == PLAYERTEMPLATE_OBSERVER || ret < PLAYERTEMPLATE_MIN || ret >= ThePlayerTemplateStore->getPlayerTemplateCount())+ ret = PlayerTemplateFromPreference(it->second);+ if (ret == PLAYERTEMPLATE_OBSERVER || !IsValidPlayerTemplatePick(ret))ret = PLAYERTEMPLATE_RANDOM;if (ret >= 0)diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cppindex d677a93df..db1ba0066 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp@@ -1725,7 +1725,7 @@ void populatePlayerInfo( Player *player, Int pos)if (disCons >= 0)stats.discons[ptIdx] = disCons;- stats.gamesAsRandom += (localSlot->getOriginalPlayerTemplate() == PLAYERTEMPLATE_RANDOM);+ stats.gamesAsRandom += IsRandomPlayerTemplate(localSlot->getOriginalPlayerTemplate());if (stats.lastGeneral != ptIdx)stats.gamesInRowWithLastGeneral = 0;diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreenGraphs.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreenGraphs.cppindex 517d8fabb..629221255 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreenGraphs.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreenGraphs.cpp@@ -1047,7 +1047,7 @@ void ScoreScreenGraphsInit( GameWindow *backdrop )mapName = map->m_displayName;elsemapName.translate( TheGameState->getMapLeafName( TheGlobalData->m_mapName ) );- s_title = newText( UIStyle::capitals( mapName ), UIStyle::titleFont( UIStyle::TEXT_TITLE ) );+ s_title = newText( UIStyle::nameCapitals( mapName ), UIStyle::titleFont( UIStyle::TEXT_TITLE ) );GameFont *wordmarkFont = UIStyle::font( UIStyle::TEXT_STRONG, TRUE );s_wordmark[ 0 ] = newText( UnicodeString( u"Zero Hour" ), wordmarkFont );s_wordmark[ 1 ] = newText( UnicodeString( u" Reforged" ), wordmarkFont );diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cppindex 7041d0668..289e8fa33 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp@@ -310,8 +310,8 @@ Int SkirmishPreferences::getPreferredFaction(void)return PLAYERTEMPLATE_RANDOM;}- ret = atoi(it->second.str());- if (ret < PLAYERTEMPLATE_MIN || ret >= ThePlayerTemplateStore->getPlayerTemplateCount())+ ret = PlayerTemplateFromPreference(it->second);+ if (!IsValidPlayerTemplatePick(ret))ret = PLAYERTEMPLATE_RANDOM;if (ret >= 0)@@ -415,8 +415,7 @@ Bool SkirmishPreferences::write(void)tmp.format("%d", TheSkirmishGameInfo->getConstSlot(0)->getColor());(*this)["Color"] = tmp;- tmp.format("%d", TheSkirmishGameInfo->getConstSlot(0)->getPlayerTemplate());- (*this)["PlayerTemplate"] = tmp;+ (*this)["PlayerTemplate"] = PlayerTemplatePreference(TheSkirmishGameInfo->getConstSlot(0)->getPlayerTemplate());(*this)["Map"] = TheSkirmishGameInfo->getMap();@@ -988,12 +987,12 @@ void updateMapStartSpots( GameInfo *myGame, GameWindow *buttonMapStartPositions[// a taken spot is filled with its team's colour, or the player's without a team; the number// stays for whoever cannot tell the colours apartconst Int spot = onLoadScreen ? gs->getApparentStartPos() : gs->getStartPos();- if (spot >= 0 && spot < mmd.m_numPlayers && gs->getPlayerTemplate() > PLAYERTEMPLATE_MIN)+ if (spot >= 0 && spot < mmd.m_numPlayers && gs->getPlayerTemplate() != PLAYERTEMPLATE_OBSERVER)startSpotFill(buttonMapStartPositions[spot])->fill =gs->getTeamNumber() >= 0 ? LobbyTeamColor(gs->getTeamNumber()) : LobbySeatColor(gs);if(onLoadScreen){- if(gs->getApparentStartPos() >=0 && gs->getApparentStartPos() < mmd.m_numPlayers && gs->getPlayerTemplate() > PLAYERTEMPLATE_MIN )+ if(gs->getApparentStartPos() >=0 && gs->getApparentStartPos() < mmd.m_numPlayers && gs->getPlayerTemplate() != PLAYERTEMPLATE_OBSERVER ){AsciiString displayNumber;displayNumber.format("NUMBER:%d",i + 1);@@ -1002,7 +1001,7 @@ void updateMapStartSpots( GameInfo *myGame, GameWindow *buttonMapStartPositions[}else{- if(gs->getStartPos() >=0 && gs->getStartPos() < mmd.m_numPlayers && gs->getPlayerTemplate() > PLAYERTEMPLATE_MIN )+ if(gs->getStartPos() >=0 && gs->getStartPos() < mmd.m_numPlayers && gs->getPlayerTemplate() != PLAYERTEMPLATE_OBSERVER ){AsciiString displayNumber;displayNumber.format("NUMBER:%d",i + 1);diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cppindex f19e6bee6..4077e7157 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp@@ -2582,7 +2582,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData)}else if (key == "PlayerTemplate"){- if (val >= PLAYERTEMPLATE_MIN && val < ThePlayerTemplateStore->getPlayerTemplateCount() && val != slot->getPlayerTemplate())+ if (IsValidPlayerTemplatePick(val) && val != slot->getPlayerTemplate()){// Validate for LimitArmies checkboxif ( game->oldFactionsOnly() )diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cppindex 887147655..bfed9aafe 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp@@ -1747,17 +1747,16 @@ WindowMsgHandledType WOLQuickMatchMenuSystem( GameWindow *window, UnsignedInt ms{// If not a forced random ladder, then we need to resolve our pick of random right now anyway, or else// we will get the same pick every darn time.- Int randomTries = 0;// Rare to hit Random 10 times in a row, but if it does then random will be converted to a set side by the very bug this tries to fix, so no harm done.-- while( randomTries < 10 && index == PLAYERTEMPLATE_RANDOM )+ // from the listed factions a plain Random may land on, as populateRandomSideAndColor draws+ std::vector<Int> sides;+ for( Int entry = 0; entry < GadgetComboBoxGetLength(comboBoxSide); ++entry ){- Int numberComboBoxEntries = GadgetComboBoxGetLength(comboBoxSide);- Int randomPick = GameClientRandomValue(0, numberComboBoxEntries - 1);- index = (Int)(intptr_t)GadgetComboBoxGetItemData( comboBoxSide, randomPick );- req.QM.side = index;-- randomTries++;+ const Int side = (Int)(intptr_t)GadgetComboBoxGetItemData( comboBoxSide, entry );+ if( side >= 0 && !ThePlayerTemplateStore->getNthPlayerTemplate(side)->isRandomExcluded() )+ sides.push_back( side );}+ if( !sides.empty() )+ req.QM.side = sides[ GameClientRandomValue(0, (Int)sides.size() - 1) ];}index = -1;diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cppindex 655d14952..af5fd4675 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp@@ -264,7 +264,7 @@ public:private:static void drawWindow( GameWindow *window, WinInstanceData *instData );- void prepare( const UnicodeString &title, const UnicodeString &subtitle );+ void prepare( const UnicodeString &titleInCapitals, const UnicodeString &subtitle );GameWindow *makeWindow( GameWindow *parent );void draw( void );void drawMatch( void );@@ -548,7 +548,7 @@ GameWindow *LoadScreenBoard::create( GameInfo *game, const char *modeLabel, Boolcash.format( u"$%u", game->getStartingCash().countMoney() );subtitle.concat( BOARD_SEPARATOR );subtitle.concat( cash );- prepare( mapName, subtitle );+ prepare( UIStyle::nameCapitals( mapName ), subtitle );// the cards: two columns with the map between, as tall as four cards a side allowm_unknown = text( UnicodeString( u"?" ), centerFont );@@ -675,11 +675,11 @@ GameWindow *LoadScreenBoard::create( GameInfo *game, const char *modeLabel, Bool}/** The header's and the foot's words, the same on every board. */-void LoadScreenBoard::prepare( const UnicodeString &title, const UnicodeString &subtitle )+void LoadScreenBoard::prepare( const UnicodeString &titleInCapitals, const UnicodeString &subtitle ){GameFont *wordmarkFont = UIStyle::font( UIStyle::TEXT_STRONG, TRUE );GameFont *tipFont = UIStyle::font( UIStyle::TEXT_BODY );- m_title = text( UIStyle::capitals( title ), UIStyle::titleFont( UIStyle::TEXT_TITLE ) );+ m_title = text( titleInCapitals, UIStyle::titleFont( UIStyle::TEXT_TITLE ) );m_subtitle = text( subtitle, tipFont );m_wordmark[ 0 ] = text( UnicodeString( u"Zero Hour" ), wordmarkFont );m_wordmark[ 1 ] = text( UnicodeString( u" Reforged" ), wordmarkFont );@@ -710,7 +710,7 @@ GameWindow *LoadScreenBoard::createMission( GameWindow *parent, const UnicodeStrconst UnicodeString *briefing, Int briefingLines ){m_mission = TRUE;- prepare( title, subtitle );+ prepare( UIStyle::capitals( title ), subtitle );const Int pad = scaled( 28 );const Int width = scaled( BOARD_COLUMN_WIDTH );diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/UIStyle.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/UIStyle.cppindex 909b0dc2f..22ef7898c 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/UIStyle.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/UIStyle.cpp@@ -24,6 +24,7 @@#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine#include "GameClient/UIStyle.h"+#include "Common/GlobalData.h"#include "GameClient/Display.h"#include "GameClient/DisplayString.h"#include "GameClient/GameFont.h"@@ -143,14 +144,49 @@ void wordmark( DisplayString *words[ 2 ], Int right, Int y )words[ 1 ]->draw( right - second, y, WORDMARK_BLUE, SHADOW );}-UnicodeString capitals( const UnicodeString &words )+/** towupper in the C locale leaves every letter past ASCII as it is ("ORDU SEç"), so Latin-1's,+ * Latin Extended-A's and Cyrillic's case pairs are mapped here, and Turkish's two i's by the language. */+static WideChar capital( WideChar letter, Bool turkish )+{+ const WideChar DOTTED_CAPITAL_I = 0x0130;+ const WideChar DOTLESS_SMALL_I = 0x0131;+ if( letter == u'i' && turkish )+ return DOTTED_CAPITAL_I;+ if( letter == DOTLESS_SMALL_I )+ return u'I';+ if( letter >= 0x00E0 && letter <= 0x00FE && letter != 0x00F7 ) // a with grave to thorn, not the division sign+ return (WideChar)( letter - 0x20 );+ if( letter >= 0x0430 && letter <= 0x044F ) // Russian's a to ya+ return (WideChar)( letter - 0x20 );+ if( letter >= 0x0450 && letter <= 0x045F ) // ie with grave to dzhe, Ukrainian's ie, i and yi among them+ return (WideChar)( letter - 0x50 );+ // pairs that start on an even code: A with macron to K with cedilla, eng to y with circumflex (g and s+ // with breve and cedilla among them), and Cyrillic's omega to ha with descender (Ukrainian's ghe with upturn)+ const Bool evenPair = ( letter >= 0x0100 && letter <= 0x0137 ) || ( letter >= 0x014A && letter <= 0x0177 )+ || ( letter >= 0x0460 && letter <= 0x0481 ) || ( letter >= 0x048A && letter <= 0x04BF );+ if( evenPair && ( letter & 1 ) )+ return (WideChar)( letter - 1 );+ return (WideChar)WideCharToUpper( letter );+}++static UnicodeString capitalsOf( const UnicodeString &words, Bool turkish ){UnicodeString result;for( Int each = 0; each < words.getLength(); each++ )- result.concat( (WideChar)WideCharToUpper( words.getCharAt( each ) ) );+ result.concat( capital( words.getCharAt( each ), turkish ) );return result;}+UnicodeString capitals( const UnicodeString &words )+{+ return capitalsOf( words, TheGlobalData->m_textLanguage == TEXT_LANGUAGE_TURKISH );+}++UnicodeString nameCapitals( const UnicodeString &name )+{+ return capitalsOf( name, FALSE );+}+/** Blue and purple house colours are too dark for words on a panel; they are lifted part of the way* to white, while a stripe, a line or a map spot keeps the colour itself. */Color readable( Color player )diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cppindex eb851b8f3..40a1333c5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp@@ -788,31 +788,6 @@ static void populateRandomSideAndColor( GameInfo *game )return;Int i;-#define MORE_RANDOM-#ifdef MORE_RANDOM- std::vector<Int> startSlots;- for (i = 0; i < ThePlayerTemplateStore->getPlayerTemplateCount(); ++i)- {- const PlayerTemplate* ptTest = ThePlayerTemplateStore->getNthPlayerTemplate(i);- if (!ptTest || ptTest->getStartingBuilding().isEmpty())- continue;-- if ( game->oldFactionsOnly() && !ptTest->isOldFaction() )- continue;-- // Prevent from selecting the disabled Generals.- // This is also enforced at GUI setup (GUIUtil.cpp).- // @todo: unlock these when something rad happens- Bool disallowLockedGenerals = TRUE;- const GeneralPersona *general = TheChallengeGenerals->getGeneralByTemplateName(ptTest->getName());- Bool startsLocked = general ? !general->isStartingEnabled() : FALSE;- if (disallowLockedGenerals && startsLocked)- continue;-- startSlots.push_back(i);- }-#endif-for (i=0; i<MAX_SLOTS; ++i){GameSlot *slot = game->getSlot(i);@@ -820,40 +795,29 @@ static void populateRandomSideAndColor( GameInfo *game )if (!slot || !slot->isOccupied())continue;- // clean up random factions+ // clean up random factions: plain Random draws from every playable template the data does not+ // keep out (RandomExcluded), a pool from the templates the player ticked; both lists come from+ // the INI and the slot string, the same on every machineInt playerTemplateIdx = slot->getPlayerTemplate();DEBUG_LOG(("Player %d has playerTemplate index %d\n", i, playerTemplateIdx));- while (playerTemplateIdx != PLAYERTEMPLATE_OBSERVER && (playerTemplateIdx < 0 || playerTemplateIdx >= ThePlayerTemplateStore->getPlayerTemplateCount()))+ if (IsRandomPlayerTemplate(playerTemplateIdx)){- DEBUG_ASSERTCRASH(playerTemplateIdx == PLAYERTEMPLATE_RANDOM, ("Non-random bad playerTemplate %d in slot %d\n", playerTemplateIdx, i));-#ifdef MORE_RANDOM+ std::vector<Int> draw;+ GetRandomDraw(playerTemplateIdx, game->oldFactionsOnly(), draw);// our RNG is basically shit -- horribly nonrandom at the start of the sequence.// get a few values at random to get rid of the dreck.// there's no mathematical basis for this, but empirically, it helps a lot.UnsignedInt silly = GetGameLogicRandomSeed() % 7;- for (Int poo = 0; poo < silly; ++poo)+ for (Int poo = 0; poo < silly; ++poo){GameLogicRandomValue(0, 1); // ignore result}- Int idxIdx = GameLogicRandomValue(0, 1000) % startSlots.size();- playerTemplateIdx = startSlots[idxIdx];-#else- playerTemplateIdx = GameLogicRandomValue(0, ThePlayerTemplateStore->getPlayerTemplateCount()-1);-#endif- const PlayerTemplate* pt = ThePlayerTemplateStore->getNthPlayerTemplate(playerTemplateIdx);- if (!pt || pt->getStartingBuilding().isEmpty())- {-#ifdef MORE_RANDOM- DEBUG_CRASH(("should not be possible"));-#endif- playerTemplateIdx = -1; // only pick playable factions- }- else- {- DEBUG_LOG(("Setting playerTemplateIdx %d to %d\n", i, playerTemplateIdx));- slot->setPlayerTemplate(playerTemplateIdx);- }+ playerTemplateIdx = draw[GameLogicRandomValue(0, 1000) % draw.size()];+ DEBUG_LOG(("Setting playerTemplateIdx %d to %d\n", i, playerTemplateIdx));+ slot->setPlayerTemplate(playerTemplateIdx);}+ DEBUG_ASSERTCRASH(playerTemplateIdx == PLAYERTEMPLATE_OBSERVER || ThePlayerTemplateStore->getNthPlayerTemplate(playerTemplateIdx),+ ("Non-random bad playerTemplate %d in slot %d\n", playerTemplateIdx, i));Int colorIdx = slot->getColor();if (colorIdx < 0 || colorIdx >= TheMultiplayerSettings->getNumColors())diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cppindex 737ee68f6..63ecd57c3 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp@@ -53,6 +53,7 @@#include "Common/PlayerTemplate.h"#include "GameNetwork/LANAPICallbacks.h" // for acceptTrueColor, etc#include "GameClient/ChallengeGenerals.h"+#include "GameClient/FactionPicker.h"#include "Common/GlobalData.h"#include "Lib/WideCharFns.h"#include "Lib/Clock.h"@@ -1393,10 +1394,12 @@ void InitLobbySeatVisuals(GameWindow *parent, const char *layoutFilename)theSeatTeam[i]->winSetDrawFunc(drawSwatch);}theSeatsShowReady = strcmp(layoutFilename, "SkirmishGameOptionsMenu.wnd") != 0;+ FactionPickerAttach(parent, layoutFilename);}void ShutdownLobbySeatVisuals(void){+ FactionPickerDetach();for (Int i = 0; i < MAX_SLOTS; ++i)theSeatCard[i] = theSeatBar[i] = theSeatSwatch[i] = theSeatTeam[i] = NULL;}@@ -1578,6 +1581,7 @@ void UpdateSlotList( GameInfo *myGame, GameWindow *comboPlayer[],}if (comboPlayerTemplate[i] != NULL) {+ FactionPickerSyncRandom(comboPlayerTemplate[i], slot->getPlayerTemplate());max = GadgetComboBoxGetLength(comboPlayerTemplate[i]);for (idx=0; idx<max; ++idx){diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cppindex 8c40f7d2a..0c934f734 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cpp@@ -39,6 +39,7 @@#include "Common/FileSystem.h"#include "Common/GameState.h"#include "Common/RandomMapGenerator.h"+#include "GameClient/ChallengeGenerals.h"#include "GameClient/GameText.h"#include "GameClient/MapUtil.h"#include "GameLogic/AI.h"@@ -63,6 +64,151 @@GameInfo *TheGameInfo = NULL;+// Random pools ------------------------------------++static const UnsignedInt RANDOM_POOL_MASK = ( 1u << RANDOM_POOL_BITS ) - 1;++Bool IsValidPlayerTemplatePick( Int pick )+{+ if( pick < PLAYERTEMPLATE_RANDOM_POOL )+ return pick >= PLAYERTEMPLATE_RANDOM_POOL - (Int)RANDOM_POOL_MASK;+ return pick >= PLAYERTEMPLATE_MIN && pick < ThePlayerTemplateStore->getPlayerTemplateCount();+}++Int EncodeRandomPool( UnsignedInt mask )+{+ mask &= RANDOM_POOL_MASK;+ if( mask == 0 || mask == GetDefaultRandomPool() )+ return PLAYERTEMPLATE_RANDOM;+ return PLAYERTEMPLATE_RANDOM_POOL - (Int)mask;+}++UnsignedInt DecodeRandomPool( Int pick )+{+ if( pick < PLAYERTEMPLATE_RANDOM_POOL )+ return (UnsignedInt)( PLAYERTEMPLATE_RANDOM_POOL - pick );+ return GetDefaultRandomPool();+}++void GetRandomPoolCandidates( std::vector<Int> &candidates )+{+ candidates.clear();+ for( Int i = 0; i < ThePlayerTemplateStore->getPlayerTemplateCount(); ++i )+ {+ const PlayerTemplate *pt = ThePlayerTemplateStore->getNthPlayerTemplate( i );+ if( pt->getStartingBuilding().isEmpty() )+ continue;+ // the generals the shell keeps locked; PopulatePlayerTemplateComboBox leaves them out too+ const GeneralPersona *general = TheChallengeGenerals->getGeneralByTemplateName( pt->getName() );+ if( general && !general->isStartingEnabled() )+ continue;+ candidates.push_back( i );+ }+}++UnsignedInt GetDefaultRandomPool( void )+{+ std::vector<Int> candidates;+ GetRandomPoolCandidates( candidates );+ UnsignedInt mask = 0;+ for( size_t n = 0; n < candidates.size() && n < RANDOM_POOL_BITS; ++n )+ {+ if( !ThePlayerTemplateStore->getNthPlayerTemplate( candidates[ n ] )->isRandomExcluded() )+ mask |= 1u << n;+ }+ return mask;+}++void GetRandomDraw( Int pick, Bool oldFactionsOnly, std::vector<Int> &draw )+{+ std::vector<Int> candidates;+ GetRandomPoolCandidates( candidates );+ const UnsignedInt mask = pick < PLAYERTEMPLATE_RANDOM_POOL ? DecodeRandomPool( pick ) : 0;+ draw.clear();+ for( Int pass = mask ? 0 : 1; pass < 2 && draw.empty(); ++pass )+ {+ for( size_t n = 0; n < candidates.size(); ++n )+ {+ const PlayerTemplate *pt = ThePlayerTemplateStore->getNthPlayerTemplate( candidates[ n ] );+ if( oldFactionsOnly && !pt->isOldFaction() )+ continue;+ // pass 0 is the player's pool, pass 1 plain Random: every candidate the data does not exclude+ const Bool inPool = pass == 0 ? ( n < RANDOM_POOL_BITS && ( mask & ( 1u << n ) ) != 0 ) : !pt->isRandomExcluded();+ if( inPool )+ draw.push_back( candidates[ n ] );+ }+ }+}++static const char *const POOL_PREFERENCE_PREFIX = "Random:";+static const char POOL_SLOT_FIELD_PREFIX = 'P';++AsciiString PlayerTemplatePreference( Int pick )+{+ AsciiString text;+ if( pick >= PLAYERTEMPLATE_RANDOM_POOL )+ {+ text.format( "%d", pick );+ return text;+ }+ std::vector<Int> candidates;+ GetRandomPoolCandidates( candidates );+ const UnsignedInt mask = DecodeRandomPool( pick );+ text = POOL_PREFERENCE_PREFIX;+ for( size_t n = 0; n < candidates.size() && n < RANDOM_POOL_BITS; ++n )+ {+ if( ( mask & ( 1u << n ) ) == 0 )+ continue;+ if( text.getLength() > (Int)strlen( POOL_PREFERENCE_PREFIX ) )+ text.concat( ',' );+ text.concat( ThePlayerTemplateStore->getNthPlayerTemplate( candidates[ n ] )->getName() );+ }+ return text;+}++Int PlayerTemplateFromPreference( const AsciiString &text )+{+ if( !text.startsWith( POOL_PREFERENCE_PREFIX ) )+ {+ // a pool written by number came from a build before the names, and its bits may be other armies now+ const Int pick = atoi( text.str() );+ return pick < PLAYERTEMPLATE_RANDOM_POOL ? (Int)PLAYERTEMPLATE_RANDOM : pick;+ }+ std::vector<Int> candidates;+ GetRandomPoolCandidates( candidates );+ AsciiString names( text.str() + strlen( POOL_PREFERENCE_PREFIX ) );+ AsciiString name;+ UnsignedInt mask = 0;+ while( names.nextToken( &name, "," ) )+ {+ for( size_t n = 0; n < candidates.size() && n < RANDOM_POOL_BITS; ++n )+ {+ if( ThePlayerTemplateStore->getNthPlayerTemplate( candidates[ n ] )->getName() == name )+ mask |= 1u << n;+ }+ }+ return EncodeRandomPool( mask );+}++AsciiString PlayerTemplateSlotField( Int pick )+{+ AsciiString field;+ if( pick < PLAYERTEMPLATE_RANDOM_POOL )+ field.format( "%c%X", POOL_SLOT_FIELD_PREFIX, DecodeRandomPool( pick ) );+ else+ field.format( "%d", pick );+ return field;+}++Int PlayerTemplateFromSlotField( const AsciiString &field )+{+ if( field.getCharAt( 0 ) != POOL_SLOT_FIELD_PREFIX )+ return atoi( field.str() );+ const UnsignedInt mask = (UnsignedInt)strtoul( field.str() + 1, NULL, 16 );+ // a mask too wide to be a pool reads as a pick IsValidPlayerTemplatePick refuses+ return mask <= RANDOM_POOL_MASK ? PLAYERTEMPLATE_RANDOM_POOL - (Int)mask : PLAYERTEMPLATE_MIN - 1;+}+// GameSlot ----------------------------------------GameSlot::GameSlot()@@ -144,7 +290,7 @@ static Bool isSlotLocalAlly(const GameSlot *slot)UnicodeString GameSlot::getApparentPlayerTemplateDisplayName( void ) const{if (TheMultiplayerSettings && TheMultiplayerSettings->showRandomPlayerTemplate() &&- m_origPlayerTemplate == PLAYERTEMPLATE_RANDOM && !isSlotLocalAlly(this))+ IsRandomPlayerTemplate(m_origPlayerTemplate) && !isSlotLocalAlly(this)){return TheGameText->fetch("GUI:Random");}@@ -1296,11 +1442,11 @@ static AsciiString buildGameInfoAsciiString( const GameInfo *game, const AsciiStif (slot && slot->isHuman()){AsciiString tmp; //all this data goes after name- tmp.format( ",%X,%d,%c%c,%d,%d,%d,%d,%d:",+ tmp.format( ",%X,%d,%c%c,%d,%s,%d,%d,%d:",slot->getIP(), slot->getPort(),(slot->isAccepted()?'T':'F'),(slot->hasMap()?'T':'F'),- slot->getColor(), slot->getPlayerTemplate(),+ slot->getColor(), PlayerTemplateSlotField(slot->getPlayerTemplate()).str(),slot->getStartPos(), slot->getTeamNumber(),slot->getNATBehavior() );@@ -1309,8 +1455,8 @@ static AsciiString buildGameInfoAsciiString( const GameInfo *game, const AsciiStelse if (slot && slot->isAI()){// an older parser stops at the team and never sees the personality after it- str.format("C%c,%d,%d,%d,%d%s:", SlotStateToOptionsChar(slot->getState()),- slot->getColor(), slot->getPlayerTemplate(),+ str.format("C%c,%d,%s,%d,%d%s:", SlotStateToOptionsChar(slot->getState()),+ slot->getColor(), PlayerTemplateSlotField(slot->getPlayerTemplate()).str(),slot->getStartPos(), slot->getTeamNumber(),AIPersonaSlotField(slot->getAIPersonality()).str());}@@ -1612,8 +1758,8 @@ Bool ParseAsciiStringToGameInfo(GameInfo *game, AsciiString options)DEBUG_LOG(("ParseAsciiStringToGameInfo - slotValue player template is empty, quitting\n"));break;}- Int playerTemplate = atoi(slotValue.str());- if (playerTemplate < PLAYERTEMPLATE_MIN || playerTemplate >= ThePlayerTemplateStore->getPlayerTemplateCount())+ Int playerTemplate = PlayerTemplateFromSlotField(slotValue);+ if (!IsValidPlayerTemplatePick(playerTemplate)){optionsOk = false;DEBUG_LOG(("ParseAsciiStringToGameInfo - player template value is invalid, quitting\n"));@@ -1727,8 +1873,8 @@ Bool ParseAsciiStringToGameInfo(GameInfo *game, AsciiString options)DEBUG_LOG(("ParseAsciiStringToGameInfo - slotValue player template is empty, quitting\n"));break;}- Int playerTemplate = atoi(slotValue.str());- if (playerTemplate < PLAYERTEMPLATE_MIN || playerTemplate >= ThePlayerTemplateStore->getPlayerTemplateCount())+ Int playerTemplate = PlayerTemplateFromSlotField(slotValue);+ if (!IsValidPlayerTemplatePick(playerTemplate)){optionsOk = false;DEBUG_LOG(("ParseAsciiStringToGameInfo - player template value is invalid, quitting\n"));diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cppindex 418eaf579..6c8d3f824 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp@@ -52,6 +52,7 @@#include "GameClient/MessageBox.h"#include "GameClient/Mouse.h"#include "GameNetwork/GameSpyOverlay.h"+#include "GameNetwork/GameInfo.h"#include "GameClient/LanguageFilter.h"#include "GameNetwork/GameSpy/BuddyDefs.h"@@ -880,7 +881,7 @@ void playerTemplateComboBoxTooltip(GameWindow *wndComboBox, WinInstanceData *insGadgetComboBoxGetSelectedPos(wndComboBox, &index);Int templateNum = (Int)(intptr_t)GadgetComboBoxGetItemData(wndComboBox, index);UnicodeString ustringTooltip;- if (templateNum == -1)+ if (IsRandomPlayerTemplate(templateNum)){// the "Random" template is always firstustringTooltip = TheGameText->fetch("TOOLTIP:BioStrategyLong_Random");@@ -911,7 +912,7 @@ void playerTemplateListBoxTooltip(GameWindow *wndListBox, WinInstanceData *instDInt templateNum = (Int)(intptr_t)GadgetListBoxGetItemData(wndListBox, row, col);UnicodeString ustringTooltip;- if (templateNum == -1)+ if (IsRandomPlayerTemplate(templateNum)){// the "Random" template is always firstustringTooltip = TheGameText->fetch("TOOLTIP:BioStrategyLong_Random");diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cppindex 78df4ef88..d1c2c8d90 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp@@ -353,8 +353,7 @@ void LANAPI::OnGameStart( void ){LANPreferences pref;AsciiString option;- option.format("%d", m_currentGame->getLANSlot( m_currentGame->getLocalSlotNum() )->getPlayerTemplate());- pref["PlayerTemplate"] = option;+ pref["PlayerTemplate"] = PlayerTemplatePreference(m_currentGame->getLANSlot( m_currentGame->getLocalSlotNum() )->getPlayerTemplate());option.format("%d", m_currentGame->getLANSlot( m_currentGame->getLocalSlotNum() )->getColor());pref["Color"] = option;if (m_currentGame->amIHost())@@ -547,9 +546,12 @@ void LANAPI::OnGameOptions( UnsignedInt playerIP, Int playerSlot, AsciiString op}else if (key == "PlayerTemplate"){- if (val >= PLAYERTEMPLATE_MIN && val < ThePlayerTemplateStore->getPlayerTemplateCount() && val != slot->getPlayerTemplate())+ if (IsValidPlayerTemplatePick(val) && val != slot->getPlayerTemplate()){slot->setPlayerTemplate(val);+ // a pool that pushes the options string past the packet would empty it for everyone+ if (GameInfoToAsciiString(m_currentGame).isEmpty())+ slot->setPlayerTemplate(PLAYERTEMPLATE_RANDOM);if (val == PLAYERTEMPLATE_OBSERVER){slot->setColor(-1);@@ -736,8 +738,7 @@ void LANAPI::OnPlayerLeave( UnicodeString player ){LANPreferences pref;AsciiString option;- option.format("%d", m_currentGame->getLANSlot( m_currentGame->getLocalSlotNum() )->getPlayerTemplate());- pref["PlayerTemplate"] = option;+ pref["PlayerTemplate"] = PlayerTemplatePreference(m_currentGame->getLANSlot( m_currentGame->getLocalSlotNum() )->getPlayerTemplate());option.format("%d", m_currentGame->getLANSlot( m_currentGame->getLocalSlotNum() )->getColor());pref["Color"] = option;if (m_currentGame->amIHost())diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cppindex 0d42ff224..ca439274b 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp@@ -1025,6 +1025,7 @@ Vector2 Render2DSentenceClass::Build_Sentence_Not_Centered (const WideChar *text//while (text != NULL) {WideChar ch = *text++;+ bool wrapped_on_space = false;//// Determine how much horizontal space this character requires; a hotkey '&' is// dropped and its letter drawn like the rest, as in Build_Sentence_Centered@@ -1091,6 +1092,8 @@ Vector2 Render2DSentenceClass::Build_Sentence_Not_Centered (const WideChar *textCursor.X = 0;Cursor.Y += char_height;calcHotKeyX = true;+ // the space that broke the line is dropped, or the next line starts one space in+ wrapped_on_space = true;}}@@ -1122,10 +1125,10 @@ Vector2 Render2DSentenceClass::Build_Sentence_Not_Centered (const WideChar *text}}- if (ch != u'\n' ) {+ if (ch != u'\n' && !wrapped_on_space) {//- // Ensure the surface is locked+ // Ensure the surface is locked//if (!justCalcExtents){diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 10633c90f..bff497cce 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -49,6 +49,11 @@#include "GameLogic/CRCSnapshotRing.h"#include "GameNetwork/GameDataMatch.h"#include "GameNetwork/GameInfo.h"+#include "Common/PlayerTemplate.h"+#include "GameClient/ChallengeGenerals.h"+#include "GameClient/UIStyle.h"+#include <fstream>+#include <sstream>#include "GameNetwork/FrameResendPolicy.h"#include "GameLogic/FPUControl.h"#include "GameNetwork/StallJudgement.h"@@ -7325,6 +7330,155 @@ TEST(gameslot_restores_the_pre_randomization_setup_on_a_restart)CHECK_EQ( fixed.getOriginalColor(), -1 );}+/* A front-end title is set in capitals, and towupper in the C locale stops at ASCII: the army+ screen's Turkish title came out "ORDU SEç". Turkish's i takes its dot along only in Turkish. */+TEST(capitals_reach_turkish_and_cyrillic_letters)+{+ GlobalData *saved = TheWritableGlobalData;+ TheWritableGlobalData = NEW GlobalData;+ const UnicodeString words( u"ordu seç, şiğ öü ı зіґ" );+ TheWritableGlobalData->m_textLanguage = TEXT_LANGUAGE_TURKISH;+ CHECK( UIStyle::capitals( words ) == UnicodeString( u"ORDU SEÇ, ŞİĞ ÖÜ I ЗІҐ" ) );+ // a map's name is English whatever the language, so its i stays plain+ CHECK( UIStyle::nameCapitals( UnicodeString( u"Twilight Flame" ) ) == UnicodeString( u"TWILIGHT FLAME" ) );+ TheWritableGlobalData->m_textLanguage = TEXT_LANGUAGE_ENGLISH;+ CHECK( UIStyle::capitals( words ) == UnicodeString( u"ORDU SEÇ, ŞIĞ ÖÜ I ЗІҐ" ) );+ CHECK( UIStyle::capitals( UnicodeString( u"ß ÷" ) ) == UnicodeString( u"ß ÷" ) );+ delete TheWritableGlobalData;+ TheWritableGlobalData = saved;+}++static Bool drawIs( Int pick, Bool oldFactionsOnly, const std::vector<Int> &want )+{+ std::vector<Int> draw;+ GetRandomDraw( pick, oldFactionsOnly, draw );+ return draw == want;+}++// A seat's Random narrowed to a pool rides in its faction number, which every lobby message, slot+// string, save and replay already carries, so the pool has to come back out of the number whole and+// the draw has to be that pool on every machine. Turkiye's RandomExcluded, read from the shipped+// master, keeps it out of a plain Random and out of the default pool; a pool can still tick it in.+TEST(random_pool_round_trips_and_plain_random_leaves_out_turkiye)+{+ CHECK( bootOnce() );+ PlayerTemplateStore *savedStore = ThePlayerTemplateStore;+ ChallengeGenerals *savedGenerals = TheChallengeGenerals;+ ChallengeGenerals generals; // no persona, so no general is locked+ TheChallengeGenerals = &generals;+ ThePlayerTemplateStore = NEW PlayerTemplateStore;+ ThePlayerTemplateStore->init();++ // Turkiye's block as the master ships it, the fields the draw reads+ std::string turkiye;+ {+ std::ifstream master( std::string( ZH_CODE_DIR ) + "/Data/INI/PlayerTemplateReforged.ini" );+ CHECK( master.good() );+ std::string line;+ Bool inBlock = FALSE;+ while( std::getline( master, line ) )+ {+ std::istringstream words( line );+ std::string first, second;+ words >> first >> second;+ if( first == "PlayerTemplate" )+ inBlock = second == "FactionTurkiye";+ if( !inBlock )+ continue;+ if( first == "PlayerTemplate" || first == "Side" || first == "StartingBuilding" || first == "OldFaction" || first == "RandomExcluded" || first == "End" )+ turkiye += line + "\n";+ if( first == "End" )+ inBlock = FALSE;+ }+ }+ CHECK( turkiye.find( "RandomExcluded" ) != std::string::npos );++ std::string text =+ "PlayerTemplate FactionObserver\n Side = Observer\nEnd\n"+ "PlayerTemplate FactionAmerica\n Side = America\n StartingBuilding = AmericaCommandCenter\n OldFaction = Yes\nEnd\n"+ "PlayerTemplate FactionAmericaAirForceGeneral\n Side = AmericaAirForceGeneral\n StartingBuilding = AirF_AmericaCommandCenter\nEnd\n"+ "PlayerTemplate FactionChina\n Side = China\n StartingBuilding = ChinaCommandCenter\n OldFaction = Yes\nEnd\n";+ text += turkiye;+ writeFile( TEST_INI, text.c_str() );+ CHECK( loadIni( TEST_INI ) );+ CHECK_EQ( ThePlayerTemplateStore->getPlayerTemplateCount(), 5 );+ CHECK( ThePlayerTemplateStore->getNthPlayerTemplate( 4 )->isRandomExcluded() );++ // the observer has no command center, so the pool's bits are America, Air Force, China, Turkiye+ std::vector<Int> candidates;+ GetRandomPoolCandidates( candidates );+ const Int four[] = { 1, 2, 3, 4 };+ CHECK( candidates == std::vector<Int>( four, four + 4 ) );+ CHECK_EQ( GetDefaultRandomPool(), 0x7u );++ // plain Random never lands on Turkiye, and the old-factions rule narrows it further+ const Int three[] = { 1, 2, 3 };+ const Int old[] = { 1, 3 };+ CHECK( drawIs( PLAYERTEMPLATE_RANDOM, FALSE, std::vector<Int>( three, three + 3 ) ) );+ CHECK( drawIs( PLAYERTEMPLATE_RANDOM, TRUE, std::vector<Int>( old, old + 2 ) ) );++ // the default pool and an empty one are plain Random, so a lobby that ticked nothing new sends -1+ CHECK_EQ( EncodeRandomPool( GetDefaultRandomPool() ), (Int)PLAYERTEMPLATE_RANDOM );+ CHECK_EQ( EncodeRandomPool( 0 ), (Int)PLAYERTEMPLATE_RANDOM );+ CHECK_EQ( DecodeRandomPool( PLAYERTEMPLATE_RANDOM ), 0x7u );++ // America and Turkiye: the pick is a Random, a valid faction number, and gives the pool back+ const Int pick = EncodeRandomPool( 0x9 );+ CHECK( pick < PLAYERTEMPLATE_RANDOM_POOL );+ CHECK( IsRandomPlayerTemplate( pick ) );+ CHECK( IsValidPlayerTemplatePick( pick ) );+ CHECK_EQ( DecodeRandomPool( pick ), 0x9u );+ const Int ticked[] = { 1, 4 };+ CHECK( drawIs( pick, FALSE, std::vector<Int>( ticked, ticked + 2 ) ) );+ // Turkiye alone in a limited-armies game leaves nothing, so it draws as plain Random+ CHECK( drawIs( EncodeRandomPool( 0x8 ), TRUE, std::vector<Int>( old, old + 2 ) ) );++ // the widest pool still round-trips; one past it, and the unused negatives, are refused+ const UnsignedInt widest = ( 1u << RANDOM_POOL_BITS ) - 1;+ CHECK_EQ( DecodeRandomPool( EncodeRandomPool( widest ) ), widest );+ CHECK( IsValidPlayerTemplatePick( EncodeRandomPool( widest ) ) );+ CHECK( !IsValidPlayerTemplatePick( EncodeRandomPool( widest ) - 1 ) );+ CHECK( !IsValidPlayerTemplatePick( -3 ) );+ CHECK( !IsValidPlayerTemplatePick( PLAYERTEMPLATE_RANDOM_POOL ) );+ CHECK( !IsValidPlayerTemplatePick( 5 ) );+ CHECK( IsValidPlayerTemplatePick( PLAYERTEMPLATE_OBSERVER ) );+ CHECK( IsValidPlayerTemplatePick( 4 ) );++ // the slot string carries a pool as its mask in hex, nine bytes at the widest where the number was eleven+ CHECK_STR( PlayerTemplateSlotField( pick ).str(), "P9" );+ CHECK_STR( PlayerTemplateSlotField( PLAYERTEMPLATE_RANDOM ).str(), "-1" );+ CHECK_STR( PlayerTemplateSlotField( 3 ).str(), "3" );+ CHECK_EQ( PlayerTemplateSlotField( EncodeRandomPool( widest ) ).getLength(), 9 );+ CHECK_EQ( PlayerTemplateFromSlotField( PlayerTemplateSlotField( pick ) ), pick );+ CHECK_EQ( PlayerTemplateFromSlotField( PlayerTemplateSlotField( EncodeRandomPool( widest ) ) ), EncodeRandomPool( widest ) );+ CHECK_EQ( PlayerTemplateFromSlotField( AsciiString( "-2" ) ), (Int)PLAYERTEMPLATE_OBSERVER );+ CHECK( !IsValidPlayerTemplatePick( PlayerTemplateFromSlotField( AsciiString( "P0" ) ) ) );+ CHECK( !IsValidPlayerTemplatePick( PlayerTemplateFromSlotField( AsciiString( "PFFFFFFFF" ) ) ) );++ // the preferences keep a pool by names, so a template added in front of them leaves the pool its armies+ CHECK_STR( PlayerTemplatePreference( pick ).str(), "Random:FactionAmerica,FactionTurkiye" );+ CHECK_STR( PlayerTemplatePreference( 2 ).str(), "2" );+ CHECK_EQ( PlayerTemplateFromPreference( PlayerTemplatePreference( pick ) ), pick );+ CHECK_EQ( PlayerTemplateFromPreference( AsciiString( "Random:FactionTurkiye,FactionGone" ) ), EncodeRandomPool( 0x8 ) );+ CHECK_EQ( PlayerTemplateFromPreference( AsciiString( "Random:FactionGone" ) ), (Int)PLAYERTEMPLATE_RANDOM );+ CHECK_EQ( PlayerTemplateFromPreference( AsciiString( "3" ) ), 3 );+ // a pool a build before the names wrote by number is dropped, its bits being anyone's now+ CHECK_EQ( PlayerTemplateFromPreference( AsciiString( "-25" ) ), (Int)PLAYERTEMPLATE_RANDOM );++ // a seat on a pool keeps its start spot; only an observer gives it up+ GameSlot slot;+ slot.setStartPos( 3 );+ slot.setPlayerTemplate( pick );+ CHECK_EQ( slot.getStartPos(), 3 );+ slot.setPlayerTemplate( PLAYERTEMPLATE_OBSERVER );+ CHECK_EQ( slot.getStartPos(), -1 );++ remove( TEST_INI );+ delete ThePlayerTemplateStore;+ ThePlayerTemplateStore = savedStore;+ TheChallengeGenerals = savedGenerals;+}+// The game's fingerprint over a BitFlags used to be taken with sizeof(this) - the size of the// pointer - so only the first four bytes of any flag set were in it. ObjectStatusMaskType is 47// bits wide, so everything from RIDER1 upwards could differ between two machines without the CRC@@ -18057,6 +18211,16 @@ TEST(lan_options_fit_eight_humans_on_a_generated_template_map)CHECK_EQ( shortestHumanName( replay ), 12 );CHECK( strstr( replay.str(), "M=00userdata/maps/rmg_v17_2147483647_8p_672c_tffffffff_bombardment beach;" ) != NULL );+ // eight seats on a pool as wide as retail's armies and Turkiye (13 bits, "P1FFF") cost three bytes+ // a seat; a wider one that does not fit is turned back to Random by the host (LANAPI::OnGameOptions)+ for( Int i = 0; i < MAX_SLOTS; ++i )+ game.getSlot( i )->setPlayerTemplate( PLAYERTEMPLATE_RANDOM_POOL - 0x1FFF );+ const AsciiString pooled = GameInfoOptionsString( &game, AsciiString( paths[4] ), m_lanMaxOptionsLength );+ printf( " pooled %d bytes, names keep %d\n", pooled.getLength(), shortestHumanName( pooled ) );+ CHECK( !pooled.isEmpty() );+ CHECK( shortestHumanName( pooled ) >= 2 );+ CHECK( strstr( pooled.str(), ",P1FFF," ) != NULL );+delete TheWritableGlobalData;TheWritableGlobalData = saved;}