Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
fix(ww3d2): three shading faults between the D3D11 frame and the D3D9 one
Olcay Seygan8c4a2e6fc7f4
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cppindex 298cae9ad..8089227f2 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp@@ -112,6 +112,31 @@ static void multiply(const float left[16], const float right[16], float result[1}}+// A light is handed to Direct3D 9 in world space and lit in camera space: the fixed-function+// pipeline carries its position and direction through the view matrix itself, once per light rather+// than once per vertex. The generated shader lights in camera space too, so the same two products+// happen here. Without them a world space light direction is dotted against a camera space normal+// and every lit model is shaded from the wrong angle - which reads as a lighting mood, not as a+// bug, and cost the whole of Alpine Assault's remaining 9.23%.+static void transform_point(const float source[4], const float matrix[16], float result[4])+{+ for (unsigned column = 0; column < 4; ++column) {+ result[column] = source[0] * matrix[column]+ + source[1] * matrix[4 + column]+ + source[2] * matrix[8 + column]+ + matrix[12 + column];+ }+}++static void transform_direction(const float source[4], const float matrix[16], float result[4])+{+ for (unsigned column = 0; column < 4; ++column) {+ result[column] = source[0] * matrix[column]+ + source[1] * matrix[4 + column]+ + source[2] * matrix[8 + column];+ }+}+// A normal is transformed by the inverse transpose of the upper three by three, not by the matrix// itself. With a uniform scale the two differ only by a factor that normalize removes, but the// engine scales models unevenly and a normal carried through the matrix itself comes out pointing@@ -984,8 +1009,8 @@ void DX11BackendClass::Upload_Constants()if (!Lights[index].Enabled) {continue;}- memcpy(vertex_block.LightFields[slot][0], Lights[index].Position, sizeof(float) * 4);- memcpy(vertex_block.LightFields[slot][1], Lights[index].Direction, sizeof(float) * 4);+ transform_point(Lights[index].Position, View, vertex_block.LightFields[slot][0]);+ transform_direction(Lights[index].Direction, View, vertex_block.LightFields[slot][1]);memcpy(vertex_block.LightFields[slot][2], Lights[index].Diffuse, sizeof(float) * 4);memcpy(vertex_block.LightFields[slot][3], Lights[index].Specular, sizeof(float) * 4);memcpy(vertex_block.LightFields[slot][4], Lights[index].Attenuation, sizeof(float) * 4);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cppindex 9febbf127..843207e90 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp@@ -398,7 +398,14 @@ static bool generate_pretransformed(const VertexPipelineDescription & descriptio" Output output;\n"" float reciprocal_w = (input.Position.w == 0.0) ? 1.0 : input.Position.w;\n"" float w = 1.0 / reciprocal_w;\n"- " float2 normalised = input.Position.xy * ViewportInverse.xy;\n"+ // Direct3D 9 puts a pixel's centre at an integer screen coordinate and Direct3D 10 onwards+ // puts it at a half-integer, so a screen space quad written for one lands half a pixel off+ // under the other. Every such quad in this engine already carries D3D9's own -0.5, which is+ // what aligns a texel with a pixel there; the half added back here cancels it. Miss it and+ // the quad samples exactly between two texels, linear filtering averages them, and the whole+ // scene comes back softened - 42% of the local contrast on Alpine Assault, with the command+ // bar beside it sharp because the bar is drawn after the composite rather than through it.+ " float2 normalised = (input.Position.xy + 0.5) * ViewportInverse.xy;\n"" output.Position = float4((normalised.x * 2.0 - 1.0) * w,\n"" (1.0 - normalised.y * 2.0) * w, input.Position.z * w, w);\n";@@ -480,7 +487,20 @@ bool VertexShader_Generate(const VertexPipelineDescription & description,}if (description.LightingEnabled) {- body += " float3 diffuse_light = GlobalAmbient.rgb;\n";+ // D3D9's vertex colour is+ // sum(atten * spot * Ldiffuse * Cdiffuse * N.L)+ // + Cambient * (Gambient + sum(atten * spot * Lambient))+ // + Cemissive+ // so the scene ambient is spent once, through the ambient material. Seeding this sum with+ // it instead spends it twice - once scaled by the diffuse material and once by the ambient+ // one - and every lit model comes out too bright. It reads as a lighting mood rather than+ // as a bug, which is why it survived six maps of zero-refusal runs: Alpine Assault at dusk+ // was 13.2% from the Direct3D 9 frame and Golden Oasis in daylight 2.57%, and the geometry+ // was in the right place in both.+ //+ // A light's own ambient is not in that second sum because DX11BackendClass::Set_Light does+ // not carry one; every light W3D creates leaves it black.+ body += " float3 diffuse_light = float3(0.0, 0.0, 0.0);\n";body += " float3 specular_light = float3(0.0, 0.0, 0.0);\n";for (unsigned index = 0; index < description.LightCount; ++index) {append_light(body, index, description.Lights[index].Type);diff --git a/GeneralsMD/Code/Tests/test_dx11backend.cpp b/GeneralsMD/Code/Tests/test_dx11backend.cppindex 84e3ed3b9..34fa8a364 100644--- a/GeneralsMD/Code/Tests/test_dx11backend.cpp+++ b/GeneralsMD/Code/Tests/test_dx11backend.cpp@@ -199,6 +199,124 @@ TEST(dx11backend_a_draw_set_up_the_d3d9_way_lands_in_the_render_target)backend.Shutdown();}+// Direct3D 9 takes a light in world space and lights in camera space, carrying the light through the+// view matrix itself. The generated shader lights in camera space too, so the backend has to make+// the same product before the light goes up; without it a world space direction is dotted against a+// camera space normal and every model is shaded from the wrong angle.+//+// The view here is a quarter turn about x and the world is its inverse, so the quad and its normal+// come out exactly where they started and the only thing the view matrix touches is the light. A+// world direction of (0,-1,0) becomes (0,0,-1) in camera space, which is straight at the quad: the+// fix lights it fully and the fault lights it not at all.+TEST(dx11backend_a_light_is_carried_into_camera_space)+{+ DX11DeviceClass device;+ CHECK(device.Create_Offscreen());+ ID3D11Device * d3d = device.Get_Device();++ DX11BackendClass backend;+ CHECK(backend.Initialise(&device));++ D3D11_TEXTURE2D_DESC target_description;+ memset(&target_description, 0, sizeof(target_description));+ target_description.Width = TARGET_SIZE;+ target_description.Height = TARGET_SIZE;+ target_description.MipLevels = 1;+ target_description.ArraySize = 1;+ target_description.Format = DXGI_FORMAT_B8G8R8A8_UNORM;+ target_description.SampleDesc.Count = 1;+ target_description.Usage = D3D11_USAGE_DEFAULT;+ target_description.BindFlags = D3D11_BIND_RENDER_TARGET;++ ID3D11Texture2D * target = NULL;+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&target_description, NULL, &target)));++ D3D11_TEXTURE2D_DESC staging_description = target_description;+ staging_description.Usage = D3D11_USAGE_STAGING;+ staging_description.BindFlags = 0;+ staging_description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;++ ID3D11Texture2D * staging = NULL;+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&staging_description, NULL, &staging)));++ ID3D11RenderTargetView * target_view = NULL;+ CHECK(SUCCEEDED(d3d->CreateRenderTargetView(target, NULL, &target_view)));++ const float clear_colour[4] = { 0.0f, 1.0f, 0.0f, 1.0f };+ device.Get_Context()->ClearRenderTargetView(target_view, clear_colour);+ device.Get_Context()->OMSetRenderTargets(1, &target_view, NULL);++ backend.Set_Viewport(0, 0, TARGET_SIZE, TARGET_SIZE);+ configure_unlit_pass_through(backend);++ // A quarter turn about x, and the world matrix that undoes it.+ float view[16];+ set_identity(view);+ view[5] = 0.0f; view[6] = 1.0f;+ view[9] = -1.0f; view[10] = 0.0f;++ float world[16];+ set_identity(world);+ world[5] = 0.0f; world[6] = -1.0f;+ world[9] = 1.0f; world[10] = 0.0f;++ backend.Set_Transform(D3DTS_WORLD, world);+ backend.Set_Transform(D3DTS_VIEW, view);++ backend.Set_Render_State(D3DRS_LIGHTING, TRUE);+ backend.Set_Render_State(D3DRS_SPECULARENABLE, FALSE);+ backend.Set_Render_State(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);+ backend.Set_Render_State(D3DRS_AMBIENT, 0);++ const float white[4] = { 1.0f, 1.0f, 1.0f, 1.0f };+ const float black[4] = { 0.0f, 0.0f, 0.0f, 0.0f };+ backend.Set_Material(black, white, black, black, 1.0f);++ // Blue brightest, red dimmest, so a channel swap is a wrong answer rather than a lucky one.+ const float light_diffuse[4] = { 0.25f, 0.5f, 0.75f, 1.0f };+ const float direction[4] = { 0.0f, -1.0f, 0.0f, 0.0f };+ const float attenuation[4] = { 1.0f, 0.0f, 0.0f, 100000.0f };+ backend.Set_Light(0, D3DLIGHT_DIRECTIONAL, black, direction, light_diffuse, black,+ attenuation, black);++ ID3D11Buffer * vertices = NULL;+ CHECK(DX11Resource_Create_Vertex_Buffer(d3d, sizeof(QUAD_VERTICES), D3DPOOL_MANAGED, 0,+ QUAD_VERTICES, &vertices));++ ID3D11Buffer * indices = NULL;+ CHECK(DX11Resource_Create_Index_Buffer(d3d, sizeof(QUAD_INDICES), D3DPOOL_MANAGED, 0,+ QUAD_INDICES, &indices));++ backend.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);++ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));++ device.Get_Context()->CopyResource(staging, target);++ D3D11_MAPPED_SUBRESOURCE mapped;+ CHECK(SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped)));++ const unsigned char * centre = static_cast<const unsigned char *>(mapped.pData)+ + mapped.RowPitch * (TARGET_SIZE / 2) + (TARGET_SIZE / 2) * 4;+ if (centre[0] < 189 || centre[0] > 193) {+ printf(" centre pixel bgra %02x %02x %02x %02x\n",+ centre[0], centre[1], centre[2], centre[3]);+ }+ CHECK(centre[0] >= 189 && centre[0] <= 193);+ CHECK(centre[1] >= 126 && centre[1] <= 130);+ CHECK(centre[2] >= 62 && centre[2] <= 66);++ device.Get_Context()->Unmap(staging, 0);++ indices->Release();+ vertices->Release();+ target_view->Release();+ staging->Release();+ target->Release();+ backend.Shutdown();+}+// The same state twice is one pipeline, and a changed stage program is a second. The engine sets// the same handful of combinations thousands of times a frame, so a cache that missed would compile// a shader per draw and the frame time would be the symptom rather than the picture.diff --git a/GeneralsMD/Code/Tests/test_ffvertex.cpp b/GeneralsMD/Code/Tests/test_ffvertex.cppindex ddbf98784..1efc256a5 100644--- a/GeneralsMD/Code/Tests/test_ffvertex.cpp+++ b/GeneralsMD/Code/Tests/test_ffvertex.cpp@@ -133,6 +133,28 @@ TEST(ffvertex_a_spot_light_adds_the_cone_to_the_point_light_terms)CHECK(contains(hlsl, "Light0Spot.z"));}+// D3D9 spends the scene ambient once, through the ambient material:+// sum(atten * spot * Ldiffuse * Cdiffuse * N.L) + Cambient * Gambient + Cemissive+// The generator used to seed the light sum with GlobalAmbient as well, which scaled it by the+// diffuse material a second time and made every lit model brighter than Direct3D 9 draws it. On a+// dusk map that was 13.2% of the frame with the geometry in exactly the right place, so nothing+// short of two pictures of one view could see it.+TEST(ffvertex_the_scene_ambient_is_spent_once)+{+ VertexPipelineDescription lit = plain_description();+ lit.LightingEnabled = true;+ lit.LightCount = 1;+ lit.Lights[0].Type = D3DLIGHT_DIRECTIONAL;++ std::string hlsl;+ CHECK(VertexShader_Generate(lit, VERTEX_SHADER_TARGET_D3D9, hlsl));++ // The light sum starts empty and the ambient enters only through the ambient material.+ CHECK(contains(hlsl, "float3 diffuse_light = float3(0.0, 0.0, 0.0);"));+ CHECK(!contains(hlsl, "float3 diffuse_light = GlobalAmbient.rgb;"));+ CHECK(contains(hlsl, "MaterialAmbient.rgb * GlobalAmbient.rgb"));+}+// D3DMCS_COLOR1 reads the diffuse vertex colour, but only where the format carries one and// D3DRS_COLORVERTEX allows it. D3D9 falls back to the material in both of those cases and so does// this, which is a fallback rather than a refusal because the device makes it silently too.@@ -276,10 +298,16 @@ TEST(ffvertex_puts_a_pretransformed_vertex_back_into_clip_space)std::string hlsl;CHECK(VertexShader_Generate(pretransformed, VERTEX_SHADER_TARGET_D3D11, hlsl));CHECK(contains(hlsl, "float4 Position : POSITION;"));- CHECK(contains(hlsl, "input.Position.xy * ViewportInverse.xy"));CHECK(contains(hlsl, "output.TexCoord0 = input.TexCoord0;"));CHECK(contains(hlsl, "output.Diffuse = input.Diffuse;"));+ // D3D9's pixel centre is at an integer screen coordinate and D3D11's at a half-integer, so the+ // half these quads already carry for D3D9 has to be given back. Without it the composite quad+ // samples the scene texture exactly between two texels and the whole frame comes back softened:+ // 42% of Alpine Assault's local contrast, with the command bar sharp beside it because the bar+ // is drawn straight to the back buffer rather than through the composite.+ CHECK(contains(hlsl, "(input.Position.xy + 0.5) * ViewportInverse.xy"));+// The one thing it must not do is transform a position that is already transformed.CHECK(!contains(hlsl, "WorldViewProjection)"));}