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): lay the spectator page out with litehtml, add net worth
Olcay Seygan5bc7a0148787
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ff7f6820c..e70850c15 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -476,7 +476,9 @@ found and fixed — EA's own, not port damage.**- Watching, clicking one player's unit is clicking his name in the player list, and clicking empty ground puts the whole match back. The command bar brings up his readouts and his money and wears his side's metal; the production rows on the left close down to his, and get longer since he has the strip to himself; the promotions on the right are his alone. The tilde key, or the general's stars on the right of the bar, then opens his promotion screen, on his side's artwork, with his skill points and his rank - greyed out, because they are not yours to spend. With nothing selected the key does nothing and the stars are dark; there is no one general to show.- A general who has taken Artillery Barrage to level 3 shows one Artillery Barrage on the promotions strip, not three copies of the same picture in a row.- The strips close up again: across a row the trays slide an eighth of a tray under each other, so a row reads as one run of metal. The cameos never overlap each other, because every tray goes down before any picture does.-- Watching, the strips can be switched off. A small "Strips" drop-down in the top left corner opens into three boxes - the production queue, the generals' promotions and the superweapon timers - and each box switches its strip the moment it is clicked and is remembered for the next match you watch. The message list moves down to start under it. Playing, there is no drop-down and every strip is up, whatever you chose in the stands. The drop-down is written as an HTML page under the game's Window folder: open it in a browser and the same boxes are there, and a box added to it for another on/off setting shows up in the next match you watch.+- Watching, the strips can be switched off. A small "Strips" drop-down in the top left corner opens into three boxes - the production queue, the generals' promotions and the superweapon timers - and each box switches its strip the moment it is clicked and is remembered for the next match you watch. The message list moves down to start under it. Playing, there is no drop-down and every strip is up, whatever you chose in the stands.+- Watching, every player's net worth is on screen under the strips drop-down, the way Dota shows it: richest first, the general's portrait, the number, and a bar measured against the richest player, green for one side and red for the other in a two-sided match and each player's own colour in a free for all. Net worth is the cash in hand plus what everything the player has standing would cost to build again, counted twice a second. Click its title to fold it away.+- Both are an ordinary web page with a stylesheet, in the game's Window folder. Change the colours, the sizes or the order there and the next match you watch draws it that way, and the page opens in a browser too.- A minimised command bar stays minimised. Changing seats, or clicking another player's unit while watching, put the whole bar back up over the battlefield you had just cleared. A new match still opens with the bar up.## Placing buildingsdiff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex 1c7ff860a..c6d270f98 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -30,7 +30,8 @@ foreach(vendored${COMP}/ZLib/deflate.c${COMP}/LZHCompress/CompLibSource/Lzhl.cpp${CMAKE_CURRENT_SOURCE_DIR}/Libraries/DirectX/Include/d3d8.h- ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Source/GameSpy/CMakeLists.txt)+ ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Source/GameSpy/CMakeLists.txt+ ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Source/litehtml/CMakeLists.txt)if(NOT EXISTS ${vendored})message(FATAL_ERROR"${vendored} is missing. Run Tools\\vendor.ps1 (build.bat does it for you).")@@ -476,6 +477,14 @@ set(GS_BUILD_TESTS OFF CACHE BOOL "" FORCE)set(GS_INCLUDE_VOICE OFF CACHE BOOL "" FORCE)add_subdirectory(${LIBSRC}/GameSpy ${CMAKE_CURRENT_BINARY_DIR}/gamespy)+# ---- litehtml -------------------------------------------------------------+# The HTML and CSS layout engine behind the pages drawn over the battlefield (GameClient/+# HtmlOverlay.cpp). It lays a page out and calls back to draw each box and each run of text, so+# the drawing stays the game's own. Its own CMakeLists sets /permissive- and C++17 for itself+# alone, and brings the gumbo HTML parser with it.+set(LITEHTML_BUILD_TESTING OFF CACHE BOOL "" FORCE)+add_subdirectory(${LIBSRC}/litehtml ${CMAKE_CURRENT_BINARY_DIR}/litehtml)+# d3d8to9 is no longer built. It was a d3d8.dll next to generals.exe that translated# every D3D8 call to Direct3D 9, which is how the renderer ran on a modern runtime# without touching the ~5600 D3D8 call sites. The renderer creates its own@@ -534,7 +543,7 @@ target_compile_definitions(gameengine PUBLICset_target_properties(gameengine PROPERTIES CXX_STANDARD 17)target_link_libraries(gameengine PUBLICww3d2 wwlib wwmath wwsaveload wwdebug wwutil compression debuglib wwdownload- benchmark eabrowserdispatch profile gamespy+ benchmark eabrowserdispatch profile gamespy litehtmldinput8 wininet imagehlp imm32)# ===========================================================================@@ -770,12 +779,12 @@ set_target_properties(test_gameengine PROPERTIES CXX_STANDARD 17)# fxlist_reforged_ini_parses_and_keeps_its_light runs the fork's own FXList file through the real# INI parser, so it needs the tracked master rather than whatever sits in Run/.# the_options_menu_buttons_all_wear_one_font reads the tracked layout master, not Run/'s copy.-# the_hud_toggles_page_binds_only_on_off_options reads the tracked page master the same way.+# the_spectator_page_names_only_on_off_options reads the tracked page master the same way.target_compile_definitions(test_gameengine PRIVATEGAMEENGINE_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}/GameEngine"FXLIST_REFORGED_INI="${CMAKE_CURRENT_SOURCE_DIR}/Data/INI/FXListReforged.ini"OPTIONS_MENU_WND="${CMAKE_CURRENT_SOURCE_DIR}/Data/Window/Menus/OptionsMenu.wnd"- HUD_TOGGLES_HTML="${CMAKE_CURRENT_SOURCE_DIR}/Data/Window/Html/HudToggles.html"+ SPECTATOR_HTML="${CMAKE_CURRENT_SOURCE_DIR}/Data/Window/Html/Spectator.html"PLATE_TEXTURE_DIR="${CMAKE_CURRENT_SOURCE_DIR}/Data/Art/Textures")# The three hand-written self-checks predate the harness; run them from ctestdiff --git a/GeneralsMD/Code/Data/Patch.str b/GeneralsMD/Code/Data/Patch.strindex bd5972e21..0a413781c 100644--- a/GeneralsMD/Code/Data/Patch.str+++ b/GeneralsMD/Code/Data/Patch.str@@ -1054,6 +1054,11 @@ GUI:HudSuperweaponStrip"Superweapon timers"END+// the spectator's list of every player's cash plus what everything he has standing cost+GUI:HudNetWorth+"Net worth"+END+// the scoreboard on TabGUI:ScoreboardAllies"YOUR SIDE"diff --git a/GeneralsMD/Code/Data/Turkish/Generals.str b/GeneralsMD/Code/Data/Turkish/Generals.strindex 2d630741b..c781ad992 100644--- a/GeneralsMD/Code/Data/Turkish/Generals.str+++ b/GeneralsMD/Code/Data/Turkish/Generals.str@@ -15585,6 +15585,10 @@ GUI:HudSuperweaponStrip"Süper silah sayaçları"END+GUI:HudNetWorth+"Net değer"+END+GUI:ScoreboardAllies"TAKIMIN"ENDdiff --git a/GeneralsMD/Code/Data/Window/Html/HudToggles.html b/GeneralsMD/Code/Data/Window/Html/HudToggles.htmldeleted file mode 100644index ac5c7083f..000000000--- a/GeneralsMD/Code/Data/Window/Html/HudToggles.html+++ /dev/null@@ -1,27 +0,0 @@-<!DOCTYPE html>-<!--- The spectator's drop-down in the top left corner of a match. The game reads a small part of- HTML (see GameClient/HtmlPanel.h): <details> and <summary>, <label>, <input type="checkbox">- and loose text, one row each. name= is an Options.ini key from OptionsCatalog.cpp that holds- yes or no; data-text= is a string table label the game shows instead of the words between the- tags. <head> is skipped, so the style below is only for opening this file in a browser.- Edit the copy under Run/Window/Html and the next match reads it.--->-<html>-<head>- <meta charset="utf-8">- <title>HUD toggles</title>- <style>- body { background: #333; color: #eee; font: 12px sans-serif; }- label { display: block; }- </style>-</head>-<body>- <details>- <summary data-text="GUI:HudToggles">Strips</summary>- <label data-text="GUI:HudProductionStrip"><input type="checkbox" name="ShowProductionStrip"> Production queue</label>- <label data-text="GUI:HudSkillStrip"><input type="checkbox" name="ShowSkillStrip"> Generals' promotions</label>- <label data-text="GUI:HudSuperweaponStrip"><input type="checkbox" name="ShowSuperweaponStrip"> Superweapon timers</label>- </details>-</body>-</html>diff --git a/GeneralsMD/Code/Data/Window/Html/Spectator.html b/GeneralsMD/Code/Data/Window/Html/Spectator.htmlnew file mode 100644index 000000000..f082c2cb9--- /dev/null+++ b/GeneralsMD/Code/Data/Window/Html/Spectator.html@@ -0,0 +1,88 @@+<!DOCTYPE html>+<!--+ What a spectator sees over the battlefield: the drop-down that switches the strips, and every+ player's net worth. Laid out by litehtml and drawn by the game (GameClient/HtmlOverlay.h).++ A CSS pixel is a pixel of an 800x600 screen and font-size is the game font's point size there;+ the page is scaled with the rest of the interface. A background on html or body is for a+ browser only. Not drawn: rounded corners, overflow clipping, list bullets, gradients other+ than linear ones.++ The game fills in, before layout (GameClient/HtmlTemplate.h):+ {{option:Key}} "on" while that Options.ini on/off option is on+ {{flip:name}} "flipped" while a data-click of flip:name has been clicked an odd number of times+ {{text:Label}} a string table label, in the player's language+ data-each="players", one copy per player still in the match, richest first, with+ {{name}} {{networth}} {{share}} (percent of the richest) {{color}} {{team}} {{teams}}+ {{portrait}} (a mapped image name, for <img src>)++ A data-click of option:Key flips that option and saves it; one of flip:name flips the name for+ the rest of the match. #hud-top's bottom edge is where the message list starts.++ Edit the copy under Run/Window/Html and the next match reads it.+-->+<html>+<head>+<meta charset="utf-8">+<title>Spectator</title>+<style>+ html, body { margin: 0; padding: 0; }+ body { background-color: #3b4a36; color: #e8e8e8; font-size: 9px; }++ #hud-top { position: absolute; left: 6px; top: 6px; width: 150px; }++ .menu { background-color: rgba(0, 0, 0, 0.6); margin-bottom: 4px; }+ .row { padding: 2px 3px; }+ .row:hover { background-color: rgba(255, 255, 255, 0.12); }+ .items { display: none; }+ .menu.flipped .items { display: block; }+ .box { display: inline-block; width: 8px; height: 8px; margin-right: 5px; border: 1px solid #c8c8c8;+ text-align: center; line-height: 8px; vertical-align: middle; }+ .on .box { background-color: #5ac85a; }+ .menu .sign::before { content: "+"; }+ .menu.flipped .sign::before { content: "-"; }++ .networth { background-color: rgba(8, 12, 16, 0.78); border-top: 1px solid #45525c; padding-bottom: 2px; }+ .title { padding: 2px 4px; color: #aab6bf; }+ .title:hover { color: #ffffff; }+ .networth .sign::before { content: "- "; }+ .networth.flipped .sign::before { content: "+ "; }+ .networth.flipped .list { display: none; }++ .player { height: 14px; margin: 1px 2px; }+ .portrait { float: left; width: 22px; height: 14px; border-left: 2px solid #888888; }+ .track { position: relative; height: 14px; margin-left: 27px; }+ .bar { position: absolute; left: 0; top: 0; height: 14px; }+ .teams2.team0 .bar { background: linear-gradient(to right, #2f6b21, #72cf4b); }+ .teams2.team1 .bar { background: linear-gradient(to right, #7a1d17, #e2553f); }+ .worth { position: relative; padding-left: 3px; line-height: 14px; font-weight: bold; color: #ffffff; }+</style>+</head>+<body>+<div id="hud-top">++ <div class="menu {{flip:strips}}">+ <div class="row" data-click="flip:strips"><span class="box sign"></span>{{text:GUI:HudToggles}}</div>+ <div class="items">+ <div class="row {{option:ShowProductionStrip}}" data-click="option:ShowProductionStrip"><span class="box"></span>{{text:GUI:HudProductionStrip}}</div>+ <div class="row {{option:ShowSkillStrip}}" data-click="option:ShowSkillStrip"><span class="box"></span>{{text:GUI:HudSkillStrip}}</div>+ <div class="row {{option:ShowSuperweaponStrip}}" data-click="option:ShowSuperweaponStrip"><span class="box"></span>{{text:GUI:HudSuperweaponStrip}}</div>+ </div>+ </div>++ <div class="networth {{flip:networth}}">+ <div class="title" data-click="flip:networth"><span class="sign"></span>{{text:GUI:HudNetWorth}}</div>+ <div class="list">+ <div class="player teams{{teams}} team{{team}}" data-each="players">+ <img class="portrait" src="{{portrait}}" style="border-color: {{color}}">+ <div class="track">+ <div class="bar" style="width: {{share}}%; background-color: {{color}}"></div>+ <span class="worth">{{networth}}</span>+ </div>+ </div>+ </div>+ </div>++</div>+</body>+</html>diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlOverlay.h b/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlOverlay.hnew file mode 100644index 000000000..acc8041e9--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlOverlay.h@@ -0,0 +1,73 @@+/*+** 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/>.+*/++// HtmlOverlay.h //////////////////////////////////////////////////////////////////////////////////+// An HTML page laid out by litehtml and drawn over the battlefield with the game's own 2D calls.+//+// The page covers the whole screen and CSS places what is on it. A CSS pixel is a pixel of the+// 800x600 screen everything else was authored at, so a page keeps its proportions at any+// resolution, and font-size is the game font's point size at 800x600. A background on <html> or+// <body> is not drawn: it is there for a browser, the battlefield is the game's background.+//+// An element with data-click="..." is a button; click() hands back that text and the caller+// decides what it means. Clicks walk up from what is under the pointer to the first element+// that has one.+//+// Not drawn: rounded corners, clipping for overflow, list bullets, and gradients other than+// linear ones, which draw as their first colour.+///////////////////////////////////////////////////////////////////////////////////////////////////++#pragma once++#ifndef _HTML_OVERLAY_H_+#define _HTML_OVERLAY_H_++#include "Lib/BaseType.h"+#include "Common/AsciiString.h"++#include <string>++class HtmlOverlayContainer;++class HtmlOverlay+{+public:+ /** `defaultFont` is the game font a page gets where its CSS names none. */+ explicit HtmlOverlay( const AsciiString &defaultFont );+ ~HtmlOverlay( void );++ /** Lay this page out, unless it is the page already laid out on a screen of the same size. */+ void setPage( const std::string &html );++ void draw( void );++ /** Move the pointer over the page, for :hover. TRUE when it is on something the page drew+ * rather than on the empty body round it. */+ Bool hover( const ICoord2D &mouse );++ /** Click at the pointer and return the data-click of what was clicked, empty for nothing. */+ std::string click( const ICoord2D &mouse );++ /** The bottom edge in screen pixels of the first element the CSS selector finds, 0 for none. */+ Int bottomOf( const char *selector );++private:+ HtmlOverlayContainer *m_container;+};++#endif // _HTML_OVERLAY_H_diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlPanel.h b/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlPanel.hdeleted file mode 100644index 6e6a6840a..000000000--- a/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlPanel.h+++ /dev/null@@ -1,69 +0,0 @@-/*-** 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/>.-*/--// HtmlPanel.h ////////////////////////////////////////////////////////////////////////////////////-// A panel over the battlefield described by an .html file under Window/Html.-//-// The game reads a small part of HTML and turns it into a column of rows: a <summary> is a row-// that opens and closes its <details>, a <label> or a bare <input type="checkbox"> is a check box-// row, and loose text is a row of words. <head>, <style>, <script> and <title> are skipped, so a-// page can carry the style a browser needs to show the same panel. There is no layout beyond the-// column and no CSS: the look is the game's.-//-// An attribute carries what the words between the tags cannot: name= on a check box is the-// Options.ini key it is bound to, data-text= is a string table label the game shows instead of-// the literal words, so the page reads in English in a browser and in the player's language in-// the game.-///////////////////////////////////////////////////////////////////////////////////////////////////--#pragma once--#ifndef _HTML_PANEL_H_-#define _HTML_PANEL_H_--#include "Lib/BaseType.h"--#include <string>-#include <vector>--enum HtmlRowKind-{- HTML_ROW_SUMMARY, ///< a <summary>: clicking it opens or closes the rows of its <details>- HTML_ROW_CHECKBOX, ///< a check box, bound to the Options.ini key in `name`- HTML_ROW_TEXT, ///< words and nothing to click-};--struct HtmlRow-{- HtmlRowKind kind;- std::string text; ///< the words between the tags, whitespace collapsed, UTF-8- std::string textKey; ///< data-text: a string table label, empty when `text` is the label- std::string name; ///< a check box's name=- Int owner; ///< the summary row of the <details> this row sits in, -1 at the top level- Bool open; ///< a summary: whether its <details> is open-};--/** The rows an HTML page describes, in document order. Anything outside the part of HTML the- * panel reads is passed over rather than refused, the way a browser passes over a tag it does- * not know. */-extern void HtmlPanel_buildRows( const std::string &html, std::vector< HtmlRow > &rows );--/** Is this row on screen: every <details> round it open? */-extern Bool HtmlPanel_isRowShown( const std::vector< HtmlRow > &rows, Int row );--#endif // _HTML_PANEL_H_diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlTemplate.h b/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlTemplate.hnew file mode 100644index 000000000..e914275a4--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlTemplate.h@@ -0,0 +1,56 @@+/*+** 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/>.+*/++// HtmlTemplate.h /////////////////////////////////////////////////////////////////////////////////+// Filling a page under Window/Html with what the game knows before it is laid out.+//+// A page is written as plain HTML and CSS. The game's numbers go into it two ways:+//+// {{name}} replaced by that value, HTML-escaped; a name with no value becomes nothing,+// so class="row {{option:Key}}" is "row on" or "row ".+// data-each="list" on an element: the element is written once for every entry of the list,+// and inside it {{name}} reads that entry's values first.+//+// Everything else is left for the layout engine, so CSS decides what "on" or "flipped" looks like.+///////////////////////////////////////////////////////////////////////////////////////////////////++#pragma once++#ifndef _HTML_TEMPLATE_H_+#define _HTML_TEMPLATE_H_++#include "Lib/BaseType.h"++#include <functional>+#include <map>+#include <string>+#include <vector>++typedef std::map< std::string, std::string > HtmlValues;+typedef std::map< std::string, std::vector< HtmlValues > > HtmlLists;++/** Asked for a name neither the entry nor the page's values hold; TRUE with `value` set if it knows it. */+typedef std::function< Bool( const std::string &name, std::string &value ) > HtmlLookup;++extern std::string HtmlTemplate_expand( const std::string &page, const HtmlValues &values,+ const HtmlLists &lists, const HtmlLookup &lookup );++/** The text with & < > " and ' written as entities, so a player's name cannot open a tag. */+extern std::string HtmlTemplate_escape( const std::string &text );++#endif // _HTML_TEMPLATE_H_diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.hindex 62a3032e0..a4bf654e3 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h@@ -43,7 +43,11 @@#include "Common/SubsystemInterface.h"#include "Common/UnicodeString.h"#include "GameClient/DisplayString.h"-#include "GameClient/HtmlPanel.h"+#include "GameClient/HtmlTemplate.h"++#include <set>++class HtmlOverlay;#include "GameClient/Mouse.h"#include "GameClient/RadiusDecal.h"#include "GameClient/View.h"@@ -1193,18 +1197,19 @@ protected:DisplayString * m_scoreboardStrings[ SCOREBOARD_STRING_COUNT ];//- // The drop-down in the top left corner that switches the strips on and off, read from- // Window/Html/HudToggles.html: one row per summary, check box or line of words in it.+ // The spectator's page over the battlefield, Window/Html/Spectator.html: the drop-down that+ // switches the strips on and off, and every player's net worth. Only while watching.//- void loadHudToggles( void );- void freeHudToggleStrings( void );- void drawHudToggles( void );- Bool handleHudTogglesClick( const ICoord2D *mouse, Bool act ); ///< TRUE when the click landed on it- Bool m_hudTogglesLoaded; ///< read once a match, so an edited page shows in the next one- Int m_hudTogglesBottom; ///< its bottom edge, so the message list starts under it- std::vector< HtmlRow > m_hudToggleRows;- std::vector< IRegion2D > m_hudToggleRects; ///< each row's place this frame, empty while it is hidden- std::vector< DisplayString * > m_hudToggleStrings;+ void drawSpectatorPage( void );+ Bool handleSpectatorPageClick( const ICoord2D *mouse, Bool act ); ///< TRUE when the click landed on it+ HtmlOverlay * m_spectatorOverlay;+ Bool m_spectatorPageLoaded; ///< read once a match, so an edited page shows in the next one+ Bool m_spectatorPageShown; ///< drawn this frame, so clicks are its to take+ std::string m_spectatorPage; ///< the page as written, before its {{values}} are filled+ std::set< std::string > m_spectatorFlipped; ///< names a data-click="flip:name" has flipped+ HtmlLists m_spectatorLists;+ UnsignedInt m_spectatorListsFrame; ///< the logic frame the lists were last gathered on+ Int m_hudTogglesBottom; ///< the bottom of the page's #hud-top, so the message list starts under itBool m_placementRangeRingUp; ///< the structure on the cursor is armed, so its reach is drawnReal m_placementRingRadius; ///< how far from its centre it hitsdiff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlOverlay.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlOverlay.cppnew file mode 100644index 000000000..f01769f96--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlOverlay.cpp@@ -0,0 +1,559 @@+/*+** 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/>.+*/++// HtmlOverlay.cpp ////////////////////////////////////////////////////////////////////////////////+// litehtml's drawing callbacks answered with the game's 2D calls, fonts and mapped images.+///////////////////////////////////////////////////////////////////////////////////////////////////++#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine++#include "Common/FileSystem.h"+#include "Common/file.h"+#include "GameClient/ControlBar.h"+#include "GameClient/Display.h"+#include "GameClient/DisplayString.h"+#include "GameClient/DisplayStringManager.h"+#include "GameClient/GameFont.h"+#include "GameClient/HtmlOverlay.h"+#include "GameClient/Image.h"+#include "GameNetwork/GameSpy/ThreadUtils.h"++// BaseType.h's min and max macros would eat std::min and std::max inside litehtml's headers+#undef min+#undef max++#include <litehtml.h>++#include <algorithm>+#include <map>+#include <math.h>++namespace+{++const litehtml::pixel_t DEFAULT_FONT_SIZE = 12; ///< CSS pixels at 800x600, where a page names none+const litehtml::pixel_t PIXELS_PER_POINT = 96.0f / 72.0f;+const litehtml::pixel_t BROWSER_DPI = 96;+const Int COLOR_BITS = 8;+const Int BOLD_WEIGHT = 600; ///< CSS font-weight from which the game's bold face is used+const Real ASCENT_SHARE = 0.8f; ///< of the font's height; GameFont only knows the height+const Real X_HEIGHT_SHARE = 0.5f;+const char *const PAGE_FOLDER = "Window\\Html\\";+const char *const GENERIC_FAMILIES[] = { "serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui" };++Color gameColor( const litehtml::web_color &color )+{+ return GameMakeColor( color.red, color.green, color.blue, color.alpha );+}++/** The first family in a CSS font-family list, without its quotes. */+std::string firstFamily( const std::string &families )+{+ std::string family = families.substr( 0, families.find( ',' ) );+ const size_t first = family.find_first_not_of( " \t\"'" );+ const size_t last = family.find_last_not_of( " \t\"'" );+ return first == std::string::npos ? std::string() : family.substr( first, last - first + 1 );+}++Bool isGenericFamily( const std::string &family )+{+ for( size_t index = 0; index < ARRAY_SIZE( GENERIC_FAMILIES ); index++ )+ if( _stricmp( family.c_str(), GENERIC_FAMILIES[ index ] ) == 0 )+ return TRUE;+ return FALSE;+}++} // namespace++//-------------------------------------------------------------------------------------------------+class HtmlOverlayContainer : public litehtml::document_container+{+public:+ explicit HtmlOverlayContainer( const AsciiString &defaultFont );+ ~HtmlOverlayContainer( void );++ void setPage( const std::string &html );+ void draw( void );+ Bool hover( const ICoord2D &mouse );+ std::string click( const ICoord2D &mouse );+ Int bottomOf( const char *selector );++ litehtml::uint_ptr create_font( const litehtml::font_description &description, const litehtml::document *document,+ litehtml::font_metrics *metrics ) override;+ void delete_font( litehtml::uint_ptr font ) override {}+ litehtml::pixel_t text_width( const char *text, litehtml::uint_ptr font ) override;+ void draw_text( litehtml::uint_ptr hdc, const char *text, litehtml::uint_ptr font, litehtml::web_color color,+ const litehtml::position &place ) override;+ litehtml::pixel_t pt_to_px( float points ) const override { return points * PIXELS_PER_POINT; }+ litehtml::pixel_t get_default_font_size( void ) const override { return DEFAULT_FONT_SIZE; }+ const char *get_default_font_name( void ) const override { return m_defaultFont.c_str(); }+ void draw_list_marker( litehtml::uint_ptr hdc, const litehtml::list_marker &marker ) override {}+ void load_image( const char *source, const char *baseUrl, bool redrawOnReady ) override {}+ void get_image_size( const char *source, const char *baseUrl, litehtml::size &size ) override;+ void draw_image( litehtml::uint_ptr hdc, const litehtml::background_layer &layer, const std::string &url,+ const std::string &baseUrl ) override;+ void draw_solid_fill( litehtml::uint_ptr hdc, const litehtml::background_layer &layer,+ const litehtml::web_color &color ) override;+ void draw_linear_gradient( litehtml::uint_ptr hdc, const litehtml::background_layer &layer,+ const litehtml::background_layer::linear_gradient &gradient ) override;+ void draw_radial_gradient( litehtml::uint_ptr hdc, const litehtml::background_layer &layer,+ const litehtml::background_layer::radial_gradient &gradient ) override;+ void draw_conic_gradient( litehtml::uint_ptr hdc, const litehtml::background_layer &layer,+ const litehtml::background_layer::conic_gradient &gradient ) override;+ void draw_borders( litehtml::uint_ptr hdc, const litehtml::borders &borders, const litehtml::position &place,+ bool root ) override;+ void set_caption( const char *caption ) override {}+ void set_base_url( const char *baseUrl ) override {}+ void link( const std::shared_ptr< litehtml::document > &document, const litehtml::element::ptr &element ) override {}+ void on_anchor_click( const char *url, const litehtml::element::ptr &element ) override {}+ bool on_element_click( const litehtml::element::ptr &element ) override;+ void on_mouse_event( const litehtml::element::ptr &element, litehtml::mouse_event event ) override {}+ void set_cursor( const char *cursor ) override {}+ void transform_text( litehtml::string &text, litehtml::text_transform transform ) override;+ void import_css( litehtml::string &text, const litehtml::string &url, litehtml::string &baseUrl ) override;+ void set_clip( const litehtml::position &place, const litehtml::border_radiuses &radiuses ) override {}+ void del_clip( void ) override {}+ void get_viewport( litehtml::position &viewport ) const override;+ litehtml::element::ptr create_element( const char *tagName, const litehtml::string_map &attributes,+ const std::shared_ptr< litehtml::document > &document ) override { return nullptr; }+ void get_media_features( litehtml::media_features &media ) const override;+ void get_language( litehtml::string &language, litehtml::string &culture ) const override;++private:+ struct CachedString+ {+ DisplayString *string;+ UnsignedInt stamp; ///< the draw that last used it+ };+ typedef std::map< std::pair< GameFont *, std::string >, CachedString > StringCache;++ Int screen( litehtml::pixel_t pagePixels ) const { return (Int)floorf( pagePixels * m_scale + 0.5f ); }+ litehtml::pixel_t page( Int screenPixels ) const { return screenPixels / m_scale; }+ litehtml::pixel_t viewportWidth( void ) const { return page( m_screenWidth ); }+ litehtml::pixel_t viewportHeight( void ) const { return page( m_screenHeight ); }+ DisplayString *displayString( GameFont *font, const char *text );+ void freeStrings( Bool all );+ void fillBox( const litehtml::position &box, const litehtml::web_color &color );++ std::string m_defaultFont;+ std::string m_page;+ litehtml::document::ptr m_document;+ Real m_scale;+ Int m_screenWidth;+ Int m_screenHeight;+ StringCache m_strings;+ UnsignedInt m_stamp;+ std::string m_clicked;+};++//-------------------------------------------------------------------------------------------------+HtmlOverlayContainer::HtmlOverlayContainer( const AsciiString &defaultFont ) :+ m_defaultFont( defaultFont.str() ),+ m_scale( 1.0f ),+ m_screenWidth( 0 ),+ m_screenHeight( 0 ),+ m_stamp( 0 )+{+}++//-------------------------------------------------------------------------------------------------+HtmlOverlayContainer::~HtmlOverlayContainer( void )+{+ m_document = nullptr;+ freeStrings( TRUE );+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::setPage( const std::string &html )+{+ const Int width = TheDisplay->getWidth();+ const Int height = TheDisplay->getHeight();+ const Real scale = ControlBarUniformScale();+ if( m_document && html == m_page && width == m_screenWidth && height == m_screenHeight && scale == m_scale )+ return;++ m_page = html;+ m_screenWidth = width;+ m_screenHeight = height;+ m_scale = scale;+ m_document = litehtml::document::createFromString( litehtml::estring( html, litehtml::encoding::utf_8 ), this );+ m_document->render( viewportWidth() );+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::draw( void )+{+ if( !m_document )+ return;++ m_stamp++;+ const litehtml::position clip( 0, 0, viewportWidth(), viewportHeight() );+ TheDisplay->beginBatch2D();+ m_document->draw( 0, 0, 0, &clip );+ TheDisplay->endBatch2D();+ freeStrings( FALSE );+}++//-------------------------------------------------------------------------------------------------+Bool HtmlOverlayContainer::hover( const ICoord2D &mouse )+{+ if( !m_document )+ return FALSE;++ litehtml::position::vector redraw;+ const litehtml::pixel_t x = page( mouse.x );+ const litehtml::pixel_t y = page( mouse.y );+ if( m_document->on_mouse_over( x, y, x, y, redraw ) )+ m_document->render( viewportWidth() );++ // the root and the body span the whole screen; only what is drawn on them is the page's+ std::shared_ptr< const litehtml::element > over = m_document->get_over_element();+ return over && over->parent() && !over->is_body();+}++//-------------------------------------------------------------------------------------------------+std::string HtmlOverlayContainer::click( const ICoord2D &mouse )+{+ m_clicked.clear();+ if( !m_document )+ return m_clicked;++ litehtml::position::vector redraw;+ const litehtml::pixel_t x = page( mouse.x );+ const litehtml::pixel_t y = page( mouse.y );+ m_document->on_lbutton_down( x, y, x, y, redraw );+ m_document->on_lbutton_up( x, y, x, y, redraw );+ return m_clicked;+}++//-------------------------------------------------------------------------------------------------+Int HtmlOverlayContainer::bottomOf( const char *selector )+{+ if( !m_document )+ return 0;++ litehtml::element::ptr element = m_document->root()->select_one( selector );+ if( !element )+ return 0;+ const litehtml::position placement = element->get_placement();+ return screen( placement.y + placement.height );+}++//-------------------------------------------------------------------------------------------------+bool HtmlOverlayContainer::on_element_click( const litehtml::element::ptr &element )+{+ const char *action = element->get_attr( "data-click" );+ if( action == NULL )+ return false;+ m_clicked = action;+ return true;+}++//-------------------------------------------------------------------------------------------------+DisplayString *HtmlOverlayContainer::displayString( GameFont *font, const char *text )+{+ const StringCache::key_type key( font, text );+ StringCache::iterator found = m_strings.find( key );+ if( found == m_strings.end() )+ {+ CachedString cached;+ cached.string = TheDisplayStringManager->newDisplayString();+ cached.string->setFont( font );+ cached.string->setText( UnicodeString( MultiByteToWideCharSingleLine( text ).c_str() ) );+ found = m_strings.insert( std::make_pair( key, cached ) ).first;+ }+ found->second.stamp = m_stamp;+ return found->second.string;+}++//-------------------------------------------------------------------------------------------------+/** Strings the last draw did not use go, so a number that changes every half second does not leave+ * a string behind for every value it has had. */+void HtmlOverlayContainer::freeStrings( Bool all )+{+ for( StringCache::iterator cached = m_strings.begin(); cached != m_strings.end(); )+ {+ if( !all && cached->second.stamp == m_stamp )+ {+ ++cached;+ continue;+ }+ TheDisplayStringManager->freeDisplayString( cached->second.string );+ cached = m_strings.erase( cached );+ }+}++//-------------------------------------------------------------------------------------------------+litehtml::uint_ptr HtmlOverlayContainer::create_font( const litehtml::font_description &description,+ const litehtml::document *document,+ litehtml::font_metrics *metrics )+{+ std::string family = firstFamily( description.family );+ if( family.empty() || isGenericFamily( family ) )+ family = m_defaultFont;++ const Int points = std::max( 1, screen( description.size ) );+ const Bool bold = description.weight >= BOLD_WEIGHT;+ GameFont *font = TheFontLibrary->getFont( AsciiString( family.c_str() ), points, bold );+ if( font == NULL )+ font = TheFontLibrary->getFont( AsciiString( m_defaultFont.c_str() ), points, bold );+ if( font == NULL )+ return 0;++ if( metrics )+ {+ metrics->font_size = description.size;+ metrics->height = page( font->height );+ metrics->ascent = metrics->height * ASCENT_SHARE;+ metrics->descent = metrics->height - metrics->ascent;+ metrics->x_height = metrics->height * X_HEIGHT_SHARE;+ metrics->ch_width = text_width( "0", (litehtml::uint_ptr)font );+ metrics->draw_spaces = false;+ }+ return (litehtml::uint_ptr)font;+}++//-------------------------------------------------------------------------------------------------+litehtml::pixel_t HtmlOverlayContainer::text_width( const char *text, litehtml::uint_ptr font )+{+ if( font == 0 )+ return 0;++ Int width = 0, height = 0;+ displayString( (GameFont *)font, text )->getSize( &width, &height );+ return page( width );+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::draw_text( litehtml::uint_ptr hdc, const char *text, litehtml::uint_ptr font,+ litehtml::web_color color, const litehtml::position &place )+{+ if( font == 0 || color.alpha == 0 )+ return;++ displayString( (GameFont *)font, text )->draw( screen( place.x ), screen( place.y ), gameColor( color ),+ GameMakeColor( 0, 0, 0, color.alpha ) );+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::get_image_size( const char *source, const char *baseUrl, litehtml::size &size )+{+ const Image *image = TheMappedImageCollection->findImageByName( AsciiString( source ) );+ size.width = image ? (litehtml::pixel_t)image->getImageWidth() : 0;+ size.height = image ? (litehtml::pixel_t)image->getImageHeight() : 0;+}++//-------------------------------------------------------------------------------------------------+/** An image source is the name of one of the game's mapped images, and it is stretched over the box. */+void HtmlOverlayContainer::draw_image( litehtml::uint_ptr hdc, const litehtml::background_layer &layer,+ const std::string &url, const std::string &baseUrl )+{+ const Image *image = TheMappedImageCollection->findImageByName( AsciiString( url.c_str() ) );+ if( image == NULL || layer.is_root )+ return;++ const litehtml::position &box = layer.origin_box;+ TheDisplay->drawImage( image, screen( box.x ), screen( box.y ), screen( box.x + box.width ), screen( box.y + box.height ) );+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::fillBox( const litehtml::position &box, const litehtml::web_color &color )+{+ const Int left = screen( box.x );+ const Int top = screen( box.y );+ const Int right = screen( box.x + box.width );+ const Int bottom = screen( box.y + box.height );+ if( color.alpha > 0 && right > left && bottom > top )+ TheDisplay->drawFillRect( left, top, right - left, bottom - top, gameColor( color ) );+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::draw_solid_fill( litehtml::uint_ptr hdc, const litehtml::background_layer &layer,+ const litehtml::web_color &color )+{+ if( layer.is_root )+ return;+ fillBox( layer.border_box, color );+}++//-------------------------------------------------------------------------------------------------+/** A line as thick as the box, run along whichever axis the gradient runs further on, one line per+ * pair of stops: the game's two-colour line blends between its ends. */+void HtmlOverlayContainer::draw_linear_gradient( litehtml::uint_ptr hdc, const litehtml::background_layer &layer,+ const litehtml::background_layer::linear_gradient &gradient )+{+ if( layer.is_root || gradient.color_points.empty() )+ return;++ std::vector< litehtml::background_layer::color_point > stops = gradient.color_points;+ if( stops.front().offset > 0 )+ stops.insert( stops.begin(), litehtml::background_layer::color_point( 0, stops.front().color ) );+ if( stops.back().offset < 1 )+ stops.push_back( litehtml::background_layer::color_point( 1, stops.back().color ) );++ const litehtml::position &box = layer.border_box;+ const Real runX = gradient.end.x - gradient.start.x;+ const Real runY = gradient.end.y - gradient.start.y;+ const Bool across = fabsf( runX ) >= fabsf( runY );+ const Int middle = across ? ( screen( box.y ) + screen( box.y + box.height ) ) / 2+ : ( screen( box.x ) + screen( box.x + box.width ) ) / 2;+ const Real thickness = across ? (Real)( screen( box.y + box.height ) - screen( box.y ) )+ : (Real)( screen( box.x + box.width ) - screen( box.x ) );++ for( size_t stop = 0; stop + 1 < stops.size(); stop++ )+ {+ const Color from = gameColor( stops[ stop ].color );+ const Color to = gameColor( stops[ stop + 1 ].color );+ if( across )+ {+ const Int startX = screen( gradient.start.x + runX * stops[ stop ].offset );+ const Int endX = screen( gradient.start.x + runX * stops[ stop + 1 ].offset );+ TheDisplay->drawLine( startX, middle, endX, middle, thickness, from, to );+ }+ else+ {+ const Int startY = screen( gradient.start.y + runY * stops[ stop ].offset );+ const Int endY = screen( gradient.start.y + runY * stops[ stop + 1 ].offset );+ TheDisplay->drawLine( middle, startY, middle, endY, thickness, from, to );+ }+ }+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::draw_radial_gradient( litehtml::uint_ptr hdc, const litehtml::background_layer &layer,+ const litehtml::background_layer::radial_gradient &gradient )+{+ if( !layer.is_root && !gradient.color_points.empty() )+ fillBox( layer.border_box, gradient.color_points.front().color );+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::draw_conic_gradient( litehtml::uint_ptr hdc, const litehtml::background_layer &layer,+ const litehtml::background_layer::conic_gradient &gradient )+{+ if( !layer.is_root && !gradient.color_points.empty() )+ fillBox( layer.border_box, gradient.color_points.front().color );+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::draw_borders( litehtml::uint_ptr hdc, const litehtml::borders &borders,+ const litehtml::position &place, bool root )+{+ if( root )+ return;++ const litehtml::border *sides[] = { &borders.top, &borders.bottom, &borders.left, &borders.right };+ for( size_t side = 0; side < ARRAY_SIZE( sides ); side++ )+ {+ const litehtml::border &border = *sides[ side ];+ if( border.width <= 0 || border.style == litehtml::border_style_none || border.style == litehtml::border_style_hidden )+ continue;++ litehtml::position edge = place;+ if( sides[ side ] == &borders.top )+ edge.height = border.width;+ else if( sides[ side ] == &borders.bottom )+ {+ edge.y = place.y + place.height - border.width;+ edge.height = border.width;+ }+ else if( sides[ side ] == &borders.left )+ edge.width = border.width;+ else+ {+ edge.x = place.x + place.width - border.width;+ edge.width = border.width;+ }+ fillBox( edge, border.color );+ }+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::transform_text( litehtml::string &text, litehtml::text_transform transform )+{+ Bool wordStart = TRUE;+ for( size_t index = 0; index < text.size(); index++ )+ {+ const unsigned char letter = (unsigned char)text[ index ];+ if( transform == litehtml::text_transform_uppercase || ( transform == litehtml::text_transform_capitalize && wordStart ) )+ text[ index ] = (char)toupper( letter );+ else if( transform == litehtml::text_transform_lowercase )+ text[ index ] = (char)tolower( letter );+ wordStart = isspace( letter ) != 0;+ }+}++//-------------------------------------------------------------------------------------------------+/** <link rel="stylesheet" href="x.css"> reads x.css from beside the pages. */+void HtmlOverlayContainer::import_css( litehtml::string &text, const litehtml::string &url, litehtml::string &baseUrl )+{+ const std::string path = std::string( PAGE_FOLDER ) + url;+ File *file = TheFileSystem->openFile( path.c_str(), File::READ | File::BINARY );+ if( file == NULL )+ {+ DEBUG_LOG(( "HtmlOverlay: the stylesheet %s is missing\n", path.c_str() ));+ return;+ }+ const Int size = file->size();+ char *contents = file->readEntireAndClose();+ text.assign( contents, size );+ delete [] contents;+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::get_viewport( litehtml::position &viewport ) const+{+ viewport = litehtml::position( 0, 0, viewportWidth(), viewportHeight() );+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::get_media_features( litehtml::media_features &media ) const+{+ media.type = litehtml::media_type_screen;+ media.width = media.device_width = viewportWidth();+ media.height = media.device_height = viewportHeight();+ media.color = COLOR_BITS;+ media.color_index = 0;+ media.monochrome = 0;+ media.resolution = BROWSER_DPI;+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::get_language( litehtml::string &language, litehtml::string &culture ) const+{+ language = "en";+ culture.clear();+}++//-------------------------------------------------------------------------------------------------+HtmlOverlay::HtmlOverlay( const AsciiString &defaultFont ) :+ m_container( new HtmlOverlayContainer( defaultFont ) )+{+}++//-------------------------------------------------------------------------------------------------+HtmlOverlay::~HtmlOverlay( void )+{+ delete m_container;+}++void HtmlOverlay::setPage( const std::string &html ) { m_container->setPage( html ); }+void HtmlOverlay::draw( void ) { m_container->draw(); }+Bool HtmlOverlay::hover( const ICoord2D &mouse ) { return m_container->hover( mouse ); }+std::string HtmlOverlay::click( const ICoord2D &mouse ) { return m_container->click( mouse ); }+Int HtmlOverlay::bottomOf( const char *selector ) { return m_container->bottomOf( selector ); }diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlPanel.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlPanel.cppdeleted file mode 100644index d4869aafb..000000000--- a/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlPanel.cpp+++ /dev/null@@ -1,376 +0,0 @@-/*-** 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/>.-*/--// HtmlPanel.cpp //////////////////////////////////////////////////////////////////////////////////-// The rows an HTML page describes. See HtmlPanel.h for the part of HTML that is read.-///////////////////////////////////////////////////////////////////////////////////////////////////--#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine--#include "GameClient/HtmlPanel.h"--#include <ctype.h>--namespace-{--struct DetailsFrame-{- Bool open; ///< the open attribute- Int summaryRow; ///< its <summary>'s row, -1 until that has been read-};--struct HtmlTag-{- std::string name; ///< lower case- Bool closing;- std::vector< std::pair< std::string, std::string > > attributes; ///< names lower case, values decoded-- const std::string *attribute( const char *wanted ) const- {- for( size_t index = 0; index < attributes.size(); index++ )- if( attributes[ index ].first == wanted )- return &attributes[ index ].second;- return NULL;- }-};--struct HtmlParse-{- std::vector< HtmlRow > *rows;- std::vector< DetailsFrame > details;- Bool rowOpen; ///< a <label> or <summary> is collecting its words into `row`- HtmlRow row;- std::string looseText; ///< words outside any label, waiting for the tag that ends them-};--struct HtmlEntity-{- const char *name;- const char *text;-};--// becomes a plain space: the panel collapses whitespace and has no line to keep together-const HtmlEntity TheHtmlEntities[] =-{- { "amp", "&" }, { "lt", "<" }, { "gt", ">" }, { "quot", "\"" }, { "apos", "'" }, { "#39", "'" }, { "nbsp", " " }-};--// elements whose content is never a row: a browser's business, or not text at all-const char *const TheSkippedElements[] = { "head", "style", "script", "title" };--// elements that sit inside a line of words, so they do not end the loose text before them-const char *const TheInlineElements[] = { "a", "b", "i", "em", "strong", "span", "small", "code" };--template< size_t COUNT >-Bool isListed( const std::string &name, const char *const (&list)[ COUNT ] )-{- for( size_t index = 0; index < COUNT; index++ )- if( name == list[ index ] )- return TRUE;- return FALSE;-}--std::string decodedEntities( const std::string &raw )-{- std::string decoded;- size_t at = 0;- while( at < raw.size() )- {- Bool replaced = FALSE;- const size_t end = raw[ at ] == '&' ? raw.find( ';', at ) : std::string::npos;- if( end != std::string::npos )- {- const std::string name = raw.substr( at + 1, end - at - 1 );- for( size_t entity = 0; entity < ARRAY_SIZE( TheHtmlEntities ) && !replaced; entity++ )- {- if( name != TheHtmlEntities[ entity ].name )- continue;- decoded += TheHtmlEntities[ entity ].text;- at = end + 1;- replaced = TRUE;- }- }- if( !replaced )- decoded += raw[ at++ ];- }- return decoded;-}--std::string collapsedWhitespace( const std::string &text )-{- std::string collapsed;- Bool gap = FALSE;- for( size_t index = 0; index < text.size(); index++ )- {- const char letter = text[ index ];- if( isspace( (unsigned char)letter ) )- {- gap = !collapsed.empty();- continue;- }- if( gap )- collapsed += ' ';- gap = FALSE;- collapsed += letter;- }- return collapsed;-}--std::string lowered( const std::string &text )-{- std::string lower = text;- for( size_t index = 0; index < lower.size(); index++ )- lower[ index ] = (char)tolower( (unsigned char)lower[ index ] );- return lower;-}--/** The summary row of the nearest <details> round this point, -1 at the top level. A <summary>- * skips its own <details>: it is the row that opens that one, so it belongs to the one outside. */-Int enclosingSummary( const std::vector< DetailsFrame > &details, Bool skipInnermost )-{- for( Int frame = (Int)details.size() - ( skipInnermost ? 2 : 1 ); frame >= 0; frame-- )- if( details[ frame ].summaryRow >= 0 )- return details[ frame ].summaryRow;- return -1;-}--/** Read the tag whose '<' is at `start`, and return the index just past its '>'. */-size_t readTag( const std::string &html, size_t start, HtmlTag &tag )-{- const size_t length = html.size();- size_t at = start + 1;-- tag.closing = at < length && html[ at ] == '/';- if( tag.closing )- at++;- while( at < length && ( isalnum( (unsigned char)html[ at ] ) || html[ at ] == '-' ) )- tag.name += (char)tolower( (unsigned char)html[ at++ ] );-- while( at < length && html[ at ] != '>' )- {- if( isspace( (unsigned char)html[ at ] ) || html[ at ] == '/' )- {- at++;- continue;- }-- std::string name;- while( at < length && !isspace( (unsigned char)html[ at ] ) && strchr( "=>/", html[ at ] ) == NULL )- name += (char)tolower( (unsigned char)html[ at++ ] );- while( at < length && isspace( (unsigned char)html[ at ] ) )- at++;-- std::string value;- if( at < length && html[ at ] == '=' )- {- at++;- while( at < length && isspace( (unsigned char)html[ at ] ) )- at++;- if( at < length && ( html[ at ] == '"' || html[ at ] == '\'' ) )- {- const size_t close = html.find( html[ at ], at + 1 );- const size_t end = close == std::string::npos ? length : close;- value = html.substr( at + 1, end - at - 1 );- at = end == length ? length : end + 1;- }- else- {- while( at < length && !isspace( (unsigned char)html[ at ] ) && html[ at ] != '>' )- value += html[ at++ ];- }- }- tag.attributes.push_back( std::make_pair( name, decodedEntities( value ) ) );- }-- return at < length ? at + 1 : length;-}--void pushRow( HtmlParse &parse, const HtmlRow &row )-{- parse.rows->push_back( row );-}--void flushLooseText( HtmlParse &parse )-{- HtmlRow row;- row.kind = HTML_ROW_TEXT;- row.text = collapsedWhitespace( decodedEntities( parse.looseText ) );- row.owner = enclosingSummary( parse.details, FALSE );- row.open = FALSE;- parse.looseText.clear();-- if( !row.text.empty() )- pushRow( parse, row );-}--void closeRow( HtmlParse &parse )-{- if( !parse.rowOpen )- return;- parse.rowOpen = FALSE;-- HtmlRow &row = parse.row;- row.text = collapsedWhitespace( decodedEntities( row.text ) );- if( row.kind == HTML_ROW_TEXT && row.text.empty() && row.textKey.empty() )- return;-- if( row.kind == HTML_ROW_SUMMARY && !parse.details.empty() && parse.details.back().summaryRow < 0 )- {- parse.details.back().summaryRow = (Int)parse.rows->size();- row.open = parse.details.back().open;- }- pushRow( parse, row );-}--void openRow( HtmlParse &parse, const HtmlTag &tag )-{- closeRow( parse );-- const Bool summary = tag.name == "summary";- const std::string *textKey = tag.attribute( "data-text" );-- parse.rowOpen = TRUE;- parse.row.kind = summary ? HTML_ROW_SUMMARY : HTML_ROW_TEXT;- parse.row.text.clear();- parse.row.textKey = textKey ? *textKey : std::string();- parse.row.name.clear();- parse.row.owner = enclosingSummary( parse.details, summary );- parse.row.open = FALSE;-}--void readCheckbox( HtmlParse &parse, const HtmlTag &tag )-{- const std::string *type = tag.attribute( "type" );- if( type == NULL || lowered( *type ) != "checkbox" )- return;-- const std::string *name = tag.attribute( "name" );- if( parse.rowOpen && parse.row.kind == HTML_ROW_TEXT )- {- parse.row.kind = HTML_ROW_CHECKBOX;- parse.row.name = name ? *name : std::string();- return;- }- if( parse.rowOpen )- return; // a check box inside a <summary> would have two things to do on one click-- HtmlRow row;- row.kind = HTML_ROW_CHECKBOX;- row.name = name ? *name : std::string();- row.owner = enclosingSummary( parse.details, FALSE );- row.open = FALSE;- pushRow( parse, row );-}--void readElement( HtmlParse &parse, const HtmlTag &tag )-{- const Bool rowElement = tag.name == "summary" || tag.name == "label";-- if( tag.closing )- {- if( rowElement )- closeRow( parse );- else if( tag.name == "details" && !parse.details.empty() )- parse.details.pop_back();- return;- }-- if( tag.name == "details" )- {- DetailsFrame frame;- frame.open = tag.attribute( "open" ) != NULL;- frame.summaryRow = -1;- parse.details.push_back( frame );- }- else if( rowElement )- openRow( parse, tag );- else if( tag.name == "input" )- readCheckbox( parse, tag );-}--} // namespace--//--------------------------------------------------------------------------------------------------void HtmlPanel_buildRows( const std::string &html, std::vector< HtmlRow > &rows )-{- rows.clear();-- HtmlParse parse;- parse.rows = &rows;- parse.rowOpen = FALSE;-- const std::string lowerHtml = lowered( html );- const size_t length = html.size();- size_t at = 0;- while( at < length )- {- // a '<' that does not start a tag is a letter, the way a browser reads "a < b"- const Bool tagStart = html[ at ] == '<' && at + 1 < length- && ( isalpha( (unsigned char)html[ at + 1 ] ) || strchr( "/!?", html[ at + 1 ] ) != NULL );- if( !tagStart )- {- const size_t next = html.find( '<', at + 1 );- const size_t end = next == std::string::npos ? length : next;- ( parse.rowOpen ? parse.row.text : parse.looseText ) += html.substr( at, end - at );- at = end;- continue;- }-- if( html.compare( at, 4, "<!--" ) == 0 )- {- const size_t end = html.find( "-->", at );- at = end == std::string::npos ? length : end + 3;- continue;- }- if( html[ at + 1 ] == '!' || html[ at + 1 ] == '?' )- {- const size_t end = html.find( '>', at );- at = end == std::string::npos ? length : end + 1;- continue;- }-- HtmlTag tag;- at = readTag( html, at, tag );-- if( !parse.rowOpen && !isListed( tag.name, TheInlineElements ) )- flushLooseText( parse );-- if( !tag.closing && isListed( tag.name, TheSkippedElements ) )- {- const size_t close = lowerHtml.find( "</" + tag.name, at );- const size_t end = close == std::string::npos ? std::string::npos : html.find( '>', close );- at = end == std::string::npos ? length : end + 1;- continue;- }-- readElement( parse, tag );- }-- closeRow( parse );- flushLooseText( parse );-}--//--------------------------------------------------------------------------------------------------Bool HtmlPanel_isRowShown( const std::vector< HtmlRow > &rows, Int row )-{- for( Int owner = rows[ row ].owner; owner >= 0; owner = rows[ owner ].owner )- if( !rows[ owner ].open )- return FALSE;- return TRUE;-}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlTemplate.cppnew file mode 100644index 000000000..160a18beb--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlTemplate.cpp@@ -0,0 +1,202 @@+/*+** 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/>.+*/++// HtmlTemplate.cpp ///////////////////////////////////////////////////////////////////////////////+// {{name}} and data-each, see HtmlTemplate.h.+///////////////////////////////////////////////////////////////////////////////////////////////////++#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine++#include "GameClient/HtmlTemplate.h"++#include <ctype.h>++namespace+{++const std::string EACH_ATTRIBUTE = "data-each=";+const std::string OPEN_BRACES = "{{";+const std::string CLOSE_BRACES = "}}";++std::string lowered( const std::string &text )+{+ std::string lower = text;+ for( size_t index = 0; index < lower.size(); index++ )+ lower[ index ] = (char)tolower( (unsigned char)lower[ index ] );+ return lower;+}++/** The page without its <!-- comments -->, which may well describe {{names}} and data-each. */+std::string withoutComments( const std::string &page )+{+ std::string kept;+ size_t at = 0;+ for( size_t open = page.find( "<!--" ); open != std::string::npos; open = page.find( "<!--", at ) )+ {+ kept.append( page, at, open - at );+ const size_t close = page.find( "-->", open );+ if( close == std::string::npos )+ return kept;+ at = close + 3;+ }+ kept.append( page, at, std::string::npos );+ return kept;+}++std::string trimmed( const std::string &text )+{+ size_t first = 0;+ size_t last = text.size();+ while( first < last && isspace( (unsigned char)text[ first ] ) )+ first++;+ while( last > first && isspace( (unsigned char)text[ last - 1 ] ) )+ last--;+ return text.substr( first, last - first );+}++std::string valueOf( const std::string &name, const HtmlValues *entry, const HtmlValues &values, const HtmlLookup &lookup )+{+ if( entry )+ {+ HtmlValues::const_iterator found = entry->find( name );+ if( found != entry->end() )+ return found->second;+ }++ HtmlValues::const_iterator found = values.find( name );+ if( found != values.end() )+ return found->second;++ std::string looked;+ if( lookup && lookup( name, looked ) )+ return looked;+ return std::string();+}++std::string filled( const std::string &text, const HtmlValues *entry, const HtmlValues &values, const HtmlLookup &lookup )+{+ std::string out;+ size_t at = 0;+ for( ;; )+ {+ const size_t open = text.find( OPEN_BRACES, at );+ const size_t close = open == std::string::npos ? std::string::npos : text.find( CLOSE_BRACES, open + OPEN_BRACES.size() );+ if( close == std::string::npos )+ {+ out.append( text, at, std::string::npos );+ return out;+ }++ out.append( text, at, open - at );+ const std::string name = trimmed( text.substr( open + OPEN_BRACES.size(), close - open - OPEN_BRACES.size() ) );+ out += HtmlTemplate_escape( valueOf( name, entry, values, lookup ) );+ at = close + CLOSE_BRACES.size();+ }+}++/** Just past the end tag of the element whose start tag is at `open`, counting elements of the same+ * name nested inside it.+ * ponytail: an element with no end tag (<img data-each>) runs to the end of the page; wrap it in a+ * <div data-each> if that ever matters. */+size_t elementEnd( const std::string &lower, size_t open, const std::string &tag )+{+ Int depth = 0;+ for( size_t at = lower.find( '<', open ); at != std::string::npos; at = lower.find( '<', at + 1 ) )+ {+ const Bool closing = at + 1 < lower.size() && lower[ at + 1 ] == '/';+ const size_t nameAt = at + ( closing ? 2 : 1 );+ const size_t after = nameAt + tag.size();+ if( lower.compare( nameAt, tag.size(), tag ) != 0 || after >= lower.size() || strchr( " \t\r\n/>", lower[ after ] ) == NULL )+ continue;++ depth += closing ? -1 : 1;+ if( depth == 0 )+ {+ const size_t end = lower.find( '>', at );+ return end == std::string::npos ? lower.size() : end + 1;+ }+ }+ return lower.size();+}++} // namespace++//-------------------------------------------------------------------------------------------------+std::string HtmlTemplate_escape( const std::string &text )+{+ std::string escaped;+ for( size_t index = 0; index < text.size(); index++ )+ {+ switch( text[ index ] )+ {+ case '&': escaped += "&"; break;+ case '<': escaped += "<"; break;+ case '>': escaped += ">"; break;+ case '"': escaped += """; break;+ case '\'': escaped += "'"; break;+ default: escaped += text[ index ]; break;+ }+ }+ return escaped;+}++//-------------------------------------------------------------------------------------------------+std::string HtmlTemplate_expand( const std::string &written, const HtmlValues &values,+ const HtmlLists &lists, const HtmlLookup &lookup )+{+ const std::string page = withoutComments( written );+ const std::string lower = lowered( page );+ std::string out;+ size_t at = 0;+ for( ;; )+ {+ const size_t attribute = lower.find( EACH_ATTRIBUTE, at );+ const size_t open = attribute == std::string::npos ? std::string::npos : lower.rfind( '<', attribute );+ if( open == std::string::npos || open < at )+ {+ out += filled( page.substr( at ), NULL, values, lookup );+ return out;+ }++ size_t nameAt = attribute + EACH_ATTRIBUTE.size();+ const char quote = nameAt < page.size() ? page[ nameAt ] : 0;+ const Bool quoted = quote == '"' || quote == '\'';+ if( quoted )+ nameAt++;+ size_t nameEnd = nameAt;+ while( nameEnd < page.size() && ( quoted ? page[ nameEnd ] != quote : strchr( " \t\r\n>", page[ nameEnd ] ) == NULL ) )+ nameEnd++;+ const std::string listName = page.substr( nameAt, nameEnd - nameAt );++ size_t tagEnd = open + 1;+ while( tagEnd < lower.size() && isalnum( (unsigned char)lower[ tagEnd ] ) )+ tagEnd++;+ const std::string tag = lower.substr( open + 1, tagEnd - open - 1 );+ const size_t end = elementEnd( lower, open, tag );++ out += filled( page.substr( at, open - at ), NULL, values, lookup );++ const std::string element = page.substr( open, end - open );+ HtmlLists::const_iterator list = lists.find( listName );+ if( list != lists.end() )+ for( size_t entry = 0; entry < list->second.size(); entry++ )+ out += filled( element, &list->second[ entry ], values, lookup );++ at = end;+ }+}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cppindex a94159719..f3fedbe55 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp@@ -64,6 +64,7 @@#include "Common/FileSystem.h"#include "Common/file.h"#include "GameNetwork/GameSpy/ThreadUtils.h"+#include "GameClient/HtmlOverlay.h"#include "GameClient/GameWindowManager.h"#include "GameClient/Drawable.h"#include "GameClient/GadgetPushButton.h"@@ -1188,7 +1189,10 @@ InGameUI::InGameUI()m_productionStripTraySource = NULL;for( Int stripString = 0; stripString < STRIP_OVERFLOW_STRINGS; stripString++ )m_productionStripOverflow[ stripString ] = NULL;- m_hudTogglesLoaded = FALSE;+ m_spectatorOverlay = NULL;+ m_spectatorPageLoaded = FALSE;+ m_spectatorPageShown = FALSE;+ m_spectatorListsFrame = 0;m_hudTogglesBottom = 0;m_scoreboardOpen = FALSE;m_scoreboardStringsUsed = 0;@@ -1309,7 +1313,8 @@ InGameUI::~InGameUI()m_productionStripTraySource = NULL;}- freeHudToggleStrings();+ delete m_spectatorOverlay;+ m_spectatorOverlay = NULL;}//-------------------------------------------------------------------------------------------------@@ -1732,17 +1737,22 @@ static Real elevatedReach( Real reach, Real range, const Coord3D ¢er, Real a}//--------------------------------------------------------------------------------------------------// The top left drop-down is a page: its rows come from this file, and each check box in it names-// the Options.ini key it flips. A loose copy under Run/ beats the archive, so it can be edited-// between two matches without a build.+// The spectator's page. A loose copy under Run/ beats the archive, so it can be edited between two+// matches without a build. What a data-click names is also the {{name}} that reads it back:+// data-click="option:Key" flips that on/off option and {{option:Key}} is "on" while it is on;+// data-click="flip:name" flips a switch that lasts the match and {{flip:name}} is "flipped" while+// it is flipped. {{text:Label}} is a string table label in the player's language.//--------------------------------------------------------------------------------------------------static const char *const HUD_TOGGLES_PAGE = "Window\\Html\\HudToggles.html";+static const char *const SPECTATOR_PAGE = "Window\\Html\\Spectator.html";+static const std::string OPTION_ACTION = "option:";+static const std::string FLIP_ACTION = "flip:";+static const std::string TEXT_LOOKUP = "text:";enum{- HUD_TOGGLES_INSET = 6, ///< from the top and left edges of the screen, 800x600- HUD_TOGGLES_WIDTH = 150, ///< the drop-down's narrowest width, 800x600; longer words widen it- HUD_TOGGLES_PAD = 3 ///< round the words and the boxes inside a row, 800x600+ HUD_TOGGLES_INSET = 6, ///< between the page's #hud-top and the messages under it, 800x600+ NET_WORTH_REFRESH_FRAMES = LOGICFRAMES_PER_SECOND / 2, ///< how often every player's worth is counted again+ PERCENT = 100};//-------------------------------------------------------------------------------------------------@@ -1764,190 +1774,198 @@ static Bool stripSwitchedOff( Bool GlobalData::* flag )}//--------------------------------------------------------------------------------------------------/** Read the drop-down's page and make a string for each of its rows. A check box whose name is not- * an on/off option has nothing to flip, so it is shown as its words alone. */+/** {{text:Label}}: a string table label, in the player's language. *///--------------------------------------------------------------------------------------------------void InGameUI::loadHudToggles( void )+static Bool lookupGameText( const std::string &name, std::string &value ){- m_hudTogglesLoaded = TRUE;- freeHudToggleStrings();- m_hudToggleRows.clear();- m_hudToggleRects.clear();+ if( name.compare( 0, TEXT_LOOKUP.size(), TEXT_LOOKUP ) != 0 )+ return FALSE;+ value = WideCharStringToMultiByte( TheGameText->fetch( name.substr( TEXT_LOOKUP.size() ).c_str() ).str() );+ return TRUE;+}- File *file = TheFileSystem->openFile( HUD_TOGGLES_PAGE, File::READ | File::BINARY );- if( file == NULL )- {- DEBUG_LOG(( "HUD toggles: %s is missing, so the drop-down is not drawn\n", HUD_TOGGLES_PAGE ));- return;- }- const Int size = file->size();- char *page = file->readEntireAndClose();- HtmlPanel_buildRows( std::string( page, size ), m_hudToggleRows );- delete [] page;+//-------------------------------------------------------------------------------------------------+static std::string cssColor( Color color )+{+ UnsignedByte red, green, blue, alpha;+ GameGetColorComponents( color, &red, &green, &blue, &alpha );+ char text[ sizeof( "#rrggbb" ) ];+ sprintf( text, "#%02x%02x%02x", red, green, blue );+ return text;+}- GameFont *font = TheFontLibrary->getFont( m_superweaponNormalFont,- TheGlobalLanguageData->adjustFontSize( HUD_OVERLAY_POINT_SIZE ), TRUE );- for( size_t row = 0; row < m_hudToggleRows.size(); row++ )- {- HtmlRow &html = m_hudToggleRows[ row ];- if( html.kind == HTML_ROW_CHECKBOX )- {- const OptionDef *option = findOptionDef( html.name.c_str() );- if( option == NULL || option->kind != OPTION_BOOL )- {- DEBUG_LOG(( "HUD toggles: check box name=\"%s\" in %s is not an on/off option\n", html.name.c_str(), HUD_TOGGLES_PAGE ));- html.kind = HTML_ROW_TEXT;- }- }+struct NetWorthGather+{+ const Player *player;+ Int worth;+};- DisplayString *words = TheDisplayStringManager->newDisplayString();- words->setFont( font );- if( html.textKey.empty() )- words->setText( UnicodeString( MultiByteToWideCharSingleLine( html.text.c_str() ).c_str() ) );- else- words->setText( TheGameText->fetch( html.textKey.c_str() ) );- m_hudToggleStrings.push_back( words );- }- m_hudToggleRects.resize( m_hudToggleRows.size() );+static void addObjectWorth( Object *obj, void *userData )+{+ NetWorthGather *gather = (NetWorthGather *)userData;+ if( !obj->isEffectivelyDead() )+ gather->worth += obj->getTemplate()->calcCostToBuild( gather->player );}//--------------------------------------------------------------------------------------------------void InGameUI::freeHudToggleStrings( void )+/** The page's "players" list: everyone still in the match, richest first, each with what his cash+ * and everything he has standing would cost to buy again. Allies both ways share a team number,+ * counted in the order the teams first appear in the player list, and every entry carries how+ * many teams there are, so a page can colour two sides the way Dota does and leave a free for all+ * in the players' own colours. */+//-------------------------------------------------------------------------------------------------+static void gatherNetWorth( std::vector< HtmlValues > &rows ){- for( size_t row = 0; row < m_hudToggleStrings.size(); row++ )- TheDisplayStringManager->freeDisplayString( m_hudToggleStrings[ row ] );- m_hudToggleStrings.clear();+ struct Worth+ {+ Player *player;+ Int worth;+ Int team;+ };+ std::vector< Worth > worths;+ const Player *local = ThePlayerList->getLocalPlayer();+ Int teams = 0;+ for( Int index = 0; index < ThePlayerList->getPlayerCount(); index++ )+ {+ Player *player = ThePlayerList->getNthPlayer( index );+ if( player == NULL || player == local || !player->isPlayerActive() || !player->isPlayableSide() )+ continue;++ NetWorthGather gather;+ gather.player = player;+ gather.worth = player->getMoney()->countMoney();+ player->iterateObjects( addObjectWorth, &gather );++ Worth worth = { player, gather.worth, -1 };+ for( size_t earlier = 0; earlier < worths.size() && worth.team < 0; earlier++ )+ {+ const Player *other = worths[ earlier ].player;+ if( player->getRelationship( other->getDefaultTeam() ) == ALLIES && other->getRelationship( player->getDefaultTeam() ) == ALLIES )+ worth.team = worths[ earlier ].team;+ }+ if( worth.team < 0 )+ worth.team = teams++;+ worths.push_back( worth );+ }++ std::stable_sort( worths.begin(), worths.end(), []( const Worth &a, const Worth &b ) { return a.worth > b.worth; } );+ const Int richest = worths.empty() ? 0 : worths.front().worth;++ rows.clear();+ for( size_t index = 0; index < worths.size(); index++ )+ {+ const Worth &worth = worths[ index ];+ const PlayerTemplate *side = worth.player->getPlayerTemplate();+ const Image *portrait = side ? side->getEnabledImage() : NULL;++ HtmlValues row;+ row[ "name" ] = WideCharStringToMultiByte( worth.player->getPlayerDisplayName().str() );+ row[ "networth" ] = std::to_string( worth.worth );+ row[ "share" ] = std::to_string( richest > 0 ? worth.worth * PERCENT / richest : 0 );+ row[ "color" ] = cssColor( clientPlayerColor( worth.player ) );+ row[ "team" ] = std::to_string( worth.team );+ row[ "teams" ] = std::to_string( teams );+ row[ "portrait" ] = portrait ? portrait->getName().str() : "";+ rows.push_back( row );+ }}//--------------------------------------------------------------------------------------------------/** The strips over the battlefield, switched on and off from a drop-down in the top left corner.+/** The spectator's page: the drop-down that switches the strips on and off, and every player's net+ * worth.*- * Watching a match three of them fight over the same picture - the production rows, the+ * Watching a match three strips fight over the same picture - the production rows, the* promotions, the superweapon countdowns - and which of them a spectator wants depends on what he- * is watching for. Closed it is one line with a plus in it. Each box flips its option the moment- * it is clicked and saves the choice with the rest of the options. Only while watching: playing,- * the top left corner belongs to the messages. */+ * is watching for. Each box flips its option the moment it is clicked and saves the choice with+ * the rest of the options. Only while watching: playing, the top left corner belongs to the+ * messages, and the other side's worth is not a player's to know. *///--------------------------------------------------------------------------------------------------void InGameUI::drawHudToggles( void )+void InGameUI::drawSpectatorPage( void ){m_hudTogglesBottom = 0;- for( size_t row = 0; row < m_hudToggleRects.size(); row++ )- m_hudToggleRects[ row ].lo = m_hudToggleRects[ row ].hi = ICoord2D();+ m_spectatorPageShown = FALSE;if( TheGameLogic == NULL || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame() )return;if( !localPlayerWatching() )return;- if( !m_hudTogglesLoaded )- loadHudToggles();- if( m_hudToggleRows.empty() )- return;-- const Int pad = stripPixels( HUD_TOGGLES_PAD );- const Int left = stripPixels( HUD_TOGGLES_INSET );- const Int top = stripPixels( HUD_TOGGLES_INSET );- const Int box = m_hudToggleStrings[ 0 ]->getFont()->height;- const Int rowH = box + 2 * pad;- const Color plate = GameMakeColor( 0, 0, 0, 150 );- const Color edge = GameMakeColor( 200, 200, 200, 255 );- const Color on = GameMakeColor( 90, 200, 90, 255 );- const Color words = GameMakeColor( 235, 235, 235, 255 );- const Color shade = GameMakeColor( 0, 0, 0, 255 );-- // one width for every row, so the plates stack into one panel- Int width = stripPixels( HUD_TOGGLES_WIDTH );- for( Int row = 0; row < (Int)m_hudToggleRows.size(); row++ )- {- if( !HtmlPanel_isRowShown( m_hudToggleRows, row ) )- continue;- Int textW = 0, textH = 0;- m_hudToggleStrings[ row ]->getSize( &textW, &textH );- width = max( width, box + textW + 3 * pad );- }-- TheDisplay->beginBatch2D();-- Int y = top;- for( Int row = 0; row < (Int)m_hudToggleRows.size(); row++ )+ if( !m_spectatorPageLoaded ){- if( !HtmlPanel_isRowShown( m_hudToggleRows, row ) )- continue;-- const HtmlRow &html = m_hudToggleRows[ row ];- IRegion2D *rect = &m_hudToggleRects[ row ];- rect->lo.x = left;- rect->lo.y = y;- rect->hi.x = left + width;- rect->hi.y = y + rowH;-- TheDisplay->drawFillRect( left, y, width, rowH, plate );-- const Int boxX = left + pad;- const Int boxY = y + pad;- Int wordsX = boxX;- if( html.kind != HTML_ROW_TEXT )+ m_spectatorPageLoaded = TRUE;+ m_spectatorPage.clear();+ File *file = TheFileSystem->openFile( SPECTATOR_PAGE, File::READ | File::BINARY );+ if( file == NULL ){- TheDisplay->drawOpenRect( boxX, boxY, box, box, 1.0f, edge );- wordsX = boxX + box + 2 * pad;- }-- if( html.kind == HTML_ROW_SUMMARY )- {- // a minus to close it, a plus to open it- const Int middleY = boxY + box / 2;- const Int middleX = boxX + box / 2;- TheDisplay->drawLine( boxX + pad, middleY, boxX + box - pad, middleY, 2.0f, edge );- if( !html.open )- TheDisplay->drawLine( middleX, boxY + pad, middleX, boxY + box - pad, 2.0f, edge );- }- else if( html.kind == HTML_ROW_CHECKBOX && findOptionDef( html.name.c_str() )->get() )- {- TheDisplay->drawFillRect( boxX + pad, boxY + pad, box - 2 * pad, box - 2 * pad, on );+ DEBUG_LOG(( "Spectator page: %s is missing, so nothing is drawn over the battlefield\n", SPECTATOR_PAGE ));+ return;}+ const Int size = file->size();+ char *page = file->readEntireAndClose();+ m_spectatorPage.assign( page, size );+ delete [] page;+ }+ if( m_spectatorPage.empty() )+ return;+ if( m_spectatorOverlay == NULL )+ m_spectatorOverlay = new HtmlOverlay( m_superweaponNormalFont );- m_hudToggleStrings[ row ]->draw( wordsX, y + pad, words, shade );- y += rowH;+ const UnsignedInt frame = TheGameLogic->getFrame();+ if( m_spectatorLists.empty() || frame < m_spectatorListsFrame || frame >= m_spectatorListsFrame + NET_WORTH_REFRESH_FRAMES )+ {+ gatherNetWorth( m_spectatorLists[ "players" ] );+ m_spectatorListsFrame = frame;}- TheDisplay->endBatch2D();+ HtmlValues values;+ for( Int row = 0; row < TheOptionCatalogCount; row++ )+ if( TheOptionCatalog[ row ].kind == OPTION_BOOL && TheOptionCatalog[ row ].get() )+ values[ OPTION_ACTION + TheOptionCatalog[ row ].iniKey ] = "on";+ for( std::set< std::string >::const_iterator name = m_spectatorFlipped.begin(); name != m_spectatorFlipped.end(); ++name )+ values[ FLIP_ACTION + *name ] = "flipped";- m_hudTogglesBottom = y;+ m_spectatorOverlay->setPage( HtmlTemplate_expand( m_spectatorPage, values, m_spectatorLists, lookupGameText ) );+ m_spectatorOverlay->hover( TheMouse->getMouseStatus()->pos );+ m_spectatorOverlay->draw();+ m_spectatorPageShown = TRUE;+ m_hudTogglesBottom = m_spectatorOverlay->bottomOf( "#hud-top" );}//--------------------------------------------------------------------------------------------------/** A click on the drop-down is the drop-down's, whatever button it was, so it never becomes a move- * order into the ground under it. Only a plain left click does anything. */+/** A click on something the page drew is the page's, whatever button it was, so it never becomes a+ * move order into the ground under it. Only a plain left click does anything. *///--------------------------------------------------------------------------------------------------Bool InGameUI::handleHudTogglesClick( const ICoord2D *mouse, Bool act )+Bool InGameUI::handleSpectatorPageClick( const ICoord2D *mouse, Bool act ){- for( size_t row = 0; row < m_hudToggleRects.size(); row++ )- {- const IRegion2D &rect = m_hudToggleRects[ row ];- if( mouse->x < rect.lo.x || mouse->x >= rect.hi.x || mouse->y < rect.lo.y || mouse->y >= rect.hi.y )- continue;+ if( !m_spectatorPageShown || !m_spectatorOverlay->hover( *mouse ) )+ return FALSE;+ if( !act )+ return TRUE;- if( !act )+ const std::string action = m_spectatorOverlay->click( *mouse );+ if( action.compare( 0, FLIP_ACTION.size(), FLIP_ACTION ) == 0 )+ {+ const std::string name = action.substr( FLIP_ACTION.size() );+ if( m_spectatorFlipped.erase( name ) == 0 )+ m_spectatorFlipped.insert( name );+ }+ else if( action.compare( 0, OPTION_ACTION.size(), OPTION_ACTION ) == 0 )+ {+ const OptionDef *option = findOptionDef( action.substr( OPTION_ACTION.size() ).c_str() );+ if( option == NULL || option->kind != OPTION_BOOL )+ {+ DEBUG_LOG(( "Spectator page: data-click=\"%s\" names no on/off option\n", action.c_str() ));return TRUE;+ }- HtmlRow &html = m_hudToggleRows[ row ];- if( html.kind == HTML_ROW_SUMMARY )- html.open = !html.open;+ const Bool now = !option->get();+ option->set( now );- if( html.kind == HTML_ROW_CHECKBOX )- {- const OptionDef *option = findOptionDef( html.name.c_str() );- const Bool now = !option->get();- option->set( now );-- OptionPreferences pref;- pref[ AsciiString( option->iniKey ) ] = AsciiString( now ? "yes" : "no" );- pref.write();- }- return TRUE;+ OptionPreferences pref;+ pref[ AsciiString( option->iniKey ) ] = AsciiString( now ? "yes" : "no" );+ pref.write();}-- return FALSE;+ return TRUE;}//-------------------------------------------------------------------------------------------------@@ -3374,7 +3392,9 @@ void InGameUI::reset( void ){m_isQuitMenuVisible = FALSE;m_scoreboardOpen = FALSE;- m_hudTogglesLoaded = FALSE;+ m_spectatorPageLoaded = FALSE;+ m_spectatorFlipped.clear();+ m_spectatorLists.clear();m_inputEnabled = true;// reset the command barTheControlBar->reset();@@ -6654,7 +6674,7 @@ void InGameUI::postDraw( void )drawSkillStrip(); // the same shelf, the other end of itdrawBlindSpots();drawPlacementReach(); // after the shade, so the outline stays bright over it- drawHudToggles();+ drawSpectatorPage();// render our display strings for the messages if on@@ -10329,7 +10349,7 @@ Bool InGameUI::handleProductionStripClick( const ICoord2D *mouse, Bool cancel )return FALSE;// the strip drop-down lies over the world the same way the strip does, so its clicks come here too- if( handleHudTogglesClick( mouse, !cancel ) )+ if( handleSpectatorPageClick( mouse, !cancel ) )return TRUE;for( Int row = 0; row < PRODUCTION_STRIP_ROWS; row++ )diff --git a/GeneralsMD/Code/Libraries/Source/litehtml/.gitignore b/GeneralsMD/Code/Libraries/Source/litehtml/.gitignorenew file mode 100644index 000000000..5e7d2734c--- /dev/null+++ b/GeneralsMD/Code/Libraries/Source/litehtml/.gitignore@@ -0,0 +1,4 @@+# Ignore everything in this directory+*+# Except this file+!.gitignorediff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 548d5f8e5..2177c9914 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -46,7 +46,7 @@#include "GameClient/ChromaKeyboard.h"#include "GameClient/MetaEvent.h"#include "GameClient/ClickTolerance.h"-#include "GameClient/HtmlPanel.h"+#include "GameClient/HtmlTemplate.h"#include "GameClient/KeyDownInfo.h"#include "GameClient/GameWindowTransitions.h"#include "GameLogic/ScenarioDrill.h"@@ -13527,70 +13527,52 @@ TEST(chroma_money_bar_is_a_thousand_credits_a_lamp)CHECK_EQ(chromaMoneySegments(400000, 15), 15);}-// A page reads as the column a browser would show: the summary first, the rows of its details-// under it and hidden while it is closed, and the head never a row even though it holds words.-TEST(html_panel_reads_details_labels_and_loose_text)+// A page's {{names}} take the entry's value first, then the page's, then the lookup's, and nothing+// at all when none of them knows it; comments go; a data-each element is written once per entry, nested+// elements of the same name inside it included, and a player's name cannot open a tag.+TEST(html_template_fills_values_and_repeats_each){const std::string page =- "<!DOCTYPE html><html><head><title>Not a row</title><style>label { display: block; }</style></head>"- "<body><!-- nor this -->"- "<details><SUMMARY data-text=\"GUI:Top\">Top</SUMMARY>"- "<label><input type=checkbox name='First'> First &\n one </label>"- "<details open><summary>Inner</summary><input type=\"checkbox\" name=\"Second\"></details>"- "Words a < b</details>"- "<p>Out<b>side</b></p></body></html>";-- std::vector< HtmlRow > rows;- HtmlPanel_buildRows( page, rows );-- CHECK_EQ( (Int)rows.size(), 6 );- if( rows.size() != 6 )- return;-- CHECK_EQ( (Int)rows[ 0 ].kind, (Int)HTML_ROW_SUMMARY );- CHECK( rows[ 0 ].textKey == "GUI:Top" );- CHECK_EQ( rows[ 0 ].owner, -1 );- CHECK( !rows[ 0 ].open );-- CHECK_EQ( (Int)rows[ 1 ].kind, (Int)HTML_ROW_CHECKBOX );- CHECK( rows[ 1 ].name == "First" );- CHECK( rows[ 1 ].text == "First & one" );- CHECK_EQ( rows[ 1 ].owner, 0 );-- CHECK_EQ( (Int)rows[ 2 ].kind, (Int)HTML_ROW_SUMMARY );- CHECK( rows[ 2 ].text == "Inner" );- CHECK_EQ( rows[ 2 ].owner, 0 );- CHECK( rows[ 2 ].open );-- CHECK_EQ( (Int)rows[ 3 ].kind, (Int)HTML_ROW_CHECKBOX );- CHECK( rows[ 3 ].name == "Second" );- CHECK_EQ( rows[ 3 ].owner, 2 );-- CHECK_EQ( (Int)rows[ 4 ].kind, (Int)HTML_ROW_TEXT );- CHECK( rows[ 4 ].text == "Words a < b" );- CHECK_EQ( rows[ 4 ].owner, 0 );-- CHECK( rows[ 5 ].text == "Outside" );- CHECK_EQ( rows[ 5 ].owner, -1 );-- // the outer details is closed, so only its summary and what lies outside it are shown- CHECK( HtmlPanel_isRowShown( rows, 0 ) );- CHECK( !HtmlPanel_isRowShown( rows, 1 ) );- CHECK( !HtmlPanel_isRowShown( rows, 3 ) );- CHECK( HtmlPanel_isRowShown( rows, 5 ) );+ "<!-- a comment may describe {{title}} and data-each=\"players\" -->"+ "<p class=\"{{option:A}}\">{{ title }}</p>"+ "<ul><li class=\"t{{team}}\" data-each=\"players\"><li>{{name}}</li>{{missing}}</li></ul>"+ "<div data-each='nobody'>gone</div>{{text:Label}}";++ HtmlValues values;+ values[ "option:A" ] = "on";+ values[ "title" ] = "T";+ values[ "team" ] = "9";++ HtmlLists lists;+ HtmlValues first;+ first[ "name" ] = "<b>&";+ HtmlValues second;+ second[ "name" ] = "Bo";+ second[ "team" ] = "1";+ lists[ "players" ].push_back( first );+ lists[ "players" ].push_back( second );++ const HtmlLookup lookup = []( const std::string &name, std::string &value ) -> Bool+ {+ if( name != "text:Label" )+ return FALSE;+ value = "looked";+ return TRUE;+ };- rows[ 0 ].open = TRUE;- CHECK( HtmlPanel_isRowShown( rows, 1 ) );- CHECK( HtmlPanel_isRowShown( rows, 3 ) );- rows[ 2 ].open = FALSE;- CHECK( !HtmlPanel_isRowShown( rows, 3 ) );+ CHECK_STR( HtmlTemplate_expand( page, values, lists, lookup ).c_str(),+ "<p class=\"on\">T</p>"+ "<ul><li class=\"t9\" data-each=\"players\"><li><b>&</li></li>"+ "<li class=\"t1\" data-each=\"players\"><li>Bo</li></li></ul>"+ "looked" );+ CHECK_STR( HtmlTemplate_escape( "a\"b'c" ).c_str(), "a"b'c" );}-// The spectator's drop-down is the shipped page. A check box whose name is not an on/off option-// would draw as words with nothing to flip, and only a match would show it.-TEST(the_hud_toggles_page_binds_only_on_off_options)+// The spectator's page is the shipped one. A data-click naming something that is not an on/off+// option draws a box that does nothing, and only a watched match would show it.+TEST(the_spectator_page_names_only_on_off_options){- FILE *fp = fopen( HUD_TOGGLES_HTML, "rb" );+ FILE *fp = fopen( SPECTATOR_HTML, "rb" );CHECK( fp != NULL );if( fp == NULL )return;@@ -13602,21 +13584,19 @@ TEST(the_hud_toggles_page_binds_only_on_off_options)page.append( chunk, got );fclose( fp );- std::vector< HtmlRow > rows;- HtmlPanel_buildRows( page, rows );-- Int checkboxes = 0;- for( size_t row = 0; row < rows.size(); row++ )+ const std::string click = "data-click=\"option:";+ Int options = 0;+ for( size_t at = page.find( click ); at != std::string::npos; at = page.find( click, at + 1 ) ){- if( rows[ row ].kind != HTML_ROW_CHECKBOX )- continue;- checkboxes++;- const OptionDef *option = findOptionDef( rows[ row ].name.c_str() );- CHECK( option != NULL );+ const size_t nameAt = at + click.size();+ const std::string name = page.substr( nameAt, page.find( '"', nameAt ) - nameAt );+ const OptionDef *option = findOptionDef( name.c_str() );CHECK( option != NULL && option->kind == OPTION_BOOL );+ options++;}- CHECK_EQ( checkboxes, 3 );- CHECK( !rows.empty() && rows[ 0 ].kind == HTML_ROW_SUMMARY );+ CHECK_EQ( options, 3 );+ CHECK( page.find( "id=\"hud-top\"" ) != std::string::npos );+ CHECK( page.find( "data-each=\"players\"" ) != std::string::npos );}#include "test_camera_behavior.inc"diff --git a/GeneralsMD/Code/Tools/vendor.ps1 b/GeneralsMD/Code/Tools/vendor.ps1index cb453ed24..98286f263 100644--- a/GeneralsMD/Code/Tools/vendor.ps1+++ b/GeneralsMD/Code/Tools/vendor.ps1@@ -115,6 +115,23 @@ function Install-GameSpy {Step "GamespySDK -> Libraries\Source\GameSpy"}+# --- litehtml 0.10, whole repository: the HTML and CSS layout engine behind the pages drawn over+# the battlefield. Its CMakeLists builds the bundled gumbo parser as well. Same .gitignore dance as+# GameSpy, for the same reason.+function Install-Litehtml {+ $destination = Join-Path $libraries 'Source\litehtml'+ if ((Test-Path (Join-Path $destination 'CMakeLists.txt')) -and -not $Force) { return }+ $archive = Get-File 'https://github.com/litehtml/litehtml/archive/9bc84b8b8d15a4e50f18b327aa30955048b441c2.zip' (Join-Path $work 'litehtml-0.10.zip')+ $source = Expand-Source $archive 'litehtml'+ $keep = Join-Path $destination '.gitignore'+ $kept = if (Test-Path $keep) { Get-Content $keep -Raw } else { $null }+ if (Test-Path $destination) { Remove-Item -Recurse -Force $destination }+ New-Item -ItemType Directory -Force -Path $destination | Out-Null+ Copy-Item (Join-Path $source '*') $destination -Recurse -Force+ if ($null -ne $kept) { Set-Content -Path $keep -Value $kept -NoNewline }+ Step "litehtml 0.10 -> Libraries\Source\litehtml"+}+# --- The fork's own upscaled art: every 3D texture at twice its size, the normal maps the models# are lit through, and the ground. Not in git - ReforgedTextures.big alone is a gigabyte, ten times# what GitHub takes in a file, and LFS in a fork is billed to the parent repository.@@ -217,5 +234,6 @@ Install-ZlibInstall-LzhlInstall-DirectXInstall-GameSpy+Install-LitehtmlInstall-ArtStep 'everything the build needs is in place'