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
perf: skip unseen shadow casters, cache hud templates and dx11 lookups
Olcay Seygana1c7b61a7e7a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex df5a25f07..c20a9d1d2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -100,7 +100,7 @@ found and fixed — EA's own, not port damage.**- The command bar stopped throwing its own layout away every frame. The few hundred positions and sizes it hands its page were written into a fresh list each frame, copied twice for the frames in front of the buttons, and thrown out, and every price and build time on a button was looked up by copying the text of every figure the bar was already showing. The list is written over in place now, nothing is copied, and the graphics card settings that did not change between two draws are not looked up again. The same Twilight Flame match from a player's seat went from 2.29ms a frame to 1.96ms, and as an observer from 1.64ms to 1.58ms. The picture is the same one.- Raise the particle limit as far as you like and every puff gets drawn. Past about sixteen thousand smoke and fire sprites on screen the game quietly stopped drawing the rest: a test with 68,000 of them showed barely a fifth. A test with 101,000 now draws all of them at 8.3ms a frame, and in 1,200 frames not one fell below 60 a second. The first version that drew them all took 22.4ms; the rest came from sorting and copying them far less and from sharing the work across every core of the processor.- Big fights no longer drag the picture down into the twenties. Every moving tank and soldier, and every puff of smoke, goes to the graphics card through one shared scratch area, and it was so small that a big fight on Bombardment Beach filled it about fifty times a frame. Each refill made the processor wait for the card, 8 to 12ms of every frame, while the card sat two thirds idle. The area is made full size once now and refills about seven times a frame, in 0.02ms. The same 16,000-frame battle, fast-forwarded, finishes in 226 seconds where it took between 263 and 325, and the seconds that fell under 50 frames a second went from 125 or more to 4.-- Crowded battles run a good deal faster. At 1080p, thirty Inferno Cannons against twenty Crusaders went from 153 to 217 frames a second, and six Brutal computer players on one map from 147 to 183. The slowest one frame in twenty got 17 to 18% shorter, and the slowest one in a hundred 15%. The game stopped re-sending lights, materials, textures and card settings that had not changed, stopped relighting the terrain when no light had moved, stopped adding up the glow of every fire particle twice, and widened 16-bit textures with a lookup instead of arithmetic on each pixel. The new renderer keeps the old one's settings back until something actually reads them, rebuilds a draw's constants only for the half that changed, and remembers each patch of ground's colours, its blend coordinates and its tread marks between frames. The command bar and the console replay what they drew last frame when nothing under them moved. The rules side runs 4% quicker too: locking, the lists of nearby units, the sleeping-unit schedule and text strings all got cheaper. The picture matches the old build in all eight test views on both renderers, and a recorded match plays back to the same checksum.+- Crowded battles run a good deal faster. At 1080p, thirty Inferno Cannons against twenty Crusaders went from 153 to 227 frames a second, and six Brutal computer players on one map from 146 to 240. The slowest one frame in twenty got 22 to 34% shorter, and the slowest one in a hundred 16 to 29%. The game stopped re-sending lights, materials, textures and card settings that had not changed, stopped relighting the terrain when no light had moved, stopped adding up the glow of every fire particle twice, and widened low-colour textures with a lookup instead of arithmetic on each pixel. The new renderer keeps the old one's settings back until something actually reads them, re-sends only the half of each draw's settings that changed, and remembers each patch of ground's colours, its blend coordinates and its tread marks between frames. Units whose shadow cannot reach the screen are no longer drawn into the shadow map, except on maps with reflecting water. The command bar and the console replay what they drew last frame when nothing under them moved, and the HUD checks for changes without rebuilding its text. The rules side runs 4% quicker too: locking, the lists of nearby units, the sleeping-unit schedule and text strings all got cheaper. The picture matches the old build in all eight test views on both renderers, and a recorded match plays back to the same checksum.- Every animation runs on a clock instead of counting frames.- Tanks and trucks move the same at any frame rate. Their treads scrolled a fixed step every picture, so at 120 frames a second they ran four times too fast, and a tank turning on the spot rolled both treads forward as if it were driving. Each tread now covers exactly the ground under it. In a tight turn the two run against each other, and backing up runs them backwards. Wheels spin with the distance driven the same way. The hull's springs used to settle four times too fast as well, and every start or stop threw the chassis to its full tilt in a single picture. Now a tank squats as it pulls away and dips its nose when it brakes, easing in over a tenth of a second and settling within half a second. In a corner it leans out, a Crusader up to two and a half degrees. The Humvee, which never moved on its springs at all, rocks too. A run drawing one picture per game tick and one drawing fourteen put every tank in the same pose, to the last digit, for as long as neither skipped a tick.- A scroll that starts after the camera has stood still no longer lurches. The first frame of the move was timed from the last time the camera moved, so after a few seconds of looking at one spot it was worth three frames of scrolling at once. The clock runs while the camera is still now, and the first frame moves one frame's worth.diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlOverlay.h b/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlOverlay.hindex d299e12f6..aa3d3a223 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlOverlay.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlOverlay.h@@ -41,9 +41,7 @@#include "Common/AsciiString.h"#include "GameClient/HtmlTemplate.h"-#include <map>#include <string>-#include <utility>#include <vector>class HtmlOverlayContainer;@@ -58,8 +56,8 @@ public:/** 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 );- /** setPage( HtmlTemplate_expand( written, values, lists, lookup ) ), expanded again only when the- * page, the values, the lists or an answer of the lookup's differ from the last call's. */+ /** setPage( HtmlTemplate_expand( written, values, lists, lookup ) ), expanded again only when+ * HtmlTemplate_matches says it would come out different from the last call's. */void setPage( const std::string &written, const HtmlValues &values, const HtmlLists &lists,const HtmlLookup &lookup );@@ -99,11 +97,8 @@ public:private:HtmlOverlayContainer *m_container;- std::string m_written; ///< the last expand's inputs- HtmlValues m_values;- HtmlLists m_lists;- std::map< std::string, std::pair< Bool, std::string > > m_asked; ///< every name it asked the lookup, and the answer- std::string m_expanded; ///< and what it made of them+ std::string m_expanded; ///< the page the last expanding setPage made+ Bool m_expandedSent; ///< and it is what the layout was last handed};#endif // _HTML_OVERLAY_H_diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlTemplate.h b/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlTemplate.hindex 630cde830..5d08b1a09 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlTemplate.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlTemplate.h@@ -50,6 +50,11 @@ typedef std::function< Bool( const std::string &name, std::string &value ) > Htmextern std::string HtmlTemplate_expand( const std::string &page, const HtmlValues &values,const HtmlLists &lists, const HtmlLookup &lookup );+/** HtmlTemplate_expand( page, values, lists, lookup ) == expanded, found without making the page: it+ * reads only what the page names, stops at the first difference and builds no string. */+extern Bool HtmlTemplate_matches( const std::string &page, const HtmlValues &values, const HtmlLists &lists,+ const HtmlLookup &lookup, const std::string &expanded );+/** 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 );diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlOverlay.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlOverlay.cppindex a620077b9..88b6f03a2 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlOverlay.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlOverlay.cpp@@ -102,7 +102,7 @@ public:explicit HtmlOverlayContainer( const AsciiString &defaultFont );~HtmlOverlayContainer( void );- void setPage( const std::string &html );+ void setPage( const std::string &html, Bool same );void draw( void );Bool hover( const ICoord2D &mouse );std::string click( const ICoord2D &mouse );@@ -263,12 +263,13 @@ HtmlOverlayContainer::~HtmlOverlayContainer( void )}//--------------------------------------------------------------------------------------------------void HtmlOverlayContainer::setPage( const std::string &html )+/** `same` when `html` is known to be the text the last call was handed, so it need not be compared. */+void HtmlOverlayContainer::setPage( const std::string &html, Bool same ){const Int width = TheDisplay->getWidth();const Int height = TheDisplay->getHeight();const Real scale = m_screenPixels ? 1.0f : m_hud ? ControlBarHudScale() : m_hudPage ? ControlBarHudPageScale() : ControlBarUniformScale();- if( m_document && html == m_page && width == m_screenWidth && height == m_screenHeight && scale == m_scale )+ if( m_document && ( same || html == m_page ) && width == m_screenWidth && height == m_screenHeight && scale == m_scale )return;m_page = html;@@ -940,7 +941,8 @@ void HtmlOverlayContainer::get_language( litehtml::string &language, litehtml::s//-------------------------------------------------------------------------------------------------HtmlOverlay::HtmlOverlay( const AsciiString &defaultFont ) :- m_container( new HtmlOverlayContainer( defaultFont ) )+ m_container( new HtmlOverlayContainer( defaultFont ) ),+ m_expandedSent( FALSE ){}@@ -950,40 +952,22 @@ HtmlOverlay::~HtmlOverlay( void )delete m_container;}-void HtmlOverlay::setPage( const std::string &html ) { m_container->setPage( html ); }+void HtmlOverlay::setPage( const std::string &html ) { m_expandedSent = FALSE; m_container->setPage( html, FALSE ); }//--------------------------------------------------------------------------------------------------/** The expanded page is made of the written page, the values, the lists and what the lookup answered- * for the names neither held, nothing else; all of them the same as last time is the same page, and- * filling 38 KB of command bar in again every pass to find that out was a share of the frame. */+/** Filling 38 KB of command bar in again every pass, to hand litehtml the page it already had, was a+ * share of the frame of its own. */void HtmlOverlay::setPage( const std::string &written, const HtmlValues &values, const HtmlLists &lists,const HtmlLookup &lookup ){- Bool same = written == m_written && values == m_values && lists == m_lists;- std::string answer;- for( std::map< std::string, std::pair< Bool, std::string > >::const_iterator asked = m_asked.begin();- same && asked != m_asked.end(); ++asked )- {- answer.clear();- const Bool known = lookup && lookup( asked->first, answer );- same = known == asked->second.first && ( !known || answer == asked->second.second );- }-+ // compared against the page it made last time, as it would be filled in now: only the names the+ // page uses are read, where comparing every value and list entry kept, and copying them all on+ // every change, was most of a pass's page cost+ const Bool same = m_expandedSent && HtmlTemplate_matches( written, values, lists, lookup, m_expanded );if( !same )- {- m_asked.clear();- const HtmlLookup asking = [ this, &lookup ]( const std::string &name, std::string &value ) -> Bool- {- const Bool known = lookup && lookup( name, value );- m_asked[ name ] = std::make_pair( known, known ? value : std::string() );- return known;- };- m_expanded = HtmlTemplate_expand( written, values, lists, asking );- m_written = written;- m_values = values;- m_lists = lists;- }- m_container->setPage( m_expanded );+ m_expanded = HtmlTemplate_expand( written, values, lists, lookup );+ m_container->setPage( m_expanded, same );+ m_expandedSent = TRUE;}void HtmlOverlay::draw( void ) { m_container->draw(); }void HtmlOverlay::setHud( Bool hud ) { m_container->m_hud = hud; }diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlTemplate.cppindex a5e9e5261..67caf0fa1 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlTemplate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlTemplate.cpp@@ -69,20 +69,47 @@ std::string trimmed( const std::string &text )return text.substr( first, last - first );}-void appendEscaped( std::string &out, const std::string &text )+/** Where a page is filled in: onto the end of `out`, or, with `against` set instead, over a page+ * already made, to learn whether it would come out the same without making it. */+struct Sink{+ std::string *out;+ const std::string *against;+ size_t at;+ Bool same;++ void put( const char *text, size_t length )+ {+ if( out )+ {+ out->append( text, length );+ return;+ }+ same = same && at + length <= against->size() && memcmp( against->data() + at, text, length ) == 0;+ at += length;+ }+};++void putEscaped( Sink &sink, const std::string &text )+{+ size_t run = 0;for( size_t index = 0; index < text.size(); index++ ){+ const char *entity = NULL;switch( text[ index ] ){- case '&': out += "&"; break;- case '<': out += "<"; break;- case '>': out += ">"; break;- case '"': out += """; break;- case '\'': out += "'"; break;- default: out += text[ index ]; break;+ case '&': entity = "&"; break;+ case '<': entity = "<"; break;+ case '>': entity = ">"; break;+ case '"': entity = """; break;+ case '\'': entity = "'"; break;+ default: continue;}+ sink.put( text.data() + run, index - run );+ sink.put( entity, strlen( entity ) );+ run = index + 1;}+ sink.put( text.data() + run, text.size() - run );}/** A stretch of page: literal text, or the trimmed name inside one {{name}}. */@@ -123,14 +150,14 @@ void split( const std::string &text, Pieces &pieces )}}-void fill( std::string &out, const Pieces &pieces, const HtmlValues *entry, const HtmlValues &values,+void fill( Sink &sink, const Pieces &pieces, const HtmlValues *entry, const HtmlValues &values,const HtmlLookup &lookup, std::string &looked ){- for( Pieces::const_iterator piece = pieces.begin(); piece != pieces.end(); ++piece )+ for( Pieces::const_iterator piece = pieces.begin(); piece != pieces.end() && sink.same; ++piece ){if( !piece->name ){- out += piece->text;+ sink.put( piece->text.data(), piece->text.size() );continue;}@@ -139,7 +166,7 @@ void fill( std::string &out, const Pieces &pieces, const HtmlValues *entry, consHtmlValues::const_iterator found = entry->find( piece->text );if( found != entry->end() ){- appendEscaped( out, found->second );+ putEscaped( sink, found->second );continue;}}@@ -147,13 +174,13 @@ void fill( std::string &out, const Pieces &pieces, const HtmlValues *entry, consHtmlValues::const_iterator found = values.find( piece->text );if( found != values.end() ){- appendEscaped( out, found->second );+ putEscaped( sink, found->second );continue;}looked.clear();if( lookup && lookup( piece->text, looked ) )- appendEscaped( out, looked );+ putEscaped( sink, looked );}}@@ -225,19 +252,9 @@ void compile( const std::string &written, Blocks &blocks )}}-} // namespace--//--------------------------------------------------------------------------------------------------std::string HtmlTemplate_escape( const std::string &text )-{- std::string escaped;- appendEscaped( escaped, text );- return escaped;-}--//--------------------------------------------------------------------------------------------------std::string HtmlTemplate_expand( const std::string &written, const HtmlValues &values,- const HtmlLists &lists, const HtmlLookup &lookup )+/** The page filled in into `sink`. */+void expandInto( Sink &sink, const std::string &written, const HtmlValues &values, const HtmlLists &lists,+ const HtmlLookup &lookup ){// the command bar's page alone is 38 KB and was lowercased and searched four times a frame;// keyed by its text, so a page that changes is cut again rather than served stale.@@ -250,25 +267,53 @@ std::string HtmlTemplate_expand( const std::string &written, const HtmlValues &vcompile( written, found->second );}- std::string out;- out.reserve( written.size() );std::string looked;- for( Blocks::const_iterator block = found->second.begin(); block != found->second.end(); ++block )+ for( Blocks::const_iterator block = found->second.begin(); block != found->second.end() && sink.same; ++block ){if( !block->each ){- fill( out, block->pieces, NULL, values, lookup, looked );+ fill( sink, block->pieces, NULL, values, lookup, looked );continue;}HtmlLists::const_iterator list = lists.find( block->list );if( list != lists.end() )- for( size_t entry = 0; entry < list->second.size(); entry++ )- fill( out, block->pieces, &list->second[ entry ], values, lookup, looked );+ for( size_t entry = 0; entry < list->second.size() && sink.same; entry++ )+ fill( sink, block->pieces, &list->second[ entry ], values, lookup, looked );}+}++} // namespace++//-------------------------------------------------------------------------------------------------+std::string HtmlTemplate_escape( const std::string &text )+{+ std::string escaped;+ Sink sink = { &escaped, NULL, 0, TRUE };+ putEscaped( sink, text );+ return escaped;+}++//-------------------------------------------------------------------------------------------------+std::string HtmlTemplate_expand( const std::string &written, const HtmlValues &values,+ const HtmlLists &lists, const HtmlLookup &lookup )+{+ std::string out;+ out.reserve( written.size() );+ Sink sink = { &out, NULL, 0, TRUE };+ expandInto( sink, written, values, lists, lookup );return out;}+//-------------------------------------------------------------------------------------------------+Bool HtmlTemplate_matches( const std::string &written, const HtmlValues &values, const HtmlLists &lists,+ const HtmlLookup &lookup, const std::string &expanded )+{+ Sink sink = { NULL, &expanded, 0, TRUE };+ expandInto( sink, written, values, lists, lookup );+ return sink.same && sink.at == expanded.size();+}+//-------------------------------------------------------------------------------------------------static Bool isPageSpace( char character ){diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cppindex 8dd1cae7e..a6d86637c 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp@@ -1942,6 +1942,17 @@ static Bool stripSwitchedOff( Bool GlobalData::* flag )* no page asks for one. */static std::map< std::string, std::string > s_gameTexts;+/** What drawProductionStrip's last sweep was of, and how many slots it filled. */+static struct+{+ Bool valid;+ UnsignedInt frame;+ const Player *player;+ ObjectID selected;+ Int count;+ Int total;+} s_stripGather;+/** {{text:Label}}: a string table label, in the player's language. *///-------------------------------------------------------------------------------------------------static Bool lookupGameText( const std::string &name, std::string &value )@@ -4163,6 +4174,7 @@ void InGameUI::reset( void )m_scoreboardPageLoaded = FALSE;m_scoreboardHtml.clear();s_gameTexts.clear(); // the map's string table goes with the map+ s_stripGather.valid = FALSE; // and the strip's sweep with the match it was ofm_earnedReadingCount = 0; // a new match and a loaded save both come through herem_controlBarPageLoaded = FALSE;m_netPageLoaded = FALSE;@@ -11761,6 +11773,25 @@ static Bool controlBarUnion( const char *const *names, IRegion2D &box )return found;}+/** The values `name`.x, `name`.y and so on, their keys built in one string kept from call to call:+ * name + ".x" made a new string for every key of every rectangle on the bar, every pass. One at a+ * time: a second one alive at once would write over the first's key. */+struct HtmlValueKey+{+ HtmlValueKey( HtmlValues &values, const std::string &name ) : m_values( values ), m_stem( name.size() ) { s_key.assign( name ); }+ std::string &at( const char *suffix )+ {+ s_key.resize( m_stem );+ s_key += suffix;+ return m_values[ s_key ];+ }++ HtmlValues &m_values;+ size_t m_stem;+ static std::string s_key;+};+std::string HtmlValueKey::s_key;+static void putPageRect( HtmlValues &values, const std::string &name, const IRegion2D &rect, Bool shown,Real scale = ControlBarUniformScale() );@@ -11830,15 +11861,16 @@ static void putFrame( HtmlValues &values, const std::string &name, const IRegionconst Int innerRight = Edge::page( content.hi.x, scale ), innerBottom = Edge::page( content.hi.y, scale );const Int right = Edge::page( box.hi.x, scale ), bottom = Edge::page( box.hi.y, scale );- values[ name + ".x" ] = std::to_string( left );- values[ name + ".y" ] = std::to_string( top );- values[ name + ".w" ] = std::to_string( shown ? max( 0, innerRight - innerLeft ) : 0 );- values[ name + ".h" ] = std::to_string( shown ? max( 0, innerBottom - innerTop ) : 0 );- values[ name + ".bl" ] = std::to_string( max( 0, innerLeft - left ) );- values[ name + ".bt" ] = std::to_string( max( 0, innerTop - top ) );- values[ name + ".br" ] = std::to_string( max( 0, right - innerRight ) );- values[ name + ".bb" ] = std::to_string( max( 0, bottom - innerBottom ) );- values[ name + ".shown" ] = shown ? "shown" : "hidden";+ HtmlValueKey key( values, name );+ key.at( ".x" ) = std::to_string( left );+ key.at( ".y" ) = std::to_string( top );+ key.at( ".w" ) = std::to_string( shown ? max( 0, innerRight - innerLeft ) : 0 );+ key.at( ".h" ) = std::to_string( shown ? max( 0, innerBottom - innerTop ) : 0 );+ key.at( ".bl" ) = std::to_string( max( 0, innerLeft - left ) );+ key.at( ".bt" ) = std::to_string( max( 0, innerTop - top ) );+ key.at( ".br" ) = std::to_string( max( 0, right - innerRight ) );+ key.at( ".bb" ) = std::to_string( max( 0, bottom - innerBottom ) );+ key.at( ".shown" ) = shown ? "shown" : "hidden";}/** The console's next well, `width` screen pixels wide from `left` between `top` and `bottom`, and@@ -12085,11 +12117,12 @@ static void putPageRect( HtmlValues &values, const std::string &name, const IRegconst Int top = REAL_TO_INT_FLOOR( rect.lo.y / scale + 0.5f );const Int right = REAL_TO_INT_FLOOR( rect.hi.x / scale + 0.5f );const Int bottom = REAL_TO_INT_FLOOR( rect.hi.y / scale + 0.5f );- values[ name + ".x" ] = std::to_string( left );- values[ name + ".y" ] = std::to_string( top );- values[ name + ".w" ] = std::to_string( shown ? right - left : 0 );- values[ name + ".h" ] = std::to_string( shown ? bottom - top : 0 );- values[ name + ".shown" ] = shown ? "shown" : "hidden";+ HtmlValueKey key( values, name );+ key.at( ".x" ) = std::to_string( left );+ key.at( ".y" ) = std::to_string( top );+ key.at( ".w" ) = std::to_string( shown ? right - left : 0 );+ key.at( ".h" ) = std::to_string( shown ? bottom - top : 0 );+ key.at( ".shown" ) = shown ? "shown" : "hidden";}static void drawCommandGridFront( GameWindow *window, WinInstanceData *instData )@@ -14020,6 +14053,7 @@ void InGameUI::drawProductionStrip( void )// An enemy's or a neutral's never gets here, and a watcher left above.//ObjectID selected = INVALID_ID;+ Object *leader = NULL;if( getSelectCount() == 1 && !m_selectedDrawables.empty() ){Object *sel = m_selectedDrawables.front()->getObject();@@ -14027,24 +14061,60 @@ void InGameUI::drawProductionStrip( void )isAllyOfLocalPlayer( sel->getControllingPlayer()->getPlayerIndex() ) ) ){selected = sel->getID();- appendProducerQueue( sel, m_productionStrip, &m_productionStripCount, PRODUCTION_STRIP_ROW_MAX,- &m_productionStripTotal, TRUE );+ leader = sel;}}//- // One sweep, one column: the queues and the buildings going up are gathered into the same- // cells and sorted against each other, so the strip is a single run of what the base has- // coming. A dozer raising a war factory now sits in the queue where its finishing time puts- // it instead of standing in a column of its own beside it.+ // What the sweep finds is the logic's - queues, building sites, build times - and the logic only+ // changes inside a logic frame, each of which moves getFrame() on; the new match or loaded save+ // that starts it over comes through reset(). So within one frame, for the same player and the+ // same building leading, the sweep finds what it found last pass, and with five or six passes+ // drawn to a frame, walking every object the player owns for it each time was a share of its own.+ // Only the slots' places are the drawing's, and they go back to the sweep's zero.//- ProductionStripGather gather;- gather.slot = m_productionStrip;- gather.count = &m_productionStripCount;- gather.total = &m_productionStripTotal;- gather.max = PRODUCTION_STRIP_ROW_MAX;- gather.skip = selected;- player->iterateObjects( gatherStripEverything, &gather );+ // Except while time is frozen: GameLogic::update still runs the scripts on every frozen pass and+ // returns before the frame moves, so a cinematic can change a queue with the frame standing still.+ // The same test as the update's own freeze return.+ const Bool timeFrozen = ( !TheGameEngine->isMultiplayerSession() && TheTacticalView->isTimeFrozen()+ && !TheTacticalView->isCameraMovementFinished() )+ || TheScriptEngine->isTimeFrozenDebug() || TheScriptEngine->isTimeFrozenScript();+ const UnsignedInt frame = TheGameLogic->getFrame();+ if( !timeFrozen && s_stripGather.valid && s_stripGather.frame == frame && s_stripGather.player == player+ && s_stripGather.selected == selected )+ {+ m_productionStripCount = s_stripGather.count;+ m_productionStripTotal = s_stripGather.total;+ for( Int i = 0; i < m_productionStripCount; i++ )+ m_productionStrip[ i ].pos.x = m_productionStrip[ i ].pos.y = 0;+ }+ else+ {+ if( leader )+ appendProducerQueue( leader, m_productionStrip, &m_productionStripCount, PRODUCTION_STRIP_ROW_MAX,+ &m_productionStripTotal, TRUE );++ //+ // One sweep, one column: the queues and the buildings going up are gathered into the same+ // cells and sorted against each other, so the strip is a single run of what the base has+ // coming. A dozer raising a war factory now sits in the queue where its finishing time puts+ // it instead of standing in a column of its own beside it.+ //+ ProductionStripGather gather;+ gather.slot = m_productionStrip;+ gather.count = &m_productionStripCount;+ gather.total = &m_productionStripTotal;+ gather.max = PRODUCTION_STRIP_ROW_MAX;+ gather.skip = selected;+ player->iterateObjects( gatherStripEverything, &gather );++ s_stripGather.valid = TRUE;+ s_stripGather.frame = frame;+ s_stripGather.player = player;+ s_stripGather.selected = selected;+ s_stripGather.count = m_productionStripCount;+ s_stripGather.total = m_productionStripTotal;+ }#ifdef DEBUG_LOGGINGtGatherEnd = Clock_Ticks();diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.hindex 82ec4cf5b..75d83e440 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h@@ -185,6 +185,7 @@ protected:///update vertex diffuse color for dynamic lights inside given rectangleInt updateVBForLight(DX8VertexBufferClass *pVB, char *data, Int x0, Int y0, Int x1, Int y1, Int originX, Int originY, W3DDynamicLight *pLights[], Int numLights);Int updateVBForLightOptimized(DX8VertexBufferClass *pVB, char *data, Int x0, Int y0, Int x1, Int y1, Int originX, Int originY, W3DDynamicLight *pLights[], Int numLights);+ static Bool quadUnderLight(W3DDynamicLight *pLights[], Int numLights, Int xCoord, Int yCoord); ///< updateVBForLight's per-quad test///update vertex buffer vertices inside given rectangleInt updateVB(DX8VertexBufferClass *pVB, char *data, Int x0, Int y0, Int x1, Int y1, Int originX, Int originY, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator);///upate vertex buffers associated with the given rectanglediff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cppindex 1ce7b4c0e..9861a851d 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp@@ -539,6 +539,27 @@ Int HeightMapRenderObjClass::updateVB(DX8VertexBufferClass *pVB, char *data, Int/** Update the dynamic lighting values only in a rectangular block of the given Vertex Buffer.The vertex locations and texture coords are unchanged.*/+/** Whether the quad at map cell (xCoord, yCoord) lies under any of the lights, where they are now or+where they were at the last relight: the test updateVBForLight relights a quad by. */+Bool HeightMapRenderObjClass::quadUnderLight(W3DDynamicLight *pLights[], Int numLights, Int xCoord, Int yCoord)+{+ for (Int k=0; k<numLights; k++) {+ if (pLights[k]->m_minX <= xCoord+1 &&+ pLights[k]->m_maxX >= xCoord &&+ pLights[k]->m_minY <= yCoord+1 &&+ pLights[k]->m_maxY >= yCoord) {+ return true;+ }+ if (pLights[k]->m_prevMinX <= xCoord+1 &&+ pLights[k]->m_prevMaxX >= xCoord &&+ pLights[k]->m_prevMinY <= yCoord+1 &&+ pLights[k]->m_prevMaxY >= yCoord) {+ return true;+ }+ }+ return false;+}+Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *data, Int x0, Int y0, Int x1, Int y1, Int originX, Int originY, W3DDynamicLight *pLights[], Int numLights){@@ -557,15 +578,42 @@ Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *dassert(x0 >= originX && y0 >= originY && x1>x0 && y1>y0 && x1<=originX+VERTEX_BUFFER_TILE_LENGTH && y1<=originY+VERTEX_BUFFER_TILE_LENGTH);#endif- DX8VertexBufferClass::WriteLockClass lockVtxBuffer(pVB);- VERTEX_FORMAT *vBase = (VERTEX_FORMAT*)lockVtxBuffer.Get_Vertex_Array();+ // Lock only from the first quad the loop below writes to the end of the last one. The+ // whole tile is 4096 vertices, and with Direct3D 11 its unlock copied every byte into the+ // D3D9 buffer and again into the D3D11 one for a light a few cells wide. The bytes outside+ // the range are untouched, and every copy of them already holds the same thing.+ Int firstVertex = -1;+ Int endVertex = 0;+ for (j=y0; j<y1; j++)+ {+ if (HALF_RES_MESH && (j&1)) continue;+ Int yCoord = getYWithOrigin(j)+m_map->getDrawOrgY()-m_map->getBorderSizeInline();+ for (i=x0; i<x1; i++)+ {+ if (HALF_RES_MESH && (i&1)) continue;+ Int xCoord = getXWithOrigin(i)+m_map->getDrawOrgX()-m_map->getBorderSizeInline();+ if (!quadUnderLight(pLights, numLights, xCoord, yCoord)) continue;+ Int offset = (j-originY)*vertsPerRow+4*(i-originX);+ if (HALF_RES_MESH) {+ offset = (j-originY)*vertsPerRow/4+2*(i-originX);+ }+ if (firstVertex < 0) firstVertex = offset;+ endVertex = offset + 4;+ }+ }+ if (firstVertex < 0)+ return 0; // no quad under a light: the loop below would write nothing++ DX8VertexBufferClass::AppendLockClass lockVtxBuffer(pVB, firstVertex, endVertex-firstVertex);+ VERTEX_FORMAT *vLocked = (VERTEX_FORMAT*)lockVtxBuffer.Get_Vertex_Array();// a failed lock - a device that has gone away - hands back nothing to light- if (vBase == NULL) {+ if (vLocked == NULL) {m_lastRelightValid = false; // nothing written, so the next pass tries againreturn 0;}+ VERTEX_FORMAT *vBase = vLocked - firstVertex; // offsets below stay tile-relativeVERTEX_FORMAT *vb;-+for (j=y0; j<y1; j++){if (HALF_RES_MESH) {diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cppindex 69a48c39f..63d6cbeb2 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp@@ -52,6 +52,8 @@#include "W3DDevice/GameClient/W3DGranny.h"#include "W3DDevice/GameClient/HeightMap.h"#include "W3DDevice/GameClient/W3DBridgeBuffer.h"+#include "W3DDevice/GameClient/W3DWater.h"+#include "GameLogic/PolygonTrigger.h"#include "d3dx9math.h"#include "Common/GlobalData.h"#include "Common/DrawModule.h"@@ -3972,6 +3974,106 @@ static void fillSmokeMap( const Matrix3D &sunTransform, const Vector3 &focus )}}+/* The 2D scene (W3DView::draw, last) is drawn through its own camera at (0, 0, 1) with a view plane+ of 2 by 1.5 at unit distance (W3DView.cpp, m_2DCamera), so its quads - the script fade and the+ team dot of W3DStatusCircle - lie on z = 0 inside |x| <= 1, |y| <= 0.75. Render2DClass draws+ the interface's quads and text with identity world, view and projection (render2d.cpp), so a+ pixel of those comes back out at its own NDC: |x|, |y| <= 1 and a depth from 0 to 1. Those that+ blend by source alpha or multiply by source colour go through the shadow program like any world+ draw, and their pixels land at those world positions: at the corner of the map, which the sun's+ box covers whenever the camera is near it. The reach is the corner of that unit cube from the+ origin, the square root of three; the filter's own reach is added by the caller. */+#define SHADOW_MAP_OVERLAY_REACH 1.75f+// ponytail: a constant pad on every caster's bounding sphere, because an HLod's sphere comes from+// its model and need not cover what a deployed state swings out (a raised Scud, the Nuke Cannon's+// barrel, a crane arm). The ceiling is a part reaching more than this past its sphere; the upgrade+// is a sphere per condition state, or the sphere of the posed sub-objects.+#define SHADOW_MAP_CASTER_PAD 30.0f++/** Whether a water mirror will read the map this pass fills. WaterRenderObjClass::renderMirror+ draws the reflected scene before the next frame's depth pass, through that frame's camera,+ while the map still holds this frame's casters, and the legacy frame buffer mirror draws one+ inside this frame through a reflected camera. Neither is a frustum known here, so a map that+ can reflect at all keeps every caster in the box. Translucent water mirrors only through its+ water areas; the grid mesh never does. */+static Bool waterMirrorReadsTheMap()+{+ if (TheWaterRenderObj == NULL)+ return FALSE;+ if (TheGlobalData->m_waterType == WaterRenderObjClass::WATER_TYPE_3_GRIDMESH)+ return FALSE;+ if (TheGlobalData->m_waterType != WaterRenderObjClass::WATER_TYPE_0_TRANSLUCENT)+ return TRUE;+ for (PolygonTrigger *area = PolygonTrigger::getFirstPolygonTrigger(); area; area = area->getNext())+ {+ if (area->isWaterArea() && area->getNumPoints() >= 3)+ return TRUE;+ }+ return FALSE;+}++/** Whether anything a pixel of this frame samples can be shadowed by a caster. The caster is its+ bounding sphere, and what it can darken lies downwind of it: the sphere swept away from the sun+ from its own sun side down to the lowest ground on the map, widened by how far the receiving+ filter reaches across the map. That capsule runs from upwind to downwind with this radius.+ Only the four sides of the view are tested: a draw with a depth-biased projection reads the+ map through near and far planes that are not the camera's, and the sides are the same for+ every one of them. The overlay's quads sit at z = 0 whatever the ground does, so for them the+ capsule runs on to overlayDownwind, swept down to z = 0 when the lowest ground is above it. */+static Bool shadowReachesTheFrame( const FrustumClass &view, const Vector3 &upwind,+ const Vector3 &downwind, const Vector3 &overlayDownwind, Real radius )+{+ Bool inView = TRUE;+ for (Int side = 1; side <= 4 && inView; ++side)+ {+ const PlaneClass &plane = view.Planes[ side ];+ inView = Vector3::Dot_Product( plane.N, upwind ) - plane.D <= radius+ || Vector3::Dot_Product( plane.N, downwind ) - plane.D <= radius;+ }+ if (inView)+ return TRUE;++ // the 2D scene's and the interface's quads, at the world's origin+ const Vector3 along = overlayDownwind - upwind;+ const Real lengthSqr = along.Length2();+ Real t = (lengthSqr > 0.0f) ? -Vector3::Dot_Product( upwind, along ) / lengthSqr : 0.0f;+ t = WWMath::Clamp( t, 0.0f, 1.0f );+ const Vector3 nearest = upwind + along * t;+ const Real reach = radius + SHADOW_MAP_OVERLAY_REACH;+ return nearest.Length2() <= reach * reach;+}++/** Render() is not only a draw. Animatable3DObjClass::Render moves a playing animation on to the+ frame the clock says, and W3DModelDraw reads that frame back (Is_Animation_Complete,+ Peek_Animation_And_Info) to step its states and carry a frame across them. The depth pass+ used to do that for every caster in the box every frame, and the frame is a running float sum,+ so a caster the pass leaves out still has its clock moved here exactly as Render would, which+ keeps every frame number what it was. The pose is what the pass no longer pays for: Render+ posed the bones and the meshes on them, and here they are only marked stale, so whatever draws+ the model or reads a bone or a sub-object's transform next poses it from the same frame and+ the same transform the pass would have used. */+class CasterAnimationClock : public Animatable3DObjClass+{+public:+ static void advance( RenderObjClass *robj )+ {+ if (robj->Class_ID() != RenderObjClass::CLASSID_HLOD || !robj->Is_Not_Hidden_At_All())+ return;+ HLodClass *hlod = (HLodClass *)robj;+ if (hlod->Get_HTree() == NULL)+ return;+ float frame, multiplier;+ int frames, mode;+ if (hlod->Peek_Animation_And_Info( frame, frames, mode, multiplier ) != NULL+ && mode != RenderObjClass::ANIM_MODE_MANUAL)+ {+ void (Animatable3DObjClass::*progress)( void ) = &CasterAnimationClock::Single_Anim_Progress;+ (hlod->*progress)();+ }+ hlod->Set_Sub_Object_Transforms_Dirty( true );+ }+};+/** The sun's depth pass. The casters are the ones that cast a volume today, drawn again from thesun into a depth buffer nothing samples yet, so this phase can be proved on its own: with itoff the frame is what it was, and with it on the map has the world in it and the frame is@@ -4058,6 +4160,25 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )#ifndef DEBUG_LOGGINGInt castersCounted = 0;#endif+ Int castersOutOfView = 0;++ const Real widest = (TheGlobalData->m_shadowMapWidest > 0.0f)+ ? TheGlobalData->m_shadowMapWidest : SHADOW_MAP_WIDEST_TEXELS;++ /* How far across the map a pixel reads, which is how far beside a caster's own outline its+ shadow can still darken one. sun_reaching in ffshader.h: the blocker search's corner tap is+ widest times the square root of two away, the filter's turned corner the same at its widest,+ the normal offset at most 0.6 of a texel, and a point sampled tap reads the texel whose centre+ is up to 0.71 away. 1.5 and 2 cover those with room. Receivers sit no lower than the+ lowest ground on the map: anything under it is seen through the ground, which is drawn and+ writes depth in front of it. A sun at the horizon sweeps forever, so then nothing is left+ out, and nothing is while a water mirror can read this map through a camera other than this+ one. */+ const FrustumClass &seen = sceneCamera.Get_Frustum();+ const Real filterReach = (widest * 1.5f + 2.0f) * texelWidth;+ const Real lowestReceiver = TheTerrainRenderObject->getMinHeight();+ const Bool cullToFrame = toSun.Z > 0.01f && !waterMirrorReadsTheMap();+for (W3DVolumetricShadow *shadow = m_shadowList; shadow; shadow = shadow->m_next){RenderObjClass *robj = shadow->getRenderObject();@@ -4068,12 +4189,33 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )see. Culling by the camera meant a tank just off the left of the screen stopped casting,so its shadow blinked out while the shadow of the tank beside it stayed - and scrollingturned that into a row of shadows flickering along the edge of the frame. */+ const SphereClass &bound = robj->Get_Bounding_Sphere();Vector3 inSun;Matrix3D::Inverse_Transform_Vector( transform, robj->Get_Position(), &inSun );- const Real reach = SHADOW_MAP_HALF_WIDTH + robj->Get_Bounding_Sphere().Radius;+ const Real reach = SHADOW_MAP_HALF_WIDTH + bound.Radius;if (inSun.X < -reach || inSun.X > reach || inSun.Y < -reach || inSun.Y > reach)continue;+ /* That tank is still in the map, because its shadow sweeps onto the screen. What can be left+ out is a caster whose shadow, followed downwind to the lowest ground and widened by the+ filter, never meets the frame: no pixel drawn this frame reads a texel it is nearest the+ sun in, so the map reads the same everywhere it is read. */+ if (cullToFrame)+ {+ const Real casterRadius = bound.Radius + SHADOW_MAP_CASTER_PAD;+ const Real radius = casterRadius + filterReach;+ const Real sweep = WWMath::Max( (bound.Center.Z - lowestReceiver + radius) / toSun.Z, 0.0f );+ const Real overlaySweep = WWMath::Max(+ (bound.Center.Z - WWMath::Min( lowestReceiver, 0.0f ) + radius) / toSun.Z, 0.0f );+ if (!shadowReachesTheFrame( seen, bound.Center + toSun * casterRadius,+ bound.Center - toSun * sweep, bound.Center - toSun * overlaySweep, radius ))+ {+ CasterAnimationClock::advance( robj );+ ++castersOutOfView;+ continue;+ }+ }+robj->Render( sunInfo );++castersCounted;}@@ -4147,8 +4289,6 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )? TheGlobalData->m_shadowMapSkyFill : SHADOW_MAP_SKY_FILL;const Real strength = (TheGlobalData->m_shadowMapStrength > 0.0f)? TheGlobalData->m_shadowMapStrength : SHADOW_MAP_STRENGTH;- const Real widest = (TheGlobalData->m_shadowMapWidest > 0.0f)- ? TheGlobalData->m_shadowMapWidest : SHADOW_MAP_WIDEST_TEXELS;Direct3D11_Set_Shadow_Parameters( SHADOW_MAP_DEPTH_BIAS, strength, widest,SHADOW_MAP_NARROWEST_TEXELS, penumbra / worldPerTexel, unitsPerUnitOfDepth, skyFill );@@ -4182,8 +4322,8 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )if (frame >= nextReportFrame){nextReportFrame = frame + LOGICFRAMES_PER_SECOND;- DEBUG_LOG(("SHADOWMAP: %d casters, %s\n", castersCounted,- Direct3D11_Shadow_Map_Report().c_str()));+ DEBUG_LOG(("SHADOWMAP: %d casters, %d left out as reaching nothing in view, %s\n",+ castersCounted, castersOutOfView, Direct3D11_Shadow_Map_Report().c_str()));}}}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cppindex 81007bc71..bcfc8b62a 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp@@ -386,6 +386,7 @@ void DX11BackendClass::Release_Cached()LastMemo = 0;NextMemo = 0;LastResolveHeld = false;+ Resolutions.clear();Forget_Last_State_Objects();for (std::map<std::string, Pipeline>::iterator entry = Pipelines.begin();@@ -1850,6 +1851,25 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)}}+ ResolveKey resolve_key;+ memset(&resolve_key, 0, sizeof(resolve_key));+ resolve_key.Format = VertexFormat;+ resolve_key.VertexProgram = VertexProgram;+ resolve_key.PixelProgram = PixelProgram;+ memcpy(&resolve_key.Vertex, &vertex_description, sizeof(vertex_description));+ memcpy(&resolve_key.Combiner, &combiner_description, sizeof(combiner_description));+ ResolutionMap::iterator resolved = Resolutions.find(resolve_key);+ if (resolved != Resolutions.end()) {+ if (resolved->second.Refused) {+ Refuse(resolved->second.Key, static_cast<RefusalReason>(resolved->second.Reason));+ return false;+ }+ pipeline = resolved->second.Resolved;+ ++resolved->second.Use->Draws;+ Remember_Resolution(resolved->second.Use, pipeline, vertex_description, combiner_description);+ return true;+ }+char format[32];snprintf(format, sizeof(format), "|%lu", VertexFormat);@@ -1871,11 +1891,19 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)std::map<std::string, Pipeline>::const_iterator existing = Pipelines.find(key);if (existing != Pipelines.end()) {pipeline = existing->second;- Remember_Resolution(key, pipeline, vertex_description, combiner_description);+ PipelineUse * const use = Record_Use(key);+ const Resolution resolution = { false, 0, pipeline, use, key };+ Resolutions[resolve_key] = resolution;+ Remember_Resolution(use, pipeline, vertex_description, combiner_description);return true;}std::map<std::string, unsigned>::const_iterator refused = RefusedPipelines.find(key);if (refused != RefusedPipelines.end()) {+ // A refusal is kept once it has been seen here, not where it is first made: the paths+ // below refuse in several places and the next draw of the same state lands here anyway.+ const Pipeline none = { NULL, NULL, NULL };+ const Resolution resolution = { true, refused->second, none, NULL, key };+ Resolutions[resolve_key] = resolution;Refuse(key, static_cast<RefusalReason>(refused->second));return false;}@@ -1952,11 +1980,27 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)FrameBuildMilliseconds += DX11Resource_Milliseconds_Now() - build_started;++FrameBuildCount;pipeline = built;- Remember_Resolution(key, pipeline, vertex_description, combiner_description);+ PipelineUse * const use = Record_Use(key);+ const Resolution resolution = { false, 0, pipeline, use, key };+ Resolutions[resolve_key] = resolution;+ Remember_Resolution(use, pipeline, vertex_description, combiner_description);return true;}-void DX11BackendClass::Remember_Resolution(const std::string & key, const Pipeline & resolved,+size_t DX11BackendClass::ResolveKey_Hash::operator()(const ResolveKey & key) const+{+ // FNV-1a a word at a time; the key is all four byte fields and zeroed padding.+ static_assert(sizeof(ResolveKey) % sizeof(unsigned) == 0, "the key hashes whole words");+ unsigned words[sizeof(ResolveKey) / sizeof(unsigned)];+ memcpy(words, &key, sizeof(words));+ unsigned long long hash = 14695981039346656037ULL;+ for (unsigned index = 0; index < sizeof(words) / sizeof(words[0]); ++index) {+ hash = (hash ^ words[index]) * 1099511628211ULL;+ }+ return static_cast<size_t>(hash);+}++void DX11BackendClass::Remember_Resolution(PipelineUse * use, const Pipeline & resolved,const VertexPipelineDescription & vertex, const CombinerDescription & combiner){ResolveMemo & memo = Memos[NextMemo];@@ -1967,7 +2011,7 @@ void DX11BackendClass::Remember_Resolution(const std::string & key, const Pipelimemo.VertexProgram = VertexProgram;memo.PixelProgram = PixelProgram;memo.Resolved = resolved;- memo.Use = Record_Use(key);+ memo.Use = use;LastResolveHeld = true;LastMemo = NextMemo;NextMemo = (NextMemo + 1) % RESOLVE_MEMO_ENTRIES;diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.hindex b159aae62..16c9d8bf8 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h@@ -56,6 +56,7 @@#include <map>#include <string.h>#include <string>+#include <unordered_map>#include <vector>// Two everywhere except the water, which binds four: the river texture, the sparkles, the noise@@ -596,9 +597,46 @@ private:ResolveMemo Memos[RESOLVE_MEMO_ENTRIES];unsigned LastMemo; ///< the entry the last hit or write used; checked firstunsigned NextMemo; ///< the entry the next miss writes over- void Remember_Resolution(const std::string & key, const Pipeline & resolved,+ void Remember_Resolution(PipelineUse * use, const Pipeline & resolved,const VertexPipelineDescription & vertex, const CombinerDescription & combiner);+ // Every resolution a memo miss has already worked out, keyed by the state's own bytes. A frame+ // asks for more pipelines in turn than the memo holds, and each miss built the string key again:+ // about twenty snprintf calls to find a pipeline it had found many times. The string key is+ // built once per state here and kept, for a refusal's count. The key is memset before it is+ // filled, so hashing and comparing its bytes is safe for the memo's reason; the map is dropped+ // in Release_Cached with the pipelines it names.+ struct ResolveKey+ {+ DWORD Format;+ EngineShaderProgram VertexProgram;+ EngineShaderProgram PixelProgram;+ VertexPipelineDescription Vertex;+ CombinerDescription Combiner;+ };+ struct ResolveKey_Hash+ {+ size_t operator()(const ResolveKey & key) const;+ };+ struct ResolveKey_Equal+ {+ bool operator()(const ResolveKey & left, const ResolveKey & right) const+ {+ return memcmp(&left, &right, sizeof(ResolveKey)) == 0;+ }+ };+ struct Resolution+ {+ bool Refused;+ unsigned Reason; ///< a RefusalReason, as RefusedPipelines holds it+ Pipeline Resolved;+ PipelineUse * Use;+ std::string Key;+ };+ typedef std::unordered_map<ResolveKey, Resolution, ResolveKey_Hash, ResolveKey_Equal>+ ResolutionMap;+ ResolutionMap Resolutions;+// Where the draws are landing. Null means the device's own back buffer and depth buffer.// The first few target changes, in order, with the draw count at each one. Which target is// bound when the scene is drawn is the whole question and no total answers it.diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cppindex 48355cea5..6441f5ce5 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp@@ -36,13 +36,6 @@ static bool PresentFailureReported = false;static bool VSyncRequested = false;static bool Active = false;static bool NormalMapsEnabled = true;-// The texture the backend's normal map was last mirrored from, and the mirror generation then.-// TextureClass::Apply hands the same one over on every bind of its texture, and each mirror call is-// three private data lookups on the D3D9 texture. Cleared when stage zero changes, which is when-// the backend drops its normal map, so the D3D9 texture at stage zero (held by the wrapper) is the-// one this was found for.-static struct IDirect3DBaseTexture9 * MirroredNormalMap = NULL;-static unsigned long long MirroredNormalMapGeneration = 0;static DX11DeviceClass Device;static DX11BackendClass Backend;static DX11PostProcessClass Post;@@ -133,7 +126,6 @@ void Direct3D11_Release()Backend.Shutdown();Device.Release();Active = false;- MirroredNormalMap = NULL;}bool Direct3D11_Resize(unsigned width, unsigned height)@@ -268,7 +260,6 @@ void Direct3D11_Mirror_Texture(unsigned stage, struct IDirect3DBaseTexture9 * te// the new one's right after this, and a texture bound any other way has none.if (stage == 0) {Backend.Set_Normal_Map(NULL);- MirroredNormalMap = NULL;}}@@ -287,15 +278,9 @@ void Direct3D11_Mirror_Normal_Map(struct IDirect3DBaseTexture9 * normal_map)if (!Active) {return;}- if (normal_map != NULL && normal_map == MirroredNormalMap- && DX11Texture_Generation() == MirroredNormalMapGeneration) {- return;- }Backend.Set_Normal_Map(normal_map == NULL? NULL: DX11Texture_Mirror(Device.Get_Device(), Device.Get_Context(), normal_map));- MirroredNormalMap = normal_map;- MirroredNormalMapGeneration = DX11Texture_Generation();}void Direct3D11_Set_Terrain_Sun(const float direction[3])diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cppindex 6486396e7..0a8a05436 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp@@ -27,6 +27,7 @@#include <stdio.h>#include <string.h>#include <string>+#include <unordered_map>#include <vector>// Where the copy and the refusal are kept on the D3D9 texture. The view goes in as an IUnknown,@@ -86,10 +87,6 @@ static void note_refusal(const char * reason)static std::vector<std::string> Notes;-// Raised whenever a texture's view is replaced or its pixels are marked for a recopy; see-// DX11Texture_Generation.-static unsigned long long Generation = 0;-static unsigned Mirrored = 0;static unsigned Refused = 0;static unsigned Reused = 0;@@ -495,11 +492,10 @@ static ID3D11ShaderResourceView * apply_lod(ID3D11Device * device, IDirect3DBasetexture->SetPrivateData(DX11_TEXTURE_VIEW, replacement, sizeof(replacement), D3DSPD_IUNKNOWN);replacement->Release();texture->SetPrivateData(DX11_TEXTURE_LOD, &lod, sizeof(lod), 0);- ++Generation;return replacement;}-ID3D11ShaderResourceView * DX11Texture_Mirror(ID3D11Device * device, ID3D11DeviceContext * context,+static ID3D11ShaderResourceView * mirror(ID3D11Device * device, ID3D11DeviceContext * context,IDirect3DBaseTexture9 * texture){ID3D11ShaderResourceView * view = NULL;@@ -545,6 +541,92 @@ ID3D11ShaderResourceView * DX11Texture_Mirror(ID3D11Device * device, ID3D11Devicreturn apply_lod(device, texture, view);}+// What mirror() last answered for each texture, so a bind that would get the same answer skips the+// three private data lookups it asks D3D9 for. Every texture bind went through them, and they were+// the d3d9.dll time under TextureClass::Apply in the profile (an unnamed export, Ordinal23, is the+// nearest label the sampler has for that code). An entry stands while its texture is alive, has+// not been written by the CPU since (DX11Texture_Mark_Dirty marks it stale) and answers the same+// level of detail; the view itself is still owned by the texture. Main thread only, like every+// other call here.+struct MirrorAnswer+{+ ID3D11ShaderResourceView * View;+ DWORD Lod; ///< GetLOD when the answer was taken, before apply_lod clamps it+ bool Stale;+};+typedef std::unordered_map<IDirect3DBaseTexture9 *, MirrorAnswer> MirrorAnswerMap;+// Never destroyed: a texture still alive when the statics are torn down at exit releases its watch+// after that, and the watch erases from this.+static MirrorAnswerMap & MirrorAnswers = *new MirrorAnswerMap;++// Hung on a texture as private data the first time it is answered for, so that D3D9 releasing its+// private data when the texture goes takes the answer with it before another texture can be made+// at the same address.+// {2E2E9C27-1B2A-4C7E-9E2F-1D0B7E9A5C01}+static const GUID DX11_TEXTURE_WATCH =+ { 0x2e2e9c27, 0x1b2a, 0x4c7e, { 0x9e, 0x2f, 0x1d, 0x0b, 0x7e, 0x9a, 0x5c, 0x01 } };++class TextureWatch : public IUnknown+{+public:+ explicit TextureWatch(IDirect3DBaseTexture9 * texture) : References(1), Texture(texture) {}++ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID id, void ** object)+ {+ if (id == IID_IUnknown) {+ *object = static_cast<IUnknown *>(this);+ AddRef();+ return S_OK;+ }+ *object = NULL;+ return E_NOINTERFACE;+ }+ ULONG STDMETHODCALLTYPE AddRef() { return ++References; }+ ULONG STDMETHODCALLTYPE Release()+ {+ const ULONG left = --References;+ if (left == 0) {+ MirrorAnswers.erase(Texture);+ delete this;+ }+ return left;+ }++private:+ ULONG References;+ IDirect3DBaseTexture9 * Texture;+};++ID3D11ShaderResourceView * DX11Texture_Mirror(ID3D11Device * device, ID3D11DeviceContext * context,+ IDirect3DBaseTexture9 * texture)+{+ MirrorAnswerMap::iterator answer = MirrorAnswers.find(texture);+ if (answer != MirrorAnswers.end() && !answer->second.Stale+ && answer->second.Lod == texture->GetLOD()) {+ if (answer->second.View != NULL) {+ ++Reused;+ }+ return answer->second.View;+ }++ ID3D11ShaderResourceView * const view = mirror(device, context, texture);+ if (answer == MirrorAnswers.end()) {+ // Without the watch nothing would take the answer back when the texture goes.+ TextureWatch * const watch = new TextureWatch(texture);+ const bool watched = SUCCEEDED(texture->SetPrivateData(DX11_TEXTURE_WATCH, watch,+ sizeof(IUnknown *), D3DSPD_IUNKNOWN));+ watch->Release();+ if (!watched) {+ return view;+ }+ }+ MirrorAnswer & held = MirrorAnswers[texture];+ held.View = view;+ held.Lod = texture->GetLOD();+ held.Stale = false;+ return view;+}+void DX11Texture_Mark_Dirty(IDirect3DSurface9 * surface){if (surface == NULL) {@@ -559,13 +641,11 @@ void DX11Texture_Mark_Dirty(IDirect3DSurface9 * surface)const unsigned char dirty = 1;texture->SetPrivateData(DX11_TEXTURE_DIRTY, &dirty, sizeof(dirty), 0);+ MirrorAnswerMap::iterator answer = MirrorAnswers.find(texture);+ if (answer != MirrorAnswers.end()) {+ answer->second.Stale = true;+ }texture->Release();- ++Generation;-}--unsigned long long DX11Texture_Generation()-{- return Generation;}bool DX11Texture_Update(ID3D11Device * device, ID3D11DeviceContext * context,diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.hindex faf958f5c..6b98272d7 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h@@ -58,12 +58,6 @@ bool DX11Texture_Update(ID3D11Device * device, ID3D11DeviceContext * context,// surface with no texture behind it is ignored.void DX11Texture_Mark_Dirty(IDirect3DSurface9 * surface);-// Changes whenever a mirror call could hand back something different for a texture it has already-// mirrored: a view replaced for a new level of detail, or pixels marked for a recopy. A caller-// that remembers a view may keep it while this holds still. A SetLOD alone does not move it; the-// next mirror call on that texture does.-unsigned long long DX11Texture_Generation();-// The render target view over the copy of the texture this surface is a level of, built on the// first call and kept on that texture with the shader resource view. Null when the surface has no// texture behind it, which is the device's own back buffer.diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex b38f8d598..c42888c2f 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -15436,6 +15436,88 @@ TEST(html_template_fills_values_and_repeats_each)CHECK_STR( HtmlTemplate_expand( "a {{ open", values, lists, lookup ).c_str(), "a {{ open" );}+// HtmlOverlay skips filling a page in again when HtmlTemplate_matches says it would come out as the+// page it already has, so matches has to say exactly what expand() == old would: a changed value,+// list entry or lookup answer, and an old page longer or shorter than the new one, all differ.+TEST(html_template_matches_says_what_expand_would)+{+ const std::string page =+ "<p class=\"{{option:A}}\">{{title}}</p>"+ "<ul><li class=\"t{{team}}\" data-each=\"players\">{{name}}</li></ul>{{text:Label}}";++ HtmlValues values;+ values[ "option:A" ] = "on";+ values[ "title" ] = "T&";+ values[ "team" ] = "9";+ HtmlLists lists;+ HtmlValues player;+ player[ "name" ] = "<b>";+ lists[ "players" ].push_back( player );+ player[ "name" ] = "Bo";+ player[ "team" ] = "1";+ lists[ "players" ].push_back( player );++ std::string answer = "looked";+ const HtmlLookup lookup = [ &answer ]( const std::string &name, std::string &value ) -> Bool+ {+ if( name != "text:Label" )+ return FALSE;+ value = answer;+ return TRUE;+ };++ const std::string old = HtmlTemplate_expand( page, values, lists, lookup );+ CHECK( HtmlTemplate_matches( page, values, lists, lookup, old ) );+ CHECK( !HtmlTemplate_matches( page, values, lists, lookup, old + "x" ) );+ CHECK( !HtmlTemplate_matches( page, values, lists, lookup, old.substr( 0, old.size() - 1 ) ) );+ CHECK( !HtmlTemplate_matches( page, values, lists, lookup, std::string() ) );++ HtmlValues changedValues = values;+ changedValues[ "title" ] = "U&";+ CHECK( !HtmlTemplate_matches( page, changedValues, lists, lookup, old ) );+ // a value the page never names changes nothing+ changedValues = values;+ changedValues[ "unused" ] = "x";+ CHECK( HtmlTemplate_matches( page, changedValues, lists, lookup, old ) );++ HtmlLists changedLists = lists;+ changedLists[ "players" ][ 1 ][ "name" ] = "Bob";+ CHECK( !HtmlTemplate_matches( page, values, changedLists, lookup, old ) );+ changedLists = lists;+ changedLists[ "players" ].pop_back();+ CHECK( !HtmlTemplate_matches( page, values, changedLists, lookup, old ) );++ answer = "other";+ CHECK( !HtmlTemplate_matches( page, values, lists, lookup, old ) );+ answer = "looked";++ // against expand itself, over values that shift lengths and escaping from case to case+ const char *const pieces[] = { "", "a", "&", "<>", "<b>", "T&", "9", "\"'", "Bo", "on" };+ const UnsignedInt count = (UnsignedInt)( sizeof( pieces ) / sizeof( pieces[ 0 ] ) );+ UnsignedInt seed = 12345;+ Int agreed = 0;+ for( Int round = 0; round < 64; round++ )+ {+ HtmlValues tryValues = values;+ HtmlLists tryLists = lists;+ seed = seed * 1103515245u + 12345u;+ const char *const piece = pieces[ ( seed >> 8 ) % count ];+ switch( ( seed >> 16 ) % 5 )+ {+ case 0: break; // the inputs it was made from+ case 1: tryValues[ "title" ] = piece; break;+ case 2: tryValues[ "team" ] = piece; break;+ case 3: tryLists[ "players" ][ 0 ][ "name" ] = piece; break;+ case 4: tryLists[ "players" ][ 1 ][ "team" ] = piece; break;+ }+ const Bool same = HtmlTemplate_expand( page, tryValues, tryLists, lookup ) == old;+ CHECK_EQ( HtmlTemplate_matches( page, tryValues, tryLists, lookup, old ), same );+ agreed += same ? 1 : 0;+ }+ // both answers came up, so the loop is not checking one side only+ CHECK( agreed > 0 && agreed < 64 );+}+// litehtml builds an element for every word and every white space character, so the page it is// handed has its stylesheet taken out for the CSS parser and each run of white space between tags// cut to one; a tag's attribute values keep theirs, a '>' inside quotes included.diff --git a/tree-check.ps1 b/tree-check.ps1index d4d545469..2f46065d5 100644--- a/tree-check.ps1+++ b/tree-check.ps1@@ -20,7 +20,7 @@# the run-to-run shimmer does not. Re-measure and move them if the reference machine changes.## Exit code is the number of views over the limit.-param([double]$Limit = 0, [string[]]$Extra = @(), [string[]]$NewEnv = @(), [string]$Base = 'generals_base.exe')+param([double]$Limit = 0, [string[]]$Extra = @(), [string[]]$NewEnv = @(), [string]$Base = 'generals_base.exe', [string]$Candidate = 'generals.exe')$env:ZH_UNATTENDED = "1" # every game this starts is unattended: no box may wait on a person (EarlyCommandLine.h)Add-Type -AssemblyName System.Drawing@@ -71,7 +71,7 @@ function Shoot($exe, $c, $tag) {$args = @('-win','-xres','1280','-yres','720','-quickstart','-noshellmap','-multiInstance','-showHudOverlay','-msaa','0','-dx11post','off','-map',"`"Maps\$($c.map)\$($c.map).map`"",'-autoskirmish','4','-aidiff','easy','-seed','5','-maxframes',($c.f+80),'-screenshot',$c.f,'-camera',$c.x,$c.y,'-logPrefix',"chk_$tag`_") + $pace + $Extra- $environment = if ($exe -eq 'generals.exe') { $NewEnv } else { @() }+ $environment = if ($exe -eq $Candidate) { $NewEnv } else { @() }try {foreach ($e in $environment) { $n, $v = $e -split '=', 2; Set-Item "env:$n" $v }$p = Start-Process (Join-Path $run $exe) -ArgumentList $args -WorkingDirectory $run -PassThru@@ -114,7 +114,7 @@ $fail = 0foreach ($c in $cases) {$tag = ($c.map -replace '[^A-Za-z]','') + "_$($c.x)_$($c.f)"$a = Shoot $Base $c "base_$tag"- $b = Shoot 'generals.exe' $c "new_$tag"+ $b = Shoot $Candidate $c "new_$tag"$d = DiffPct $a $b$lim = if ($Limit -gt 0) { $Limit } else { $c.lim }$verdict = if ($d -le $lim) { 'ok' } else { 'DIFFERENT'; }