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(w3ddevice): let the ground and the models read the sun depth buffer

Olcay Seygan85ca5517d9ea
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index de69c5547..dea984bca 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -177,6 +177,7 @@ public:
Bool m_shadowsForParticles; // "ShadowsForParticles": big alpha-blended particle clouds drop a soft blob on the ground
Bool m_shadowMap; // "-shadowmap": draw the casters into the sun's depth buffer as well
Bool m_shadowMapReport; // "-shadowmapreport": log what ended up in that buffer, once a second
+ Bool m_shadowMapOnly; // "-shadowmaponly": the map's shadows with the stencil volumes' own darkening off
Bool m_particleGroundBounce; // "-particlebounce": terrain collision on for every particle system
Real m_smokeThickness; // "-smoke": how much longer and thicker every smoke system runs, 0 for shipped behaviour
Int m_particleCapOverride; // "-particlecap": stand in for the options slider's MaxParticleCount, 0 to use it
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index e2529a700..b422ff6da 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -944,6 +944,21 @@ Int parseShadowMapReport(char *args[], int num)
return 1;
}
+/* -shadowmaponly: the map's shadows and nothing else, for looking at one of them at a time.
+
+ The casters are still registered and still drawn into the map; what stops is the stencil
+ volumes' own darkening pass over the frame. Turning the volumes off in the options instead
+ would take the caster list with them and leave the map empty. */
+Int parseShadowMapOnly(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ {
+ TheWritableGlobalData->m_shadowMap = TRUE;
+ TheWritableGlobalData->m_shadowMapOnly = TRUE;
+ }
+ return 1;
+}
+
/* -noparticleshadows: take the soft blob back off the ground under every particle cloud.
ShadowsForParticles is on by default and the shipped INI has no entry for it, so without this
@@ -2172,6 +2187,7 @@ static CommandLineParam params[] =
{ "-particlecap", parseParticleCap },
{ "-shadowmap", parseShadowMap },
{ "-shadowmapreport", parseShadowMapReport },
+ { "-shadowmaponly", parseShadowMapOnly },
{ "-noparticleshadows", parseNoParticleShadows },
{ "-quickstart", parseQuickStart },
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index 93f03f71a..78c874d41 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -681,6 +681,7 @@ GlobalData::GlobalData()
m_shadowsForParticles = TRUE; //on by default: the shipped INI has no entry for it
m_shadowMap = FALSE; //the sun's depth pass is off until something reads it
m_shadowMapReport = FALSE;
+ m_shadowMapOnly = FALSE;
m_textureReductionFactor = -1;
m_enableBehindBuildingMarkers = TRUE;
m_scriptDebug = FALSE;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
index 90b99abb5..d4c625afb 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
@@ -105,6 +105,12 @@ const Real cosAngleToCare = cos ((0.2 * PI) / 180.0); //1.5 degree difference
#define SHADOW_MAP_SUN_DISTANCE 2000.0f
#define SHADOW_MAP_NEAR_CLIP 10.0f
#define SHADOW_MAP_FAR_CLIP 4000.0f
+// How far a surface has to be behind what the map holds before it counts as shadowed, how dark a
+// fully blocked pixel goes, and how far the filter reaches in texels. The first is the one that
+// decides between a surface shadowing itself in stripes and a shadow lifting off its own caster.
+#define SHADOW_MAP_DEPTH_BIAS 0.0015f
+#define SHADOW_MAP_STRENGTH 0.45f
+#define SHADOW_MAP_FILTER_TEXELS 1.0f
//#define SV_DEBUG
//#define SV_DEBUG_BOUNDS
@@ -3867,6 +3873,14 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )
// whole picture rather than a corner of it.
sceneCamera.Apply();
+ /* And what turns the map into a shadow. The matrix that takes a pixel from the frame's clip
+ space into the sun's is built in the backend, out of the sun's own view and projection as it
+ held them during the pass and the frame's as it holds them now: both are already there, in
+ one convention, and a matrix assembled on this side would have to agree with a layout it
+ cannot see. SHADOW-MAP-PLAN.md phase 2. */
+ Direct3D11_Set_Shadow_Parameters( SHADOW_MAP_DEPTH_BIAS, SHADOW_MAP_STRENGTH,
+ SHADOW_MAP_FILTER_TEXELS );
+
// The report costs a full stall of the pipeline, so it is one line a second rather than one a
// frame: what it answers is whether the pass draws the world at all, and that does not change
// thirty times a second.
@@ -3889,6 +3903,12 @@ void W3DVolumetricShadowManager::renderShadows( Bool forceStencilFill )
W3DVolumetricShadow *shadow;
Int numRenderedShadows = 0;
+ /* -shadowmaponly leaves the casters registered, and so in the sun's map, while taking the
+ volumes' own darkening off the frame. Turning the volumes off in the options instead would
+ stop the casters being registered at all and leave the map with nothing in it. */
+ if (TheGlobalData->m_shadowMapOnly)
+ return;
+
AABoxClass bbox;
SphereClass bsphere;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
index 3ee63e754..6537f6933 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -208,6 +208,11 @@ DX11BackendClass::DX11BackendClass()
, ShadowMapSavedWidth(0)
, ShadowMapSavedHeight(0)
, ShadowMapSavedTarget(NULL)
+ , ShadowMapSampler(NULL)
+ , ShadowBias(0.0f)
+ , ShadowStrength(0.0f)
+ , ShadowRadius(1.0f)
+ , ShadowReceiving(false)
, NormalMappedDraws(0)
, DrawsMade(0)
, DrawsRefused(0)
@@ -394,6 +399,10 @@ void DX11BackendClass::Shutdown()
ShadowMapSurface->Release();
ShadowMapSurface = NULL;
}
+ if (ShadowMapSampler != NULL) {
+ ShadowMapSampler->Release();
+ ShadowMapSampler = NULL;
+ }
ShadowMapSize = 0;
ShadowMapBound = false;
Device = NULL;
@@ -479,6 +488,9 @@ void DX11BackendClass::End_Shadow_Map()
}
ShadowMapBound = false;
+ // What the sun was looking through, kept for the draws that will read the map.
+ multiply(View, Projection, SunViewProjection);
+ ShadowFromClipValid = false;
// Back to whatever the frame was drawing into, which is a texture the post chain shows and not
// the back buffer.
Set_Render_Target(ShadowMapSavedTarget);
@@ -489,6 +501,72 @@ void DX11BackendClass::End_Shadow_Map()
Forget_Bindings();
}
+void DX11BackendClass::Set_Shadow_Parameters(float bias, float strength, float radius_in_texels)
+{
+ if (ShadowMapTexture == NULL) {
+ Clear_Shadow_Parameters();
+ return;
+ }
+ ShadowBias = bias;
+ ShadowStrength = strength;
+ ShadowRadius = radius_in_texels;
+ ShadowReceiving = true;
+}
+
+void DX11BackendClass::Clear_Shadow_Parameters()
+{
+ ShadowReceiving = false;
+ ShadowFromClipValid = false;
+}
+
+/** The inverse of a four by four, by cofactors. Nothing else in the backend needed one: every
+ other matrix it holds arrives ready to use, and this is the one journey that goes the other
+ way, out of the frame's clip space and back into the world. */
+static bool invert(const float in[16], float out[16])
+{
+ const float a00 = in[0], a01 = in[1], a02 = in[2], a03 = in[3];
+ const float a10 = in[4], a11 = in[5], a12 = in[6], a13 = in[7];
+ const float a20 = in[8], a21 = in[9], a22 = in[10], a23 = in[11];
+ const float a30 = in[12], a31 = in[13], a32 = in[14], a33 = in[15];
+
+ const float b00 = a00 * a11 - a01 * a10;
+ const float b01 = a00 * a12 - a02 * a10;
+ const float b02 = a00 * a13 - a03 * a10;
+ const float b03 = a01 * a12 - a02 * a11;
+ const float b04 = a01 * a13 - a03 * a11;
+ const float b05 = a02 * a13 - a03 * a12;
+ const float b06 = a20 * a31 - a21 * a30;
+ const float b07 = a20 * a32 - a22 * a30;
+ const float b08 = a20 * a33 - a23 * a30;
+ const float b09 = a21 * a32 - a22 * a31;
+ const float b10 = a21 * a33 - a23 * a31;
+ const float b11 = a22 * a33 - a23 * a32;
+
+ const float determinant = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+ if (determinant > -1e-12f && determinant < 1e-12f) {
+ return false;
+ }
+ const float scale = 1.0f / determinant;
+
+ out[0] = ( a11 * b11 - a12 * b10 + a13 * b09) * scale;
+ out[1] = (-a01 * b11 + a02 * b10 - a03 * b09) * scale;
+ out[2] = ( a31 * b05 - a32 * b04 + a33 * b03) * scale;
+ out[3] = (-a21 * b05 + a22 * b04 - a23 * b03) * scale;
+ out[4] = (-a10 * b11 + a12 * b08 - a13 * b07) * scale;
+ out[5] = ( a00 * b11 - a02 * b08 + a03 * b07) * scale;
+ out[6] = (-a30 * b05 + a32 * b02 - a33 * b01) * scale;
+ out[7] = ( a20 * b05 - a22 * b02 + a23 * b01) * scale;
+ out[8] = ( a10 * b10 - a11 * b08 + a13 * b06) * scale;
+ out[9] = (-a00 * b10 + a01 * b08 - a03 * b06) * scale;
+ out[10] = ( a30 * b04 - a31 * b02 + a33 * b00) * scale;
+ out[11] = (-a20 * b04 + a21 * b02 - a23 * b00) * scale;
+ out[12] = (-a10 * b09 + a11 * b07 - a12 * b06) * scale;
+ out[13] = ( a00 * b09 - a01 * b07 + a02 * b06) * scale;
+ out[14] = (-a30 * b03 + a31 * b01 - a32 * b00) * scale;
+ out[15] = ( a20 * b03 - a21 * b01 + a22 * b00) * scale;
+ return true;
+}
+
/** What is in the map, read back once. A caster pass that drew nothing leaves every texel at the
clear value, which no draw count tells apart from a pass that drew the whole world. */
std::string DX11BackendClass::Shadow_Map_Report()
@@ -1086,9 +1164,42 @@ bool DX11BackendClass::Build_Combiner_Description(CombinerDescription & descript
description.StageCount = stage + 1;
}
description.NormalMapped = description.StageCount > 0 && Normal_Mapped();
+ description.ShadowReceiving = description.StageCount > 0 && Shadow_Receiving();
return description.StageCount > 0;
}
+/** Which draws take a shadow. The world's, and only while the sun's map holds this frame's casters:
+ a screen space quad has no place in the world to look up, a draw that is adding light to the
+ frame rather than painting it would come out darker rather than shadowed, and the pass that
+ fills the map must not shadow itself. */
+bool DX11BackendClass::Shadow_Receiving() const
+{
+ if (!ShadowReceiving || ShadowMapBound || ShadowMapTexture == NULL) {
+ return false;
+ }
+ // A transcribed terrain or road program takes one too: the ground is where a shadow is seen,
+ // and those programs carry the sampling whether a frame has a map or not. The water and the
+ // trees keep their own shadows for now.
+ if (PixelProgram != ENGINE_SHADER_NONE && !EngineShader_Paints_Ground(PixelProgram)) {
+ return false;
+ }
+ if (VertexProgram != ENGINE_SHADER_NONE && PixelProgram == ENGINE_SHADER_NONE) {
+ return false;
+ }
+ if ((VertexFormat & D3DFVF_XYZRHW) != 0) {
+ return false; // already in screen space: the interface, the filters, the darkening quad
+ }
+ if (RenderStates.Get_Render_State(D3DRS_ALPHABLENDENABLE) != FALSE) {
+ const DWORD source = RenderStates.Get_Render_State(D3DRS_SRCBLEND);
+ const DWORD destination = RenderStates.Get_Render_State(D3DRS_DESTBLEND);
+ if (destination == D3DBLEND_ONE || source == D3DBLEND_ONE
+ || destination == D3DBLEND_DESTCOLOR || source == D3DBLEND_DESTCOLOR) {
+ return false; // additive and multiplicative passes: fire, glow, the shadows themselves
+ }
+ }
+ return true;
+}
+
bool DX11BackendClass::Build_Vertex_Description(VertexPipelineDescription & description) const
{
memset(&description, 0, sizeof(description));
@@ -1476,6 +1587,32 @@ void DX11BackendClass::Upload_Constants()
}
}
+ if (ShadowReceiving) {
+ if (!ShadowFromClipValid
+ || memcmp(ShadowFromClipView, View, sizeof(View)) != 0
+ || memcmp(ShadowFromClipProjection, Projection, sizeof(Projection)) != 0) {
+ float scene_clip[16];
+ float clip_to_world[16];
+ multiply(View, Projection, scene_clip);
+ if (invert(scene_clip, clip_to_world)) {
+ multiply(clip_to_world, SunViewProjection, ShadowFromClip);
+ memcpy(ShadowFromClipView, View, sizeof(View));
+ memcpy(ShadowFromClipProjection, Projection, sizeof(Projection));
+ ShadowFromClipValid = true;
+ }
+ }
+ memcpy(pixel_block.ShadowFromClip, ShadowFromClip, sizeof(pixel_block.ShadowFromClip));
+ pixel_block.ShadowParameters[0] = (ShadowMapSize > 0)
+ ? 1.0f / static_cast<float>(ShadowMapSize) : 0.0f;
+ pixel_block.ShadowParameters[1] = ShadowBias;
+ pixel_block.ShadowParameters[2] = ShadowStrength;
+ pixel_block.ShadowParameters[3] = ShadowRadius;
+ pixel_block.ShadowViewport[0] = (ViewportWidth > 0)
+ ? 1.0f / static_cast<float>(ViewportWidth) : 0.0f;
+ pixel_block.ShadowViewport[1] = (ViewportHeight > 0)
+ ? 1.0f / static_cast<float>(ViewportHeight) : 0.0f;
+ }
+
if ((!PixelConstantsHeld
|| memcmp(&HeldPixelConstants, &pixel_block, sizeof(pixel_block)) != 0)
&& SUCCEEDED(context->Map(PixelConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {
@@ -1671,6 +1808,26 @@ void DX11BackendClass::Bind_State_Objects()
context->PSSetShaderResources(DX11_BACKEND_TEXTURE_STAGES, 1, &NormalMap);
Bound.NormalMap = NormalMap;
}
+
+ // The sun's map at t5 with a sampler of its own at s5, clamped so a pixel past the edge of the
+ // box reads the edge rather than wrapping the far side of the map over it.
+ if (ShadowReceiving && ShadowMapTexture != NULL) {
+ if (ShadowMapSampler == NULL) {
+ D3D11_SAMPLER_DESC description;
+ memset(&description, 0, sizeof(description));
+ description.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
+ description.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
+ description.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
+ description.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
+ description.ComparisonFunc = D3D11_COMPARISON_NEVER;
+ description.MaxLOD = D3D11_FLOAT32_MAX;
+ Device->Get_Device()->CreateSamplerState(&description, &ShadowMapSampler);
+ }
+ context->PSSetShaderResources(DX11_BACKEND_TEXTURE_STAGES + 1, 1, &ShadowMapTexture);
+ if (ShadowMapSampler != NULL) {
+ context->PSSetSamplers(DX11_BACKEND_TEXTURE_STAGES + 1, 1, &ShadowMapSampler);
+ }
+ }
}
void DX11BackendClass::Bind_Pipeline(const Pipeline & pipeline, ID3D11Buffer * vertices, UINT stride,
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
index 37feecbb6..0fc7206d3 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
@@ -156,6 +156,13 @@ public:
// asked for. SHADOW-MAP-PLAN.md phase 1.
bool Begin_Shadow_Map(unsigned size);
void End_Shadow_Map();
+
+ // The filter's own numbers, set once a frame by the pass that fills the map. The matrix that
+ // takes a pixel into the sun's clip space is built here rather than handed in: the sun's view
+ // and projection are the ones this held while the map was bound, and the frame's are the ones
+ // it holds when the draw arrives, so both halves are already in one convention.
+ void Set_Shadow_Parameters(float bias, float strength, float radius_in_texels);
+ void Clear_Shadow_Parameters();
bool Shadow_Map_Bound() const { return ShadowMapBound; }
ID3D11ShaderResourceView * Shadow_Map() const { return ShadowMapTexture; }
@@ -271,11 +278,18 @@ private:
float NormalLightDiffuse[NORMAL_MAPPED_LIGHTS][4];
float NormalMapParameters[4];
float TerrainSunDirection[4];
+ // Clip space to the sun's clip space, and the filter's own numbers: texel size, depth bias,
+ // how dark a fully blocked pixel goes, and the radius in texels.
+ float ShadowFromClip[16];
+ float ShadowParameters[4];
+ float ShadowViewport[4];
};
// A model under directional lights, drawn by generated programs.
bool Normal_Mapped() const;
// The ground, drawn by one of the transcribed terrain programs with its light baked in.
bool Terrain_Bumped() const;
+ // A draw that is painting the world and can take a shadow from the sun's map.
+ bool Shadow_Receiving() const;
bool Resolve(Pipeline & pipeline);
bool Build_Vertex_Description(VertexPipelineDescription & description) const;
@@ -340,6 +354,19 @@ private:
// the scene goes into a texture and the post chain puts it on the screen, so restoring the back
// buffer here left the rest of the frame painting somewhere nobody shows.
ID3D11RenderTargetView * ShadowMapSavedTarget;
+ ID3D11SamplerState * ShadowMapSampler;
+ float SunViewProjection[16]; ///< what the sun was looking through while the map was filled
+ float ShadowBias;
+ float ShadowStrength;
+ float ShadowRadius;
+ bool ShadowReceiving;
+ // The frame's clip space to the sun's, worked out from a scene view and projection pair and
+ // kept until one of them changes, because an inverse a draw does not need is an inverse nobody
+ // should pay for.
+ float ShadowFromClip[16];
+ float ShadowFromClipView[16];
+ float ShadowFromClipProjection[16];
+ bool ShadowFromClipValid;
float MaterialAmbient[4];
float MaterialDiffuse[4];
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
index 5a6ef3db0..efb560063 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
@@ -292,6 +292,20 @@ bool Direct3D11_Shadow_Map_Bound()
return Active ? Backend.Shadow_Map_Bound() : false;
}
+void Direct3D11_Set_Shadow_Parameters(float bias, float strength, float radius_in_texels)
+{
+ if (Active) {
+ Backend.Set_Shadow_Parameters(bias, strength, radius_in_texels);
+ }
+}
+
+void Direct3D11_Clear_Shadow_Parameters()
+{
+ if (Active) {
+ Backend.Clear_Shadow_Parameters();
+ }
+}
+
std::string Direct3D11_Shadow_Map_Report()
{
return Active ? Backend.Shadow_Map_Report() : std::string("no Direct3D 11 backend");
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
index c1039da65..5b34d2ba3 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
@@ -108,6 +108,13 @@ void Direct3D11_End_Shadow_Map();
bool Direct3D11_Shadow_Map_Bound();
std::string Direct3D11_Shadow_Map_Report();
+// What turns the map into a shadow: the matrix that takes a pixel's clip space position into the
+// sun's clip space, the depth bias that keeps a surface from shadowing itself, how dark a fully
+// blocked pixel goes and how wide the filter reaches, in texels. Set once a frame, cleared when
+// the frame has no map.
+void Direct3D11_Set_Shadow_Parameters(float bias, float strength, float radius_in_texels);
+void Direct3D11_Clear_Shadow_Parameters();
+
// The CPU has just written this surface. The next bind of its texture fills the Direct3D 11 copy
// again. A no-op when the backend is not running.
void Direct3D11_Mark_Surface_Dirty(struct IDirect3DSurface9 * surface);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
index a7e5e7e60..557f4e012 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
@@ -226,8 +226,9 @@ static void write_pixel_preamble(std::string & hlsl, bool bumped = false)
" float4 TextureFactor;\n"
" float4 FogColour;\n"
" float4 AlphaReference;\n";
- if (bumped) {
- // The whole of DX11BackendClass::PixelConstantBlock up to the sun, in its order.
+ {
+ // The whole of DX11BackendClass::PixelConstantBlock up to the sun, in its order. Declared
+ // whether this program lights with it or not, because what follows is found by offset.
char line[256];
snprintf(line, sizeof(line),
" float4 NormalLightDirection[%u];\n"
@@ -237,10 +238,17 @@ static void write_pixel_preamble(std::string & hlsl, bool bumped = false)
NORMAL_MAPPED_LIGHTS, NORMAL_MAPPED_LIGHTS);
hlsl += line;
}
+ // The shadow fields close the block, in the backend's order, and every transcribed program
+ // declares them whether it reads them or not: a field is found by what comes before it.
+ hlsl +=
+ " row_major float4x4 ShadowFromClip;\n"
+ " float4 ShadowParameters;\n"
+ " float4 ShadowViewport;\n";
hlsl += "};\n";
if (bumped) {
hlsl += "Texture2D NormalMap : register(t4);\n";
}
+ hlsl += SHADOW_SAMPLING;
hlsl +=
"\n"
"struct Input\n"
@@ -397,6 +405,9 @@ static void write_multiply_chain(std::string & hlsl, const EngineShaderEntry & e
hlsl += ");\n";
}
+ // The ground is where a shadow is read, so every transcribed program that paints it takes one.
+ hlsl += " current.rgb *= sun_reaching(input.Position);\n";
+
if (!bumped) {
return;
}
@@ -422,6 +433,14 @@ static void write_multiply_chain(std::string & hlsl, const EngineShaderEntry & e
hlsl += line;
}
+bool EngineShader_Paints_Ground(EngineShaderProgram program)
+{
+ return program == ENGINE_SHADER_TERRAIN || program == ENGINE_SHADER_TERRAIN_NOISE
+ || program == ENGINE_SHADER_TERRAIN_NOISE_2 || program == ENGINE_SHADER_FLAT_TERRAIN
+ || program == ENGINE_SHADER_FLAT_TERRAIN_BASE || program == ENGINE_SHADER_FLAT_TERRAIN_NOISE
+ || program == ENGINE_SHADER_FLAT_TERRAIN_NOISE_2 || program == ENGINE_SHADER_ROAD_NOISE_2;
+}
+
bool EngineShader_Can_Bump(EngineShaderProgram program)
{
return program == ENGINE_SHADER_TERRAIN || program == ENGINE_SHADER_TERRAIN_NOISE
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h
index 274bc3621..622ac0831 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h
@@ -94,6 +94,10 @@ bool EngineShader_Pixel_Program(EngineShaderProgram program,
// Whether a program is one bumped can be asked of.
bool EngineShader_Can_Bump(EngineShaderProgram program);
+// Which transcribed programs paint the ground, and so read the sun's shadow map. The water and
+// the trees are not among them: both have shadows of their own.
+bool EngineShader_Paints_Ground(EngineShaderProgram program);
+
// What the pipeline cache keys this program under and what the dump calls its file.
const char * EngineShader_Name(EngineShaderProgram program);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
index 11264fcc7..0bb129648 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp
@@ -355,7 +355,11 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh
" float4 TextureFactor;\n"
" float4 FogColour;\n"
" float4 AlphaReference;\n";
- if (description.NormalMapped) {
+ // A shader declares a prefix of the block the backend uploads, so a field is found by what
+ // comes before it and not by its name. The shadow fields sit behind the normal mapped ones
+ // and the terrain's sun, so a program that reads them has to declare those too, used or
+ // not: without them a shadow matrix lands where the first light's direction is.
+ if (description.NormalMapped || description.ShadowReceiving) {
char line[256];
snprintf(line, sizeof(line),
" float4 NormalLightDirection[%u];\n"
@@ -364,10 +368,22 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh
NORMAL_MAPPED_LIGHTS, NORMAL_MAPPED_LIGHTS);
hlsl += line;
}
+ if (description.ShadowReceiving) {
+ hlsl +=
+ " float4 TerrainSunDirection;\n"
+ // row_major for the reason the vertex half gives: every matrix the engine has is a
+ // D3D9 matrix and D3D9 stores one by rows.
+ " row_major float4x4 ShadowFromClip;\n"
+ " float4 ShadowParameters;\n"
+ " float4 ShadowViewport;\n";
+ }
hlsl += "};\n";
if (description.NormalMapped) {
hlsl += "Texture2D NormalMap : register(t4);\n";
}
+ if (description.ShadowReceiving) {
+ hlsl += SHADOW_SAMPLING;
+ }
}
else {
for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
@@ -426,6 +442,11 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh
hlsl += " current.rgb = saturate(current.rgb + highlight);\n";
}
+ // Before the fog: a shadow is a thing in the world and the fog is between the world and the eye.
+ if (description.ShadowReceiving) {
+ hlsl += " current.rgb *= sun_reaching(input.Position);\n";
+ }
+
if (target == COMBINER_SHADER_TARGET_D3D11
&& !CombinerShader_Append_Pixel_Pipeline(description.PixelPipeline, hlsl)) {
return false;
@@ -499,5 +520,8 @@ std::string CombinerShader_Key(const CombinerDescription & description)
if (description.NormalMapped) {
key += ":N";
}
+ if (description.ShadowReceiving) {
+ key += ":S";
+ }
return key;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
index 8fd9382b2..da6bafa33 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
@@ -89,12 +89,54 @@ struct CombinerDescription
// The vertex half has to have been generated with the same flag. Initialised here because
// callers fill a description field by field and one written before this existed never sets it.
bool NormalMapped = false;
+
+ // D3D11 only: take the pixel back out of clip space, look it up in the sun's depth buffer at t5
+ // and darken it by how much of the filter comes back blocked. No vertex half is involved: the
+ // position comes from SV_Position and one matrix, which is what keeps this off the varyings the
+ // two generators have to agree on. SHADOW-MAP-PLAN.md phase 2.
+ bool ShadowReceiving = false;
};
// The normal mapped pixel program reads this many directional lights from its constants. Slots
// past the draw's own lights carry no colour and add nothing.
const unsigned NORMAL_MAPPED_LIGHTS = 4;
+// How much of the sun reaches a pixel, shared by the generated programs and the transcribed ones so
+// the two cannot drift. The pixel is taken back out of clip space by one matrix, which lands it in
+// the sun's own clip space, and the filter is a square of taps around it: the share that come back
+// blocked is the share of the light that is missing. ShadowParameters is the map's texel size, the
+// depth bias, how dark a fully blocked pixel goes and the radius in texels; a strength of zero is a
+// frame with no shadow map and every pixel in full sun. SHADOW-MAP-PLAN.md phase 2.
+#define SHADOW_SAMPLING \
+ "Texture2D ShadowMap : register(t5);\n" \
+ "SamplerState ShadowSampler : register(s5);\n" \
+ "\n" \
+ "float sun_reaching(float4 position)\n" \
+ "{\n" \
+ " if (ShadowParameters.z <= 0.0) return 1.0;\n" \
+ " float2 ndc = float2(position.x * ShadowViewport.x * 2.0 - 1.0,\n" \
+ " 1.0 - position.y * ShadowViewport.y * 2.0);\n" \
+ " float4 sun = mul(float4(ndc, position.z, 1.0), ShadowFromClip);\n" \
+ " if (sun.w <= 0.0) return 1.0;\n" \
+ " sun /= sun.w;\n" \
+ " float2 map = float2(0.5 * sun.x + 0.5, 0.5 - 0.5 * sun.y);\n" \
+ " if (map.x < 0.0 || map.x > 1.0 || map.y < 0.0 || map.y > 1.0) return 1.0;\n" \
+ " if (sun.z < 0.0 || sun.z > 1.0) return 1.0;\n" \
+ " float texel = ShadowParameters.x;\n" \
+ " float bias = ShadowParameters.y;\n" \
+ " float radius = ShadowParameters.w;\n" \
+ " float blocked = 0.0;\n" \
+ " for (int y = -1; y <= 1; ++y) {\n" \
+ " for (int x = -1; x <= 1; ++x) {\n" \
+ " float2 at = map + float2(x, y) * texel * radius;\n" \
+ " float depth = ShadowMap.SampleLevel(ShadowSampler, at, 0).r;\n" \
+ " blocked += (depth + bias < sun.z) ? 1.0 : 0.0;\n" \
+ " }\n" \
+ " }\n" \
+ " return 1.0 - ShadowParameters.z * (blocked / 9.0);\n" \
+ "}\n" \
+ "\n"
+
// The HLSL for one description, or false when the description names an operation or an argument
// this does not generate. A refusal is not a failure: the caller keeps the fixed-function path for
// that draw, which is the only reason an unmeasured operation is safe to meet at run time.