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): a post-process chain over the Direct3D 11 frame

Olcay Seyganecf2e777d5a0
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index 1792d20b2..dcfc3dbf4 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -276,6 +276,16 @@ set_target_properties(dx11texture PROPERTIES CXX_STANDARD 17)
target_include_directories(dx11texture PUBLIC ${WW}/WW3D2)
target_link_libraries(dx11texture PUBLIC dx11resource d3d9 d3d11 dxguid)
+# ---- dx11post -------------------------------------------------------------
+# The offscreen render target between the scene and the swap chain, and the full
+# screen passes over it. Depends on the device and on nothing else: it reads a
+# texture and writes a render target, and knows nothing about the state
+# translation the rest of the backend is.
+add_library(dx11post STATIC ${WW}/WW3D2/dx11post.cpp)
+set_target_properties(dx11post PROPERTIES CXX_STANDARD 17)
+target_include_directories(dx11post PUBLIC ${WW}/WW3D2)
+target_link_libraries(dx11post PUBLIC dx11device d3d11)
+
# ---- dx11backend ----------------------------------------------------------
# The renderer itself: the engine's D3D9-shaped calls taken as they are and resolved
# into a D3D11 pipeline at the moment of the draw. Ties the five pieces above
@@ -341,7 +351,7 @@ target_include_directories(ww3d2
# D3DX9 has no import library anywhere and is bound at runtime instead: see
# WW3D2/d3dx9runtime.h. vfw32 is FramGrab.cpp writing AVIs.
target_link_libraries(ww3d2
- PUBLIC d3d9 dxguid vfw32 d3dx9runtime ffshader dx11backend dx11twin dx11texture
+ PUBLIC d3d9 dxguid vfw32 d3dx9runtime ffshader dx11backend dx11post dx11twin dx11texture
PRIVATE wwlib wwmath wwdebug wwsaveload)
# dx8webbrowser.cpp is the one file /MP cannot have: MSVC rejects #import under
# multi-process compilation (C2813) and finds the directive by a lexical scan, so
@@ -708,6 +718,7 @@ add_lib_test(test_dx11pipeline dx11device dx11state dx11layout ffshader ffvertex
add_lib_test(test_dx11resource dx11resource dx11device)
add_lib_test(test_engineshader engineshader)
add_lib_test(test_dx11backend dx11backend)
+add_lib_test(test_dx11post dx11post dx11device user32)
add_lib_test(test_dx11twin dx11twin dx11device)
add_lib_test(test_dx11texture dx11texture dx11device user32)
# Both runtimes in one binary, so where a triangle edge lands is a measurement rather than a reading
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index e4eb1c950..408ecb1d0 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -126,6 +126,7 @@ public:
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
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;
Int m_yResolution;
Int m_maxShellScreens; ///< this many shells layouts can be loaded at once
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index d3551b0d2..247ddb255 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -1395,6 +1395,40 @@ Int parseDirect3D11Present(char *args[], int num)
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.
+ *
+ * "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
+ * an eight bit target throws that away: the middle of a fireball is the same white as its edge.
+ * With bloom in the chain the scene goes into half floats, the bright pass thresholds on the
+ * amount by which something beat white, and the frame comes back to eight bits through a tone
+ * curve whose knee leaves everything ordinary exactly where it was.
+ *
+ * Everything else in the backend exists to draw the frame Direct3D 9 draws and this exists to
+ * draw a different one, so it is off unless it is asked for and dx11-check.ps1 is run without
+ * it. */
+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];
+ return 2;
+ }
+ TheWritableGlobalData->m_direct3D11PostChain = "fxaa";
+ }
+ return 1;
+}
+
Int parseCombinerShaders(char *args[], int num)
{
if (TheWritableGlobalData)
@@ -2164,6 +2198,7 @@ static CommandLineParam params[] =
{ "-dx11", parseDirect3D11 },
{ "-dx11present", parseDirect3D11Present },
{ "-dx11dump", parseDirect3D11Dump },
+ { "-dx11post", parseDirect3D11Post },
{ "-autocamera", parseAutoCamera },
{ "-camera", parseCameraLook },
{ "-tracemove", parseTraceMove },
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index 254015c19..23fab7c63 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -651,6 +651,7 @@ GlobalData::GlobalData()
m_direct3D11 = FALSE;
m_direct3D11Present = FALSE;
m_direct3D11DumpPath.clear();
+ m_direct3D11PostChain.clear();
m_xResolution = 800;
m_yResolution = 600;
m_maxShellScreens = 0;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index e54a01083..167370f49 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -504,6 +504,8 @@ W3DDisplay::~W3DDisplay()
if( Direct3D11_Diagnostic()[0] != '\0' )
DEBUG_LOG(("-dx11 note: %s\n", Direct3D11_Diagnostic()));
+ DEBUG_LOG(("-dx11 post: %s\n", Direct3D11_Post_Diagnostic()));
+
const unsigned traceCount = Direct3D11_Target_Trace_Count();
for( unsigned trace = 0; trace < traceCount; trace++ )
DEBUG_LOG(("-dx11 target trace: %s\n", Direct3D11_Target_Trace( trace )));
@@ -1029,6 +1031,12 @@ void W3DDisplay::init( void )
Direct3D11_Enable( TheGlobalData->m_direct3D11 != FALSE );
Direct3D11_Present_Enable( TheGlobalData->m_direct3D11Present != FALSE );
Direct3D11_Dump_Programs_To( TheGlobalData->m_direct3D11DumpPath.str() );
+ if( !Direct3D11_Post_Chain( TheGlobalData->m_direct3D11PostChain.str() )
+ && !TheGlobalData->m_direct3D11PostChain.isEmpty() )
+ {
+ DEBUG_LOG(( "-dx11post: '%s' names no effect this build has, so no chain runs\n",
+ TheGlobalData->m_direct3D11PostChain.str() ));
+ }
// Same problem, same answer: the filter table is built the moment the device exists and WW3D2
// cannot see GlobalData, so the player's texture filtering goes in here. Nothing in the game
@@ -2301,6 +2309,12 @@ AGAIN:
QueryPerformanceCounter( (LARGE_INTEGER *)&tSceneEnd );
#endif
+ // W3DView::draw has normally run the chain already, at the point where the world
+ // was finished and before the health bars went over it. This is the frame that
+ // drew no view at all: without it the scene would sit in the offscreen texture with
+ // the command bar drawn over a black screen.
+ Direct3D11_Finish_Scene();
+
// draw the user interface
TheInGameUI->DRAW();
#ifdef DEBUG_LOGGING
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp
index 6657dc16b..d70c9ba9e 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp
@@ -91,6 +91,7 @@
#include "WW3D2/Coltype.h"
#include "WW3D2/PredLod.h"
#include "WW3D2/WW3D.h"
+#include "WW3D2/dx11runtime.h"
#include "W3DDevice/GameClient/camerashakesystem.h"
@@ -2048,6 +2049,17 @@ void W3DView::draw( void )
// they are all drawn
/// @todo we might want to consider wiping this iterate out if there is nothing to post draw
//
+ // The world is finished here and everything below this line is drawn over it: health bars,
+ // veterancy chevrons, unit names, the 2D scene. So this is where -dx11post's chain runs, and
+ // the reason it is here rather than at the end of the frame is a health bar. Its border is one
+ // pixel of dark blue and an edge filter cannot tell a one pixel line from the edge of something
+ // bigger: run FXAA over it and the border is blended into the fill at one end and into the
+ // grass at the other, which reads as a bar with a frayed edge. The same argument moved it off
+ // the command bar first, where it was doubling the strokes of the font.
+ //
+ // Nothing happens here unless a chain was asked for, and only the first view of a frame runs it.
+ Direct3D11_Finish_Scene();
+
TheGameClient->resetRenderedObjectCount();
// the post draw is where health bars are drawn, and each one records where it landed
TheGameClient->clearHealthBarPickRegions();
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
index 924f76746..ba2a6e2e8 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -551,7 +551,7 @@ void DX11BackendClass::Begin_Scene()
return;
}
- ID3D11RenderTargetView * target = Device->Get_Back_Buffer_View();
+ ID3D11RenderTargetView * target = Device->Get_Scene_View();
if (target == NULL) {
return;
}
@@ -630,7 +630,7 @@ void DX11BackendClass::Set_Render_Target(ID3D11RenderTargetView * target)
Trace_Target("back buffer", 0, 0);
CurrentTarget = NULL;
CurrentDepth = NULL;
- ID3D11RenderTargetView * back_buffer = Device->Get_Back_Buffer_View();
+ ID3D11RenderTargetView * back_buffer = Device->Get_Scene_View();
if (back_buffer != NULL) {
Device->Get_Context()->OMSetRenderTargets(1, &back_buffer,
Device->Get_Depth_Stencil_View());
@@ -700,7 +700,7 @@ void DX11BackendClass::Clear(bool colour, bool depth, const float colour_value[4
// Whatever the draws are landing in is what a clear clears; a pass that clears its own render
// target and then draws into it would otherwise clear the picture instead.
ID3D11RenderTargetView * target = (CurrentTarget != NULL)
- ? CurrentTarget : Device->Get_Back_Buffer_View();
+ ? CurrentTarget : Device->Get_Scene_View();
ID3D11DepthStencilView * depth_view = (CurrentTarget != NULL)
? CurrentDepth : Device->Get_Depth_Stencil_View();
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp
index 6a6b7475f..f268f04ed 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.cpp
@@ -46,6 +46,7 @@ DX11DeviceClass::DX11DeviceClass()
, Context(NULL)
, SwapChain(NULL)
, BackBufferView(NULL)
+ , SceneView(NULL)
, DepthStencilView(NULL)
, DepthStencilTexture(NULL)
, FeatureLevel(D3D_FEATURE_LEVEL_11_0)
@@ -198,6 +199,9 @@ void DX11DeviceClass::Release_Views()
ID3D11RenderTargetView * no_target = NULL;
Context->OMSetRenderTargets(1, &no_target, NULL);
}
+ // Whoever lent it a scene view sized the texture behind it to the buffers that are about to go,
+ // so the loan ends here and the next frame asks for a new one.
+ SceneView = NULL;
release_interface(reinterpret_cast<IUnknown **>(&DepthStencilView));
release_interface(reinterpret_cast<IUnknown **>(&DepthStencilTexture));
release_interface(reinterpret_cast<IUnknown **>(&BackBufferView));
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h
index 5d56ca761..b1e20e0a6 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11device.h
@@ -78,6 +78,19 @@ public:
ID3D11RenderTargetView * Get_Back_Buffer_View() const { return BackBufferView; }
ID3D11DepthStencilView * Get_Depth_Stencil_View() const { return DepthStencilView; }
+ // Where the scene goes, which is not always the swap chain. The post-process chain hands its
+ // own texture's view over here at the top of every frame and the backend binds whatever it
+ // finds, so nothing between the two knows the frame is being drawn somewhere else first. NULL
+ // puts it back on the swap chain, which is what an absent or a failed chain leaves behind.
+ //
+ // The view is borrowed, not owned: whoever handed it over releases it, and hands it over again
+ // on the next frame if it is still there to hand over.
+ void Set_Scene_View(ID3D11RenderTargetView * view) { SceneView = view; }
+ ID3D11RenderTargetView * Get_Scene_View() const
+ {
+ return (SceneView != NULL) ? SceneView : BackBufferView;
+ }
+
unsigned Get_Width() const { return Width; }
unsigned Get_Height() const { return Height; }
@@ -106,6 +119,7 @@ private:
ID3D11DeviceContext * Context;
IDXGISwapChain * SwapChain;
ID3D11RenderTargetView * BackBufferView;
+ ID3D11RenderTargetView * SceneView;
ID3D11DepthStencilView * DepthStencilView;
ID3D11Texture2D * DepthStencilTexture;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.cpp
new file mode 100644
index 000000000..7463c53cd
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.cpp
@@ -0,0 +1,920 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "dx11post.h"
+
+#include "dx11device.h"
+
+#include <stdio.h>
+#include <string.h>
+#include <string>
+#include <windows.h>
+
+typedef HRESULT (WINAPI *D3DCompileFunction)(LPCVOID source_data, SIZE_T source_size,
+ LPCSTR source_name, const D3D_SHADER_MACRO * defines, ID3DInclude * include,
+ LPCSTR entry_point, LPCSTR target, UINT flags1, UINT flags2, ID3DBlob ** code,
+ ID3DBlob ** error_messages);
+
+// The same hand binding dx11backend.cpp does, and deliberately its own copy: this is a separate
+// static library and linking it against the backend to share twelve lines would drag the whole
+// state translation in behind them.
+static const char * const COMPILER_MODULE = "d3dcompiler_47.dll";
+static const char * const ENTRY_POINT = "main";
+static const char * const VERTEX_PROFILE = "vs_4_0";
+static const char * const PIXEL_PROFILE = "ps_4_0";
+
+static const unsigned FULL_SCREEN_VERTEX_COUNT = 3;
+
+// The swap chain's own format for the eight bit stages, so the last pass in a chain writes what it
+// reads and nothing converts anything on the way out.
+static const DXGI_FORMAT EIGHT_BIT_FORMAT = DXGI_FORMAT_B8G8R8A8_UNORM;
+
+// Half floats rather than full ones: the scene is a colour, sixteen bits of it are more range than
+// this game's art can fill, and it halves the bandwidth of every pass over the frame.
+static const DXGI_FORMAT FLOAT_FORMAT = DXGI_FORMAT_R16G16B16A16_FLOAT;
+
+// Bloom runs at a quarter of the window on each axis. A glow is low frequency by definition, so
+// the resolution it is computed at is the one thing about it nobody can see, and a quarter costs a
+// sixteenth of the samples.
+static const unsigned BLOOM_DIVISOR = 4;
+
+// Two horizontal and two vertical, which at a quarter resolution reaches about sixteen pixels of
+// the finished frame. A third pair was tried and the glow got wider without getting better.
+static const unsigned BLOOM_BLUR_PASSES = 2;
+
+// What counts as bright enough to bleed, what the bleed is worth when it is added back, and where
+// the tone curve starts bending.
+//
+// A threshold of one means brighter than white, which is a thing an eight bit target could not have
+// said at all, and it was worth checking that the game ever gets there rather than assuming it.
+// Eight inferno cannons firing into a column does not: at a threshold of one the frame comes back
+// unchanged even with the intensity at four, because a fire a few pixels across never stacks enough
+// additive particles to pass white. Thirty of them does, and at the same threshold of one the
+// fireballs come back with white centres and a glow on the ground around them. So the float target
+// earns its place, and the threshold stays where it is: a lower one blooms pale buildings and the
+// sky, which is the look this is trying not to have.
+//
+// An intensity of 1.5 against a quiet frame with nothing burning costs half a level a channel,
+// which is the cost of having this on when there is nothing for it to do.
+static const float BLOOM_THRESHOLD = 1.0f;
+static const float BLOOM_INTENSITY = 1.5f;
+static const float TONE_CURVE_KNEE = 0.8f;
+
+struct PostConstantBlock
+{
+ // One over the size of the texture being sampled, and its size. Per pass rather than per
+ // frame, because the bloom passes do not run at the size of the window.
+ float TexelSize[4];
+
+ // The step a separable blur takes, already in texture coordinates.
+ float BlurDirection[4];
+
+ // Threshold, intensity, knee.
+ float Tuning[4];
+};
+
+// A triangle big enough to cover the screen, made out of nothing. No vertex buffer and no input
+// layout: SV_VertexID walks 0, 1, 2 and the arithmetic turns them into (0,0), (2,0), (0,2) in
+// texture coordinates, whose triangle covers the whole of the unit square.
+static const char * const VERTEX_SHADER_SOURCE =
+ "struct VertexOutput\n"
+ "{\n"
+ " float4 Position : SV_POSITION;\n"
+ " float2 Texture : TEXCOORD0;\n"
+ "};\n"
+ "\n"
+ "VertexOutput main(uint index : SV_VertexID)\n"
+ "{\n"
+ " VertexOutput output;\n"
+ " output.Texture = float2((index << 1) & 2, index & 2);\n"
+ " output.Position = float4(output.Texture.x * 2.0 - 1.0,\n"
+ " 1.0 - output.Texture.y * 2.0, 0.0, 1.0);\n"
+ " return output;\n"
+ "}\n";
+
+static const char * const PIXEL_SHADER_PROLOGUE =
+ "struct VertexOutput\n"
+ "{\n"
+ " float4 Position : SV_POSITION;\n"
+ " float2 Texture : TEXCOORD0;\n"
+ "};\n"
+ "\n"
+ "Texture2D Source : register(t0);\n"
+ "Texture2D Extra : register(t1);\n"
+ "SamplerState Sampler : register(s0);\n"
+ "\n"
+ "cbuffer PostConstants : register(b0)\n"
+ "{\n"
+ " float4 TexelSize;\n"
+ " float4 BlurDirection;\n"
+ " float4 Tuning;\n"
+ "};\n"
+ "\n"
+ // Below the knee nothing moves, so a frame with nothing overbright in it comes back out as the
+ // frame that went in and the tone curve costs the picture nothing. From the knee upward every
+ // value between it and infinity is folded into the gap between the knee and white, which is
+ // what an eight bit buffer could not do: there, everything over white was white.
+ "float3 tone_curve(float3 colour)\n"
+ "{\n"
+ " float knee = Tuning.z;\n"
+ " float headroom = max(1.0 - knee, 0.0001);\n"
+ " float3 excess = max(colour - knee, 0.0);\n"
+ " return min(colour, knee) + headroom * (1.0 - exp(-excess / headroom));\n"
+ "}\n"
+ "\n";
+
+static const char * const COPY_SHADER_BODY =
+ "float4 main(VertexOutput input) : SV_TARGET\n"
+ "{\n"
+ " return Source.Sample(Sampler, input.Texture);\n"
+ "}\n";
+
+static const char * const TONE_MAP_SHADER_BODY =
+ "float4 main(VertexOutput input) : SV_TARGET\n"
+ "{\n"
+ " return float4(tone_curve(Source.Sample(Sampler, input.Texture).rgb), 1.0);\n"
+ "}\n";
+
+// FXAA, the 2009 shape of it: read the luminance of the four diagonal neighbours and the centre,
+// leave the pixel alone unless the spread between them says an edge runs through it, work out which
+// way the edge lies from which pair of corners is brighter, and average along it. Two samples give
+// the cheap answer and four the better one; if the four sample answer has strayed outside the
+// luminance range the neighbourhood had, it has blurred across something and the two sample answer
+// is taken instead.
+//
+// It runs on the finished world with no depth and no motion vectors, which is why it can sit here
+// at all. What it cannot do is recover an edge the frame never had: a thin wire drawn into one
+// pixel column stays one pixel wide.
+static const char * const FXAA_SHADER_BODY =
+ "static const float3 LUMINANCE_WEIGHTS = float3(0.299, 0.587, 0.114);\n"
+ "static const float EDGE_THRESHOLD = 0.125;\n"
+ "static const float EDGE_THRESHOLD_MINIMUM = 0.0416;\n"
+ "static const float SPAN_MAXIMUM = 8.0;\n"
+ "static const float REDUCE_SCALE = 0.125;\n"
+ "static const float REDUCE_MINIMUM = 0.0078125;\n"
+ "\n"
+ "float luminance(float3 colour)\n"
+ "{\n"
+ " return dot(colour, LUMINANCE_WEIGHTS);\n"
+ "}\n"
+ "\n"
+ "float4 main(VertexOutput input) : SV_TARGET\n"
+ "{\n"
+ " float2 texel = TexelSize.xy;\n"
+ " float3 centre = Source.Sample(Sampler, input.Texture).rgb;\n"
+ " float3 northWest = Source.Sample(Sampler, input.Texture + float2(-texel.x, -texel.y)).rgb;\n"
+ " float3 northEast = Source.Sample(Sampler, input.Texture + float2(texel.x, -texel.y)).rgb;\n"
+ " float3 southWest = Source.Sample(Sampler, input.Texture + float2(-texel.x, texel.y)).rgb;\n"
+ " float3 southEast = Source.Sample(Sampler, input.Texture + float2(texel.x, texel.y)).rgb;\n"
+ "\n"
+ " float centreLuminance = luminance(centre);\n"
+ " float northWestLuminance = luminance(northWest);\n"
+ " float northEastLuminance = luminance(northEast);\n"
+ " float southWestLuminance = luminance(southWest);\n"
+ " float southEastLuminance = luminance(southEast);\n"
+ "\n"
+ " float lowest = min(centreLuminance, min(min(northWestLuminance, northEastLuminance),\n"
+ " min(southWestLuminance, southEastLuminance)));\n"
+ " float highest = max(centreLuminance, max(max(northWestLuminance, northEastLuminance),\n"
+ " max(southWestLuminance, southEastLuminance)));\n"
+ " float spread = highest - lowest;\n"
+ " if (spread < max(EDGE_THRESHOLD_MINIMUM, highest * EDGE_THRESHOLD)) {\n"
+ " return float4(centre, 1.0);\n"
+ " }\n"
+ "\n"
+ " float2 direction;\n"
+ " direction.x = -((northWestLuminance + northEastLuminance)\n"
+ " - (southWestLuminance + southEastLuminance));\n"
+ " direction.y = (northWestLuminance + southWestLuminance)\n"
+ " - (northEastLuminance + southEastLuminance);\n"
+ "\n"
+ " float reduction = max((northWestLuminance + northEastLuminance + southWestLuminance\n"
+ " + southEastLuminance) * 0.25 * REDUCE_SCALE, REDUCE_MINIMUM);\n"
+ " float shortest = 1.0 / (min(abs(direction.x), abs(direction.y)) + reduction);\n"
+ " direction = clamp(direction * shortest, -SPAN_MAXIMUM, SPAN_MAXIMUM) * texel;\n"
+ "\n"
+ " float3 inner = 0.5 * (Source.Sample(Sampler, input.Texture + direction * (1.0 / 3.0 - 0.5)).rgb\n"
+ " + Source.Sample(Sampler, input.Texture + direction * (2.0 / 3.0 - 0.5)).rgb);\n"
+ " float3 outer = inner * 0.5\n"
+ " + 0.25 * (Source.Sample(Sampler, input.Texture + direction * -0.5).rgb\n"
+ " + Source.Sample(Sampler, input.Texture + direction * 0.5).rgb);\n"
+ "\n"
+ " float outerLuminance = luminance(outer);\n"
+ " float3 result = (outerLuminance < lowest || outerLuminance > highest) ? inner : outer;\n"
+ " return float4(result, 1.0);\n"
+ "}\n";
+
+// Unsharp mask: the pixel plus what it has that a blur of its neighbours does not. The amount is
+// low on purpose. This runs over the world and the world alone, but the world holds thin wires and
+// aerials as well as ground, and anything stronger rings around them.
+static const char * const SHARPEN_SHADER_BODY =
+ "static const float SHARPEN_AMOUNT = 0.35;\n"
+ "\n"
+ "float4 main(VertexOutput input) : SV_TARGET\n"
+ "{\n"
+ " float2 texel = TexelSize.xy;\n"
+ " float4 centre = Source.Sample(Sampler, input.Texture);\n"
+ " float3 neighbours = Source.Sample(Sampler, input.Texture + float2(-texel.x, 0.0)).rgb\n"
+ " + Source.Sample(Sampler, input.Texture + float2(texel.x, 0.0)).rgb\n"
+ " + Source.Sample(Sampler, input.Texture + float2(0.0, -texel.y)).rgb\n"
+ " + Source.Sample(Sampler, input.Texture + float2(0.0, texel.y)).rgb;\n"
+ " float3 sharpened = centre.rgb + (centre.rgb - neighbours * 0.25) * SHARPEN_AMOUNT;\n"
+ " return float4(saturate(sharpened), centre.a);\n"
+ "}\n";
+
+// The bright pass, downsampling as it goes: four taps of the full size frame averaged into one
+// quarter size texel, then the threshold taken off what is left. What survives is the amount by
+// which something was brighter than white, which is a quantity an eight bit scene target could not
+// have held.
+static const char * const BLOOM_EXTRACT_SHADER_BODY =
+ "float4 main(VertexOutput input) : SV_TARGET\n"
+ "{\n"
+ " float2 texel = TexelSize.xy;\n"
+ " float3 sum = Source.Sample(Sampler, input.Texture + float2(-texel.x, -texel.y)).rgb\n"
+ " + Source.Sample(Sampler, input.Texture + float2(texel.x, -texel.y)).rgb\n"
+ " + Source.Sample(Sampler, input.Texture + float2(-texel.x, texel.y)).rgb\n"
+ " + Source.Sample(Sampler, input.Texture + float2(texel.x, texel.y)).rgb;\n"
+ " return float4(max(sum * 0.25 - Tuning.x, 0.0), 1.0);\n"
+ "}\n";
+
+// One half of a separable gaussian. The direction comes in as a constant, so the same program is
+// the horizontal pass and the vertical one.
+static const char * const BLOOM_BLUR_SHADER_BODY =
+ "static const float WEIGHTS[5] =\n"
+ " { 0.227027, 0.1945946, 0.1216216, 0.054054, 0.016216 };\n"
+ "\n"
+ "float4 main(VertexOutput input) : SV_TARGET\n"
+ "{\n"
+ " float2 step = BlurDirection.xy;\n"
+ " float3 sum = Source.Sample(Sampler, input.Texture).rgb * WEIGHTS[0];\n"
+ " for (int index = 1; index < 5; ++index) {\n"
+ " float2 offset = step * index;\n"
+ " sum += Source.Sample(Sampler, input.Texture + offset).rgb * WEIGHTS[index];\n"
+ " sum += Source.Sample(Sampler, input.Texture - offset).rgb * WEIGHTS[index];\n"
+ " }\n"
+ " return float4(sum, 1.0);\n"
+ "}\n";
+
+// The scene and the glow added, then the tone curve, then eight bits. One pass rather than two
+// because the addition is what makes a value overbright and the curve is what brings it back, and
+// splitting them would mean writing the sum into a float target nobody else reads.
+static const char * const BLOOM_COMPOSITE_SHADER_BODY =
+ "float4 main(VertexOutput input) : SV_TARGET\n"
+ "{\n"
+ " float3 scene = Source.Sample(Sampler, input.Texture).rgb;\n"
+ " float3 glow = Extra.Sample(Sampler, input.Texture).rgb;\n"
+ " return float4(tone_curve(scene + glow * Tuning.y), 1.0);\n"
+ "}\n";
+
+static D3DCompileFunction compiler_function()
+{
+ static D3DCompileFunction compiler = NULL;
+ static bool attempted = false;
+ if (!attempted) {
+ attempted = true;
+ HMODULE module = LoadLibraryA(COMPILER_MODULE);
+ if (module != NULL) {
+ compiler = reinterpret_cast<D3DCompileFunction>(GetProcAddress(module, "D3DCompile"));
+ }
+ }
+ return compiler;
+}
+
+static void release_interface(IUnknown ** object)
+{
+ if (*object != NULL) {
+ (*object)->Release();
+ *object = NULL;
+ }
+}
+
+static const char * simple_effect_body(DX11PostEffect effect)
+{
+ switch (effect) {
+ case DX11_POST_FXAA:
+ return FXAA_SHADER_BODY;
+ case DX11_POST_SHARPEN:
+ return SHARPEN_SHADER_BODY;
+ default:
+ return COPY_SHADER_BODY;
+ }
+}
+
+const char * DX11Post_Effect_Name(DX11PostEffect effect)
+{
+ switch (effect) {
+ case DX11_POST_FXAA:
+ return "fxaa";
+ case DX11_POST_SHARPEN:
+ return "sharpen";
+ case DX11_POST_BLOOM:
+ return "bloom";
+ default:
+ return "copy";
+ }
+}
+
+bool DX11Post_Parse_Chain(const char * text, DX11PostEffect effects[DX11_POST_CHAIN_LIMIT],
+ unsigned & count)
+{
+ count = 0;
+ if (text == NULL) {
+ return false;
+ }
+
+ std::string remaining(text);
+ while (!remaining.empty()) {
+ const std::string::size_type separator = remaining.find(',');
+ std::string name = remaining.substr(0, separator);
+ remaining = (separator == std::string::npos) ? std::string() : remaining.substr(separator + 1);
+
+ if (name.empty()) {
+ continue;
+ }
+ if (name == "off" || name == "none") {
+ count = 0;
+ return true;
+ }
+ if (count == DX11_POST_CHAIN_LIMIT) {
+ count = 0;
+ return false;
+ }
+
+ if (name == "copy") {
+ effects[count++] = DX11_POST_COPY;
+ }
+ else if (name == "fxaa") {
+ effects[count++] = DX11_POST_FXAA;
+ }
+ else if (name == "sharpen") {
+ effects[count++] = DX11_POST_SHARPEN;
+ }
+ else if (name == "bloom") {
+ // Bloom decides the format the scene is kept in and hands the frame back in eight bits,
+ // so a chain cannot reach it after something else has already read the scene. Refusing
+ // beats quietly reordering: "fxaa,bloom" is a request somebody meant, and it is not one
+ // this can answer.
+ if (count != 0) {
+ count = 0;
+ return false;
+ }
+ effects[count++] = DX11_POST_BLOOM;
+ }
+ else {
+ count = 0;
+ return false;
+ }
+ }
+ return true;
+}
+
+DX11PostProcessClass::DX11PostProcessClass()
+ : Device(NULL)
+ , VertexShader(NULL)
+ , ToneMapShader(NULL)
+ , BloomExtractShader(NULL)
+ , BloomBlurShader(NULL)
+ , BloomCompositeShader(NULL)
+ , Sampler(NULL)
+ , BlendState(NULL)
+ , DepthState(NULL)
+ , RasterizerState(NULL)
+ , ConstantBuffer(NULL)
+ , ChainLength(0)
+ , Width(0)
+ , Height(0)
+ , BloomWidth(0)
+ , BloomHeight(0)
+ , TargetsAreFloat(false)
+ , ShadersReady(false)
+ , Resolved(false)
+{
+ memset(PixelShaders, 0, sizeof(PixelShaders));
+ memset(&SceneTarget, 0, sizeof(SceneTarget));
+ memset(ChainTargets, 0, sizeof(ChainTargets));
+ memset(BloomTargets, 0, sizeof(BloomTargets));
+ memset(Chain, 0, sizeof(Chain));
+ strcpy(Diagnostic, "post-process off");
+}
+
+DX11PostProcessClass::~DX11PostProcessClass()
+{
+ Shutdown();
+}
+
+bool DX11PostProcessClass::Initialise(DX11DeviceClass * device)
+{
+ Shutdown();
+ Device = device;
+ if (Device == NULL || Device->Get_Device() == NULL) {
+ strcpy(Diagnostic, "post-process off: no device");
+ return false;
+ }
+
+ ShadersReady = Create_Shaders() && Create_States();
+ if (!ShadersReady) {
+ Shutdown();
+ strcpy(Diagnostic, "post-process off: the compiler refused the passes");
+ return false;
+ }
+
+ Describe();
+ return true;
+}
+
+void DX11PostProcessClass::Shutdown()
+{
+ Release_Targets();
+ release_interface(reinterpret_cast<IUnknown **>(&ConstantBuffer));
+ release_interface(reinterpret_cast<IUnknown **>(&RasterizerState));
+ release_interface(reinterpret_cast<IUnknown **>(&DepthState));
+ release_interface(reinterpret_cast<IUnknown **>(&BlendState));
+ release_interface(reinterpret_cast<IUnknown **>(&Sampler));
+ release_interface(reinterpret_cast<IUnknown **>(&BloomCompositeShader));
+ release_interface(reinterpret_cast<IUnknown **>(&BloomBlurShader));
+ release_interface(reinterpret_cast<IUnknown **>(&BloomExtractShader));
+ release_interface(reinterpret_cast<IUnknown **>(&ToneMapShader));
+ for (unsigned index = 0; index < DX11_POST_SIMPLE_EFFECTS; ++index) {
+ release_interface(reinterpret_cast<IUnknown **>(&PixelShaders[index]));
+ }
+ release_interface(reinterpret_cast<IUnknown **>(&VertexShader));
+ Device = NULL;
+ ShadersReady = false;
+ Resolved = false;
+}
+
+void DX11PostProcessClass::Set_Chain(const DX11PostEffect effects[DX11_POST_CHAIN_LIMIT],
+ unsigned count)
+{
+ ChainLength = (count > DX11_POST_CHAIN_LIMIT) ? DX11_POST_CHAIN_LIMIT : count;
+ for (unsigned index = 0; index < ChainLength; ++index) {
+ Chain[index] = effects[index];
+ }
+ Describe();
+}
+
+bool DX11PostProcessClass::Scene_Is_Float() const
+{
+ return ChainLength > 0 && Chain[0] == DX11_POST_BLOOM;
+}
+
+static bool compile_pixel_shader(D3DCompileFunction compiler, ID3D11Device * device,
+ const char * body, ID3D11PixelShader ** shader)
+{
+ const std::string source = std::string(PIXEL_SHADER_PROLOGUE) + body;
+ ID3DBlob * code = NULL;
+ ID3DBlob * errors = NULL;
+ HRESULT result = compiler(source.c_str(), source.size(), "dx11post.ps", NULL, NULL, ENTRY_POINT,
+ PIXEL_PROFILE, 0, 0, &code, &errors);
+ release_interface(reinterpret_cast<IUnknown **>(&errors));
+ if (FAILED(result) || code == NULL) {
+ release_interface(reinterpret_cast<IUnknown **>(&code));
+ return false;
+ }
+ result = device->CreatePixelShader(code->GetBufferPointer(), code->GetBufferSize(), NULL, shader);
+ release_interface(reinterpret_cast<IUnknown **>(&code));
+ return SUCCEEDED(result);
+}
+
+bool DX11PostProcessClass::Create_Shaders()
+{
+ D3DCompileFunction compiler = compiler_function();
+ if (compiler == NULL) {
+ return false;
+ }
+
+ ID3DBlob * code = NULL;
+ ID3DBlob * errors = NULL;
+ HRESULT result = compiler(VERTEX_SHADER_SOURCE, strlen(VERTEX_SHADER_SOURCE), "dx11post.vs",
+ NULL, NULL, ENTRY_POINT, VERTEX_PROFILE, 0, 0, &code, &errors);
+ release_interface(reinterpret_cast<IUnknown **>(&errors));
+ if (FAILED(result) || code == NULL) {
+ release_interface(reinterpret_cast<IUnknown **>(&code));
+ return false;
+ }
+ result = Device->Get_Device()->CreateVertexShader(code->GetBufferPointer(),
+ code->GetBufferSize(), NULL, &VertexShader);
+ release_interface(reinterpret_cast<IUnknown **>(&code));
+ if (FAILED(result)) {
+ return false;
+ }
+
+ ID3D11Device * device = Device->Get_Device();
+ for (unsigned index = 0; index < DX11_POST_SIMPLE_EFFECTS; ++index) {
+ if (!compile_pixel_shader(compiler, device,
+ simple_effect_body(static_cast<DX11PostEffect>(index)), &PixelShaders[index])) {
+ return false;
+ }
+ }
+
+ return compile_pixel_shader(compiler, device, TONE_MAP_SHADER_BODY, &ToneMapShader)
+ && compile_pixel_shader(compiler, device, BLOOM_EXTRACT_SHADER_BODY, &BloomExtractShader)
+ && compile_pixel_shader(compiler, device, BLOOM_BLUR_SHADER_BODY, &BloomBlurShader)
+ && compile_pixel_shader(compiler, device, BLOOM_COMPOSITE_SHADER_BODY,
+ &BloomCompositeShader);
+}
+
+bool DX11PostProcessClass::Create_States()
+{
+ ID3D11Device * device = Device->Get_Device();
+
+ D3D11_SAMPLER_DESC sampler;
+ ZeroMemory(&sampler, sizeof(sampler));
+ // Bilinear, because FXAA samples between texels on purpose and the bloom passes read a smaller
+ // texture than they write. At the one to one mapping the full size passes have, a sample on a
+ // texel centre still returns that texel exactly.
+ sampler.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
+ sampler.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
+ sampler.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
+ sampler.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
+ sampler.ComparisonFunc = D3D11_COMPARISON_NEVER;
+ sampler.MaxLOD = D3D11_FLOAT32_MAX;
+ if (FAILED(device->CreateSamplerState(&sampler, &Sampler))) {
+ return false;
+ }
+
+ D3D11_BLEND_DESC blend;
+ ZeroMemory(&blend, sizeof(blend));
+ blend.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
+ if (FAILED(device->CreateBlendState(&blend, &BlendState))) {
+ return false;
+ }
+
+ D3D11_DEPTH_STENCIL_DESC depth;
+ ZeroMemory(&depth, sizeof(depth));
+ if (FAILED(device->CreateDepthStencilState(&depth, &DepthState))) {
+ return false;
+ }
+
+ D3D11_RASTERIZER_DESC rasterizer;
+ ZeroMemory(&rasterizer, sizeof(rasterizer));
+ rasterizer.FillMode = D3D11_FILL_SOLID;
+ // The full screen triangle is written once and its winding is whatever the arithmetic gives; not
+ // culling means the pass cannot be lost to a sign somewhere in it.
+ rasterizer.CullMode = D3D11_CULL_NONE;
+ rasterizer.DepthClipEnable = TRUE;
+ if (FAILED(device->CreateRasterizerState(&rasterizer, &RasterizerState))) {
+ return false;
+ }
+
+ D3D11_BUFFER_DESC constants;
+ ZeroMemory(&constants, sizeof(constants));
+ constants.ByteWidth = sizeof(PostConstantBlock);
+ constants.Usage = D3D11_USAGE_DYNAMIC;
+ constants.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
+ constants.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ return SUCCEEDED(device->CreateBuffer(&constants, NULL, &ConstantBuffer));
+}
+
+bool DX11PostProcessClass::Create_Target(Target & target, unsigned width, unsigned height,
+ DXGI_FORMAT format)
+{
+ ID3D11Device * device = Device->Get_Device();
+
+ D3D11_TEXTURE2D_DESC description;
+ ZeroMemory(&description, sizeof(description));
+ description.Width = width;
+ description.Height = height;
+ description.MipLevels = 1;
+ description.ArraySize = 1;
+ description.Format = format;
+ description.SampleDesc.Count = 1;
+ description.Usage = D3D11_USAGE_DEFAULT;
+ description.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
+
+ if (FAILED(device->CreateTexture2D(&description, NULL, &target.Texture))) {
+ return false;
+ }
+ if (FAILED(device->CreateRenderTargetView(target.Texture, NULL, &target.View))) {
+ return false;
+ }
+ return SUCCEEDED(device->CreateShaderResourceView(target.Texture, NULL, &target.Resource));
+}
+
+bool DX11PostProcessClass::Create_Targets(unsigned width, unsigned height, bool floating)
+{
+ const DXGI_FORMAT scene_format = floating ? FLOAT_FORMAT : EIGHT_BIT_FORMAT;
+ if (!Create_Target(SceneTarget, width, height, scene_format)) {
+ Release_Targets();
+ return false;
+ }
+
+ const unsigned chain_target_count = sizeof(ChainTargets) / sizeof(ChainTargets[0]);
+ for (unsigned index = 0; index < chain_target_count; ++index) {
+ if (!Create_Target(ChainTargets[index], width, height, EIGHT_BIT_FORMAT)) {
+ Release_Targets();
+ return false;
+ }
+ }
+
+ // A window narrower than the divisor would ask for a zero wide texture, which is refused.
+ BloomWidth = (width / BLOOM_DIVISOR) > 0 ? (width / BLOOM_DIVISOR) : 1;
+ BloomHeight = (height / BLOOM_DIVISOR) > 0 ? (height / BLOOM_DIVISOR) : 1;
+ if (floating) {
+ const unsigned bloom_target_count = sizeof(BloomTargets) / sizeof(BloomTargets[0]);
+ for (unsigned index = 0; index < bloom_target_count; ++index) {
+ if (!Create_Target(BloomTargets[index], BloomWidth, BloomHeight, FLOAT_FORMAT)) {
+ Release_Targets();
+ return false;
+ }
+ }
+ }
+
+ Width = width;
+ Height = height;
+ TargetsAreFloat = floating;
+ return true;
+}
+
+void DX11PostProcessClass::Release_Target(Target & target)
+{
+ release_interface(reinterpret_cast<IUnknown **>(&target.Resource));
+ release_interface(reinterpret_cast<IUnknown **>(&target.View));
+ release_interface(reinterpret_cast<IUnknown **>(&target.Texture));
+}
+
+void DX11PostProcessClass::Release_Targets()
+{
+ Release_Target(SceneTarget);
+ const unsigned chain_target_count = sizeof(ChainTargets) / sizeof(ChainTargets[0]);
+ for (unsigned index = 0; index < chain_target_count; ++index) {
+ Release_Target(ChainTargets[index]);
+ }
+ const unsigned bloom_target_count = sizeof(BloomTargets) / sizeof(BloomTargets[0]);
+ for (unsigned index = 0; index < bloom_target_count; ++index) {
+ Release_Target(BloomTargets[index]);
+ }
+ Width = 0;
+ Height = 0;
+ BloomWidth = 0;
+ BloomHeight = 0;
+ TargetsAreFloat = false;
+}
+
+bool DX11PostProcessClass::Ensure_Buffers()
+{
+ if (!ShadersReady || ChainLength == 0 || Device == NULL) {
+ return false;
+ }
+
+ const unsigned width = Device->Get_Width();
+ const unsigned height = Device->Get_Height();
+ if (width == 0 || height == 0) {
+ return false;
+ }
+
+ const bool floating = Scene_Is_Float();
+ if (SceneTarget.View != NULL && Width == width && Height == height
+ && TargetsAreFloat == floating) {
+ return true;
+ }
+
+ // A resolution change makes the old set the wrong size, and a chain that gained or lost bloom
+ // makes the scene target the wrong format. Both are for the rest of the run, not for a frame.
+ Release_Targets();
+ if (!Create_Targets(width, height, floating)) {
+ Release_Targets();
+ strcpy(Diagnostic, "post-process off: the device refused the offscreen targets");
+ return false;
+ }
+ Describe();
+ return true;
+}
+
+ID3D11RenderTargetView * DX11PostProcessClass::Scene_View()
+{
+ return Ensure_Buffers() ? SceneTarget.View : NULL;
+}
+
+void DX11PostProcessClass::Begin_Frame()
+{
+ Resolved = false;
+}
+
+void DX11PostProcessClass::Draw_Pass(const PassSetup & pass)
+{
+ ID3D11DeviceContext * context = Device->Get_Context();
+
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ if (FAILED(context->Map(ConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {
+ return;
+ }
+ PostConstantBlock block;
+ block.TexelSize[0] = 1.0f / static_cast<float>(pass.SourceWidth);
+ block.TexelSize[1] = 1.0f / static_cast<float>(pass.SourceHeight);
+ block.TexelSize[2] = static_cast<float>(pass.SourceWidth);
+ block.TexelSize[3] = static_cast<float>(pass.SourceHeight);
+ block.BlurDirection[0] = pass.BlurX;
+ block.BlurDirection[1] = pass.BlurY;
+ block.BlurDirection[2] = 0.0f;
+ block.BlurDirection[3] = 0.0f;
+ block.Tuning[0] = BLOOM_THRESHOLD;
+ block.Tuning[1] = BLOOM_INTENSITY;
+ block.Tuning[2] = TONE_CURVE_KNEE;
+ block.Tuning[3] = 0.0f;
+ memcpy(mapped.pData, &block, sizeof(block));
+ context->Unmap(ConstantBuffer, 0);
+
+ // No depth: the pass covers every pixel exactly once and a depth buffer left bound would test
+ // the triangle against the scene it is reading.
+ context->OMSetRenderTargets(1, &pass.Destination, NULL);
+
+ D3D11_VIEWPORT viewport;
+ viewport.TopLeftX = 0.0f;
+ viewport.TopLeftY = 0.0f;
+ viewport.Width = static_cast<float>(pass.DestinationWidth);
+ viewport.Height = static_cast<float>(pass.DestinationHeight);
+ viewport.MinDepth = 0.0f;
+ viewport.MaxDepth = 1.0f;
+ context->RSSetViewports(1, &viewport);
+
+ const float blend_factor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
+ context->OMSetBlendState(BlendState, blend_factor, 0xffffffff);
+ context->OMSetDepthStencilState(DepthState, 0);
+ context->RSSetState(RasterizerState);
+
+ context->IASetInputLayout(NULL);
+ context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ context->VSSetShader(VertexShader, NULL, 0);
+ context->PSSetShader(pass.Shader, NULL, 0);
+ context->PSSetSamplers(0, 1, &Sampler);
+ ID3D11ShaderResourceView * resources[2] = { pass.Source, pass.Extra };
+ context->PSSetShaderResources(0, 2, resources);
+ context->PSSetConstantBuffers(0, 1, &ConstantBuffer);
+
+ context->Draw(FULL_SCREEN_VERTEX_COUNT, 0);
+
+ // The texture this pass read is the target the next one writes, and D3D11 unbinds a resource
+ // silently when it is bound both ways at once. Letting go here says which of the two bindings
+ // was meant.
+ ID3D11ShaderResourceView * no_resources[2] = { NULL, NULL };
+ context->PSSetShaderResources(0, 2, no_resources);
+}
+
+ID3D11ShaderResourceView * DX11PostProcessClass::Run_Bloom(ID3D11RenderTargetView * destination)
+{
+ const float bloom_texel_x = 1.0f / static_cast<float>(BloomWidth);
+ const float bloom_texel_y = 1.0f / static_cast<float>(BloomHeight);
+
+ PassSetup pass;
+ memset(&pass, 0, sizeof(pass));
+
+ // The bright pass reads the full size scene and writes the quarter size target, so it is the
+ // one pass whose source and destination sizes differ.
+ pass.Shader = BloomExtractShader;
+ pass.Source = SceneTarget.Resource;
+ pass.Destination = BloomTargets[0].View;
+ pass.DestinationWidth = BloomWidth;
+ pass.DestinationHeight = BloomHeight;
+ pass.SourceWidth = Width;
+ pass.SourceHeight = Height;
+ Draw_Pass(pass);
+
+ pass.Shader = BloomBlurShader;
+ pass.SourceWidth = BloomWidth;
+ pass.SourceHeight = BloomHeight;
+ unsigned source = 0;
+ for (unsigned iteration = 0; iteration < BLOOM_BLUR_PASSES; ++iteration) {
+ for (unsigned axis = 0; axis < 2; ++axis) {
+ const unsigned other = 1 - source;
+ pass.Source = BloomTargets[source].Resource;
+ pass.Destination = BloomTargets[other].View;
+ pass.BlurX = (axis == 0) ? bloom_texel_x : 0.0f;
+ pass.BlurY = (axis == 0) ? 0.0f : bloom_texel_y;
+ Draw_Pass(pass);
+ source = other;
+ }
+ }
+
+ pass.Shader = BloomCompositeShader;
+ pass.Source = SceneTarget.Resource;
+ pass.Extra = BloomTargets[source].Resource;
+ pass.Destination = destination;
+ pass.DestinationWidth = Width;
+ pass.DestinationHeight = Height;
+ pass.SourceWidth = Width;
+ pass.SourceHeight = Height;
+ pass.BlurX = 0.0f;
+ pass.BlurY = 0.0f;
+ Draw_Pass(pass);
+
+ return ChainTargets[0].Resource;
+}
+
+bool DX11PostProcessClass::Finish(const DX11PostEffect * effects, unsigned count)
+{
+ if (Resolved || count == 0 || !Ensure_Buffers()) {
+ return false;
+ }
+
+ ID3D11RenderTargetView * back_buffer = Device->Get_Back_Buffer_View();
+ if (back_buffer == NULL) {
+ return false;
+ }
+
+ unsigned first = 0;
+ ID3D11ShaderResourceView * source = SceneTarget.Resource;
+ if (effects[0] == DX11_POST_BLOOM) {
+ // Bloom is the only effect that reads the half float scene, and the frame is eight bits by
+ // the time it hands over. If it is also the last thing in the chain it writes the screen.
+ const bool alone = (count == 1);
+ source = Run_Bloom(alone ? back_buffer : ChainTargets[0].View);
+ if (alone) {
+ Resolved = true;
+ return true;
+ }
+ first = 1;
+ }
+
+ // Each remaining pass reads one eight bit target and writes the other, and the last one writes
+ // the swap chain instead, so an odd or an even chain both end up on the screen.
+ unsigned destination = (first == 0) ? 0u : 1u;
+ PassSetup pass;
+ memset(&pass, 0, sizeof(pass));
+ pass.DestinationWidth = Width;
+ pass.DestinationHeight = Height;
+ pass.SourceWidth = Width;
+ pass.SourceHeight = Height;
+ for (unsigned index = first; index < count; ++index) {
+ const bool last = (index + 1 == count);
+ pass.Shader = PixelShaders[effects[index]];
+ pass.Source = source;
+ pass.Destination = last ? back_buffer : ChainTargets[destination].View;
+ Draw_Pass(pass);
+ source = ChainTargets[destination].Resource;
+ destination = 1 - destination;
+ }
+
+ Resolved = true;
+ return true;
+}
+
+bool DX11PostProcessClass::Run_Chain()
+{
+ return Finish(Chain, ChainLength);
+}
+
+bool DX11PostProcessClass::Copy_Through()
+{
+ if (Resolved || ChainLength == 0 || !Ensure_Buffers()) {
+ return false;
+ }
+
+ ID3D11RenderTargetView * back_buffer = Device->Get_Back_Buffer_View();
+ if (back_buffer == NULL) {
+ return false;
+ }
+
+ // The tone curve rather than the copy when the scene is half float, because the swap chain
+ // cannot hold what the scene target holds and a raw write would clamp it. In eight bits the
+ // copy is exact, which is what the plumbing test measures.
+ PassSetup pass;
+ memset(&pass, 0, sizeof(pass));
+ pass.Shader = TargetsAreFloat ? ToneMapShader : PixelShaders[DX11_POST_COPY];
+ pass.Source = SceneTarget.Resource;
+ pass.Destination = back_buffer;
+ pass.DestinationWidth = Width;
+ pass.DestinationHeight = Height;
+ pass.SourceWidth = Width;
+ pass.SourceHeight = Height;
+ Draw_Pass(pass);
+
+ Resolved = true;
+ return true;
+}
+
+void DX11PostProcessClass::Describe()
+{
+ if (!ShadersReady) {
+ return;
+ }
+ if (ChainLength == 0) {
+ strcpy(Diagnostic, "post-process off");
+ return;
+ }
+
+ std::string names;
+ for (unsigned index = 0; index < ChainLength; ++index) {
+ if (index > 0) {
+ names += ",";
+ }
+ names += DX11Post_Effect_Name(Chain[index]);
+ }
+ snprintf(Diagnostic, sizeof(Diagnostic), "post-process %s over %ux%u, scene in %s", names.c_str(),
+ Width, Height, TargetsAreFloat ? "half floats" : "eight bits");
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.h
new file mode 100644
index 000000000..e39d78e02
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11post.h
@@ -0,0 +1,212 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/*
+** A render target between the scene and the swap chain, and full screen passes over it.
+**
+** Everything the Direct3D 11 backend does up to here answers one question: does it draw the same
+** frame Direct3D 9 draws. This is the first thing that deliberately draws a different one. The
+** scene goes into a texture instead of into the back buffer, a pixel shader reads that texture and
+** writes the back buffer, and what that shader does is the effect. Nothing above this knows: the
+** backend binds Get_Scene_View() where it used to bind the back buffer view and the change ends
+** there.
+**
+** The chain is off by default and the exit measurement for the backend is taken with it off. An
+** effect that improves the picture makes the frame differ from Direct3D 9's on purpose, which is
+** the one thing dx11-check.ps1 is built to refuse, so the two cannot both be the default and this
+** is the one that gives way.
+**
+** Where it runs matters as much as what it does. W3DView::draw calls for the chain at the moment
+** the world is finished and before the health bars, the unit names and the command bar go over it.
+** An edge filter cannot tell a one pixel line from the edge of something bigger, so run over a
+** health bar it eats the border, and run over the command bar it doubles the strokes of the font.
+** Both of those were measured before the call moved.
+**
+** The pass sets its own viewport with no half pixel in it. DX11BackendClass::Set_Viewport carries
+** Direct3D 9's pixel centre for the scene's geometry; a full screen triangle wants the texel it is
+** over and nothing else, and inheriting that offset resamples the whole frame half a pixel across.
+**
+** Bloom is why the scene target can be a float one. Generals blends its explosion particles
+** additively, so a stack of them is already brighter than white before it is written down; in an
+** eight bit target that arrives clamped and the middle of a fireball is the same white as its edge.
+** With a half float target the energy survives, the bright pass can threshold on it, and what
+** blooms is the fireball rather than every pale building. The frame comes back to eight bits
+** through a tone curve with a knee: below the knee nothing moves at all, so a frame with nothing
+** overbright in it is the frame that went in, and everything above the knee is folded into the gap
+** between the knee and white.
+*/
+
+#ifndef DX11POST_H
+#define DX11POST_H
+
+#include <d3d11.h>
+
+class DX11DeviceClass;
+
+enum DX11PostEffect
+{
+ // Straight copy, which is what proves the plumbing rather than the shader: with this in the
+ // chain the frame that reaches the screen has been through the offscreen texture and the full
+ // screen pass and has to come out unchanged.
+ DX11_POST_COPY,
+
+ // Edge antialiasing in one pass over the finished world. The Direct3D 9 device offers
+ // multisampling and the swap chain here asks for one sample, so this is what the D3D11 frame
+ // has against a jagged edge.
+ DX11_POST_FXAA,
+
+ // Unsharp mask. The game's textures are 2003 vintage and a 1080p window magnifies them; this
+ // is a taste knob and it is not in the default chain.
+ DX11_POST_SHARPEN,
+
+ // Bright things bleed light, and the scene is kept in half floats so that "bright" means
+ // brighter than white rather than close to it. Several passes rather than one, and it takes
+ // the frame from half float back to eight bits, so it can only be the first effect in a chain.
+ DX11_POST_BLOOM
+};
+
+// The effects that are one pass over one texture. Bloom is not one of them and is handled apart.
+const unsigned DX11_POST_SIMPLE_EFFECTS = DX11_POST_BLOOM;
+
+// Room for every effect at once. A chain longer than the effects that exist repeats one, which is
+// allowed and is how sharpening twice is asked for.
+const unsigned DX11_POST_CHAIN_LIMIT = 4;
+
+// Reads "fxaa", "bloom,fxaa", "copy", "off" or "none". Returns false and leaves count at zero for
+// a name it does not know and for a chain with bloom anywhere but first, so a misspelt or
+// impossible switch turns the chain off loudly rather than silently drawing something else.
+// Separated from the class so it can be tested without a device.
+bool DX11Post_Parse_Chain(const char * text, DX11PostEffect effects[DX11_POST_CHAIN_LIMIT],
+ unsigned & count);
+
+// The name a parsed effect goes back to, for the report line.
+const char * DX11Post_Effect_Name(DX11PostEffect effect);
+
+class DX11PostProcessClass
+{
+public:
+ DX11PostProcessClass();
+ ~DX11PostProcessClass();
+
+ bool Initialise(DX11DeviceClass * device);
+ void Shutdown();
+
+ // An empty chain is the whole feature turned off: Scene_View gives back nothing and the device
+ // keeps drawing into the swap chain the way it always has.
+ void Set_Chain(const DX11PostEffect effects[DX11_POST_CHAIN_LIMIT], unsigned count);
+ unsigned Chain_Length() const { return ChainLength; }
+
+ // True when the scene is being kept in half floats, which is what bloom asks for.
+ bool Scene_Is_Float() const;
+
+ // Where the scene is drawn: the offscreen texture while a chain is set and the buffers are
+ // built, and NULL otherwise, which the device reads as the swap chain. So a failure anywhere
+ // in here costs the effect and not the picture.
+ ID3D11RenderTargetView * Scene_View();
+
+ // Runs the chain into the swap chain's back buffer. Called when the world has been drawn and
+ // before anything two dimensional goes on top of it. Returns false when this frame is already
+ // finished.
+ bool Run_Chain();
+
+ // The scene into the swap chain with no effect over it, for a frame nobody ran the chain on: a
+ // menu, a loading screen. Without this a frame that never reached the world would sit in the
+ // offscreen texture and the screen would stay black. A half float scene still goes through the
+ // tone curve here, because the swap chain cannot hold what it holds.
+ bool Copy_Through();
+
+ // Call at the top of a frame. Arms the two above again.
+ void Begin_Frame();
+
+ // One line for the shutdown report: the chain, the size of the buffers, and the reason there is
+ // no chain if there is not one.
+ const char * Diagnostic_Line() const { return Diagnostic; }
+
+private:
+ DX11PostProcessClass(const DX11PostProcessClass &);
+ DX11PostProcessClass & operator=(const DX11PostProcessClass &);
+
+ struct Target
+ {
+ ID3D11Texture2D * Texture;
+ ID3D11RenderTargetView * View;
+ ID3D11ShaderResourceView * Resource;
+ };
+
+ // Everything one full screen pass needs. It grew past what a readable argument list holds once
+ // bloom arrived: the passes no longer all read one texture, and no longer all run at the size
+ // of the window.
+ struct PassSetup
+ {
+ ID3D11PixelShader * Shader;
+ ID3D11ShaderResourceView * Source;
+ ID3D11ShaderResourceView * Extra;
+ ID3D11RenderTargetView * Destination;
+ unsigned DestinationWidth;
+ unsigned DestinationHeight;
+ unsigned SourceWidth;
+ unsigned SourceHeight;
+ float BlurX;
+ float BlurY;
+ };
+
+ bool Create_Shaders();
+ bool Create_States();
+ bool Create_Target(Target & target, unsigned width, unsigned height, DXGI_FORMAT format);
+ bool Create_Targets(unsigned width, unsigned height, bool floating);
+ void Release_Target(Target & target);
+ void Release_Targets();
+ bool Ensure_Buffers();
+ bool Finish(const DX11PostEffect * effects, unsigned count);
+ ID3D11ShaderResourceView * Run_Bloom(ID3D11RenderTargetView * destination);
+ void Draw_Pass(const PassSetup & pass);
+ void Describe();
+
+ DX11DeviceClass * Device;
+ ID3D11VertexShader * VertexShader;
+ ID3D11PixelShader * PixelShaders[DX11_POST_SIMPLE_EFFECTS];
+ ID3D11PixelShader * ToneMapShader;
+ ID3D11PixelShader * BloomExtractShader;
+ ID3D11PixelShader * BloomBlurShader;
+ ID3D11PixelShader * BloomCompositeShader;
+ ID3D11SamplerState * Sampler;
+ ID3D11BlendState * BlendState;
+ ID3D11DepthStencilState * DepthState;
+ ID3D11RasterizerState * RasterizerState;
+ ID3D11Buffer * ConstantBuffer;
+
+ // The scene lands in the first. The other two are what a chain of more than one effect uses in
+ // turn, and they are always eight bit: the frame is back from half float by the time any of the
+ // one pass effects sees it.
+ Target SceneTarget;
+ Target ChainTargets[2];
+ Target BloomTargets[2];
+
+ DX11PostEffect Chain[DX11_POST_CHAIN_LIMIT];
+ unsigned ChainLength;
+ unsigned Width;
+ unsigned Height;
+ unsigned BloomWidth;
+ unsigned BloomHeight;
+ bool TargetsAreFloat;
+ bool ShadersReady;
+ bool Resolved;
+ char Diagnostic[192];
+};
+
+#endif // DX11POST_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
index c9c907ce9..0508fb0a9 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
@@ -23,6 +23,7 @@
#include "dx11backend.h"
#include "dx11device.h"
+#include "dx11post.h"
#include "dx11texture.h"
#include "dx11twin.h"
@@ -31,10 +32,16 @@ static bool PresentRequested = false;
static bool Active = false;
static DX11DeviceClass Device;
static DX11BackendClass Backend;
+static DX11PostProcessClass Post;
static unsigned TwinBuffers = 0;
static unsigned long long TwinBytes = 0;
static std::string DumpDirectory;
+// 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];
+static unsigned PostChainLength = 0;
+
// Which shipped shader each created Direct3D 9 shader came from. Registered at load, read at every
// bind. It outlives the shaders themselves, which cost the map an entry each and nothing else: the
// engine loads ten of them once and releases them when the game ends.
@@ -78,6 +85,13 @@ bool Direct3D11_Create(HWND window, unsigned width, unsigned height)
}
Backend.Set_Dump_Directory(DumpDirectory.c_str());
+
+ // 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.
+ if (Post.Initialise(&Device)) {
+ Post.Set_Chain(PostChain, PostChainLength);
+ }
+
Active = true;
return true;
}
@@ -87,6 +101,8 @@ void Direct3D11_Release()
if (!Active) {
return;
}
+ Post.Shutdown();
+ Device.Set_Scene_View(NULL);
Backend.Shutdown();
Device.Release();
Active = false;
@@ -261,9 +277,51 @@ bool Direct3D11_Present_Is_Enabled()
return PresentRequested && Active;
}
+bool Direct3D11_Post_Chain(const char * chain)
+{
+ const bool understood = DX11Post_Parse_Chain(chain, PostChain, PostChainLength);
+ if (Active) {
+ Post.Set_Chain(PostChain, PostChainLength);
+ }
+ return understood;
+}
+
+const char * Direct3D11_Post_Diagnostic()
+{
+ return Active ? Post.Diagnostic_Line() : "post-process off";
+}
+
+// Whatever put the frame in front of the player, the swap chain is where everything after it has to
+// be drawn. Rebinding through the backend rather than by hand is what gets the depth buffer and the
+// scene's own viewport offset back at the same time.
+static void take_the_frame_to_the_screen()
+{
+ Device.Set_Scene_View(NULL);
+ Backend.Begin_Scene();
+}
+
+void Direct3D11_Finish_Scene()
+{
+ if (Active && Post.Run_Chain()) {
+ take_the_frame_to_the_screen();
+ }
+}
+
+void Direct3D11_Finish_Frame()
+{
+ if (Active && Post.Copy_Through()) {
+ take_the_frame_to_the_screen();
+ }
+}
+
void Direct3D11_Begin_Scene()
{
if (Active) {
+ // Before the backend binds anything: the scene goes wherever this says it goes, and a frame
+ // that asked for a chain and could not have one falls back to the swap chain here rather
+ // than half way through.
+ Post.Begin_Frame();
+ Device.Set_Scene_View(Post.Scene_View());
Backend.Begin_Scene();
}
}
@@ -287,6 +345,11 @@ unsigned char * Direct3D11_Capture_Back_Buffer(unsigned & width, unsigned & heig
return NULL;
}
+ // A screenshot is of what the player sees, so the chain runs first. The present path asks for
+ // the same thing a moment later and gets it for nothing, because the second Resolve of a frame
+ // does not run.
+ Direct3D11_Finish_Frame();
+
ID3D11Resource * back_buffer = NULL;
Device.Get_Back_Buffer_View()->GetResource(&back_buffer);
@@ -336,6 +399,7 @@ void Direct3D11_Release_Capture(unsigned char * pixels)
void Direct3D11_End_Scene(bool flip_frames)
{
if (Active && flip_frames && PresentRequested) {
+ Direct3D11_Finish_Frame();
Device.Present(0);
}
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
index a3c82b0de..c16a014dc 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
@@ -111,6 +111,29 @@ void Direct3D11_Dump_Programs_To(const char * directory);
void Direct3D11_Present_Enable(bool enabled);
bool Direct3D11_Present_Is_Enabled();
+// -dx11post: the effects run over the finished frame, named in the order they run, as in "fxaa" or
+// "fxaa,sharpen". "off" or an empty chain draws straight into the swap chain the way the backend
+// always has. Returns false for a name it does not know and turns the chain off, so a misspelt
+// switch is a plain frame and a report line rather than a different picture.
+//
+// This is the first thing in the backend that draws a frame Direct3D 9 does not draw, so it is off
+// unless it is asked for and dx11-check.ps1's exit measurement is taken without it.
+bool Direct3D11_Post_Chain(const char * chain);
+
+// The chain and the size it runs at, for the shutdown report, or why there is no chain.
+const char * Direct3D11_Post_Diagnostic();
+
+// Run the chain into the swap chain's back buffer, now, because the world is drawn and the command
+// bar is about to go on top of it. Everything drawn after this lands in the swap chain directly.
+// An edge filter over a bitmap font does not antialias the letters, it doubles them, so where this
+// is called from is as much a part of the feature as the shader is.
+void Direct3D11_Finish_Scene();
+
+// The scene in front of the player with nothing over it, for a frame that never reached the world:
+// a menu, a loading screen. The present path and the screenshot path both call it and neither knows
+// whether the other has, so the first one to ask pays and the second finds the work done.
+void Direct3D11_Finish_Frame();
+
// The back buffer as it stands, in the eight-bit blue-green-red-alpha order the screenshot writer
// wants, top row first. Has to be called before the present that discards it. Null when there is
// nothing to read; what comes back is freed with Direct3D11_Release_Capture and nothing else.
diff --git a/GeneralsMD/Code/Main/WinMain.cpp b/GeneralsMD/Code/Main/WinMain.cpp
index 5abd26a09..04a8c79aa 100644
--- a/GeneralsMD/Code/Main/WinMain.cpp
+++ b/GeneralsMD/Code/Main/WinMain.cpp
@@ -1039,13 +1039,21 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
/*
** Convert WinMain arguments to simple main argc and argv
*/
+ /*
+ ** EA's array held 32 and the loop stopped there without saying so, which is a switch that
+ ** does nothing and logs nothing: an unattended run reaches this easily, since every one of
+ ** them is driven entirely from the command line. A -scenario at position 31 of 35 was
+ ** simply gone, and the only clue was that the log's own echo of the arguments ended in the
+ ** middle. 128 is past anything the scripts here build, and hitting it now says so.
+ */
+ const int MAXIMUM_ARGUMENTS = 128;
int argc = 1;
- char * argv[32];
+ char * argv[MAXIMUM_ARGUMENTS];
argv[0] = NULL;
char *token;
token = nextParam(lpCmdLine, "\" ");
- while (argc < 32 && token != NULL) {
+ while (argc < MAXIMUM_ARGUMENTS && token != NULL) {
argv[argc++] = strtrim(token);
//added a preparse step for this flag because it affects window creation style
if (stricmp(token,"-win")==0)
@@ -1078,10 +1086,16 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
ApplicationIsWindowed=true;
ApplicationIsHeadless=true;
}
- token = nextParam(NULL, "\" ");
+ token = nextParam(NULL, "\" ");
+ }
+
+ if (argc == MAXIMUM_ARGUMENTS && token != NULL)
+ {
+ DEBUG_LOG(("command line: more than %d arguments, everything from '%s' onward was "
+ "dropped\n", MAXIMUM_ARGUMENTS - 1, token));
}
- if (argc>2 && strcmp(argv[1],"-DX")==0) {
+ if (argc>2 && strcmp(argv[1],"-DX")==0) {
Int i;
DEBUG_LOG(("\n--- DX STACK DUMP\n"));
for (i=2; i<argc; i++) {
diff --git a/GeneralsMD/Code/Tests/test_dx11post.cpp b/GeneralsMD/Code/Tests/test_dx11post.cpp
new file mode 100644
index 000000000..ae5551443
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_dx11post.cpp
@@ -0,0 +1,589 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// The post-process chain, run for real on a device with a swap chain.
+//
+// A known picture is written into the texture the scene would have been drawn into, the chain is
+// run, and the swap chain's back buffer is read back. So these are not tests that the code was
+// called; they are tests of what came out the other end.
+//
+// The two that matter are opposites. The copy pass has to give back every pixel unchanged, which
+// is what says the offscreen target, the full screen triangle, the sampler and the viewport are all
+// exactly one to one - a half pixel anywhere in that path shows up here as a whole frame that moved.
+// FXAA has to change a stepped diagonal and leave a flat field alone, which is what says the shader
+// is doing the thing it is named after rather than blurring or nothing.
+//
+// A machine with no Direct3D 11 device at all reports these as skipped: there is nothing to check
+// there, and the build agents that cannot make a device still have to come back green.
+
+#include "test_harness.h"
+
+#include "dx11device.h"
+#include "dx11post.h"
+
+#include <d3d11.h>
+#include <windows.h>
+#include <stdio.h>
+#include <string.h>
+
+static const unsigned SURFACE_SIZE = 64;
+static const unsigned BYTES_A_PIXEL = 4;
+static const unsigned char DARK_LEVEL = 0;
+static const unsigned char LIGHT_LEVEL = 255;
+static const unsigned char OPAQUE_ALPHA = 255;
+
+// A device with a swap chain, and the window it needs, torn down together.
+class DeviceFixture
+{
+public:
+ DeviceFixture() : Window(NULL) {}
+
+ ~DeviceFixture()
+ {
+ Post.Shutdown();
+ Device.Release();
+ if (Window != NULL) {
+ DestroyWindow(Window);
+ }
+ }
+
+ bool Create()
+ {
+ Window = CreateWindowExA(0, "STATIC", "dx11post", WS_OVERLAPPED, 0, 0, SURFACE_SIZE,
+ SURFACE_SIZE, NULL, NULL, GetModuleHandle(NULL), NULL);
+ if (Window == NULL) {
+ return false;
+ }
+ if (!Device.Create(Window, SURFACE_SIZE, SURFACE_SIZE)) {
+ return false;
+ }
+ return Post.Initialise(&Device);
+ }
+
+ DX11DeviceClass & Get_Device() { return Device; }
+ DX11PostProcessClass & Get_Post() { return Post; }
+
+private:
+ DeviceFixture(const DeviceFixture &);
+ DeviceFixture & operator=(const DeviceFixture &);
+
+ HWND Window;
+ DX11DeviceClass Device;
+ DX11PostProcessClass Post;
+};
+
+// One pixel of the test picture, in the swap chain's own blue-green-red-alpha order.
+static void set_pixel(unsigned char * pixels, unsigned x, unsigned y, unsigned char level)
+{
+ unsigned char * pixel = pixels + (y * SURFACE_SIZE + x) * BYTES_A_PIXEL;
+ pixel[0] = level;
+ pixel[1] = level;
+ pixel[2] = level;
+ pixel[3] = OPAQUE_ALPHA;
+}
+
+static unsigned char pixel_level(const unsigned char * pixels, unsigned pitch, unsigned x,
+ unsigned y)
+{
+ return pixels[y * pitch + x * BYTES_A_PIXEL];
+}
+
+// Everything one level, which has no edge in it for an edge filter to find.
+static void fill_flat(unsigned char * pixels, unsigned char level)
+{
+ for (unsigned y = 0; y < SURFACE_SIZE; ++y) {
+ for (unsigned x = 0; x < SURFACE_SIZE; ++x) {
+ set_pixel(pixels, x, y, level);
+ }
+ }
+}
+
+// A diagonal, which is the shape that aliases. A vertical or a horizontal edge lands exactly on
+// the pixel grid and has nothing to antialias, and FXAA leaves those alone by design, so a test
+// built on one would pass whether the shader worked or not.
+static void fill_diagonal(unsigned char * pixels)
+{
+ for (unsigned y = 0; y < SURFACE_SIZE; ++y) {
+ for (unsigned x = 0; x < SURFACE_SIZE; ++x) {
+ set_pixel(pixels, x, y, (x > y) ? LIGHT_LEVEL : DARK_LEVEL);
+ }
+ }
+}
+
+// Write the picture into the texture the scene would have been drawn into.
+static bool write_scene(DX11DeviceClass & device, DX11PostProcessClass & post,
+ const unsigned char * pixels)
+{
+ ID3D11RenderTargetView * view = post.Scene_View();
+ if (view == NULL) {
+ return false;
+ }
+
+ ID3D11Resource * resource = NULL;
+ view->GetResource(&resource);
+ if (resource == NULL) {
+ return false;
+ }
+ device.Get_Context()->UpdateSubresource(resource, 0, NULL, pixels,
+ SURFACE_SIZE * BYTES_A_PIXEL, 0);
+ resource->Release();
+ return true;
+}
+
+// The swap chain's back buffer, copied into a staging texture and mapped. The caller frees it.
+static unsigned char * read_back_buffer(DX11DeviceClass & device, unsigned & pitch)
+{
+ pitch = 0;
+ ID3D11RenderTargetView * view = device.Get_Back_Buffer_View();
+ if (view == NULL) {
+ return NULL;
+ }
+
+ ID3D11Resource * back_buffer = NULL;
+ view->GetResource(&back_buffer);
+ if (back_buffer == NULL) {
+ return NULL;
+ }
+
+ D3D11_TEXTURE2D_DESC description;
+ ((ID3D11Texture2D *)back_buffer)->GetDesc(&description);
+ description.Usage = D3D11_USAGE_STAGING;
+ description.BindFlags = 0;
+ description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+ description.MiscFlags = 0;
+
+ ID3D11Texture2D * staging = NULL;
+ if (FAILED(device.Get_Device()->CreateTexture2D(&description, NULL, &staging))) {
+ back_buffer->Release();
+ return NULL;
+ }
+ device.Get_Context()->CopyResource(staging, back_buffer);
+
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ unsigned char * pixels = NULL;
+ if (SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped))) {
+ pitch = SURFACE_SIZE * BYTES_A_PIXEL;
+ pixels = new unsigned char[pitch * SURFACE_SIZE];
+ for (unsigned row = 0; row < SURFACE_SIZE; ++row) {
+ memcpy(pixels + row * pitch, (const unsigned char *)mapped.pData + row * mapped.RowPitch,
+ pitch);
+ }
+ device.Get_Context()->Unmap(staging, 0);
+ }
+
+ staging->Release();
+ back_buffer->Release();
+ return pixels;
+}
+
+// How many pixels of the result differ from the picture that went in.
+static unsigned differing_pixels(const unsigned char * source, const unsigned char * result,
+ unsigned pitch)
+{
+ unsigned differing = 0;
+ for (unsigned y = 0; y < SURFACE_SIZE; ++y) {
+ for (unsigned x = 0; x < SURFACE_SIZE; ++x) {
+ if (pixel_level(source, SURFACE_SIZE * BYTES_A_PIXEL, x, y)
+ != pixel_level(result, pitch, x, y)) {
+ ++differing;
+ }
+ }
+ }
+ return differing;
+}
+
+// Runs one chain over one picture and hands back what reached the swap chain. NULL when this
+// machine has no device to run it on.
+static unsigned char * run_chain(DeviceFixture & fixture, const DX11PostEffect * effects,
+ unsigned count, const unsigned char * picture, unsigned & pitch)
+{
+ fixture.Get_Post().Set_Chain(effects, count);
+ fixture.Get_Post().Begin_Frame();
+ if (!write_scene(fixture.Get_Device(), fixture.Get_Post(), picture)) {
+ return NULL;
+ }
+ fixture.Get_Post().Run_Chain();
+ return read_back_buffer(fixture.Get_Device(), pitch);
+}
+
+TEST(dx11post_chain_names_parse)
+{
+ DX11PostEffect effects[DX11_POST_CHAIN_LIMIT];
+ unsigned count = 0;
+
+ CHECK(DX11Post_Parse_Chain("fxaa", effects, count));
+ CHECK_EQ(1u, count);
+ CHECK_EQ((int)DX11_POST_FXAA, (int)effects[0]);
+
+ CHECK(DX11Post_Parse_Chain("fxaa,sharpen", effects, count));
+ CHECK_EQ(2u, count);
+ CHECK_EQ((int)DX11_POST_FXAA, (int)effects[0]);
+ CHECK_EQ((int)DX11_POST_SHARPEN, (int)effects[1]);
+
+ CHECK(DX11Post_Parse_Chain("copy", effects, count));
+ CHECK_EQ(1u, count);
+ CHECK_EQ((int)DX11_POST_COPY, (int)effects[0]);
+
+ CHECK(DX11Post_Parse_Chain("bloom", effects, count));
+ CHECK_EQ(1u, count);
+ CHECK_EQ((int)DX11_POST_BLOOM, (int)effects[0]);
+
+ // Bloom first and antialiasing after it is the order that means something: the frame is back in
+ // eight bits by then and FXAA is looking at what the player will see.
+ CHECK(DX11Post_Parse_Chain("bloom,fxaa", effects, count));
+ CHECK_EQ(2u, count);
+ CHECK_EQ((int)DX11_POST_BLOOM, (int)effects[0]);
+
+ // The other way round cannot be answered, so it is refused rather than quietly reordered.
+ CHECK(!DX11Post_Parse_Chain("fxaa,bloom", effects, count));
+ CHECK_EQ(0u, count);
+
+ CHECK_STR("fxaa", DX11Post_Effect_Name(DX11_POST_FXAA));
+ CHECK_STR("sharpen", DX11Post_Effect_Name(DX11_POST_SHARPEN));
+ CHECK_STR("copy", DX11Post_Effect_Name(DX11_POST_COPY));
+ CHECK_STR("bloom", DX11Post_Effect_Name(DX11_POST_BLOOM));
+}
+
+TEST(dx11post_off_and_nonsense_both_leave_no_chain)
+{
+ DX11PostEffect effects[DX11_POST_CHAIN_LIMIT];
+ unsigned count = 0;
+
+ // "off" is understood and asks for nothing.
+ CHECK(DX11Post_Parse_Chain("off", effects, count));
+ CHECK_EQ(0u, count);
+ CHECK(DX11Post_Parse_Chain("none", effects, count));
+ CHECK_EQ(0u, count);
+ CHECK(DX11Post_Parse_Chain("", effects, count));
+ CHECK_EQ(0u, count);
+
+ // A name nobody knows is refused rather than skipped, so -dx11post motionblur does not quietly
+ // run something else.
+ CHECK(!DX11Post_Parse_Chain("motionblur", effects, count));
+ CHECK_EQ(0u, count);
+ CHECK(!DX11Post_Parse_Chain("fxaa,motionblur", effects, count));
+ CHECK_EQ(0u, count);
+ CHECK(!DX11Post_Parse_Chain(NULL, effects, count));
+ CHECK_EQ(0u, count);
+
+ // Longer than the chain can hold is refused too, rather than being cut short.
+ CHECK(!DX11Post_Parse_Chain("fxaa,fxaa,fxaa,fxaa,fxaa", effects, count));
+ CHECK_EQ(0u, count);
+}
+
+TEST(dx11post_no_chain_leaves_the_scene_on_the_swap_chain)
+{
+ DeviceFixture fixture;
+ if (!fixture.Create()) {
+ printf("skip: no Direct3D 11 device on this machine\n");
+ return;
+ }
+
+ fixture.Get_Post().Set_Chain(NULL, 0);
+ CHECK_EQ(0u, fixture.Get_Post().Chain_Length());
+ // NULL is the device's word for the swap chain, so an absent chain costs nothing at all: the
+ // scene is drawn where it has always been drawn.
+ CHECK(fixture.Get_Post().Scene_View() == NULL);
+}
+
+TEST(dx11post_copy_gives_every_pixel_back_unchanged)
+{
+ DeviceFixture fixture;
+ if (!fixture.Create()) {
+ printf("skip: no Direct3D 11 device on this machine\n");
+ return;
+ }
+
+ unsigned char * picture = new unsigned char[SURFACE_SIZE * SURFACE_SIZE * BYTES_A_PIXEL];
+ fill_diagonal(picture);
+
+ const DX11PostEffect chain[] = { DX11_POST_COPY };
+ unsigned pitch = 0;
+ unsigned char * result = run_chain(fixture, chain, 1, picture, pitch);
+ CHECK(result != NULL);
+ if (result != NULL) {
+ // Exactly zero. A sampler set to point instead of linear, a viewport carrying the scene's
+ // half pixel, or a triangle that does not land on the corners would all put a number here.
+ CHECK_EQ(0u, differing_pixels(picture, result, pitch));
+ delete [] result;
+ }
+ delete [] picture;
+}
+
+TEST(dx11post_fxaa_leaves_a_flat_picture_alone)
+{
+ DeviceFixture fixture;
+ if (!fixture.Create()) {
+ printf("skip: no Direct3D 11 device on this machine\n");
+ return;
+ }
+
+ unsigned char * picture = new unsigned char[SURFACE_SIZE * SURFACE_SIZE * BYTES_A_PIXEL];
+ fill_flat(picture, 128);
+
+ const DX11PostEffect chain[] = { DX11_POST_FXAA };
+ unsigned pitch = 0;
+ unsigned char * result = run_chain(fixture, chain, 1, picture, pitch);
+ CHECK(result != NULL);
+ if (result != NULL) {
+ // The edge threshold is what keeps the filter off a surface that has no edge in it. Without
+ // it every flat wall in the game would be run through a blur.
+ CHECK_EQ(0u, differing_pixels(picture, result, pitch));
+ delete [] result;
+ }
+ delete [] picture;
+}
+
+TEST(dx11post_fxaa_works_on_a_stepped_diagonal)
+{
+ DeviceFixture fixture;
+ if (!fixture.Create()) {
+ printf("skip: no Direct3D 11 device on this machine\n");
+ return;
+ }
+
+ unsigned char * picture = new unsigned char[SURFACE_SIZE * SURFACE_SIZE * BYTES_A_PIXEL];
+ fill_diagonal(picture);
+
+ const DX11PostEffect chain[] = { DX11_POST_FXAA };
+ unsigned pitch = 0;
+ unsigned char * result = run_chain(fixture, chain, 1, picture, pitch);
+ CHECK(result != NULL);
+ if (result != NULL) {
+ // The staircase is 64 steps long and every step has pixels either side of it that should
+ // have come out between the two levels. Well short of that and the shader is not running.
+ const unsigned changed = differing_pixels(picture, result, pitch);
+ CHECK(changed > 32u);
+
+ // And it is antialiasing rather than repainting: the far corners are nowhere near the edge
+ // and have to come back untouched.
+ CHECK_EQ(DARK_LEVEL, pixel_level(result, pitch, 1, SURFACE_SIZE - 2));
+ CHECK_EQ(LIGHT_LEVEL, pixel_level(result, pitch, SURFACE_SIZE - 2, 1));
+ delete [] result;
+ }
+ delete [] picture;
+}
+
+TEST(dx11post_a_frame_with_no_world_in_it_goes_through_untouched)
+{
+ DeviceFixture fixture;
+ if (!fixture.Create()) {
+ printf("skip: no Direct3D 11 device on this machine\n");
+ return;
+ }
+
+ unsigned char * picture = new unsigned char[SURFACE_SIZE * SURFACE_SIZE * BYTES_A_PIXEL];
+ fill_diagonal(picture);
+
+ // A menu draws no world, so nothing calls Run_Chain and the frame would sit in the offscreen
+ // texture with the screen black behind it. Copy_Through is what the present path falls back to,
+ // and because it is a copy rather than the chain, a screen made entirely of text is not run
+ // through an edge filter on its way out.
+ const DX11PostEffect chain[] = { DX11_POST_FXAA };
+ fixture.Get_Post().Set_Chain(chain, 1);
+ fixture.Get_Post().Begin_Frame();
+ CHECK(write_scene(fixture.Get_Device(), fixture.Get_Post(), picture));
+ CHECK(fixture.Get_Post().Copy_Through());
+
+ unsigned pitch = 0;
+ unsigned char * result = read_back_buffer(fixture.Get_Device(), pitch);
+ CHECK(result != NULL);
+ if (result != NULL) {
+ CHECK_EQ(0u, differing_pixels(picture, result, pitch));
+ delete [] result;
+ }
+ delete [] picture;
+}
+
+// Half floats, written by hand. Only three values are needed and a general converter would be more
+// code than the constants: 4.0 is sign 0, exponent 17 biased, mantissa 0, and 1.0 is exponent 15.
+static const unsigned short HALF_ZERO = 0x0000;
+static const unsigned short HALF_ONE = 0x3C00;
+static const unsigned short HALF_FOUR = 0x4400;
+
+static const unsigned BRIGHT_BLOCK_SIZE = 4;
+static const unsigned HALF_CHANNELS = 4;
+
+// Clear the scene to one colour. Works whatever the target's format, which an UpdateSubresource of
+// eight bit pixels does not: with bloom in the chain the scene target holds half floats.
+static bool clear_scene(DX11DeviceClass & device, DX11PostProcessClass & post, float level)
+{
+ ID3D11RenderTargetView * view = post.Scene_View();
+ if (view == NULL) {
+ return false;
+ }
+ const float colour[4] = { level, level, level, 1.0f };
+ device.Get_Context()->ClearRenderTargetView(view, colour);
+ return true;
+}
+
+// A small block of light in the middle of a black scene, at four times the brightness of white.
+static bool write_bright_block(DX11DeviceClass & device, DX11PostProcessClass & post)
+{
+ ID3D11RenderTargetView * view = post.Scene_View();
+ if (view == NULL) {
+ return false;
+ }
+
+ unsigned short block[BRIGHT_BLOCK_SIZE * BRIGHT_BLOCK_SIZE * HALF_CHANNELS];
+ for (unsigned index = 0; index < BRIGHT_BLOCK_SIZE * BRIGHT_BLOCK_SIZE; ++index) {
+ block[index * HALF_CHANNELS + 0] = HALF_FOUR;
+ block[index * HALF_CHANNELS + 1] = HALF_FOUR;
+ block[index * HALF_CHANNELS + 2] = HALF_FOUR;
+ block[index * HALF_CHANNELS + 3] = HALF_ONE;
+ }
+
+ ID3D11Resource * resource = NULL;
+ view->GetResource(&resource);
+ if (resource == NULL) {
+ return false;
+ }
+
+ const unsigned left = SURFACE_SIZE / 2;
+ const unsigned top = SURFACE_SIZE / 2;
+ D3D11_BOX box;
+ box.left = left;
+ box.top = top;
+ box.front = 0;
+ box.right = left + BRIGHT_BLOCK_SIZE;
+ box.bottom = top + BRIGHT_BLOCK_SIZE;
+ box.back = 1;
+ device.Get_Context()->UpdateSubresource(resource, 0, &box, block,
+ BRIGHT_BLOCK_SIZE * HALF_CHANNELS * sizeof(unsigned short), 0);
+ resource->Release();
+ return true;
+}
+
+TEST(dx11post_bloom_keeps_ordinary_levels_and_folds_overbright_to_white)
+{
+ DeviceFixture fixture;
+ if (!fixture.Create()) {
+ printf("skip: no Direct3D 11 device on this machine\n");
+ return;
+ }
+
+ const DX11PostEffect chain[] = { DX11_POST_BLOOM };
+ fixture.Get_Post().Set_Chain(chain, 1);
+ CHECK(fixture.Get_Post().Scene_Is_Float());
+
+ // Half of white is below the tone curve's knee and below the bright threshold, so it has to
+ // come back out as half of white. If it does not, the curve is being applied to the whole range
+ // and every ordinary pixel in the game has been moved.
+ fixture.Get_Post().Begin_Frame();
+ CHECK(clear_scene(fixture.Get_Device(), fixture.Get_Post(), 0.5f));
+ CHECK(fixture.Get_Post().Run_Chain());
+ unsigned pitch = 0;
+ unsigned char * result = read_back_buffer(fixture.Get_Device(), pitch);
+ CHECK(result != NULL);
+ if (result != NULL) {
+ const unsigned char level = pixel_level(result, pitch, SURFACE_SIZE / 2, SURFACE_SIZE / 2);
+ CHECK(level >= 127 && level <= 128);
+ delete [] result;
+ }
+
+ // Four times white is what an eight bit target could not have held at all. It arrives as white
+ // rather than as anything darker, which is the curve reaching its asymptote.
+ fixture.Get_Post().Begin_Frame();
+ CHECK(clear_scene(fixture.Get_Device(), fixture.Get_Post(), 4.0f));
+ CHECK(fixture.Get_Post().Run_Chain());
+ result = read_back_buffer(fixture.Get_Device(), pitch);
+ CHECK(result != NULL);
+ if (result != NULL) {
+ CHECK_EQ(255, (int)pixel_level(result, pitch, SURFACE_SIZE / 2, SURFACE_SIZE / 2));
+ delete [] result;
+ }
+}
+
+TEST(dx11post_bloom_spreads_light_past_the_pixels_that_carry_it)
+{
+ DeviceFixture fixture;
+ if (!fixture.Create()) {
+ printf("skip: no Direct3D 11 device on this machine\n");
+ return;
+ }
+
+ const DX11PostEffect chain[] = { DX11_POST_BLOOM };
+ fixture.Get_Post().Set_Chain(chain, 1);
+ fixture.Get_Post().Begin_Frame();
+ CHECK(clear_scene(fixture.Get_Device(), fixture.Get_Post(), 0.0f));
+ CHECK(write_bright_block(fixture.Get_Device(), fixture.Get_Post()));
+ CHECK(fixture.Get_Post().Run_Chain());
+
+ unsigned pitch = 0;
+ unsigned char * result = read_back_buffer(fixture.Get_Device(), pitch);
+ CHECK(result != NULL);
+ if (result != NULL) {
+ // Ten pixels above the block there was nothing at all in the scene. The glow reaches it,
+ // which is the whole of what bloom is; without the bright pass or the blur this is zero.
+ // "near" is a macro in windows.h, which is why this is not called that.
+ const unsigned char aboveTheBlock = pixel_level(result, pitch, SURFACE_SIZE / 2,
+ SURFACE_SIZE / 2 - 10);
+ CHECK(aboveTheBlock > 0);
+
+ // The opposite corner is far outside the blur's reach and has to stay black, or the glow is
+ // not a glow, it is a wash over the frame.
+ CHECK_EQ(0, (int)pixel_level(result, pitch, 1, 1));
+ delete [] result;
+ }
+}
+
+TEST(dx11post_resolves_once_a_frame)
+{
+ DeviceFixture fixture;
+ if (!fixture.Create()) {
+ printf("skip: no Direct3D 11 device on this machine\n");
+ return;
+ }
+
+ unsigned char * first = new unsigned char[SURFACE_SIZE * SURFACE_SIZE * BYTES_A_PIXEL];
+ unsigned char * second = new unsigned char[SURFACE_SIZE * SURFACE_SIZE * BYTES_A_PIXEL];
+ fill_flat(first, LIGHT_LEVEL);
+ fill_flat(second, DARK_LEVEL);
+
+ const DX11PostEffect chain[] = { DX11_POST_COPY };
+ unsigned pitch = 0;
+ unsigned char * result = run_chain(fixture, chain, 1, first, pitch);
+ CHECK(result != NULL);
+ delete [] result;
+
+ // A second finish without a Begin_Frame between them is the screenshot path asking for a frame
+ // the present path has already finished. It has to do nothing, or the shot and the screen would
+ // be two different pictures.
+ CHECK(write_scene(fixture.Get_Device(), fixture.Get_Post(), second));
+ CHECK(!fixture.Get_Post().Run_Chain());
+ CHECK(!fixture.Get_Post().Copy_Through());
+ result = read_back_buffer(fixture.Get_Device(), pitch);
+ CHECK(result != NULL);
+ if (result != NULL) {
+ CHECK_EQ(LIGHT_LEVEL, pixel_level(result, pitch, SURFACE_SIZE / 2, SURFACE_SIZE / 2));
+ delete [] result;
+ }
+
+ // Armed again, the new picture goes through.
+ fixture.Get_Post().Begin_Frame();
+ CHECK(fixture.Get_Post().Run_Chain());
+ result = read_back_buffer(fixture.Get_Device(), pitch);
+ CHECK(result != NULL);
+ if (result != NULL) {
+ CHECK_EQ(DARK_LEVEL, pixel_level(result, pitch, SURFACE_SIZE / 2, SURFACE_SIZE / 2));
+ delete [] result;
+ }
+
+ delete [] first;
+ delete [] second;
+}
diff --git a/dx11-check.ps1 b/dx11-check.ps1
index 70d61d176..ab9c9d673 100644
--- a/dx11-check.ps1
+++ b/dx11-check.ps1
@@ -45,6 +45,10 @@
#
# -MeanMargin is the pass threshold in levels a channel, and 1.0 is the frame buffer's own step: two
# frames that agree to within the smallest value the buffer can hold are the same frame.
+#
+# -dx11post is the one switch that must never be added here. It runs an effect over the finished
+# frame on purpose, so a run with it on disagrees with Direct3D 9 by design and this script would be
+# measuring the effect rather than the backend. Its own before and after is a pair of pictures.
param([double]$Margin = 1.0, [double]$MeanMargin = 1.0, [string]$Map = '',
[switch]$BackendNoise, [switch]$CountRule, [string[]]$Extra = @())