Skip to content

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.

feat(ww3d2): draw with Direct3D 11 by default, without the stutters

Olcay Seygana8582c9c67b5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 33a00c4cc..bfb606ef1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,8 @@ found and fixed — EA's own, not port damage.**
- On a machine with two graphics chips, the game used to draw on the first one it found, which was the slow one. It now uses the dedicated card, and a match holds about 260 frames a second with the trees, the shadows and the filtering left on.
- Display options has a vertical sync box. Off, the picture still runs free. On, it waits for the monitor so the frame does not tear. The box takes effect when you Accept.
- A slow moment costs you a dropped frame, not a slow game.
+- Explosions no longer catch the picture. The first time each kind of fire, smoke or blast reached the screen, the game stopped for 25 to 60ms to prepare it, and the opening volley of a fight cost 300ms at once. That work is kept on disk and ships with the game, so it happens while the map loads, in about 3ms, and the worst frame of the same battle went from 141ms to 38ms.
+- The price, build time and power figures on the command bar buttons stopped costing you frames. All the buttons shared one piece of text, so every figure on the bar was lettered from scratch every frame, about 33 of them. Each now keeps its own: a battle that averaged 14ms a frame averages 11.7ms, frames slower than 60 a second went from one in six to one in a hundred, and the old renderer gets about 0.8ms back too. The money readout was lettered again every frame as well, for a number that had not changed; it is lettered when the number moves. Over a whole battle the game now letters 163 pieces of text where it lettered 68,227.
- Every animation runs on a clock instead of counting frames.
- Briefing and cutscene subtitles hold long enough to read again.
- The radar's under-attack pulse throbs instead of strobing, and no longer ends early.
@@ -196,6 +198,7 @@ found and fixed — EA's own, not port damage.**
## Sharper textures, for free
+- The game draws its picture through Direct3D 11 now, and falls back to the old renderer on a machine that cannot make a Direct3D 11 device. Eight views over five maps come out within one step of one colour channel of the old picture, which is the smallest difference a screen can show.
- 481 base-game textures at four times the resolution now beat Zero Hour's downscaled copies.
- A long thin texture loads at the size it was drawn at. Anything wider than eight to one used to be stretched onto a bigger, blurrier one, because that was the limit of a 2002 graphics card; the card is asked now, and modern ones have no such limit.
- Anything standing still keeps its shadow in the fog. A town you have already walked through used
@@ -1069,4 +1072,6 @@ found and fixed — EA's own, not port damage.**
## Not there yet
- Online and LAN play are untested.
+- A frame through Direct3D 11 still costs more than it did through the old renderer: 13.6ms against 8.6ms in a screen full of inferno cannon fire, down from 16.9ms once the old renderer stopped drawing a second copy of every frame that nobody saw. `-d3d9` on the command line puts the old renderer back on its own.
+- Antialiasing from the display page does not reach the Direct3D 11 picture yet, and the rolling-wave sea is drawn only by the old renderer, so it is missing from the new one.
- You need to own the game; no game data ships here.
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index 2f173d573..010218bb7 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -122,10 +122,7 @@ public:
///< is derived from it and is what the device layer reads.
Int m_msaaLevel; ///< multisampling, as an index into the levels the options menu offers
Bool m_vsync; ///< wait for the monitor; off is the uncapped picture the frame-rate cap removal shipped
- Bool m_fixedFunctionProbe; ///< -ffprobe: count the fixed-function combinations the frame actually uses
- Bool m_combinerShaders; ///< -ffshader: draw with generated pixel shaders instead of the stage combiners
- Bool m_direct3D11; ///< -dx11: render through the native Direct3D 11 backend
- Bool m_direct3D11Present; ///< -dx11present: show that backend's frame instead of Direct3D 9's
+ Bool m_direct3D11; ///< draw and present through the Direct3D 11 backend; -d3d9 and -headless turn it off
AsciiString m_direct3D11DumpPath; ///< -dx11dump: where to write each generated program
AsciiString m_direct3D11PostChain; ///< -dx11post: the effects run over the finished D3D11 frame
Int m_xResolution;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index 8f96ab617..8b125c0a7 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -1325,6 +1325,8 @@ Int parseHeadless(char *args[], int num)
TheWritableGlobalData->m_soundsOn = FALSE;
TheWritableGlobalData->m_speechOn = FALSE;
TheWritableGlobalData->m_videoOn = FALSE;
+ // a run that draws nothing has no use for a second device mirroring every buffer it loads
+ TheWritableGlobalData->m_direct3D11 = FALSE;
}
return 1;
}
@@ -1388,79 +1390,42 @@ Int parseMSAA(char *args[], int num)
return 1;
}
-/* -ffprobe: count the fixed-function combinations the frame actually uses.
+/* -d3d9: draw and present with Direct3D 9 alone, the way the game did before the Direct3D 11
+ * backend became the renderer.
*
- * RENDERER-ROADMAP.md's phase 2 replaces fixed-function multitexture with HLSL, and the size of
- * that job is not the number of combinations shader.h can express - tens of thousands - but the
- * number the game sets during a match. This reads the stage combiners and the pixel-affecting
- * render states back off the device at every draw call, so a call site that set its own states
- * without going through DX8Wrapper is counted too, and writes Run/ffprobe.txt at shutdown, most
- * used first. Reading forty states per draw is slow; pair it with -maxframes. */
-Int parseFixedFunctionProbe(char *args[], int num)
+ * The Direct3D 11 frame is the default, and this is the reference it is measured against:
+ * dx11-check.ps1 photographs one frame both ways, and a frame-time comparison of the two
+ * backends needs a run where the second device does not exist at all. */
+Int parseDirect3D9(char *args[], int num)
{
if (TheWritableGlobalData)
{
- TheWritableGlobalData->m_fixedFunctionProbe = TRUE;
+ TheWritableGlobalData->m_direct3D11 = FALSE;
}
return 1;
}
-/* -ffshader: draw with generated pixel shaders instead of the texture stage combiners.
- *
- * The other half of -ffprobe, and RENDERER-ROADMAP.md phase 2's way of proving a generator
- * before anything is carried to a second backend: D3D11 has no combiners, so what they compute
- * has to be written as a shader, and a shader that runs on the existing D3D9 device can be
- * compared against the pipeline it replaces with tree-check.ps1. A draw whose description the
- * generator refuses stays on the fixed-function path, and one that brought its own pixel shader
- * is left alone. The counts go to the log at shutdown. */
-Int parseDirect3D11(char *args[], int num)
-{
- if (TheWritableGlobalData)
- {
- TheWritableGlobalData->m_direct3D11 = TRUE;
- }
- return 1;
-}
-
-/* -dx11present: put the Direct3D 11 frame on the screen, and read screenshots back from it.
- *
- * Implies -dx11. Without it the backend draws into a back buffer nothing ever shows, which is
- * how both renderers can run in the same frame while phase 2 is unfinished; with it the window
- * and the .bmp are the D3D11 picture, so tree-check.ps1 can photograph one against the other.
- * A frame the backend refuses parts of is a frame with those parts missing - that is the point
- * of looking. */
/* -dx11dump <directory>: write every program the Direct3D 11 backend generates into that
* directory as it is built, named by the order it was built in with the state it came from on
- * its first line. Implies -dx11. A generated program that draws the wrong thing cannot be read
- * any other way: the state is a key and the key is not the code. */
+ * its first line. A generated program that draws the wrong thing cannot be read any other way:
+ * the state is a key and the key is not the code. */
Int parseDirect3D11Dump(char *args[], int num)
{
if (num > 1 && TheWritableGlobalData)
{
- TheWritableGlobalData->m_direct3D11 = TRUE;
TheWritableGlobalData->m_direct3D11DumpPath = args[1];
return 2;
}
return 1;
}
-Int parseDirect3D11Present(char *args[], int num)
-{
- if (TheWritableGlobalData)
- {
- TheWritableGlobalData->m_direct3D11 = TRUE;
- TheWritableGlobalData->m_direct3D11Present = TRUE;
- }
- return 1;
-}
-
/* -dx11post [chain]: run a pixel shader over the finished Direct3D 11 frame before it is shown.
*
* The chain is the effects in the order they run, comma separated: "bloom", "fxaa", "sharpen",
* "copy" for the pass that changes nothing, or "off". Bare -dx11post is "fxaa", which is the
* cheapest one worth having: the swap chain asks for a single sample, so an edge in the D3D11
- * frame has nothing else working on it. Implies -dx11present, because a chain over a frame
- * nobody sees is only a cost.
+ * frame has nothing else working on it. Under -d3d9 there is no such frame and the chain does
+ * nothing.
*
* "bloom" has to come first and it changes what the scene is kept in. Explosion particles are
* blended additively, so a stack of them is brighter than white before it is written down, and
@@ -1476,8 +1441,6 @@ Int parseDirect3D11Post(char *args[], int num)
{
if (TheWritableGlobalData)
{
- TheWritableGlobalData->m_direct3D11 = TRUE;
- TheWritableGlobalData->m_direct3D11Present = TRUE;
if (num > 1 && args[1][0] != '-')
{
TheWritableGlobalData->m_direct3D11PostChain = args[1];
@@ -1488,15 +1451,6 @@ Int parseDirect3D11Post(char *args[], int num)
return 1;
}
-Int parseCombinerShaders(char *args[], int num)
-{
- if (TheWritableGlobalData)
- {
- TheWritableGlobalData->m_combinerShaders = TRUE;
- }
- return 1;
-}
-
/* -camera <x> <y>: point the camera at one map position and leave it there.
*
* -screenshot only made a picture; it could not say of what. The camera starts at the local
@@ -2255,10 +2209,7 @@ static CommandLineParam params[] =
{ "-maxframes", parseMaxGameFrames },
{ "-screenshot", parseScreenShot },
{ "-msaa", parseMSAA },
- { "-ffprobe", parseFixedFunctionProbe },
- { "-ffshader", parseCombinerShaders },
- { "-dx11", parseDirect3D11 },
- { "-dx11present", parseDirect3D11Present },
+ { "-d3d9", parseDirect3D9 },
{ "-dx11dump", parseDirect3D11Dump },
{ "-dx11post", parseDirect3D11Post },
{ "-autocamera", parseAutoCamera },
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index 22bf23e25..2b594d182 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -647,10 +647,7 @@ GlobalData::GlobalData()
m_windowMode = WINDOW_MODE_FULLSCREEN;
m_msaaLevel = 0;
m_vsync = FALSE;
- m_fixedFunctionProbe = FALSE;
- m_combinerShaders = FALSE;
- m_direct3D11 = FALSE;
- m_direct3D11Present = FALSE;
+ m_direct3D11 = TRUE;
m_direct3D11DumpPath.clear();
m_direct3D11PostChain.clear();
m_xResolution = 800;
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplayString.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplayString.h
index 65c1764c9..5cae6c660 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplayString.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplayString.h
@@ -60,6 +60,9 @@
// FORWARD REFERENCES /////////////////////////////////////////////////////////
class W3DDisplayStringManager;
+// Writes the strings whose sentence was built most often this run to the log, most first.
+void W3DDisplayString_logSentenceBuilds( void );
+
// TYPE DEFINES ///////////////////////////////////////////////////////////////
// W3DDisplayString -----------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp
index c1b6f9cf3..2fb64df1d 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp
@@ -201,30 +201,58 @@ static void drawButtonText( GameWindow *window, WinInstanceData *instData )
} // end drawButtonText
+// badgeString ================================================================
+/** The display string for one badge's text. A display string keeps the texture
+ * its text was built into, so each one is only ever handed text it already
+ * holds: one shared string set to every button's number in turn rebuilt a text
+ * texture for every badge on the bar every frame, about 33 of them, and on the
+ * Direct3D 11 frame each of those was a texture made and copied as well. */
+//=============================================================================
+static const Int BADGE_STRING_SLOTS = 64;
+static DisplayString *theBadgeStrings[ BADGE_STRING_SLOTS ] = { NULL };
+static Int theNextBadgeSlot = 0;
+
+static DisplayString *badgeString( const UnicodeString &text, GameFont *font )
+{
+ for( Int slot = 0; slot < BADGE_STRING_SLOTS; ++slot )
+ {
+ DisplayString *candidate = theBadgeStrings[ slot ];
+ if( candidate != NULL && candidate->getFont() == font && candidate->getText() == text )
+ return candidate;
+ }
+
+ // ponytail: round-robin eviction; a bar never shows 64 different badges at once, a per-button
+ // string would be the upgrade if one ever does
+ DisplayString *&slotString = theBadgeStrings[ theNextBadgeSlot ];
+ theNextBadgeSlot = ( theNextBadgeSlot + 1 ) % BADGE_STRING_SLOTS;
+ if( slotString == NULL )
+ {
+ slotString = TheDisplayStringManager->newDisplayString();
+ if( slotString == NULL )
+ return NULL;
+ }
+
+ slotString->setText( text );
+ if( font != NULL )
+ slotString->setFont( font );
+ return slotString;
+
+} // end badgeString
+
// drawCountBadge =============================================================
/** Draw a small number badge in the button's bottom right corner (queued unit
* counts, selection sizes). One shared DisplayString serves every button. */
//=============================================================================
static void drawCountBadge( GameWindow *window, Int count )
{
- static DisplayString *badge = NULL;
ICoord2D origin, size, textPos;
Int width, height;
- if( badge == NULL )
- {
- badge = TheDisplayStringManager->newDisplayString();
- if( badge == NULL )
- return;
- }
-
UnicodeString text;
text.format( L"%d", count );
- badge->setText( text );
-
- GameFont *font = getBadgeFont( window );
- if( font != NULL && badge->getFont() != font )
- badge->setFont( font );
+ DisplayString *badge = badgeString( text, getBadgeFont( window ) );
+ if( badge == NULL )
+ return;
window->winGetScreenPosition( &origin.x, &origin.y );
window->winGetSize( &size.x, &size.y );
@@ -251,24 +279,14 @@ static void drawCountBadge( GameWindow *window, Int count )
//=============================================================================
static void drawSecondsBadge( GameWindow *window, Int seconds )
{
- static DisplayString *label = NULL;
ICoord2D origin, size, textPos;
Int width, height;
- if( label == NULL )
- {
- label = TheDisplayStringManager->newDisplayString();
- if( label == NULL )
- return;
- }
-
UnicodeString text;
text.format( L"%ds", seconds );
- label->setText( text );
-
- GameFont *font = getBadgeFont( window );
- if( font != NULL && label->getFont() != font )
- label->setFont( font );
+ DisplayString *label = badgeString( text, getBadgeFont( window ) );
+ if( label == NULL )
+ return;
window->winGetScreenPosition( &origin.x, &origin.y );
window->winGetSize( &size.x, &size.y );
@@ -292,24 +310,14 @@ static void drawSecondsBadge( GameWindow *window, Int seconds )
//=============================================================================
static void drawCostBadge( GameWindow *window, Int cost )
{
- static DisplayString *label = NULL;
ICoord2D origin, size, textPos;
Int width, height;
- if( label == NULL )
- {
- label = TheDisplayStringManager->newDisplayString();
- if( label == NULL )
- return;
- }
-
UnicodeString text;
text.format( L"$%d", cost );
- label->setText( text );
-
- GameFont *font = getBadgeFont( window );
- if( font != NULL && label->getFont() != font )
- label->setFont( font );
+ DisplayString *label = badgeString( text, getBadgeFont( window ) );
+ if( label == NULL )
+ return;
window->winGetScreenPosition( &origin.x, &origin.y );
window->winGetSize( &size.x, &size.y );
@@ -336,27 +344,17 @@ static void drawCostBadge( GameWindow *window, Int cost )
//=============================================================================
static void drawPowerBadge( GameWindow *window, Int power )
{
- static DisplayString *label = NULL;
ICoord2D origin, size, textPos;
Int width, height;
- if( label == NULL )
- {
- label = TheDisplayStringManager->newDisplayString();
- if( label == NULL )
- return;
- }
-
// the game's own sign: a template's EnergyProduction is negative when it consumes
const Int draws = -power;
UnicodeString text;
text.format( draws > 0 ? L"-%d" : L"+%d", draws > 0 ? draws : -draws );
- label->setText( text );
-
- GameFont *font = getBadgeFont( window );
- if( font != NULL && label->getFont() != font )
- label->setFont( font );
+ DisplayString *label = badgeString( text, getBadgeFont( window ) );
+ if( label == NULL )
+ return;
window->winGetScreenPosition( &origin.x, &origin.y );
window->winGetSize( &size.x, &size.y );
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
index ea5755ded..9da5c34b2 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
@@ -573,7 +573,8 @@ Int W3DProjectedShadowManager::renderProjectedTerrainShadow(W3DProjectedShadow *
if (DX8Wrapper::_Is_Triangle_Draw_Enabled())
{
Debug_Statistics::Record_DX8_Polys_And_Vertices(numPolys,numVerts,ShaderClass::_PresetOpaqueShader);
- m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,nShadowStartBatchVertex,0,numVerts,nShadowStartBatchIndex,numPolys);
+ if (!Direct3D11_Present_Is_Enabled())
+ m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,nShadowStartBatchVertex,0,numVerts,nShadowStartBatchIndex,numPolys);
Direct3D11_Draw_Indexed_Triangles(numIndex,nShadowStartBatchIndex,nShadowStartBatchVertex);
}
@@ -824,7 +825,8 @@ void W3DProjectedShadowManager::flushDecals(W3DShadowTexture *texture, ShadowTyp
if (DX8Wrapper::_Is_Triangle_Draw_Enabled())
{
Debug_Statistics::Record_DX8_Polys_And_Vertices(nShadowDecalPolysInBatch,nShadowDecalVertsInBatch,ShaderClass::_PresetOpaqueShader);
- m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,nShadowDecalStartBatchVertex,0,nShadowDecalVertsInBatch,nShadowDecalStartBatchIndex,nShadowDecalPolysInBatch);
+ if (!Direct3D11_Present_Is_Enabled())
+ m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,nShadowDecalStartBatchVertex,0,nShadowDecalVertsInBatch,nShadowDecalStartBatchIndex,nShadowDecalPolysInBatch);
Direct3D11_Draw_Indexed_Triangles(nShadowDecalPolysInBatch*3,nShadowDecalStartBatchIndex,
nShadowDecalStartBatchVertex);
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
index 1dc7e1166..cae58e5f7 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
@@ -1569,7 +1569,8 @@ void W3DVolumetricShadow::RenderMeshVolume(Int meshIndex, Int lightIndex, const
if (DX8Wrapper::_Is_Triangle_Draw_Enabled())
{
Debug_Statistics::Record_DX8_Polys_And_Vertices(numPolys,numVerts,ShaderClass::_PresetOpaqueShader);
- m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,vbSlot->m_start,0,numVerts,ibSlot->m_start,numPolys);
+ if (!Direct3D11_Present_Is_Enabled())
+ m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,vbSlot->m_start,0,numVerts,ibSlot->m_start,numPolys);
Direct3D11_Draw_Indexed_Triangles(numIndex,ibSlot->m_start,vbSlot->m_start);
}
@@ -1710,7 +1711,8 @@ void W3DVolumetricShadow::RenderDynamicMeshVolume(Int meshIndex, Int lightIndex,
if (DX8Wrapper::_Is_Triangle_Draw_Enabled())
{
Debug_Statistics::Record_DX8_Polys_And_Vertices(numPolys,numVerts,ShaderClass::_PresetOpaqueShader);
- m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,nShadowStartBatchVertex,0,numVerts,nShadowStartBatchIndex,numPolys);
+ if (!Direct3D11_Present_Is_Enabled())
+ m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,nShadowStartBatchVertex,0,numVerts,nShadowStartBatchIndex,numPolys);
Direct3D11_Draw_Indexed_Triangles(numIndex,nShadowStartBatchIndex,nShadowStartBatchVertex);
}
@@ -1862,7 +1864,8 @@ void W3DVolumetricShadow::RenderMeshVolumeBounds(Int meshIndex, Int lightIndex,
m_pDev->SetStreamSource(0,shadowVertexBufferD3D,0,sizeof(SHADOW_DYNAMIC_VOLUME_VERTEX));
m_pDev->SetFVF(SHADOW_DYNAMIC_VOLUME_FVF);
- m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,nShadowStartBatchVertex,0,numVerts,nShadowStartBatchIndex,numPolys);
+ if (!Direct3D11_Present_Is_Enabled())
+ m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,nShadowStartBatchVertex,0,numVerts,nShadowStartBatchIndex,numPolys);
nShadowVertsInBuf += numVerts;
nShadowStartBatchVertex=nShadowVertsInBuf;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index ebd4b6097..64513c1c0 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -84,6 +84,7 @@ static void drawFramerateBar(void);
#include "W3DDevice/GameClient/W3DVideoBuffer.h"
#include "W3DDevice/GameClient/W3DShaderManager.h"
#include "W3DDevice/GameClient/W3DDebugDisplay.h"
+#include "W3DDevice/GameClient/W3DDisplayString.h"
#include "W3DDevice/GameClient/W3DProjectedShadow.h"
#include "W3DDevice/GameClient/W3DShroud.h"
#include "WWMath/WWMath.h"
@@ -494,6 +495,13 @@ W3DDisplay::~W3DDisplay()
if( Direct3D11_Texture_First_Refusal()[0] != '\0' )
DEBUG_LOG(("-dx11 texture: %s\n", Direct3D11_Texture_First_Refusal()));
+ const unsigned shapeCount = Direct3D11_Texture_Copy_Shape_Count();
+ for( unsigned shape = 0; shape < shapeCount; shape++ )
+ DEBUG_LOG(("-dx11 copies: %s\n", Direct3D11_Texture_Copy_Shape( shape )));
+
+ // The text textures lead that list, and these are the strings they were built for.
+ W3DDisplayString_logSentenceBuilds();
+
unsigned long long targetsBound = 0;
unsigned long long targetsRestored = 0;
unsigned long long drawsIntoTargets = 0;
@@ -1035,11 +1043,12 @@ void W3DDisplay::init( void )
DX8Wrapper::Set_Requested_VSync( TheGlobalData->m_vsync != FALSE );
Direct3D11_Set_VSync( TheGlobalData->m_vsync != FALSE );
- // Same reason: WW3D2 cannot see GlobalData, so -ffprobe and -ffshader are pushed in from here.
- FixedFunctionProbe_Enable( TheGlobalData->m_fixedFunctionProbe != FALSE );
- CombinerShaders_Enable( TheGlobalData->m_combinerShaders != FALSE );
+ // Same reason: WW3D2 cannot see GlobalData, so the backend choice is pushed in from here. The
+ // fixed-function probe and the generated combiner shaders are always on.
+ FixedFunctionProbe_Enable( true );
+ CombinerShaders_Enable( true );
Direct3D11_Enable( TheGlobalData->m_direct3D11 != FALSE );
- Direct3D11_Present_Enable( TheGlobalData->m_direct3D11Present != FALSE );
+ Direct3D11_Present_Enable( TheGlobalData->m_direct3D11 != FALSE );
Direct3D11_Dump_Programs_To( TheGlobalData->m_direct3D11DumpPath.str() );
if( !Direct3D11_Post_Chain( TheGlobalData->m_direct3D11PostChain.str() )
&& !TheGlobalData->m_direct3D11PostChain.isEmpty() )
@@ -2444,6 +2453,22 @@ AGAIN:
// render is all done!
WW3D::End_Render();
+ /* A pipeline is compiled and a texture copied the first time it reaches a Direct3D 11
+ draw, which is the frame a new explosion first shows up on. A frame that spent more
+ than a few milliseconds doing that says so, with the logic frame to set beside the
+ SLOW PASS line it caused. */
+ {
+ const double DX11_FRAME_COST_REPORT_MS = 5.0;
+ double pipelineMS = 0.0;
+ unsigned pipelines = 0;
+ double textureMS = 0.0;
+ unsigned textures = 0;
+ Direct3D11_Take_Frame_Cost( pipelineMS, pipelines, textureMS, textures );
+ if( pipelineMS + textureMS > DX11_FRAME_COST_REPORT_MS )
+ DEBUG_LOG(("DX11 FRAME COST frame %d: %u pipelines built in %.1f ms, %u textures copied in %.1f ms\n",
+ TheGameLogic->getFrame(), pipelines, pipelineMS, textures, textureMS));
+ }
+
/* End_Render is where a lost device is noticed and reset, and that reset is the most
dangerous thing this process does: it hands every default-pool resource back and asks
the driver to rebuild the swap chain, and under -d3d12 it has been seen to fault
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp
index 388bff859..27cfcae9c 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp
@@ -47,6 +47,10 @@
// SYSTEM INCLUDES ////////////////////////////////////////////////////////////
#include <stdlib.h>
+#include <algorithm>
+#include <map>
+#include <string>
+#include <vector>
// USER INCLUDES //////////////////////////////////////////////////////////////
#include "GameClient/GameClient.h"
@@ -67,6 +71,29 @@
// PRIVATE DATA ///////////////////////////////////////////////////////////////
+// Every sentence build by the text it was built for, for the report at shutdown. A build makes a
+// new texture, and on the Direct3D 11 frame a new copy of that texture too, so a string rebuilt
+// every frame is a texture made and thrown away every frame.
+static std::map<std::string, Int> theSentenceBuilds;
+static const size_t SENTENCE_BUILD_REPORT_LINES = 12;
+
+void W3DDisplayString_logSentenceBuilds( void )
+{
+ std::vector< std::pair<Int, std::string> > ranked;
+ Int total = 0;
+ for( std::map<std::string, Int>::const_iterator entry = theSentenceBuilds.begin();
+ entry != theSentenceBuilds.end(); ++entry )
+ {
+ ranked.push_back( std::make_pair( entry->second, entry->first ) );
+ total += entry->second;
+ }
+ std::sort( ranked.rbegin(), ranked.rend() );
+
+ DEBUG_LOG(( "SENTENCE BUILDS: %d builds of %d distinct strings\n", total, (Int)ranked.size() ));
+ for( size_t index = 0; index < ranked.size() && index < SENTENCE_BUILD_REPORT_LINES; ++index )
+ DEBUG_LOG(( "SENTENCE BUILDS: %d '%s'\n", ranked[ index ].first, ranked[ index ].second.c_str() ));
+}
+
// PUBLIC DATA ////////////////////////////////////////////////////////////////
// PRIVATE PROTOTYPES /////////////////////////////////////////////////////////
@@ -201,6 +228,10 @@ void W3DDisplayString::draw( Int x, Int y, Color color, Color dropColor, Int xDr
m_textChanged = FALSE;
needNewPolys = TRUE;
+ AsciiString builtText;
+ builtText.translate( getText() );
+ ++theSentenceBuilds[ builtText.str() ];
+
} // end if
//
@@ -401,10 +432,15 @@ void W3DDisplayString::setWordWrap( Int wordWrap )
void W3DDisplayString::setUseHotkey( Bool useHotkey, Color hotKeyColor )
{
+ const Bool unchanged = ( m_useHotKey == useHotkey && m_hotKeyColor == hotKeyColor );
m_useHotKey = useHotkey;
m_hotKeyColor = hotKeyColor;
m_textRenderer.Set_Hot_Key_Parse(useHotkey);
- notifyTextChanged();
+
+ // W3DStaticText asks again on every draw, and a rebuilt sentence is a new text texture: the money
+ // readout was built once a frame for a number that had not changed.
+ if( !unchanged )
+ notifyTextChanged();
}
// W3DDisplayString::setWordWrapCentered ======================================
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
index 8ecd041a9..ba52fe2d0 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
@@ -2588,14 +2588,16 @@ void WaterRenderObjClass::renderWaterMesh(void)
//Shroud shader uses z-compare of EQUAL which wouldn't work on water because it doesn't
//write to the zbuffer. Change to LESSEQUAL.
DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
- m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,m_vertexBufferD3DOffset,0,mx*my,0,m_numIndices-2);
+ if (!Direct3D11_Present_Is_Enabled())
+ m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,m_vertexBufferD3DOffset,0,mx*my,0,m_numIndices-2);
Direct3D11_Draw_Indexed_Strip(m_numIndices,0,m_vertexBufferD3DOffset);
DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_EQUAL);
W3DShaderManager::resetShader(W3DShaderManager::ST_SHROUD_TEXTURE);
}
else
{
- m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,m_vertexBufferD3DOffset,0,mx*my,0,m_numIndices-2);
+ if (!Direct3D11_Present_Is_Enabled())
+ m_pDev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP,m_vertexBufferD3DOffset,0,mx*my,0,m_numIndices-2);
Direct3D11_Draw_Indexed_Strip(m_numIndices,0,m_vertexBufferD3DOffset);
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
index 527f3716a..3e40f44a1 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -61,6 +61,28 @@ static D3DCompileFunction compiler_function()
return compiler;
}
+// The cache file is this marker, then one record a program: the hash, the byte count, the bytes.
+static const char SHADER_CACHE_MAGIC[8] = { 'D', 'X', '1', '1', 'S', 'C', '1', '\0' };
+static const unsigned SHADER_CACHE_LARGEST_PROGRAM = 1u << 20;
+
+// FNV-1a over the profile and the source, which between them decide the bytecode. The generated
+// text is the key rather than the pipeline's state key, so a build that changes what a state
+// generates compiles again instead of drawing with the previous build's program.
+static unsigned long long program_hash(const char * profile, const std::string & source)
+{
+ const unsigned long long FNV_OFFSET = 14695981039346656037ULL;
+ const unsigned long long FNV_PRIME = 1099511628211ULL;
+
+ unsigned long long hash = FNV_OFFSET;
+ for (const char * cursor = profile; *cursor != '\0'; ++cursor) {
+ hash = (hash ^ static_cast<unsigned char>(*cursor)) * FNV_PRIME;
+ }
+ for (size_t index = 0; index < source.size(); ++index) {
+ hash = (hash ^ static_cast<unsigned char>(source[index])) * FNV_PRIME;
+ }
+ return hash;
+}
+
static void set_identity(float matrix[16])
{
memset(matrix, 0, sizeof(float) * 16);
@@ -157,6 +179,9 @@ DX11BackendClass::DX11BackendClass()
, UserBuffer(NULL)
, UserBufferBytes(0)
, PipelinesBuilt(0)
+ , FrameBuildMilliseconds(0.0)
+ , FrameBuildCount(0)
+ , ShaderCacheChanged(false)
, TracedUserStrip(false)
, MaskWhileTargeted(0)
, TargetsBound(0)
@@ -298,6 +323,10 @@ void DX11BackendClass::Release_Cached()
void DX11BackendClass::Shutdown()
{
+ if (ShaderCacheChanged) {
+ Save_Shader_Cache();
+ ShaderCacheChanged = false;
+ }
Release_Cached();
if (EngineConstantBuffer != NULL) {
@@ -508,6 +537,95 @@ void DX11BackendClass::Set_Dump_Directory(const char * directory)
}
}
+void DX11BackendClass::Set_Shader_Cache_Path(const char * path)
+{
+ ShaderCachePath = (path == NULL) ? "" : path;
+ if (ShaderCachePath.empty()) {
+ return;
+ }
+
+ FILE * file = fopen(ShaderCachePath.c_str(), "rb");
+ if (file == NULL) {
+ return;
+ }
+
+ // A file cut short by a crash while it was written loses its last record and nothing else:
+ // every record is read whole or not at all.
+ char magic[sizeof(SHADER_CACHE_MAGIC)];
+ if (fread(magic, sizeof(magic), 1, file) == 1
+ && memcmp(magic, SHADER_CACHE_MAGIC, sizeof(magic)) == 0) {
+ unsigned long long hash = 0;
+ unsigned int size = 0;
+ while (fread(&hash, sizeof(hash), 1, file) == 1 && fread(&size, sizeof(size), 1, file) == 1
+ && size > 0 && size <= SHADER_CACHE_LARGEST_PROGRAM) {
+ std::vector<unsigned char> bytecode(size);
+ if (fread(&bytecode[0], size, 1, file) != 1) {
+ break;
+ }
+ CompiledPrograms[hash].swap(bytecode);
+ }
+ }
+ fclose(file);
+}
+
+void DX11BackendClass::Save_Shader_Cache() const
+{
+ if (ShaderCachePath.empty()) {
+ return;
+ }
+
+ FILE * file = fopen(ShaderCachePath.c_str(), "wb");
+ if (file == NULL) {
+ return;
+ }
+
+ fwrite(SHADER_CACHE_MAGIC, sizeof(SHADER_CACHE_MAGIC), 1, file);
+ for (std::map<unsigned long long, std::vector<unsigned char> >::const_iterator entry
+ = CompiledPrograms.begin(); entry != CompiledPrograms.end(); ++entry) {
+ const unsigned int size = static_cast<unsigned int>(entry->second.size());
+ fwrite(&entry->first, sizeof(entry->first), 1, file);
+ fwrite(&size, sizeof(size), 1, file);
+ fwrite(&entry->second[0], size, 1, file);
+ }
+ fclose(file);
+}
+
+bool DX11BackendClass::Compile_Program(const std::string & source, const char * name,
+ const char * profile, std::vector<unsigned char> & bytecode)
+{
+ const unsigned long long hash = program_hash(profile, source);
+ std::map<unsigned long long, std::vector<unsigned char> >::const_iterator known
+ = CompiledPrograms.find(hash);
+ if (known != CompiledPrograms.end()) {
+ bytecode = known->second;
+ return true;
+ }
+
+ D3DCompileFunction compiler = compiler_function();
+ if (compiler == NULL) {
+ return false;
+ }
+
+ ID3DBlob * code = NULL;
+ ID3DBlob * errors = NULL;
+ if (FAILED(compiler(source.c_str(), source.size(), name, NULL, NULL, ENTRY_POINT, profile, 0, 0,
+ &code, &errors))) {
+ Record_Compiler_Error(name, errors);
+ return false;
+ }
+ if (errors != NULL) {
+ errors->Release();
+ }
+
+ const unsigned char * bytes = static_cast<const unsigned char *>(code->GetBufferPointer());
+ bytecode.assign(bytes, bytes + code->GetBufferSize());
+ code->Release();
+
+ CompiledPrograms[hash] = bytecode;
+ ShaderCacheChanged = true;
+ return true;
+}
+
// The key has characters a file name cannot carry, so it becomes the file's first line and the
// name is a number. Both programs of one pipeline go in one file, in the order they run.
void DX11BackendClass::Dump_Program(const std::string & key, const std::string & vertex_hlsl,
@@ -834,12 +952,7 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)
return false;
}
- D3DCompileFunction compiler = compiler_function();
- if (compiler == NULL) {
- Refuse(key, REFUSED_NO_PROGRAM);
- return false;
- }
-
+ const double build_started = DX11Resource_Milliseconds_Now();
std::string vertex_hlsl;
std::string pixel_hlsl;
const bool wrote_vertex = (VertexProgram != ENGINE_SHADER_NONE)
@@ -869,29 +982,13 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)
return false;
}
- ID3DBlob * vertex_code = NULL;
- ID3DBlob * pixel_code = NULL;
- ID3DBlob * errors = NULL;
- if (FAILED(compiler(vertex_hlsl.c_str(), vertex_hlsl.size(), "ffvertex", NULL, NULL,
- ENTRY_POINT, VERTEX_PROFILE, 0, 0, &vertex_code, &errors))) {
- Record_Compiler_Error("ffvertex", errors);
- Refuse(key, REFUSED_NO_PROGRAM);
- return false;
- }
- if (errors != NULL) {
- errors->Release();
- errors = NULL;
- }
- if (FAILED(compiler(pixel_hlsl.c_str(), pixel_hlsl.size(), "ffshader", NULL, NULL,
- ENTRY_POINT, PIXEL_PROFILE, 0, 0, &pixel_code, &errors))) {
- Record_Compiler_Error("ffshader", errors);
- vertex_code->Release();
+ std::vector<unsigned char> vertex_code;
+ std::vector<unsigned char> pixel_code;
+ if (!Compile_Program(vertex_hlsl, "ffvertex", VERTEX_PROFILE, vertex_code)
+ || !Compile_Program(pixel_hlsl, "ffshader", PIXEL_PROFILE, pixel_code)) {
Refuse(key, REFUSED_NO_PROGRAM);
return false;
}
- if (errors != NULL) {
- errors->Release();
- }
Pipeline built;
built.VertexShader = NULL;
@@ -899,15 +996,12 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)
built.Layout = NULL;
ID3D11Device * device = Device->Get_Device();
- const bool created = SUCCEEDED(device->CreateVertexShader(vertex_code->GetBufferPointer(),
- vertex_code->GetBufferSize(), NULL, &built.VertexShader))
- && SUCCEEDED(device->CreatePixelShader(pixel_code->GetBufferPointer(),
- pixel_code->GetBufferSize(), NULL, &built.PixelShader))
- && SUCCEEDED(device->CreateInputLayout(elements, element_count,
- vertex_code->GetBufferPointer(), vertex_code->GetBufferSize(), &built.Layout));
-
- pixel_code->Release();
- vertex_code->Release();
+ const bool created = SUCCEEDED(device->CreateVertexShader(&vertex_code[0], vertex_code.size(),
+ NULL, &built.VertexShader))
+ && SUCCEEDED(device->CreatePixelShader(&pixel_code[0], pixel_code.size(), NULL,
+ &built.PixelShader))
+ && SUCCEEDED(device->CreateInputLayout(elements, element_count, &vertex_code[0],
+ vertex_code.size(), &built.Layout));
if (!created) {
if (built.Layout != NULL) {
@@ -926,6 +1020,8 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)
Pipelines[key] = built;
++PipelinesBuilt;
+ FrameBuildMilliseconds += DX11Resource_Milliseconds_Now() - build_started;
+ ++FrameBuildCount;
pipeline = built;
Remember_Resolution(key, pipeline, vertex_description, combiner_description);
return true;
@@ -1584,3 +1680,11 @@ void DX11BackendClass::Statistics(unsigned & pipelines_built, unsigned long long
draws_made = DrawsMade;
draws_refused = DrawsRefused;
}
+
+void DX11BackendClass::Take_Frame_Build_Cost(double & milliseconds, unsigned & pipelines)
+{
+ milliseconds = FrameBuildMilliseconds;
+ pipelines = FrameBuildCount;
+ FrameBuildMilliseconds = 0.0;
+ FrameBuildCount = 0;
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
index d78a3b047..be7355b28 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
@@ -117,6 +117,12 @@ public:
// description is a key, and the key is not the code.
void Set_Dump_Directory(const char * directory);
+ // Keep every compiled program in this file across runs: read now, written at Shutdown when a
+ // program was compiled that the file did not hold. A program compiled mid-match costs 25 to
+ // 60ms on the frame that first needs it, which is the stutter a new explosion brought.
+ void Set_Shader_Cache_Path(const char * path);
+ unsigned Compiled_Program_Count() const { return static_cast<unsigned>(CompiledPrograms.size()); }
+
// Binds the swap chain's back buffer and depth buffer and sets the viewport over the whole of
// it. D3D11 keeps no default target: without this every draw is complete, legal, and lands
// nowhere. Called at the start of each scene rather than once, because a resize replaces both
@@ -152,6 +158,11 @@ public:
void Statistics(unsigned & pipelines_built, unsigned long long & draws_made,
unsigned long long & draws_refused) const;
+ // The pipelines built since the last call and the milliseconds they took, generation, compile
+ // and device objects together. A pipeline is built the first time its state reaches a draw, so
+ // this is the stutter a new effect costs on the frame it first appears.
+ void Take_Frame_Build_Cost(double & milliseconds, unsigned & pipelines);
+
// Why the refusals happened, in the order Draw checks them: no buffer bound, no texture stage
// enabled, a vertex format with no input layout, and a program the generator or the compiler
// would not produce. "Half the draws are refused" is not a finding; which half is.
@@ -408,6 +419,8 @@ private:
unsigned PipelinesBuilt;
unsigned long long DrawsMade;
unsigned long long DrawsRefused;
+ double FrameBuildMilliseconds;
+ unsigned FrameBuildCount;
enum RefusalReason { REFUSED_NO_STAGE, REFUSED_NO_LAYOUT, REFUSED_NO_PROGRAM,
REFUSED_NO_OBJECT };
@@ -417,10 +430,19 @@ private:
bool Any_Missing_Texture() const;
void Dump_Program(const std::string & key, const std::string & vertex_hlsl,
const std::string & pixel_hlsl);
+ bool Compile_Program(const std::string & source, const char * name, const char * profile,
+ std::vector<unsigned char> & bytecode);
+ void Save_Shader_Cache() const;
std::string CompilerError;
std::string DumpDirectory;
+ // Bytecode by the hash of the profile and the source it was compiled from. Two pipelines that
+ // generate the same vertex program share one compile, and so do two runs through the file.
+ std::map<unsigned long long, std::vector<unsigned char> > CompiledPrograms;
+ std::string ShaderCachePath;
+ bool ShaderCacheChanged;
+
unsigned long long RefusedNoBuffer;
unsigned long long RefusedNoStage;
unsigned long long RefusedNoLayout;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.h
index d31758dee..0ed1ad42c 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11resource.h
@@ -38,6 +38,16 @@
#include <d3d9.h>
#include <d3d11.h>
+// Wall time in milliseconds, for the per-frame costs the backend and the texture copies report.
+inline double DX11Resource_Milliseconds_Now()
+{
+ LARGE_INTEGER counter;
+ LARGE_INTEGER frequency;
+ QueryPerformanceCounter(&counter);
+ QueryPerformanceFrequency(&frequency);
+ return 1000.0 * static_cast<double>(counter.QuadPart) / static_cast<double>(frequency.QuadPart);
+}
+
// DXGI_FORMAT_UNKNOWN comes back for a format with no D3D11 counterpart, which the caller has to
// treat as a refusal: a texture created as UNKNOWN is not a texture. Two of the engine's formats
// are in that class - the palettised ones, which D3D11 dropped outright.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
index 463da9f1c..da6b0928c 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
@@ -38,6 +38,9 @@ static unsigned TwinBuffers = 0;
static unsigned long long TwinBytes = 0;
static std::string DumpDirectory;
+// Relative to the working directory, which for the game is Run/, next to the exe.
+static const char * const SHADER_CACHE_FILE = "dx11shaders.cache";
+
// What -dx11post asked for, kept as the effects rather than as the text so a name nobody knows is
// refused when the switch is read and not once a frame.
static DX11PostEffect PostChain[DX11_POST_CHAIN_LIMIT];
@@ -86,6 +89,7 @@ bool Direct3D11_Create(HWND window, unsigned width, unsigned height)
}
Backend.Set_Dump_Directory(DumpDirectory.c_str());
+ Backend.Set_Shader_Cache_Path(SHADER_CACHE_FILE);
// The chain is the one thing here that is allowed to fail without taking the backend with it:
// a machine whose compiler refuses the passes still gets the frame, just not the effect.
@@ -268,6 +272,16 @@ const char * Direct3D11_Texture_Note(unsigned index)
return DX11Texture_Note(index);
}
+unsigned Direct3D11_Texture_Copy_Shape_Count()
+{
+ return DX11Texture_Copy_Shape_Count();
+}
+
+const char * Direct3D11_Texture_Copy_Shape(unsigned index)
+{
+ return DX11Texture_Copy_Shape(index);
+}
+
void Direct3D11_Dump_Programs_To(const char * directory)
{
DumpDirectory = directory == NULL ? "" : directory;
@@ -598,3 +612,14 @@ void Direct3D11_Statistics(unsigned & pipelines_built, unsigned long long & draw
Backend.Statistics(pipelines_built, draws_made, draws_refused);
}
}
+
+void Direct3D11_Take_Frame_Cost(double & pipeline_milliseconds, unsigned & pipelines,
+ double & texture_milliseconds, unsigned & textures)
+{
+ pipeline_milliseconds = 0.0;
+ pipelines = 0;
+ if (Active) {
+ Backend.Take_Frame_Build_Cost(pipeline_milliseconds, pipelines);
+ }
+ DX11Texture_Take_Frame_Cost(texture_milliseconds, textures);
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
index bf197a5bc..e9dfd17e5 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
@@ -202,12 +202,21 @@ const char * Direct3D11_Texture_First_Refusal();
unsigned Direct3D11_Texture_Note_Count();
const char * Direct3D11_Texture_Note(unsigned index);
+// The texture shapes copied most often, most first. Count before reading the lines.
+unsigned Direct3D11_Texture_Copy_Shape_Count();
+const char * Direct3D11_Texture_Copy_Shape(unsigned index);
+
// What the run did, for the log: how many pipelines were built and how many draws the backend
// refused. A backend that refuses most of the draws looks like a renderer with a lot missing and
// says nothing about it otherwise.
void Direct3D11_Statistics(unsigned & pipelines_built, unsigned long long & draws_made,
unsigned long long & draws_refused);
+// What the frame since the last call spent building pipelines and copying textures, and how many
+// of each. Taking it resets it.
+void Direct3D11_Take_Frame_Cost(double & pipeline_milliseconds, unsigned & pipelines,
+ double & texture_milliseconds, unsigned & textures);
+
// The refusals split by cause: no buffer bound, no texture stage enabled, a vertex format with no
// input layout, and a program that could not be generated or compiled.
void Direct3D11_Refusals(unsigned long long & no_buffer, unsigned long long & no_stage,
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp
index bfb318706..b3dc62e55 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp
@@ -22,6 +22,8 @@
#include <d3d9.h>
#include <d3d11.h>
+#include <algorithm>
+#include <map>
#include <stdio.h>
#include <string.h>
#include <string>
@@ -62,6 +64,19 @@ static std::vector<std::string> Notes;
static unsigned Mirrored = 0;
static unsigned Refused = 0;
static unsigned Reused = 0;
+static double FrameCopyMilliseconds = 0.0;
+static unsigned FrameCopyCount = 0;
+
+// Builds and refreshes by the shape of the texture, for the report. A shape built thousands of
+// times in a match is a texture the engine makes and throws away every frame.
+struct CopyShapeCounts
+{
+ unsigned Builds;
+ unsigned Refreshes;
+};
+static std::map<std::string, CopyShapeCounts> CopyShapes;
+static std::vector<std::string> CopyShapeLines;
+static const unsigned COPY_SHAPE_REPORT_LINES = 10;
// D3DFMT_X8R8G8B8 has no alpha and its bytes hold whatever the loader left there. Read as
// B8G8R8A8 those bytes are the alpha channel, and a texture whose alpha reads as zero is a texture
@@ -356,6 +371,28 @@ static bool refresh_copy(ID3D11DeviceContext * context, ID3D11ShaderResourceView
return uploaded;
}
+static CopyShapeCounts & copy_shape(IDirect3DBaseTexture9 * texture)
+{
+ char shape[96] = "not a 2D texture";
+ IDirect3DTexture9 * two_dimensional = NULL;
+ if (SUCCEEDED(texture->QueryInterface(IID_IDirect3DTexture9, (void **)&two_dimensional))) {
+ D3DSURFACE_DESC description;
+ if (SUCCEEDED(two_dimensional->GetLevelDesc(0, &description))) {
+ snprintf(shape, sizeof(shape), "%ux%u format %d pool %d, %lu levels", description.Width,
+ description.Height, static_cast<int>(description.Format),
+ static_cast<int>(description.Pool), two_dimensional->GetLevelCount());
+ }
+ two_dimensional->Release();
+ }
+
+ std::map<std::string, CopyShapeCounts>::iterator entry = CopyShapes.find(shape);
+ if (entry == CopyShapes.end()) {
+ const CopyShapeCounts none = { 0, 0 };
+ entry = CopyShapes.insert(std::make_pair(std::string(shape), none)).first;
+ }
+ return entry->second;
+}
+
ID3D11ShaderResourceView * DX11Texture_Mirror(ID3D11Device * device, ID3D11DeviceContext * context,
IDirect3DBaseTexture9 * texture)
{
@@ -366,8 +403,12 @@ ID3D11ShaderResourceView * DX11Texture_Mirror(ID3D11Device * device, ID3D11Devic
// own, so this one is handed straight back.
view->Release();
if (texture_is_dirty(texture)) {
+ const double refresh_started = DX11Resource_Milliseconds_Now();
refresh_copy(context, view, texture);
clear_dirty(texture);
+ FrameCopyMilliseconds += DX11Resource_Milliseconds_Now() - refresh_started;
+ ++FrameCopyCount;
+ ++copy_shape(texture).Refreshes;
}
++Reused;
return view;
@@ -379,7 +420,11 @@ ID3D11ShaderResourceView * DX11Texture_Mirror(ID3D11Device * device, ID3D11Devic
return NULL;
}
+ const double build_started = DX11Resource_Milliseconds_Now();
view = build(device, context, texture);
+ FrameCopyMilliseconds += DX11Resource_Milliseconds_Now() - build_started;
+ ++FrameCopyCount;
+ ++copy_shape(texture).Builds;
if (view == NULL) {
const unsigned char marker = 1;
texture->SetPrivateData(DX11_TEXTURE_REFUSED, &marker, sizeof(marker), 0);
@@ -537,6 +582,14 @@ ID3D11RenderTargetView * DX11Texture_Target(ID3D11Device * device, ID3D11DeviceC
return target;
}
+void DX11Texture_Take_Frame_Cost(double & milliseconds, unsigned & copies)
+{
+ milliseconds = FrameCopyMilliseconds;
+ copies = FrameCopyCount;
+ FrameCopyMilliseconds = 0.0;
+ FrameCopyCount = 0;
+}
+
void DX11Texture_Statistics(unsigned & mirrored, unsigned & reused, unsigned & refused)
{
mirrored = Mirrored;
@@ -558,3 +611,30 @@ const char * DX11Texture_Note(unsigned index)
{
return (index < Notes.size()) ? Notes[index].c_str() : "";
}
+
+static bool more_copies(const std::pair<std::string, CopyShapeCounts> & left,
+ const std::pair<std::string, CopyShapeCounts> & right)
+{
+ return left.second.Builds + left.second.Refreshes > right.second.Builds + right.second.Refreshes;
+}
+
+unsigned DX11Texture_Copy_Shape_Count()
+{
+ std::vector<std::pair<std::string, CopyShapeCounts> > ranked(CopyShapes.begin(),
+ CopyShapes.end());
+ std::sort(ranked.begin(), ranked.end(), more_copies);
+
+ CopyShapeLines.clear();
+ for (size_t index = 0; index < ranked.size() && index < COPY_SHAPE_REPORT_LINES; ++index) {
+ char line[160];
+ snprintf(line, sizeof(line), "%s: %u built, %u refreshed", ranked[index].first.c_str(),
+ ranked[index].second.Builds, ranked[index].second.Refreshes);
+ CopyShapeLines.push_back(line);
+ }
+ return static_cast<unsigned>(CopyShapeLines.size());
+}
+
+const char * DX11Texture_Copy_Shape(unsigned index)
+{
+ return (index < CopyShapeLines.size()) ? CopyShapeLines[index].c_str() : "";
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h
index 28e117581..6b98272d7 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h
@@ -68,6 +68,9 @@ ID3D11RenderTargetView * DX11Texture_Target(ID3D11Device * device, ID3D11DeviceC
// the texture, and how many could not be copied at all.
void DX11Texture_Statistics(unsigned & mirrored, unsigned & reused, unsigned & refused);
+// The copies built or refreshed since the last call and the milliseconds they took.
+void DX11Texture_Take_Frame_Cost(double & milliseconds, unsigned & copies);
+
// Why the first refused texture was refused. Empty when none was.
const char * DX11Texture_First_Refusal();
@@ -78,4 +81,9 @@ const char * DX11Texture_First_Refusal();
unsigned DX11Texture_Note_Count();
const char * DX11Texture_Note(unsigned index);
+// The texture shapes copied most often, most first, one line each with how many copies were built
+// and how many refreshed. The count ranks them, so it is called before the lines are read.
+unsigned DX11Texture_Copy_Shape_Count();
+const char * DX11Texture_Copy_Shape(unsigned index);
+
#endif // DX11TEXTURE_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
index fc5fe523d..a3820aca4 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
@@ -1362,11 +1362,9 @@ bool DX8Wrapper::Set_Render_Device(int dev, int width, int height, int bits, int
WWDEBUG_SAY(("Reset/Create_Device done, reset_device=%d, restore_assets=%d\n", reset_device, restore_assets));
- // -dx11 builds the Direct3D 11 device beside the Direct3D 9 one rather than instead of it.
- // Phase 2 of RENDERER-ROADMAP.md is not finished: 236 places still call the D3D9 device
- // directly, so taking it away would be a black screen rather than a second backend. What this
- // gets is a device and a backend that the wrapper's own state calls reach, and a count at
- // shutdown of how much of the frame that turned out to be.
+ // The Direct3D 11 device is built beside the Direct3D 9 one rather than instead of it: 236
+ // places still call the D3D9 device directly, so taking it away would be a black screen. It
+ // is on unless -d3d9 or -headless turned it off.
if (Direct3D11_Is_Enabled() && !Direct3D11_Is_Active()) {
const bool created = Direct3D11_Create((HWND)_Hwnd,
_PresentParameters.BackBufferWidth, _PresentParameters.BackBufferHeight);
@@ -2341,13 +2339,15 @@ void DX8Wrapper::Draw_Sorting_IB_VB(
DX8_RECORD_INDEX_BUFFER_CHANGE();
DX8_RECORD_DRAW_CALLS();
- DX8CALL(DrawIndexedPrimitive(
- D3DPT_TRIANGLELIST,
- dyn_vb_access.VertexBufferOffset, // base vertex index, was SetIndices' second argument
- 0, // start vertex
- vertex_count,
- dyn_ib_access.IndexBufferOffset,
- polygon_count));
+ if (!Direct3D11_Present_Is_Enabled()) {
+ DX8CALL(DrawIndexedPrimitive(
+ D3DPT_TRIANGLELIST,
+ dyn_vb_access.VertexBufferOffset, // base vertex index, was SetIndices' second argument
+ 0, // start vertex
+ vertex_count,
+ dyn_ib_access.IndexBufferOffset,
+ polygon_count));
+ }
DX8_RECORD_RENDER(polygon_count,vertex_count,render_state.shader);
}
@@ -2531,13 +2531,20 @@ void DX8Wrapper::Draw(
}*/
DX8_RECORD_RENDER(polygon_count,vertex_count,render_state.shader);
DX8_RECORD_DRAW_CALLS();
- DX8CALL(DrawIndexedPrimitive(
- (D3DPRIMITIVETYPE)primitive_type,
- render_state.index_base_offset+render_state.vba_offset, // base vertex index, was SetIndices' second argument
- min_vertex_index,
- vertex_count,
- start_index+render_state.iba_offset,
- polygon_count));
+ // When Direct3D 11 owns the window, the Direct3D 9 frame is never shown and nothing
+ // reads its pixels back, so drawing it is only GPU time. The state is still set on
+ // the D3D9 device above: the fixed-function probe reads it, and the wrapper's own
+ // cache relies on it. _Draw_DX8_Primitive_UP keeps its D3D9 draw, because the smudge
+ // hardware test draws with it and reads the D3D9 target back.
+ if (!Direct3D11_Present_Is_Enabled()) {
+ DX8CALL(DrawIndexedPrimitive(
+ (D3DPRIMITIVETYPE)primitive_type,
+ render_state.index_base_offset+render_state.vba_offset, // base vertex index, was SetIndices' second argument
+ min_vertex_index,
+ vertex_count,
+ start_index+render_state.iba_offset,
+ polygon_count));
+ }
// The same draw through the Direct3D 11 backend, into its own back buffer. Only
// triangle lists go: a strip or a fan would need its indices rebuilt, and the
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.h
index 4dede1fc4..84815feae 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.h
@@ -34,13 +34,14 @@
#include <d3d9.h>
-// Off unless -ffprobe was given. Reading forty states back per draw call is not free.
+// Off until W3DDisplay turns it on, which the game always does. Reading forty states back per
+// draw call is not free.
void FixedFunctionProbe_Enable(bool enabled);
bool FixedFunctionProbe_Is_Enabled();
-// Off unless -ffshader was given. Replaces the texture stage combiners with a generated pixel
-// shader for every draw the generator will take, which is what phase 2 compares against the
-// fixed-function pipeline before carrying any of it to a second backend.
+// Off until W3DDisplay turns it on, which the game always does. Replaces the texture stage
+// combiners on the Direct3D 9 device with a generated pixel shader for every draw the generator
+// will take.
void CombinerShaders_Enable(bool enabled);
bool CombinerShaders_Are_Enabled();
diff --git a/GeneralsMD/Code/Tests/test_dx11backend.cpp b/GeneralsMD/Code/Tests/test_dx11backend.cpp
index 34fa8a364..20ca9b15c 100644
--- a/GeneralsMD/Code/Tests/test_dx11backend.cpp
+++ b/GeneralsMD/Code/Tests/test_dx11backend.cpp
@@ -29,7 +29,9 @@
#include "dx11backend.h"
#include "dx11resource.h"
+#include <stdio.h>
#include <string.h>
+#include <vector>
static const unsigned TARGET_SIZE = 64;
static const DWORD BACKEND_FVF = D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX2|D3DFVF_DIFFUSE;
@@ -365,6 +367,81 @@ TEST(dx11backend_the_same_state_resolves_to_one_pipeline)
backend.Shutdown();
}
+static const char * const CACHE_FILE_NAME = "dx11backend_test_shaders.cache";
+static const long LAST_RECORD_CUT_BYTES = 4;
+
+// A pipeline compiled in one run is not compiled again in the next: the backend writes what it
+// compiled when it shuts down, and a second one reading the file holds both halves of the program
+// before it has drawn anything. A file cut short while it was written gives up its last record and
+// keeps the rest, which is what a crash during the write leaves behind.
+TEST(dx11backend_compiled_programs_are_kept_in_the_cache_file)
+{
+ char path[MAX_PATH];
+ const DWORD directory_length = GetTempPathA(MAX_PATH, path);
+ CHECK(directory_length > 0 && directory_length + strlen(CACHE_FILE_NAME) < MAX_PATH);
+ strcat(path, CACHE_FILE_NAME);
+ DeleteFileA(path);
+
+ DX11DeviceClass device;
+ CHECK(device.Create_Offscreen());
+
+ DX11BackendClass writer;
+ CHECK(writer.Initialise(&device));
+ writer.Set_Shader_Cache_Path(path);
+ CHECK_EQ(writer.Compiled_Program_Count(), 0u);
+
+ ID3D11Buffer * vertices = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(device.Get_Device(), sizeof(QUAD_VERTICES),
+ D3DPOOL_MANAGED, 0, QUAD_VERTICES, &vertices));
+ ID3D11Buffer * indices = NULL;
+ CHECK(DX11Resource_Create_Index_Buffer(device.Get_Device(), sizeof(QUAD_INDICES),
+ D3DPOOL_MANAGED, 0, QUAD_INDICES, &indices));
+
+ writer.Set_Viewport(0, 0, TARGET_SIZE, TARGET_SIZE);
+ configure_unlit_pass_through(writer);
+ writer.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);
+ writer.Set_Indices(indices, DXGI_FORMAT_R16_UINT);
+ CHECK(writer.Draw_Indexed_Triangles(6, 0, 0));
+ CHECK_EQ(writer.Compiled_Program_Count(), 2u);
+
+ indices->Release();
+ vertices->Release();
+ writer.Shutdown();
+
+ DX11BackendClass reader;
+ CHECK(reader.Initialise(&device));
+ reader.Set_Shader_Cache_Path(path);
+ CHECK_EQ(reader.Compiled_Program_Count(), 2u);
+ reader.Shutdown();
+
+ std::vector<unsigned char> bytes;
+ FILE * file = fopen(path, "rb");
+ CHECK(file != NULL);
+ if (file != NULL) {
+ fseek(file, 0, SEEK_END);
+ bytes.resize(static_cast<size_t>(ftell(file)));
+ fseek(file, 0, SEEK_SET);
+ CHECK(fread(&bytes[0], bytes.size(), 1, file) == 1);
+ fclose(file);
+ }
+ CHECK(bytes.size() > static_cast<size_t>(LAST_RECORD_CUT_BYTES));
+
+ file = fopen(path, "wb");
+ CHECK(file != NULL);
+ if (file != NULL) {
+ fwrite(&bytes[0], bytes.size() - LAST_RECORD_CUT_BYTES, 1, file);
+ fclose(file);
+ }
+
+ DX11BackendClass cut_short;
+ CHECK(cut_short.Initialise(&device));
+ cut_short.Set_Shader_Cache_Path(path);
+ CHECK_EQ(cut_short.Compiled_Program_Count(), 1u);
+ cut_short.Shutdown();
+
+ DeleteFileA(path);
+}
+
// The alpha test, which on D3D11 is a clip inside the generated pixel shader rather than anything
// the pipeline does. The vertices carry an alpha of 0xff, so a reference above it cuts the whole
// quad away and the target keeps the colour it was cleared to. Get the comparison backwards and
diff --git a/dx11-check.ps1 b/dx11-check.ps1
index ab9c9d673..adbb781ea 100644
--- a/dx11-check.ps1
+++ b/dx11-check.ps1
@@ -6,8 +6,8 @@
# those right and still draw the wrong picture: the white terrain had a correct atlas, a correct
# program and a correct draw count for two sessions. Only two pictures of one frame settle it.
#
-# All three shots come from one exe. -dx11present is the only difference between them, so a view
-# that comes back apart is the backend and not a build, a map or a seed.
+# All three shots come from one exe. -d3d9 is the only difference between them, so a view that
+# comes back apart is the backend and not a build, a map or a seed.
#
# Three shots, not two. The instrument has noise of its own: particles advance per rendered frame,
# so each view is photographed twice through Direct3D 9 as well and the pair's own disagreement is
@@ -133,13 +133,13 @@ if ($cases.Count -eq 0) { throw "no view matches -Map $Map" }
$fail = 0
foreach ($c in $cases) {
$tag = ($c.map -replace '[^A-Za-z]','') + "_$($c.x)_$($c.f)"
- $nine = Shoot $c "d3d9a_$tag" @()
- $eleven = Shoot $c "dx11_$tag" @('-dx11present')
+ $nine = Shoot $c "d3d9a_$tag" @('-d3d9')
+ $eleven = Shoot $c "dx11_$tag" @()
if ($BackendNoise) {
- $again = Shoot $c "dx11b_$tag" @('-dx11present')
+ $again = Shoot $c "dx11b_$tag" @()
$noise = DiffPct $eleven $again
} else {
- $again = Shoot $c "d3d9b_$tag" @()
+ $again = Shoot $c "d3d9b_$tag" @('-d3d9')
$noise = DiffPct $nine $again
}
$signal = DiffPct $nine $eleven