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): draw the modern water on direct3d 11

Olcay Seygan60b4ae55e5b1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 83ba719fc..4685e26e4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,9 +13,10 @@ found and fixed — EA's own, not port damage.**
- A tree's shadow used to be its outline laid flat at the foot of the trunk, which sank into the ground on a slope and never darkened a tank parked under it. Now every tree, the palms included, puts its real leaves into the sun's shadow, gaps between the fronds and all, and that shadow falls over the hillside and over the units standing in the wood. Direct3D 11 on Windows and Linux both draw it; the Direct3D 9 renderer keeps the old flat shadows.
- Linux gets the sun's shadows Windows already had, soft under a helicopter and hard under a tank, and the smoke shadow that darkens a battlefield under a thick plume. Your own cloaked units still cast only a faint part of theirs.
-## Modern water on Linux
+## Modern water
-- Options has a Water Style box. Modern rolls the sea in waves whose crests catch the sun all the way into the shallows, and at the shore they turn along the bank and pile up foam. Boats push foam off their hulls. Classic stays the default, and either way a map keeps the water colour and depth its maker gave it. Linux only for now.
+- Options has a Water Style box. Modern rolls the sea in waves whose crests catch the sun all the way into the shallows, and at the shore they turn along the bank and pile up foam. Boats push foam off their hulls. Classic stays the default, and either way a map keeps the water colour and depth its maker gave it.
+- Windows has it now on the default renderer, and the box switches it in the middle of a match. The Direct3D 9 renderer and macOS keep the Classic water and hide the box. Linux still draws one thing Windows does not, a second band of foam laid over the surf where waves break on a beach. The first Modern frame on a fresh install stops for about a minute while its two water shaders compile; every match after that loads them from the cache.
## Volumetric hazard clouds
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifest
index 4aee42da3..60171ca65 100644
--- a/GeneralsMD/Code/BuildFingerprint.manifest
+++ b/GeneralsMD/Code/BuildFingerprint.manifest
@@ -1992,6 +1992,7 @@ Libraries/Include/Platform/HazardCloudPolicy.h
Libraries/Include/Platform/IsWindows9x.h
Libraries/Include/Platform/LoadTiming.h
Libraries/Include/Platform/MSVCCompat.h
+Libraries/Include/Platform/ModernWaterBuild.h
Libraries/Include/Platform/ModernWaterConfig.h
Libraries/Include/Platform/ModernWaterMaterial.h
Libraries/Include/Platform/MsvcFloatCasts.h
@@ -2008,6 +2009,7 @@ Libraries/Include/Platform/WaterBedMaterial.h
Libraries/Include/Platform/WaterBowLift.h
Libraries/Include/Platform/WaterBowRefinement.h
Libraries/Include/Platform/WaterBowShoulder.h
+Libraries/Include/Platform/WaterConstants.h
Libraries/Include/Platform/WaterFftFiltering.h
Libraries/Include/Platform/WaterFftGeometry.h
Libraries/Include/Platform/WaterFftSampling.h
@@ -2198,6 +2200,8 @@ Libraries/Source/WWVegas/WW3D2/dx11texture.cpp
Libraries/Source/WWVegas/WW3D2/dx11texture.h
Libraries/Source/WWVegas/WW3D2/dx11twin.cpp
Libraries/Source/WWVegas/WW3D2/dx11twin.h
+Libraries/Source/WWVegas/WW3D2/dx11water.cpp
+Libraries/Source/WWVegas/WW3D2/dx11water.h
Libraries/Source/WWVegas/WW3D2/dx8caps.cpp
Libraries/Source/WWVegas/WW3D2/dx8caps.h
Libraries/Source/WWVegas/WW3D2/dx8fvf.cpp
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index f1532fecb..53a707999 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -691,7 +691,7 @@ target_link_libraries(dx11post PUBLIC dx11device d3d11)
# 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
# together, which is why it is the last of them and the one with a drawing test.
-add_library(dx11backend STATIC ${WW}/WW3D2/dx11backend.cpp)
+add_library(dx11backend STATIC ${WW}/WW3D2/dx11backend.cpp ${WW}/WW3D2/dx11water.cpp)
set_target_properties(dx11backend PROPERTIES CXX_STANDARD 17)
target_include_directories(dx11backend PUBLIC ${WW}/WW3D2)
target_link_libraries(dx11backend PUBLIC dx11device dx11state dx11layout dx11resource
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index d4bb084a7..e729d27f7 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -32,6 +32,7 @@
#include "zhio.h"
#include "Common/MessageBoxFlags.h" // MessageBoxWrapper and its flags
#include "Platform/SleepMilliseconds.h"
+#include "Platform/ModernWaterBuild.h"
#if !defined(_WIN32)
#include <unistd.h> // getpid, for the model-checksum cache's scratch file
#endif
@@ -1103,7 +1104,7 @@ void GameEngine::init( int argc, char *argv[] )
ini.load( AsciiString( "Data\\INI\\Water.ini" ), INI_LOAD_OVERWRITE, &xferCRC );
// Visual material rules have their own parser, shared with the standalone preview.
// They do not change gameplay state or the legacy map WaterTransparency values.
-#if defined(__linux__)
+#if ZH_MODERN_WATER
loadModernWaterSettings();
#endif
ini.load( AsciiString( "Data\\INI\\Default\\Weather.ini" ), INI_LOAD_OVERWRITE, &xferCRC );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp
index 5da6255e9..feae54fb5 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp
@@ -74,6 +74,7 @@
#include "GameLogic/ScriptEngine.h"
#include "WWDownload/Registry.h"
#include "Platform/HazardCloud.h"
+#include "Platform/ModernWaterBuild.h"
//added by saad
//used to access a messagebox that does "ok" and "cancel"
#include "GameClient/MessageBox.h"
@@ -1130,15 +1131,16 @@ static void fillCatalogWidgets( void )
if( widget == NULL )
continue;
-#if !defined(__linux__)
- // Modern water is provided by the Linux renderer.
- if (strcmp(def.iniKey, "WaterStyle") == 0) {
- widget->winHide(TRUE);
- GameWindow *label=TheWindowManager->winGetWindowFromId(NULL,NAMEKEY("OptionsMenu.wnd:LabelWaterStyle"));
- if (label) label->winHide(TRUE);
- continue;
- }
-#endif
+ if (strcmp(def.iniKey, "WaterStyle") == 0)
+ {
+ // The Linux renderer and Direct3D 11 draw the Modern water; -d3d9, -headless and macOS do not.
+ const Bool supported = ModernWater::Supported();
+ widget->winHide(!supported);
+ GameWindow *label = TheWindowManager->winGetWindowFromId(
+ NULL, NAMEKEY("OptionsMenu.wnd:LabelWaterStyle"));
+ if (label) label->winHide(!supported);
+ if (!supported) continue;
+ }
if (strcmp(def.iniKey, "CloudStyle") == 0)
{
// The display is initialized before the shell. Query when the menu
@@ -1199,6 +1201,8 @@ static void readCatalogWidgets( OptionPreferences &out )
// A hidden, unfilled combo must not overwrite the player's opt-in.
if (strcmp(def.iniKey, "CloudStyle") == 0 && !HazardCloud::Supported())
continue;
+ if (strcmp(def.iniKey, "WaterStyle") == 0 && !ModernWater::Supported())
+ continue;
Int value;
switch( def.kind )
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
index 2b9e2c1a2..bd08969df 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
@@ -37,6 +37,7 @@
#include "WW3D2/streak.h"
#include "WW3D2/rinfo.h"
#include "WWLib/bittype.h"
+#include "Platform/ModernWaterBuild.h"
#include <vector>
@@ -112,7 +113,7 @@ private:
{
ParticleSystem * system;
Real fade; ///< ParticleSystem::getStealthFade, above zero
-#if defined(__linux__)
+#if ZH_MODERN_WATER
ObjectID owner; ///< vessel foam's attached object at the sync point
#endif
};
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h
index 1d81e2a93..a33133000 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h
@@ -46,6 +46,7 @@
#include "Common/Snapshot.h"
#include "GameLogic/WaterGridMotion.h"
#include "Platform/RenderTypes.h"
+#include "Platform/ModernWaterBuild.h"
#include "Platform/WaterOpticalContext.h"
#include "Platform/WaterProjectedMesh.h"
#include "Platform/WaterHullVisual.h"
@@ -125,7 +126,7 @@ public:
void reset( void ); ///< reset any resources we need to
void load(void); ///< load/setup any map dependent features
void update( void ); ///< update phase of the water
-#if defined(__linux__)
+#if ZH_MODERN_WATER
void takeReadsForRender(void);
#endif
void enableWaterGrid(Bool state); ///< used to active custom water for special maps. (i.e DAM). The grid is TerrainLogic's WaterGrid; this builds its buffers
@@ -237,7 +238,7 @@ protected:
Vector3 position; Real radius,height,major,minor,cosine,sine; Bool box,hasHull=FALSE;
};
std::vector<ModernWaterObstacle> m_modernObstacles, m_modernPatchObstacles;
-#if defined(__linux__)
+#if ZH_MODERN_WATER
struct ModernWaterObject {
Drawable *drawable;
Vector3 position;
@@ -349,7 +350,7 @@ protected:
};
Setting m_settings[ TIME_OF_DAY_COUNT ]; ///< settings for each time of day
-#if defined(__linux__)
+#if ZH_MODERN_WATER
void drawRiverWater(const WaterPolygonForDraw *pTrig);
#else
void drawRiverWater(PolygonTrigger *pTrig);
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp
index 278be1492..a71dfadc7 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp
@@ -1,7 +1,9 @@
// Entry points for builds without a hazard cloud renderer backend: the tests
// that link no device. The game links SDL GPU's or Direct3D 11's instead.
+// The options menu asks the Modern water the same question, answered here the same way.
// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
#include "Platform/HazardCloud.h"
+#include "Platform/ModernWaterBuild.h"
namespace HazardCloud {
@@ -10,3 +12,9 @@ std::unique_ptr<Layer> CreateLayer() { return nullptr; }
void ReleaseDevice() {}
} // namespace HazardCloud
+
+namespace ModernWater {
+
+bool Supported() { return false; }
+
+} // namespace ModernWater
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index fc0a29dfc..f7272cc6a 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -548,7 +548,10 @@ W3DDisplay::~W3DDisplay()
texturesMirrored, texturesReused, texturesRefused,
pipelines, drawsMade, drawsRefused));
if( Direct3D11_Is_Active() )
+ {
DEBUG_LOG(("-dx11 constants: %s\n", Direct3D11_Constant_Path()));
+ DEBUG_LOG(("-dx11 water: %s\n", Direct3D11_Water_Report().c_str()));
+ }
unsigned programsShipped = 0;
unsigned programsHeld = 0;
Direct3D11_Program_Statistics( programsShipped, programsHeld );
@@ -2337,7 +2340,7 @@ static void takeReadsForRender( Bool renders )
TheInGameUI->recordDraw();
TheTerrainRenderObject->takeWaypointsForRender();
TheTerrainRenderObject->stepTrees(); // before the particles: a falling tree's FX makes systems
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (TheWaterRenderObj) TheWaterRenderObj->takeReadsForRender();
#endif
static_cast<W3DParticleSystemManager *>( TheParticleSystemManager )->takeReadsForRender();
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
index cc99ab84d..db49d09ec 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
@@ -87,7 +87,7 @@ extern Real TheParticleFillMS;
extern UnsignedInt TheParticlesPastGroupLimit;
#endif
-#if defined(__linux__)
+#if ZH_MODERN_WATER
// Modern water replaces only verified vessel-surface particles, after that hull's water draw. The
// owner is the one the frame view took at the sync point, so the draw reads no live object.
static Bool replaceLegacyVesselFoam(ParticleSystem *sys, ObjectID owner)
@@ -1755,7 +1755,7 @@ void W3DParticleSystemManager::refreshFrameView( void )
SystemView view;
view.system = sys;
view.fade = fade;
-#if defined(__linux__)
+#if ZH_MODERN_WATER
view.owner = INVALID_ID;
if (sys->getAttachedDrawable() != INVALID_DRAWABLE_ID) {
const Drawable *drawable = TheGameClient->findDrawableByID(sys->getAttachedDrawable());
@@ -1958,7 +1958,7 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
for (size_t v = 0; v < m_frameView.size(); ++v)
{
ParticleSystem *sys = m_frameView[ v ].system;
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (replaceLegacyVesselFoam(sys, m_frameView[ v ].owner))
continue;
#endif
@@ -2057,7 +2057,7 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
#endif
continue;
}
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (replaceLegacyVesselFoam(sys, m_frameView[ v ].owner))
continue;
#endif
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
index 865366446..6ee310d92 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
@@ -457,7 +457,7 @@ Bool WaterRenderObjClass::modernHasHull(UnsignedInt objectID) const
Bool WaterRenderObjClass::hasModernVesselFoam(UnsignedInt objectID) const
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
return m_useModernWater && !m_renderingMirror && m_trapezoidWaterPixelShader
&& m_modernFoamDrawFrame == WW3D::Get_Frame_Count()
&& std::find(m_modernFoamDrawObjectIDs.begin(), m_modernFoamDrawObjectIDs.end(), objectID)
@@ -467,7 +467,7 @@ Bool WaterRenderObjClass::hasModernVesselFoam(UnsignedInt objectID) const
#endif
}
-#if defined(__linux__)
+#if ZH_MODERN_WATER
void WaterRenderObjClass::takeWaterPolygonsForDraw(void)
{
LOGIC_WINDOW_READ( WINDOW_TERRAIN );
@@ -502,7 +502,10 @@ void WaterRenderObjClass::takeReadsForRender(void)
m_modernObjectsForDraw.clear();m_modernObstacles.clear();m_modernObstacleObjectIDs.clear();
m_modernReadsReady=m_useModernWater && TheGameLogic && TheTerrainLogic &&
TheTerrainRenderObject && TheTerrainRenderObject->getMap();
+#if defined(__linux__)
+ // Windows' wave tracks still update in their own flush, as they always have.
if (m_waterTrackSystem) m_waterTrackSystem->takeReadsForRender();
+#endif
if (!m_modernReadsReady) return;
for (const Object *object=TheGameLogic->getFirstObject();object;object=object->getNextObject()) {
@@ -541,7 +544,7 @@ void WaterRenderObjClass::takeReadsForRender(void)
Bool WaterRenderObjClass::isModernWaterMirrorForOwner(UnsignedInt objectID) const
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if(!m_useModernWater || !m_renderingMirror || m_waterType!=WATER_TYPE_0_TRANSLUCENT || !m_trapezoidWaterPixelShader ||
!m_pReflectionTexture || !m_modernReadsReady) return FALSE;
const auto found=m_modernObjectsForDraw.find(objectID);
@@ -571,7 +574,7 @@ Real WaterRenderObjClass::modernHullDamping(Real x,Real y,Real level) const
void WaterRenderObjClass::updateModernWaterHulls(void)
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
m_modernHulls.clear();
m_modernContactHulls.clear();
m_modernVisualHulls.clear();
@@ -848,7 +851,7 @@ void WaterRenderObjClass::invalidateModernWaterShore(void)
void WaterRenderObjClass::updateModernWaterShore(void)
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (m_modernShoreAttempted != m_modernShoreRevision) {
m_modernShoreAttempted = m_modernShoreRevision;
m_modernShoreReady = FALSE;
@@ -896,9 +899,35 @@ void WaterRenderObjClass::updateModernWaterShore(void)
#endif
}
+namespace ModernWater {
+
+bool Supported()
+{
+#if defined(_WIN32)
+ return Direct3D11_Is_Active() && Direct3D11_Present_Is_Enabled();
+#else
+ return ZH_MODERN_WATER;
+#endif
+}
+
+} // namespace ModernWater
+
+#if ZH_MODERN_WATER
+/** The Modern water's registers run to c895, past any Direct3D 9 device; on Windows they go to the
+ Direct3D 11 backend's own bank, which is the only device that draws with them. */
+static void setModernWaterConstants(UnsignedInt first, const float *values, size_t count)
+{
+#if defined(_WIN32)
+ Direct3D11_Set_Water_Constants(first, values, (UnsignedInt)count);
+#else
+ DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(first, values, (UnsignedInt)count);
+#endif
+}
+#endif
+
void WaterRenderObjClass::bindModernWaterFoam(Real level, Bool river)
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
D3DXVECTOR4 area(0, 0, 0, 0), parameters(0, level, 0, m_modernWaveTime);
TextureClass *texture = NULL;
const Bool vessel = m_modernFoamHistory.HasFoam();
@@ -986,8 +1015,8 @@ void WaterRenderObjClass::bindModernWaterFoam(Real level, Bool river)
}
}
}
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(88, area, 1);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(89, parameters, 1);
+ setModernWaterConstants(88, area, 1);
+ setModernWaterConstants(89, parameters, 1);
DX8Wrapper::Set_DX8_Texture(14, texture ? texture->Peek_D3D_Texture() : NULL);
#endif
}
@@ -995,13 +1024,10 @@ void WaterRenderObjClass::bindModernWaterFoam(Real level, Bool river)
void WaterRenderObjClass::registerWaterStyleShaders(void)
{
-#if defined(__linux__)
+ // The Classic names draw the transcription of EA's shaders; the plain names draw the Modern text.
+#if ZH_MODERN_WATER
const Bool modern = m_useModernWater;
-#elif defined(_WIN32)
- // Keep the original shader identities on Windows.
- const Bool modern = TRUE;
#else
- // The SDL renderer uses explicit legacy variants outside Linux.
const Bool modern = FALSE;
#endif
if (m_riverWaterPixelShader)
@@ -1014,8 +1040,8 @@ void WaterRenderObjClass::registerWaterStyleShaders(void)
void WaterRenderObjClass::synchronizeWaterStyle(void)
{
-#if defined(__linux__)
- const Bool modern = TheGlobalData && TheGlobalData->m_waterStyle != 0;
+#if ZH_MODERN_WATER
+ const Bool modern = TheGlobalData && TheGlobalData->m_waterStyle != 0 && ModernWater::Supported();
if (modern == m_useModernWater) return;
// Apply before any reflected or main-scene water draw. Existing recorded draws keep
@@ -1039,7 +1065,7 @@ void WaterRenderObjClass::synchronizeWaterStyle(void)
void WaterRenderObjClass::setupModernWaterShader(Bool river, Bool heightCorrection, Bool waveCage)
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (!m_useModernWater) return;
updateModernWaterTextures();
const Bool reflection = m_pReflectionTexture && !m_renderingMirror &&
@@ -1058,25 +1084,25 @@ void WaterRenderObjClass::setupModernWaterShader(Bool river, Bool heightCorrecti
const RGBColor &colour = TheGlobalData->m_terrainDiffuse[0];
const D3DXVECTOR4 direction(-sun.x, -sun.y, -sun.z, 0.0f);
const D3DXVECTOR4 light(colour.red, colour.green, colour.blue, 0.0f);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(1, parameters, 1);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(2, area, 1);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(3, direction, 1);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(4, light, 1);
+ setModernWaterConstants(1, parameters, 1);
+ setModernWaterConstants(2, area, 1);
+ setModernWaterConstants(3, direction, 1);
+ setModernWaterConstants(4, light, 1);
WorldHeightMap *map = TheTerrainRenderObject ? TheTerrainRenderObject->getMap() : NULL;
const D3DXVECTOR4 terrain(map ? map->getBorderSize() * MAP_XY_FACTOR : 0.0f,
m_modernHeightSide * MAP_XY_FACTOR, 255.0f * MAP_HEIGHT_SCALE, m_modernHeightTexture ? 1.0f : 0.0f);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(5, terrain, 1);
+ setModernWaterConstants(5, terrain, 1);
TextureClass *optical = river ? NULL : modernWaterOpticalTexture(m_modernOpticalLevel);
const D3DXVECTOR4 optics(TheWaterTransparency->m_transparentWaterDepth,
TheWaterTransparency->m_minWaterOpacity, optical ? 1.0f : 0.0f, heightCorrection && !river ? 1.0f : 0.0f);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(6, optics, 1);
+ setModernWaterConstants(6, optics, 1);
D3DXVECTOR4 materialColor, materialParameters;
getModernWaterMaterial(&materialColor.x, &materialParameters.x);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(ModernWaterMaterial::RegisterColor, materialColor, 1);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(ModernWaterMaterial::RegisterParameters, materialParameters, 1);
+ setModernWaterConstants(ModernWaterMaterial::RegisterColor, materialColor, 1);
+ setModernWaterConstants(ModernWaterMaterial::RegisterParameters, materialParameters, 1);
const RGBColor &ambient = TheGlobalData->m_terrainAmbient[0];
const D3DXVECTOR4 hullParameters(river ? 0.0f : float(m_modernHulls.size()), ambient.red, ambient.green, ambient.blue);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(7, hullParameters, 1);
+ setModernWaterConstants(7, hullParameters, 1);
// Match the terrain's authored ambient + up to three directional lights. Reset all
// fill slots on every draw so a later one-light map cannot inherit old illumination.
D3DXVECTOR4 foamFillLights[4] = {D3DXVECTOR4(0, 0, 0, 0), D3DXVECTOR4(0, 0, 0, 0),
@@ -1095,11 +1121,11 @@ void WaterRenderObjClass::setupModernWaterShader(Bool river, Bool heightCorrecti
foamFillLights[slot].z = fillDirection.Z;
foamFillLights[slot + 1] = D3DXVECTOR4(diffuse.red, diffuse.green, diffuse.blue, 0);
}
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(90, &foamFillLights[0].x, 4);
+ setModernWaterConstants(90, &foamFillLights[0].x, 4);
if (!river && !m_modernHulls.empty()) {
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(8, &m_modernHulls[0].data[0][0],
+ setModernWaterConstants(8, &m_modernHulls[0].data[0][0],
m_modernHulls.size() * WaterHullModel::RegistersPerHull);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(96, &m_modernContactHulls[0].data[0][0],
+ setModernWaterConstants(96, &m_modernContactHulls[0].data[0][0],
m_modernContactHulls.size() * WaterHullModel::RegistersPerHull);
}
{
@@ -1111,9 +1137,9 @@ void WaterRenderObjClass::setupModernWaterShader(Bool river, Bool heightCorrecti
memcpy(metadata[h], m_modernVisualHulls[h].metadata, sizeof(metadata[h]));
memcpy(packets[h * WaterHullVisualLayout::RegistersPerHull], m_modernVisualHulls[h].data, sizeof(m_modernVisualHulls[h].data));
}
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(WaterHullVisualLayout::MetadataRegister,
+ setModernWaterConstants(WaterHullVisualLayout::MetadataRegister,
&metadata[0][0], WaterHullVisualLayout::MaxHulls);
- DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(WaterHullVisualLayout::PacketRegister,
+ setModernWaterConstants(WaterHullVisualLayout::PacketRegister,
&packets[0][0], WaterHullVisualLayout::PacketRegisters);
}
DX8Wrapper::Set_DX8_Texture(4, optical ? optical->Peek_D3D_Texture() : NULL);
@@ -1151,7 +1177,7 @@ void WaterRenderObjClass::setupModernWaterShader(Bool river, Bool heightCorrecti
// The terrain fallback refreshes when the map heights or dimensions change.
void WaterRenderObjClass::updateModernWaterTextures(void)
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (!m_modernBedTexture) {
const Int side=256;
std::vector<UnsignedInt> pixels(side*side);
@@ -1235,7 +1261,7 @@ void WaterRenderObjClass::clearModernWaterOpticalTextures(void)
void WaterRenderObjClass::refreshModernWaterOpticalPolygons(void)
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
std::vector<WaterOpticalContext::Polygon> polygons;
size_t points=0;
Bool valid=TRUE;
@@ -1264,7 +1290,7 @@ void WaterRenderObjClass::refreshModernWaterOpticalPolygons(void)
TextureClass *WaterRenderObjClass::modernWaterOpticalTexture(Real level)
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (!m_modernOpticalPolygonsValid) return NULL;
for (size_t i=0;i<m_modernOpticalTextures.size();++i)
if (m_modernOpticalTextures[i].level==level) return m_modernOpticalTextures[i].texture;
@@ -1378,8 +1404,8 @@ WaterRenderObjClass::~WaterRenderObjClass(void)
//-------------------------------------------------------------------------------------------------
WaterRenderObjClass::WaterRenderObjClass(void)
{
-#if defined(__linux__)
- m_useModernWater = TheGlobalData && TheGlobalData->m_waterStyle != 0;
+#if ZH_MODERN_WATER
+ m_useModernWater = TheGlobalData && TheGlobalData->m_waterStyle != 0 && ModernWater::Supported();
#endif
memset( &m_settings, 0, sizeof( m_settings ) );
m_dx=0;
@@ -2274,7 +2300,7 @@ void WaterRenderObjClass::updateMapOverrides(void)
// ------------------------------------------------------------------------------------------------
void WaterRenderObjClass::reset( void )
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
m_modernObjectsForDraw.clear();m_modernObstacleObjectIDs.clear();m_waterPolygonsForDraw.clear();
m_modernReadsReady=FALSE;
#endif
@@ -2367,7 +2393,7 @@ void WaterRenderObjClass::update( void )
takeGridForDraw();
synchronizeWaterStyle();
-#if defined(__linux__)
+#if ZH_MODERN_WATER
takeWaterPolygonsForDraw();
takeMotionReadsForRender();
#endif
@@ -2412,7 +2438,7 @@ void WaterRenderObjClass::update( void )
elapsedSec = 0.1f; // a level load must not jump the surface forward
// a pause or a script's time freeze stops every unit and particle; the water stops with them
-#if defined(__linux__)
+#if ZH_MODERN_WATER
const Bool waterFrozen=m_modernMotionFrozen;
#else
const Bool waterFrozen=TheGameLogic->isGamePaused() || TheScriptEngine->isTimeFrozenScript() || TheScriptEngine->isTimeFrozenDebug();
@@ -2420,7 +2446,7 @@ void WaterRenderObjClass::update( void )
if (waterFrozen) elapsedSec = 0.0f;
m_modernWaveTime = WaterSurfaceModel::AdvanceTime(m_modernWaveTime, elapsedSec, false, false, false);
-#if defined(__linux__)
+#if ZH_MODERN_WATER
// Client updates are independent of water visibility and reflected render recursion.
// Build every level once, then advance the fixed-world source even when the camera pans away.
if(m_useModernWater && m_trapezoidWaterPixelShader) {
@@ -2594,13 +2620,13 @@ void WaterRenderObjClass::updateRenderTargetTextures(CameraClass *cam)
Bool waterBehindCamera = FALSE;
Vector2 areaMin(1.0f, 1.0f);
Vector2 areaMax(-1.0f, -1.0f);
-#if defined(__linux__)
+#if ZH_MODERN_WATER
for (const WaterPolygonForDraw &polygon:m_waterPolygonsForDraw)
#else
for (PolygonTrigger *pTrig=PolygonTrigger::getFirstPolygonTrigger(); pTrig; pTrig = pTrig->getNext())
#endif
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
const WaterPolygonForDraw *pTrig=&polygon;
#endif
if (!pTrig->isWaterArea() || pTrig->getNumPoints() < 3)
@@ -2692,7 +2718,7 @@ void WaterRenderObjClass::renderMirror(CameraClass *cam, Real level)
// Clear the backbuffer
// The sea's cloud plane fills its background; map water has no such plane, so its target is
// cleared to white, which the overlay multiplies in as no change at all.
-#if !defined(__linux__)
+#if !ZH_MODERN_WATER
WW3D::Begin_Render(m_waterType == WATER_TYPE_0_TRANSLUCENT,true,WATER_REFLECTION_SKY_COLOR);
#else
// Modern water supplies its own sky. Classic multiplies a white-background mirror.
@@ -2802,21 +2828,26 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
return;
}
-#if defined(__linux__)
+#if ZH_MODERN_WATER
WaterShoreOverlay::Scope shoreScope(DX8Wrapper::_Get_D3D_Device(),
m_useModernWater && m_waterType==WATER_TYPE_0_TRANSLUCENT && m_trapezoidWaterPixelShader &&
!TheGlobalData->m_isWorldBuilder && !TheGlobalData->m_usingWaterTrackEditor);
m_modernFoamDrawFrame=~0u;m_modernFoamDrawObjectIDs.clear();
- RenderUInt32 oldModernCoordIndex=0,oldModernTransformFlags=0;
- RenderUInt32 oldModernBaseCoordIndex=0,oldModernBaseTransformFlags=0;
+ unsigned oldModernCoordIndex=0,oldModernTransformFlags=0;
+ unsigned oldModernBaseCoordIndex=0,oldModernBaseTransformFlags=0;
+ Bool oldModernStagesKnown=FALSE;
IDirect3DBaseTexture9 *oldModernBed=NULL,*oldModernOptical=NULL,*oldModernFoam=NULL;
if (m_useModernWater) {
- DX8Wrapper::_Get_D3D_Device()->GetTextureStageState(0,D3DTSS_TEXCOORDINDEX,&oldModernBaseCoordIndex);
- DX8Wrapper::_Get_D3D_Device()->GetTextureStageState(0,D3DTSS_TEXTURETRANSFORMFLAGS,&oldModernBaseTransformFlags);
- DX8Wrapper::_Get_D3D_Device()->GetTextureStageState(1,D3DTSS_TEXCOORDINDEX,&oldModernCoordIndex);
- DX8Wrapper::_Get_D3D_Device()->GetTextureStageState(1,D3DTSS_TEXTURETRANSFORMFLAGS,&oldModernTransformFlags);
- DX8Wrapper::_Get_D3D_Device()->GetTexture(7,&oldModernBed);
- DX8Wrapper::_Get_D3D_Device()->GetTexture(4,&oldModernOptical);
+ // The wrapper's own record: under Direct3D 11 the Direct3D 9 device is behind it (Defer_D3D9_State).
+ // Stage 14 is past the wrapper's stages and is set on the device at once.
+ oldModernStagesKnown=DX8Wrapper::Get_DX8_Texture_Stage_State(0,D3DTSS_TEXCOORDINDEX,oldModernBaseCoordIndex)
+ & DX8Wrapper::Get_DX8_Texture_Stage_State(0,D3DTSS_TEXTURETRANSFORMFLAGS,oldModernBaseTransformFlags)
+ & DX8Wrapper::Get_DX8_Texture_Stage_State(1,D3DTSS_TEXCOORDINDEX,oldModernCoordIndex)
+ & DX8Wrapper::Get_DX8_Texture_Stage_State(1,D3DTSS_TEXTURETRANSFORMFLAGS,oldModernTransformFlags);
+ oldModernBed=DX8Wrapper::Get_DX8_Texture(7);
+ if (oldModernBed) oldModernBed->AddRef();
+ oldModernOptical=DX8Wrapper::Get_DX8_Texture(4);
+ if (oldModernOptical) oldModernOptical->AddRef();
DX8Wrapper::_Get_D3D_Device()->GetTexture(14,&oldModernFoam);
updateModernWaterTextures();
refreshModernWaterOpticalPolygons();
@@ -3036,12 +3067,14 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
default:
break;
}//switch
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (m_useModernWater) {
- DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_TEXCOORDINDEX,oldModernBaseCoordIndex);
- DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_TEXTURETRANSFORMFLAGS,oldModernBaseTransformFlags);
- DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_TEXCOORDINDEX,oldModernCoordIndex);
- DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_TEXTURETRANSFORMFLAGS,oldModernTransformFlags);
+ if (oldModernStagesKnown) {
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_TEXCOORDINDEX,oldModernBaseCoordIndex);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_TEXTURETRANSFORMFLAGS,oldModernBaseTransformFlags);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_TEXCOORDINDEX,oldModernCoordIndex);
+ DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_TEXTURETRANSFORMFLAGS,oldModernTransformFlags);
+ }
DX8Wrapper::Set_DX8_Texture(7,oldModernBed);
if (oldModernBed) oldModernBed->Release();
DX8Wrapper::Set_DX8_Texture(4,oldModernOptical);
@@ -3069,7 +3102,7 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
if (m_waterTrackSystem)
m_waterTrackSystem->flush(rinfo);
-#if defined(__linux__)
+#if ZH_MODERN_WATER
#endif
@@ -3341,13 +3374,13 @@ void WaterRenderObjClass::drawSea(RenderInfoClass & rinfo)
//-------------------------------------------------------------------------------------------------
void WaterRenderObjClass::renderWater(void)
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
for (const WaterPolygonForDraw &polygon:m_waterPolygonsForDraw)
#else
for (PolygonTrigger *pTrig=PolygonTrigger::getFirstPolygonTrigger(); pTrig; pTrig = pTrig->getNext())
#endif
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
const WaterPolygonForDraw *pTrig=&polygon;
#endif
if (pTrig->isWaterArea()) {
@@ -3371,7 +3404,7 @@ void WaterRenderObjClass::renderWater(void)
points[2].Set(pt2.x, pt2.y, pt2.z);
points[3].Set(pt3.x, pt3.y, pt3.z);
-#if defined(__linux__)
+#if ZH_MODERN_WATER
// Modern depth intersections replace legacy tilted feather copies. Render exactly
// one surface at the authored elevation; duplicate layers could expose patch seams.
if (m_useModernWater && m_trapezoidWaterPixelShader) {
@@ -3726,7 +3759,7 @@ void WaterRenderObjClass::renderWaterMesh(void)
#endif
vb->u2=(float)(i)*cellSizeX/BUMP_SIZE;
vb->v2=v2Offset;
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (m_useModernWater && m_trapezoidWaterPixelShader) {
Vector3 world;
Matrix3D::Transform_Vector(Transform,Vector3(x,y,pData->height),&world);
@@ -3948,7 +3981,7 @@ Real WaterRenderObjClass::modernWaterDamping(Real x, Real y, Real z, Real offsho
// same canonical analytic samples regardless of whether the GPU ocean field is available.
void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool river, Real riverStart, Real riverEnd)
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
m_modernOpticalLevel = points[0].Z;
Vector3 boundsMin = points[0], boundsMax = points[0];
for (Int i = 1; i < 4; ++i) {
@@ -4538,7 +4571,7 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
//-------------------------------------------------------------------------------------------------
//Draw a many sided river polygon.
//-------------------------------------------------------------------------------------------------
-#if defined(__linux__)
+#if ZH_MODERN_WATER
void WaterRenderObjClass::drawRiverWater(const WaterPolygonForDraw *pTrig)
#else
void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig)
@@ -4554,7 +4587,7 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig)
if (m_drawnPushed) return;
m_drawingRiver = true;
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (m_useModernWater && m_riverWaterPixelShader) {
Int inner=pTrig->getRiverStart(),outer=inner+1;
if (inner<0 || inner>=pTrig->getNumPoints()-1) return;
@@ -4797,7 +4830,7 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig)
//-------------------------------------------------------------------------------------------------
void WaterRenderObjClass::drawReflection(Int triangleCount, Int vertexCount)
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (m_useModernWater) return; // Modern water samples the mirror in its surface shader.
#endif
if (!m_pReflectionTexture || !m_reflectionPixelShader)
@@ -4957,7 +4990,7 @@ void WaterRenderObjClass::setupFlatWaterShader(Bool heightCorrection,Bool waveCa
//-------------------------------------------------------------------------------------------------
void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4])
{
-#if defined(__linux__)
+#if ZH_MODERN_WATER
if (m_useModernWater && m_trapezoidWaterPixelShader) { drawModernWaterPatch(points,FALSE); return; }
#endif
Vector3 origin(points[0]);
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/ModernWaterBuild.h b/GeneralsMD/Code/Libraries/Include/Platform/ModernWaterBuild.h
new file mode 100644
index 000000000..532edaf23
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/ModernWaterBuild.h
@@ -0,0 +1,18 @@
+// Where the Modern water is compiled in: the SDL GPU device on Linux and the Direct3D 11 backend on
+// Windows. macOS, -d3d9 and -headless stay on the Classic water.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#pragma once
+
+#if defined(__linux__) || defined(_WIN32)
+#define ZH_MODERN_WATER 1
+#else
+#define ZH_MODERN_WATER 0
+#endif
+
+namespace ModernWater {
+
+// Whether this run's device draws the Modern water: the SDL GPU device, or Direct3D 11 presenting.
+// W3DWater.cpp answers for the game; the tests that link no device take HazardCloudUnsupported.cpp's no.
+bool Supported();
+
+} // namespace ModernWater
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterConstants.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterConstants.h
new file mode 100644
index 000000000..c6a98d66a
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterConstants.h
@@ -0,0 +1,186 @@
+// The Modern water's pixel constant block, built from the float4 registers W3DWater sets and the
+// camera the draw is made with. The SDL GPU device and the Direct3D 11 backend draw the same text
+// (engineshader.cpp, write_modern_water). This is the Direct3D 11 builder; field for field it is
+// PosixDevice9::Build_Water_Constants, which the SDL device keeps until it can be built against it.
+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+#pragma once
+
+#include "Platform/ModernWaterMaterial.h"
+#include "Platform/WaterFoamHistory.h"
+#include "Platform/WaterHullVisualLayout.h"
+
+#include <cmath>
+#include <cstddef>
+#include <cstring>
+
+namespace WaterConstants {
+
+// The b0 block both stages read, field for field WaterFftSampling::UniformSource's cbuffer. The
+// first three are the combiner's, which the appended alpha test and fog read.
+struct Block
+{
+ float TextureFactor[4];
+ float FogColour[4];
+ float AlphaReference[4];
+ float WorldFromClip[16];
+ float CameraPosition[4];
+ float SunDirection[4];
+ float SunColour[4];
+ float Viewport[4];
+ float ReflectionArea[4];
+ float WaterParameters[4]; // animation seconds, river flag, reflection available, mirror height
+ float TerrainParameters[4]; // height texture border, world size, height scale, available
+ float SceneParameters[4]; // refraction available, inverse scene-target width/height, scene depth available
+ float OpticalParameters[4]; // authored depth/opacity, offshore context available, flat UV0 height correction available
+ float HullParameters[4]; // number of visible vessel contours, authored ambient RGB for vessel foam
+ float HullData[80][4]; // eight vessels, ten float4 registers each; runtime waterline geometry
+ float FftParameters[4]; // x: the dedicated vertex displacement and six sampled ocean maps are bound
+ float FoamHistoryArea[4]; // world origin XY, inverse world width/height; sampled at undisplaced surface XY
+ float FoamHistoryParameters[4]; // available, water level, cell world size, simulation time of atlas
+ float ContactHullData[80][4]; // optional foam-only contours; count < 3 falls back to the matching mean hull
+ float FoamFillLights[4][4]; // two direction/colour pairs; first direction.w enables the main light for foam
+#define MODERN_WATER_CONSTANTS_UNIFORM(name) float name[4];
+ MODERN_WATER_MATERIAL_UNIFORMS(MODERN_WATER_CONSTANTS_UNIFORM)
+#undef MODERN_WATER_CONSTANTS_UNIFORM
+};
+static_assert(sizeof(Block) == WaterHullVisualLayout::VertexCommonRegisters * 16, "water uniform packing");
+static_assert(offsetof(Block, MaterialColor) == 184 * 16 && offsetof(Block, MaterialParameters) == 185 * 16,
+ "water material tail packing");
+
+// The pixel half's b0: the block above and the hull meshes' metadata after it.
+struct VisualBlock
+{
+ Block Water;
+ float VisualHullMeta[WaterHullVisualLayout::MaxHulls][4];
+};
+static_assert(sizeof(VisualBlock) == WaterHullVisualLayout::FragmentCommonRegisters * 16,
+ "fragment hull metadata packing");
+
+// The draw's camera: view and projection in the Direct3D layout (row vectors), the viewport in
+// target pixels with its depth range.
+struct Camera
+{
+ const float *view;
+ const float *projection;
+ float x, y, width, height, minZ, maxZ;
+};
+
+// Visual-only inverse for reconstructing the water surface from depth. Double intermediates keep
+// distant camera translations stable; this does not reach simulation or replay arithmetic.
+inline bool Inverse(const float source[16], float result[16])
+{
+ double rows[4][8];
+ for (unsigned r = 0; r < 4; ++r)
+ for (unsigned c = 0; c < 8; ++c)
+ rows[r][c] = c < 4 ? source[r * 4 + c] : (c - 4 == r ? 1.0 : 0.0);
+ for (unsigned c = 0; c < 4; ++c) {
+ unsigned pivot = c;
+ for (unsigned r = c + 1; r < 4; ++r)
+ if (std::fabs(rows[r][c]) > std::fabs(rows[pivot][c])) pivot = r;
+ if (!std::isfinite(rows[pivot][c]) || std::fabs(rows[pivot][c]) < 1e-15) return false;
+ for (unsigned k = 0; k < 8; ++k) {
+ const double saved = rows[c][k]; rows[c][k] = rows[pivot][k]; rows[pivot][k] = saved;
+ }
+ const double scale = rows[c][c];
+ for (unsigned k = 0; k < 8; ++k) rows[c][k] /= scale;
+ for (unsigned r = 0; r < 4; ++r) {
+ if (r == c) continue;
+ const double factor = rows[r][c];
+ for (unsigned k = 0; k < 8; ++k) rows[r][k] -= factor * rows[c][k];
+ }
+ }
+ for (unsigned r = 0; r < 4; ++r)
+ for (unsigned c = 0; c < 4; ++c) result[r * 4 + c] = (float)rows[r][c + 4];
+ return true;
+}
+
+inline void Multiply(const float left[16], const float right[16], float result[16])
+{
+ for (unsigned row = 0; row < 4; ++row)
+ for (unsigned column = 0; column < 4; ++column) {
+ float sum = 0.0f;
+ for (unsigned index = 0; index < 4; ++index) sum += left[row * 4 + index] * right[index * 4 + column];
+ result[row * 4 + column] = sum;
+ }
+}
+
+// Whether c88/c89 describe a foam atlas the shader may read: history is an optional CPU-authored
+// image, so a stale binding, an invalid mapping or a river draw never makes it a required input.
+inline bool FoamHistoryRegisters(const float (*registers)[4])
+{
+ if (registers[1][1] > 0.5f || registers[89][0] <= 0.5f) return false;
+ for (unsigned c = 0; c < 4; ++c)
+ if (!std::isfinite(registers[88][c]) || !std::isfinite(registers[89][c])) return false;
+ if (registers[88][2] <= 0 || registers[88][3] <= 0 || registers[89][2] <= 0) return false;
+ const float flags = registers[89][0];
+ return !(flags > 7 || std::floor(flags) != flags || (static_cast<unsigned>(flags) & 3u) == 0u);
+}
+
+// The packed format has two equal logical tiles; a malformed or stale binding must not reinterpret
+// a middle row as a history/direction boundary. Legacy atlases remain valid.
+inline bool FoamHistoryAtlas(const float (*registers)[4], unsigned width, unsigned height)
+{
+ if (width == 0 || height == 0) return false;
+ return (static_cast<unsigned>(registers[89][0]) & 4u) == 0u || (height % 2 == 0
+ && width <= WaterFoamHistory::MaxAtlasSide && height <= 2 * WaterFoamHistory::MaxAtlasSide);
+}
+
+// Everything but the combiner's three fields, which the caller's own pipeline fills. registers is
+// the WaterHullVisualLayout::PixelRegisterCount bank; history says whether the atlas at stage 14
+// passed the two checks above.
+inline void Fill(const float (*registers)[4], const Camera &camera, bool history, Block &water)
+{
+ std::memset(&water, 0, sizeof(water));
+ float view_projection[16], inverse_view[16];
+ Multiply(camera.view, camera.projection, view_projection);
+ if (!Inverse(view_projection, water.WorldFromClip) || !Inverse(camera.view, inverse_view)) {
+ std::memset(water.WorldFromClip, 0, sizeof(water.WorldFromClip));
+ std::memset(inverse_view, 0, sizeof(inverse_view));
+ for (unsigned i = 0; i < 4; ++i) water.WorldFromClip[i * 5] = inverse_view[i * 5] = 1.0f;
+ }
+ water.CameraPosition[0] = inverse_view[12];
+ water.CameraPosition[1] = inverse_view[13];
+ water.CameraPosition[2] = inverse_view[14];
+ // Both SV_Position.z and sampled scene depth include the viewport's depth range. Compose its
+ // inverse into the unprojection so custom MinZ/MaxZ use the same shader path as the normal range.
+ const float depth_range = camera.maxZ - camera.minZ;
+ if (depth_range > 1.0e-8f) {
+ for (unsigned int column = 0; column < 4; ++column) {
+ const float z_row = water.WorldFromClip[8 + column] / depth_range;
+ water.WorldFromClip[12 + column] -= camera.minZ * z_row;
+ water.WorldFromClip[8 + column] = z_row;
+ }
+ }
+ water.Viewport[0] = camera.x + 0.5f;
+ water.Viewport[1] = camera.y + 0.5f;
+ water.Viewport[2] = camera.width;
+ water.Viewport[3] = camera.height;
+ std::memcpy(water.WaterParameters, registers[1], sizeof(water.WaterParameters));
+ std::memcpy(water.ReflectionArea, registers[2], sizeof(water.ReflectionArea));
+ std::memcpy(water.SunDirection, registers[3], sizeof(water.SunDirection));
+ std::memcpy(water.SunColour, registers[4], sizeof(water.SunColour));
+ std::memcpy(water.TerrainParameters, registers[5], sizeof(water.TerrainParameters));
+ std::memcpy(water.OpticalParameters, registers[6], sizeof(water.OpticalParameters));
+ std::memcpy(water.HullParameters, registers[7], sizeof(water.HullParameters));
+ std::memcpy(water.HullData, registers[8], sizeof(water.HullData));
+ std::memcpy(water.ContactHullData, registers[96], sizeof(water.ContactHullData));
+ std::memcpy(water.FoamFillLights, registers[90], sizeof(water.FoamFillLights));
+ std::memcpy(water.MaterialColor, registers[ModernWaterMaterial::RegisterColor], sizeof(water.MaterialColor));
+ std::memcpy(water.MaterialParameters, registers[ModernWaterMaterial::RegisterParameters], sizeof(water.MaterialParameters));
+ if (history) {
+ std::memcpy(water.FoamHistoryArea, registers[88], sizeof(water.FoamHistoryArea));
+ std::memcpy(water.FoamHistoryParameters, registers[89], sizeof(water.FoamHistoryParameters));
+ }
+ // River draws must never inherit a preceding ocean draw's hull field.
+ if (water.WaterParameters[1] > 0.5f) water.HullParameters[0] = 0;
+}
+
+inline void FillVisual(const Block &water, const float (*registers)[4], VisualBlock &visual)
+{
+ visual.Water = water;
+ std::memcpy(visual.VisualHullMeta, registers[WaterHullVisualLayout::MetadataRegister], sizeof(visual.VisualHullMeta));
+ // River and empty hull draws must not activate a preceding ocean's packet metadata.
+ if (water.HullParameters[0] <= 0) std::memset(visual.VisualHullMeta, 0, sizeof(visual.VisualHullMeta));
+}
+
+} // namespace WaterConstants
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreOverlay.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreOverlay.h
index d894b2054..3e6a72df2 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreOverlay.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreOverlay.h
@@ -137,4 +137,17 @@ struct Scope {
Scope &operator=(const Scope &)=delete;
};
}
+#else
+// The Direct3D 11 backend draws the Modern water without the shore overlay's second pass yet: the
+// coast keeps the foam the surface shader draws itself.
+struct IDirect3DDevice9;
+inline void PosixWaterShorePatch(IDirect3DDevice9 *,const WaterShoreOverlay::Quad *) {}
+inline void PosixWaterShoreTrack(IDirect3DDevice9 *,const WaterShoreOverlay::Quad *) {}
+namespace WaterShoreOverlay {
+struct Scope {
+ Scope(IDirect3DDevice9 *,bool) {}
+ Scope(const Scope &)=delete;
+ Scope &operator=(const Scope &)=delete;
+};
+}
#endif
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
index fbf5b730a..e813197a7 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -338,6 +338,9 @@ DX11BackendClass::DX11BackendClass()
}
ViewportWidth = 1;
ViewportHeight = 1;
+ ViewportX = 0;
+ ViewportY = 0;
+ Water = Create_Water();
// The device's own defaults, so a stage nobody has written to is a stage that is off.
for (unsigned stage = 0; stage < DX11_BACKEND_TEXTURE_STAGES; ++stage) {
@@ -354,6 +357,7 @@ DX11BackendClass::DX11BackendClass()
DX11BackendClass::~DX11BackendClass()
{
Shutdown();
+ Destroy_Water(Water);
}
bool DX11BackendClass::Initialise(DX11DeviceClass * device)
@@ -521,6 +525,7 @@ void DX11BackendClass::Shutdown()
ShaderCacheChanged = false;
}
Release_Cached();
+ Release_Water();
Release_Constant_Ring(EngineConstantRing);
Release_Constant_Ring(PixelConstantRing);
@@ -1633,6 +1638,9 @@ void DX11BackendClass::Set_Texture(unsigned stage, ID3D11ShaderResourceView * te
}
Textures[stage] = texture;
}
+ else {
+ Set_Water_Texture(stage, texture);
+ }
}
void DX11BackendClass::Set_Headlights(const float * lights, unsigned count, const float gain[3])
@@ -1985,6 +1993,7 @@ void DX11BackendClass::Begin_Scene()
{
SceneDepthStale = true;
SceneColourStale = true;
+ Water_Scene_Changed(NULL);
// A scene can begin with a render target already set: the water's reflection and the shadow
// projector both set theirs and then call WW3D::Begin_Render, and forcing the back buffer here
@@ -2137,6 +2146,8 @@ void DX11BackendClass::Set_Viewport(unsigned x, unsigned y, unsigned width, unsi
viewport.MaxDepth = 1.0f;
Device->Get_Context()->RSSetViewports(1, &viewport);
+ ViewportX = x;
+ ViewportY = y;
ViewportWidth = (width == 0) ? 1 : width;
ViewportHeight = (height == 0) ? 1 : height;
ConstantsChanged = true;
@@ -2153,6 +2164,12 @@ void DX11BackendClass::Clear(bool colour, bool depth, const float colour_value[4
if (colour && target != NULL) {
Device->Get_Context()->ClearRenderTargetView(target, colour_value);
+ ID3D11Resource * cleared = CurrentTargetResource;
+ if (CurrentTarget == NULL) {
+ target->GetResource(&cleared);
+ cleared->Release(); // the device holds the scene target for as long as it lives
+ }
+ Water_Scene_Changed(cleared);
}
if (depth && depth_view != NULL) {
Device->Get_Context()->ClearDepthStencilView(depth_view,
@@ -2422,8 +2439,11 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)
std::vector<unsigned char> vertex_code;
std::vector<unsigned char> pixel_code;
+ // The Modern water writes a dynamically indexed array, which shader model 4 refuses; every other
+ // program keeps the profile its cached and shipped bytecode was compiled at.
+ const char * const pixel_profile = EngineShader_Is_Modern_Water(PixelProgram) ? "ps_5_0" : PIXEL_PROFILE;
if (!Compile_Program(vertex_hlsl, "ffvertex", VERTEX_PROFILE, vertex_code)
- || !Compile_Program(pixel_hlsl, "ffshader", PIXEL_PROFILE, pixel_code)) {
+ || !Compile_Program(pixel_hlsl, "ffshader", pixel_profile, pixel_code)) {
Refuse(key, REFUSED_NO_PROGRAM);
return false;
}
@@ -3180,13 +3200,25 @@ bool DX11BackendClass::Draw_Indexed(unsigned index_count, unsigned start_index,
++DrawsRefused;
return false;
}
+ // The sun's map has no water in it, and a water program there only writes its depth.
+ const bool water = EngineShader_Is_Modern_Water(PixelProgram) && !ShadowMapBound;
+ if (water && !Prepare_Water()) {
+ ++DrawsRefused;
+ return false;
+ }
ID3D11DeviceContext * context = Device->Get_Context();
Upload_Constants();
Bind_State_Objects();
Bind_Pipeline(pipeline, StreamBuffer, StreamStride, StreamOffset, IndexBuffer, IndexFormat, topology);
+ if (water) {
+ Bind_Water();
+ }
context->DrawIndexed(index_count, start_index, base_vertex);
+ if (water) {
+ Unbind_Water();
+ }
++DrawsMade;
// The soft particles' copy of the depth is behind whatever this wrote into the scene's depth
@@ -3225,6 +3257,11 @@ bool DX11BackendClass::Draw_Triangles(unsigned vertex_count, unsigned start_vert
++DrawsRefused;
return false;
}
+ const bool water = EngineShader_Is_Modern_Water(PixelProgram) && !ShadowMapBound;
+ if (water && !Prepare_Water()) {
+ ++DrawsRefused;
+ return false;
+ }
ID3D11DeviceContext * context = Device->Get_Context();
Upload_Constants();
@@ -3232,7 +3269,13 @@ bool DX11BackendClass::Draw_Triangles(unsigned vertex_count, unsigned start_vert
Bind_Pipeline(pipeline, StreamBuffer, StreamStride, StreamOffset, NULL, DXGI_FORMAT_UNKNOWN,
D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ if (water) {
+ Bind_Water();
+ }
context->Draw(vertex_count, start_vertex);
+ if (water) {
+ Unbind_Water();
+ }
++DrawsMade;
// The soft particles' copy of the depth is behind whatever this wrote into the scene's depth
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
index 570c09ade..ed09007ef 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
@@ -140,6 +140,13 @@ public:
// The engine's own float4 shader constant bank, as it sets it. The transcribed programs index
// it by the same register number the SetVertexShaderConstantF call used.
void Set_Vertex_Program_Constant(unsigned first_register, const float * values, unsigned count);
+
+ // The Modern water's float4 registers as W3DWater sets them (Platform/WaterConstants.h), up to
+ // DX11_WATER_REGISTERS. Only a Modern water draw reads them, through dx11water.cpp's blocks.
+ void Set_Water_Constants(unsigned first_register, const float * values, unsigned count);
+ // What the Modern water drew with, for the shutdown report: its draws, the GPU ocean's updates,
+ // or why the analytic surface stood in for it.
+ std::string Water_Report() const;
void Set_Stream_Source(ID3D11Buffer * buffer, unsigned stride, unsigned offset);
void Set_Indices(ID3D11Buffer * buffer, DXGI_FORMAT format);
@@ -528,6 +535,23 @@ private:
// What the viewport is, so a pre-transformed vertex can be put back into clip space.
unsigned ViewportWidth;
unsigned ViewportHeight;
+ unsigned ViewportX;
+ unsigned ViewportY;
+
+ // The Modern water (dx11water.cpp): its registers, the stages past the fourth, the copies of the
+ // scene it refracts through, the GPU ocean and the displaced vertex programs. Prepare runs
+ // before a water draw binds anything, because the ocean's passes take the context; Bind after
+ // the draw's own bindings, Unbind after the draw.
+ struct WaterResources;
+ WaterResources * Water;
+ static WaterResources * Create_Water();
+ static void Destroy_Water(WaterResources * water);
+ void Set_Water_Texture(unsigned stage, ID3D11ShaderResourceView * texture);
+ bool Prepare_Water();
+ void Bind_Water();
+ void Unbind_Water();
+ void Water_Scene_Changed(ID3D11Resource * target); // null: a new frame, every copy is old
+ void Release_Water();
// The sun's depth buffer and the two views of it: one to draw into, one to sample. The
// viewport the frame was using is kept while it is bound, because the map is square and the
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
index c6ddd5b57..f847b00e8 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
@@ -1089,6 +1089,18 @@ void Direct3D11_Mirror_Vertex_Shader_Constant(unsigned first_register, const flo
}
}
+void Direct3D11_Set_Water_Constants(unsigned first_register, const float * values, unsigned count)
+{
+ if (Active) {
+ Backend.Set_Water_Constants(first_register, values, count);
+ }
+}
+
+std::string Direct3D11_Water_Report()
+{
+ return Active ? Backend.Water_Report() : std::string("no Direct3D 11 backend");
+}
+
bool Direct3D11_Draw_Indexed_Triangles(unsigned index_count, unsigned start_index,
unsigned base_vertex)
{
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
index eb4b0f314..d4250e8e4 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
@@ -324,6 +324,11 @@ void Direct3D11_Register_Engine_Shader(const void * shader, const char * file_pa
void Direct3D11_Mirror_Vertex_Shader_Constant(unsigned first_register, const float * values,
unsigned count);
+// The Modern water's pixel registers, c0 to the last hull packet (DX11_WATER_REGISTERS), which
+// W3DWater sets for its own draws and nothing else reads; and what its draws did, for the log.
+void Direct3D11_Set_Water_Constants(unsigned first_register, const float * values, unsigned count);
+std::string Direct3D11_Water_Report();
+
// The draw, made alongside the Direct3D 9 one rather than instead of it: phase 2 is finished when
// the D3D11 picture can replace the D3D9 one, and until then both have to be able to produce it.
// False means the backend could not resolve a pipeline for this state and drew nothing, which is
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
index fc96e672d..4c75206b2 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
@@ -141,6 +141,8 @@ void Direct3D11_Mirror_Vertex_Shader(const void *) {}
// transcriptions by the name they were registered under, as the Direct3D 11 backend does (A3e).
void Direct3D11_Register_Engine_Shader(const void * shader, const char * name) { PosixDevice_Name_Shader(shader, name); }
void Direct3D11_Mirror_Vertex_Shader_Constant(unsigned, const float *, unsigned) {}
+void Direct3D11_Set_Water_Constants(unsigned, const float *, unsigned) {}
+std::string Direct3D11_Water_Report() { return std::string("no Direct3D 11 backend"); }
bool Direct3D11_Draw_Indexed_Triangles(unsigned, unsigned, unsigned) { return false; }
bool Direct3D11_Draw_Indexed_Strip(unsigned, unsigned, unsigned) { return false; }
bool Direct3D11_Draw_User_Strip(const void *, unsigned, unsigned) { return false; }
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11water.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11water.cpp
new file mode 100644
index 000000000..fac22bcdc
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11water.cpp
@@ -0,0 +1,789 @@
+/*
+** The Modern water's half of DX11BackendClass: what a water draw binds beside the generated
+** pipeline, and the GPU ocean its open sea is displaced by. The SDL GPU device does the same in
+** PosixDevice9Draw.cpp and SdlGpuFrame.cpp, and both read one text (engineshader.cpp,
+** write_modern_water) and one constant block (Platform/WaterConstants.h).
+**
+** A Modern water draw differs from every other draw in five ways. Its pixel half reads fifteen
+** stages, where the backend mirrors four: t4 the shore's optical field, t5 a copy of the scene it
+** refracts, t6 a copy of the scene's depth, t7 the bed's detail, t8 to t13 the ocean's six maps and
+** t14 the vessels' foam. It reads four constant blocks, the water's own and three of hull packets,
+** none of which the combiners' block holds. Over open sea its vertex half samples three of the
+** ocean maps and the terrain, and reads the water's block at b1. The ocean is rendered on the
+** context first, which takes the targets away from the scene. And a destination alpha feather
+** becomes a plain alpha blend, because the shader already attenuates the bed it refracts.
+**
+** Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+*/
+
+#include "dx11backend.h"
+#include "dx11water.h"
+#include "Platform/WaterConstants.h"
+#include "Platform/WaterFftSampling.h"
+#include "Platform/WaterFftSpectrum.h"
+
+#include <float.h>
+#include <stdio.h>
+#include <string.h>
+
+namespace Spectrum = WaterFftSpectrum;
+
+namespace {
+
+template <class T> void drop(T *& object)
+{
+ if (object != NULL) {
+ object->Release();
+ object = NULL;
+ }
+}
+
+// One render target the ocean draws into and samples back.
+struct OceanSurface
+{
+ ID3D11Texture2D * Texture = NULL;
+ ID3D11ShaderResourceView * View = NULL;
+ ID3D11RenderTargetView * Target = NULL;
+};
+
+void drop(OceanSurface & surface)
+{
+ drop(surface.Target);
+ drop(surface.View);
+ drop(surface.Texture);
+}
+
+bool make(ID3D11Device * device, OceanSurface & surface, unsigned width, unsigned levels,
+ bool target, const float * initial)
+{
+ D3D11_TEXTURE2D_DESC description;
+ memset(&description, 0, sizeof(description));
+ description.Width = width;
+ description.Height = Spectrum::Resolution;
+ description.MipLevels = levels;
+ description.ArraySize = 1;
+ description.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
+ description.SampleDesc.Count = 1;
+ description.Usage = target ? D3D11_USAGE_DEFAULT : D3D11_USAGE_IMMUTABLE;
+ description.BindFlags = D3D11_BIND_SHADER_RESOURCE | (target ? D3D11_BIND_RENDER_TARGET : 0);
+ description.MiscFlags = levels > 1 ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0;
+ D3D11_SUBRESOURCE_DATA data;
+ data.pSysMem = initial;
+ data.SysMemPitch = width * 4 * sizeof(float);
+ data.SysMemSlicePitch = 0;
+ return SUCCEEDED(device->CreateTexture2D(&description, initial != NULL ? &data : NULL, &surface.Texture))
+ && SUCCEEDED(device->CreateShaderResourceView(surface.Texture, NULL, &surface.View))
+ && (!target || SUCCEEDED(device->CreateRenderTargetView(surface.Texture, NULL, &surface.Target)));
+}
+
+ID3D11SamplerState * make_sampler(ID3D11Device * device, D3D11_FILTER filter,
+ D3D11_TEXTURE_ADDRESS_MODE address, float most_detailed_levels)
+{
+ D3D11_SAMPLER_DESC description;
+ memset(&description, 0, sizeof(description));
+ description.Filter = filter;
+ description.AddressU = address;
+ description.AddressV = address;
+ description.AddressW = address;
+ description.ComparisonFunc = D3D11_COMPARISON_NEVER;
+ description.MaxLOD = most_detailed_levels;
+ ID3D11SamplerState * sampler = NULL;
+ device->CreateSamplerState(&description, &sampler);
+ return sampler;
+}
+
+bool upload(ID3D11DeviceContext * context, ID3D11Buffer * buffer, const void * bytes, unsigned size)
+{
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ if (FAILED(context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {
+ return false;
+ }
+ memcpy(mapped.pData, bytes, size);
+ context->Unmap(buffer, 0);
+ return true;
+}
+
+ID3D11Buffer * make_constants(ID3D11Device * device, unsigned size)
+{
+ D3D11_BUFFER_DESC description;
+ memset(&description, 0, sizeof(description));
+ description.ByteWidth = size;
+ description.Usage = D3D11_USAGE_DYNAMIC;
+ description.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
+ description.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ ID3D11Buffer * buffer = NULL;
+ device->CreateBuffer(&description, NULL, &buffer);
+ return buffer;
+}
+
+// The texture behind a view, for its size and whether it is a render target.
+bool view_texture(ID3D11ShaderResourceView * view, D3D11_TEXTURE2D_DESC & description)
+{
+ D3D11_SHADER_RESOURCE_VIEW_DESC how;
+ view->GetDesc(&how);
+ if (how.ViewDimension != D3D11_SRV_DIMENSION_TEXTURE2D) {
+ return false;
+ }
+ ID3D11Resource * resource = NULL;
+ view->GetResource(&resource);
+ static_cast<ID3D11Texture2D *>(resource)->GetDesc(&description);
+ resource->Release();
+ return true;
+}
+
+} // namespace
+
+bool DX11Water_Ocean_Vertex_Program(const VertexPipelineDescription & description, std::string & hlsl)
+{
+ return !description.LightingEnabled
+ && VertexShader_Generate(description, VERTEX_SHADER_TARGET_D3D11, hlsl)
+ && WaterFftSampling::WrapVertex(hlsl);
+}
+
+std::string DX11Water_Ocean_Pass_Program(unsigned pass)
+{
+ std::string source = pass == 0 ? WaterFftSpectrum::SpectrumHlsl()
+ : pass == 1 ? WaterFftSpectrum::ButterflyHlsl() : WaterFftSpectrum::PostHlsl();
+ // Register spaces are shader model 5.1; the passes bind nothing else, so plain slots are the same.
+ static const char * const SPACES[] = { ", space2)", ", space3)" };
+ for (const char * space : SPACES) {
+ const size_t length = strlen(space);
+ for (size_t at = source.find(space); at != std::string::npos; at = source.find(space, at)) {
+ source.replace(at, length, ")");
+ }
+ }
+ return source;
+}
+
+const char * DX11Water_Ocean_Pass_Vertex_Program()
+{
+ return WaterFftSpectrum::VertexHlsl();
+}
+
+struct DX11BackendClass::WaterResources
+{
+ float Registers[DX11_WATER_REGISTERS][4] = {};
+ // What the engine bound at the stages past the backend's four, as it bound them.
+ ID3D11ShaderResourceView * Textures[DX11_WATER_STAGES] = {};
+
+ // Made with the first draw; Refused for good when the device would not.
+ bool Made = false;
+ bool Refused = false;
+ ID3D11Texture2D * WhiteTexture = NULL;
+ ID3D11ShaderResourceView * White = NULL;
+ ID3D11SamplerState * ClampLinear = NULL;
+ ID3D11SamplerState * ClampPoint = NULL;
+ ID3D11SamplerState * WrapLinear = NULL;
+ ID3D11Buffer * Constants = NULL;
+ ID3D11Buffer * Packets[WaterHullVisualLayout::BlockCount] = {};
+ float HeldPackets[WaterHullVisualLayout::PacketRegisters][4] = {};
+ bool PacketsHeld = false;
+
+ // The scene before the first water draw of a frame into a target, and its depth.
+ ID3D11Texture2D * Colour = NULL;
+ ID3D11ShaderResourceView * ColourView = NULL;
+ ID3D11Resource * ColourSource = NULL;
+ bool ColourStale = true;
+ unsigned TargetWidth = 1;
+ unsigned TargetHeight = 1;
+ ID3D11Texture2D * Depth = NULL;
+ ID3D11ShaderResourceView * DepthView = NULL;
+ ID3D11Resource * DepthSource = NULL;
+
+ // The ocean: three initial spectra, two sets of six to ping-pong the FFT through, the six maps
+ // the water samples with their mips, and the butterfly table.
+ bool OceanFailed = false;
+ bool OceanReady = false;
+ float OceanTime = 0.0f;
+ std::string OceanStatus = "not asked for";
+ OceanSurface Initial[Spectrum::Cascades];
+ OceanSurface Ping[2][Spectrum::Maps];
+ OceanSurface Fields[Spectrum::Maps];
+ OceanSurface Twiddles;
+ ID3D11VertexShader * OceanVertex = NULL;
+ ID3D11PixelShader * OceanPixels[DX11_WATER_OCEAN_PASSES] = {};
+ ID3D11Buffer * OceanConstants = NULL;
+ ID3D11SamplerState * OceanPoint = NULL;
+ ID3D11SamplerState * OceanLinear = NULL;
+ ID3D11RasterizerState * NoCull = NULL;
+ std::map<std::string, ID3D11VertexShader *> VertexPrograms;
+
+ // The draw in hand.
+ bool Fft = false;
+ ID3D11VertexShader * DrawVertex = NULL;
+ bool HaveColour = false;
+ bool HaveDepth = false;
+
+ unsigned long long Draws = 0;
+ unsigned long long DisplacedDraws = 0;
+ unsigned long long OceanUpdates = 0;
+
+ bool Make(ID3D11Device * device);
+ bool Fail_Ocean(const char * reason);
+ bool Make_Ocean(DX11BackendClass & backend, ID3D11Device * device);
+ bool Prepare_Ocean(DX11BackendClass & backend, ID3D11Device * device, ID3D11DeviceContext * context,
+ float time);
+ void Ocean_Pass(ID3D11DeviceContext * context, unsigned which, OceanSurface * targets,
+ ID3D11ShaderResourceView * const * sources, unsigned count, const float parameters[8]);
+ void Take_Scene(DX11DeviceClass & device, ID3D11Resource * source, ID3D11RenderTargetView * view,
+ bool scene_depth);
+ void Release();
+};
+
+bool DX11BackendClass::WaterResources::Make(ID3D11Device * device)
+{
+ if (Made || Refused) {
+ return Made;
+ }
+ D3D11_TEXTURE2D_DESC description;
+ memset(&description, 0, sizeof(description));
+ description.Width = 1;
+ description.Height = 1;
+ description.MipLevels = 1;
+ description.ArraySize = 1;
+ description.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ description.SampleDesc.Count = 1;
+ description.Usage = D3D11_USAGE_IMMUTABLE;
+ description.BindFlags = D3D11_BIND_SHADER_RESOURCE;
+ const unsigned white = 0xffffffff;
+ D3D11_SUBRESOURCE_DATA data = { &white, 4, 0 };
+ device->CreateTexture2D(&description, &data, &WhiteTexture);
+ if (WhiteTexture != NULL) {
+ device->CreateShaderResourceView(WhiteTexture, NULL, &White);
+ }
+ ClampLinear = make_sampler(device, D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT, D3D11_TEXTURE_ADDRESS_CLAMP, 0.0f);
+ ClampPoint = make_sampler(device, D3D11_FILTER_MIN_MAG_MIP_POINT, D3D11_TEXTURE_ADDRESS_CLAMP, 0.0f);
+ WrapLinear = make_sampler(device, D3D11_FILTER_MIN_MAG_MIP_LINEAR, D3D11_TEXTURE_ADDRESS_WRAP, FLT_MAX);
+ Constants = make_constants(device, sizeof(WaterConstants::VisualBlock));
+ bool packets = true;
+ for (unsigned block = 0; block < WaterHullVisualLayout::BlockCount; ++block) {
+ Packets[block] = make_constants(device, WaterHullVisualLayout::BlockRegisters(block) * 16);
+ packets = packets && Packets[block] != NULL;
+ }
+ Made = White != NULL && ClampLinear != NULL && ClampPoint != NULL && WrapLinear != NULL
+ && Constants != NULL && packets;
+ Refused = !Made;
+ return Made;
+}
+
+bool DX11BackendClass::WaterResources::Fail_Ocean(const char * reason)
+{
+ OceanFailed = true;
+ OceanReady = false;
+ OceanStatus = std::string("analytic: ") + reason;
+ return false;
+}
+
+bool DX11BackendClass::WaterResources::Make_Ocean(DX11BackendClass & backend, ID3D11Device * device)
+{
+ // Mip generation is what keeps a distant swell from shimmering; without it the analytic surface
+ // stands in, as it does on the SDL device without float targets.
+ UINT support = 0;
+ const UINT wanted = D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_RENDER_TARGET
+ | D3D11_FORMAT_SUPPORT_SHADER_SAMPLE | D3D11_FORMAT_SUPPORT_MIP_AUTOGEN;
+ if (FAILED(device->CheckFormatSupport(DXGI_FORMAT_R32G32B32A32_FLOAT, &support)) || (support & wanted) != wanted) {
+ return Fail_Ocean("no filtered, mip-generated RGBA32F target");
+ }
+ const unsigned side = Spectrum::Resolution;
+ const std::vector<float> initial = Spectrum::InitialSpectrum();
+ const std::vector<float> butterfly = Spectrum::Butterfly();
+ bool made = true;
+ for (unsigned cascade = 0; cascade < Spectrum::Cascades; ++cascade) {
+ made = made && make(device, Initial[cascade], side, 1, false, &initial[cascade * side * side * 4]);
+ }
+ for (unsigned set = 0; set < 2; ++set) {
+ for (unsigned map = 0; map < Spectrum::Maps; ++map) {
+ made = made && make(device, Ping[set][map], side, 1, true, NULL);
+ }
+ }
+ for (unsigned map = 0; map < Spectrum::Maps; ++map) {
+ made = made && make(device, Fields[map], side, Spectrum::Phases + 1, true, NULL);
+ }
+ made = made && make(device, Twiddles, Spectrum::Phases, 1, false, &butterfly[0]);
+ if (!made) {
+ return Fail_Ocean("the device refused the ocean's textures");
+ }
+
+ std::vector<unsigned char> code;
+ if (!backend.Compile_Program(DX11Water_Ocean_Pass_Vertex_Program(), "ocean vertex", "vs_5_0", code)
+ || FAILED(device->CreateVertexShader(&code[0], code.size(), NULL, &OceanVertex))) {
+ return Fail_Ocean("the ocean's vertex pass would not compile");
+ }
+ for (unsigned pass = 0; pass < DX11_WATER_OCEAN_PASSES; ++pass) {
+ if (!backend.Compile_Program(DX11Water_Ocean_Pass_Program(pass), "ocean pass", "ps_5_0", code)
+ || FAILED(device->CreatePixelShader(&code[0], code.size(), NULL, &OceanPixels[pass]))) {
+ return Fail_Ocean("an ocean pass would not compile");
+ }
+ }
+ OceanConstants = make_constants(device, 8 * sizeof(float));
+ OceanPoint = make_sampler(device, D3D11_FILTER_MIN_MAG_MIP_POINT, D3D11_TEXTURE_ADDRESS_WRAP, 0.0f);
+ OceanLinear = make_sampler(device, D3D11_FILTER_MIN_MAG_MIP_LINEAR, D3D11_TEXTURE_ADDRESS_WRAP,
+ float(Spectrum::Phases));
+ D3D11_RASTERIZER_DESC rasterizer;
+ memset(&rasterizer, 0, sizeof(rasterizer));
+ rasterizer.FillMode = D3D11_FILL_SOLID;
+ rasterizer.CullMode = D3D11_CULL_NONE;
+ rasterizer.DepthClipEnable = TRUE;
+ device->CreateRasterizerState(&rasterizer, &NoCull);
+ if (OceanConstants == NULL || OceanPoint == NULL || OceanLinear == NULL || NoCull == NULL) {
+ return Fail_Ocean("the device refused the ocean's states");
+ }
+ OceanStatus = "GPU field";
+ return true;
+}
+
+void DX11BackendClass::WaterResources::Ocean_Pass(ID3D11DeviceContext * context, unsigned which,
+ OceanSurface * targets, ID3D11ShaderResourceView * const * sources, unsigned count, const float parameters[8])
+{
+ // The sources of this pass were the last one's targets: they are let go as targets before they
+ // are bound to be read, or the runtime unbinds them as textures and the pass reads zero.
+ ID3D11ShaderResourceView * const none[Spectrum::Maps + 1] = {};
+ context->PSSetShaderResources(0, Spectrum::Maps + 1, none);
+ ID3D11RenderTargetView * views[Spectrum::Maps];
+ for (unsigned map = 0; map < Spectrum::Maps; ++map) {
+ views[map] = targets[map].Target;
+ }
+ context->OMSetRenderTargets(Spectrum::Maps, views, NULL);
+ context->PSSetShaderResources(0, count, sources);
+ upload(context, OceanConstants, parameters, 8 * sizeof(float));
+ context->PSSetShader(OceanPixels[which], NULL, 0);
+ context->Draw(3, 0);
+}
+
+bool DX11BackendClass::WaterResources::Prepare_Ocean(DX11BackendClass & backend, ID3D11Device * device,
+ ID3D11DeviceContext * context, float time)
+{
+ const unsigned maps = Spectrum::Maps;
+ if (!(time == time) || OceanFailed) {
+ return false;
+ }
+ if (OceanReady && time == OceanTime) {
+ return true;
+ }
+ if (OceanVertex == NULL && !Make_Ocean(backend, device)) {
+ return false;
+ }
+
+ ID3D11RenderTargetView * saved_target = NULL;
+ ID3D11DepthStencilView * saved_depth = NULL;
+ context->OMGetRenderTargets(1, &saved_target, &saved_depth);
+ D3D11_VIEWPORT saved_viewport;
+ UINT viewports = 1;
+ context->RSGetViewports(&viewports, &saved_viewport);
+
+ context->IASetInputLayout(NULL);
+ context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ context->VSSetShader(OceanVertex, NULL, 0);
+ context->RSSetState(NoCull);
+ context->OMSetBlendState(NULL, NULL, 0xffffffff);
+ context->OMSetDepthStencilState(NULL, 0);
+ ID3D11SamplerState * points[maps + 1];
+ for (unsigned slot = 0; slot <= maps; ++slot) {
+ points[slot] = OceanPoint;
+ }
+ context->PSSetSamplers(0, maps + 1, points);
+ context->PSSetConstantBuffers(0, 1, &OceanConstants);
+ const float side = float(Spectrum::Resolution);
+ const D3D11_VIEWPORT field = { 0.0f, 0.0f, side, side, 0.0f, 1.0f };
+ context->RSSetViewports(1, &field);
+
+ float parameters[8] = { side, time, 0.0f, 0.0f, Spectrum::Sizes[0], Spectrum::Sizes[1], Spectrum::Sizes[2], 0.0f };
+ ID3D11ShaderResourceView * sources[maps + 1];
+ for (unsigned cascade = 0; cascade < Spectrum::Cascades; ++cascade) {
+ sources[cascade] = Initial[cascade].View;
+ }
+ Ocean_Pass(context, 0, Ping[0], sources, Spectrum::Cascades, parameters);
+ unsigned ping = 0;
+ for (unsigned axis = 0; axis < 2; ++axis) {
+ for (unsigned phase = 0; phase < Spectrum::Phases; ++phase) {
+ for (unsigned map = 0; map < maps; ++map) {
+ sources[map] = Ping[ping][map].View;
+ }
+ sources[maps] = Twiddles.View;
+ parameters[2] = float(phase);
+ parameters[3] = float(axis);
+ Ocean_Pass(context, 1, Ping[1 - ping], sources, maps + 1, parameters);
+ ping = 1 - ping;
+ }
+ }
+ for (unsigned map = 0; map < maps; ++map) {
+ sources[map] = Ping[ping][map].View;
+ }
+ Ocean_Pass(context, 2, Fields, sources, maps, parameters);
+
+ ID3D11ShaderResourceView * const none[maps + 1] = {};
+ context->PSSetShaderResources(0, maps + 1, none);
+ context->OMSetRenderTargets(1, &saved_target, saved_depth);
+ for (unsigned map = 0; map < maps; ++map) {
+ context->GenerateMips(Fields[map].View);
+ }
+ if (viewports == 1) {
+ context->RSSetViewports(1, &saved_viewport);
+ }
+ drop(saved_target);
+ drop(saved_depth);
+ backend.Forget_Bindings();
+
+ OceanTime = time;
+ OceanReady = true;
+ ++OceanUpdates;
+ return true;
+}
+
+/** The scene the water refracts, copied at the first water draw of a frame into a target, and the
+ depth with it when the draw tests against the scene's own: later water draws of the frame see
+ the bed and not the water already laid over it, as on the SDL device. */
+void DX11BackendClass::WaterResources::Take_Scene(DX11DeviceClass & device, ID3D11Resource * source,
+ ID3D11RenderTargetView * view, bool scene_depth)
+{
+ if (!ColourStale && source == ColourSource) {
+ HaveColour = ColourView != NULL;
+ HaveDepth = scene_depth && DepthView != NULL && DepthSource == source;
+ return;
+ }
+ ID3D11Device * const d3d = device.Get_Device();
+ ID3D11DeviceContext * const context = device.Get_Context();
+ D3D11_TEXTURE2D_DESC description;
+ static_cast<ID3D11Texture2D *>(source)->GetDesc(&description);
+ if (Colour != NULL) {
+ D3D11_TEXTURE2D_DESC held;
+ Colour->GetDesc(&held);
+ if (held.Width != description.Width || held.Height != description.Height || held.Format != description.Format) {
+ drop(ColourView);
+ drop(Colour);
+ }
+ }
+ if (Colour == NULL && description.SampleDesc.Count == 1) {
+ D3D11_RENDER_TARGET_VIEW_DESC written;
+ view->GetDesc(&written);
+ D3D11_TEXTURE2D_DESC copy = description;
+ copy.MipLevels = 1;
+ copy.BindFlags = D3D11_BIND_SHADER_RESOURCE;
+ copy.MiscFlags = 0;
+ copy.Usage = D3D11_USAGE_DEFAULT;
+ copy.CPUAccessFlags = 0;
+ D3D11_SHADER_RESOURCE_VIEW_DESC read;
+ memset(&read, 0, sizeof(read));
+ read.Format = written.Format;
+ read.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
+ read.Texture2D.MipLevels = 1;
+ if (FAILED(d3d->CreateTexture2D(&copy, NULL, &Colour))
+ || FAILED(d3d->CreateShaderResourceView(Colour, &read, &ColourView))) {
+ drop(ColourView);
+ drop(Colour);
+ }
+ }
+ if (Colour != NULL && description.MipLevels == 1) {
+ context->CopyResource(Colour, source);
+ }
+ else if (Colour != NULL) {
+ context->CopySubresourceRegion(Colour, 0, 0, 0, 0, source, 0, NULL);
+ }
+ TargetWidth = description.Width;
+ TargetHeight = description.Height;
+ ColourSource = source;
+ ColourStale = false;
+ HaveColour = ColourView != NULL;
+
+ DepthSource = NULL;
+ ID3D11ShaderResourceView * const depth_view = device.Get_Depth_Texture();
+ if (scene_depth && depth_view != NULL) {
+ ID3D11Resource * depth = NULL;
+ depth_view->GetResource(&depth);
+ D3D11_TEXTURE2D_DESC depth_description;
+ static_cast<ID3D11Texture2D *>(depth)->GetDesc(&depth_description);
+ if (Depth != NULL) {
+ D3D11_TEXTURE2D_DESC held;
+ Depth->GetDesc(&held);
+ if (held.Width != depth_description.Width || held.Height != depth_description.Height
+ || held.Format != depth_description.Format) {
+ drop(DepthView);
+ drop(Depth);
+ }
+ }
+ if (Depth == NULL) {
+ D3D11_TEXTURE2D_DESC copy = depth_description;
+ copy.BindFlags = D3D11_BIND_SHADER_RESOURCE;
+ copy.MiscFlags = 0;
+ copy.Usage = D3D11_USAGE_DEFAULT;
+ copy.CPUAccessFlags = 0;
+ D3D11_SHADER_RESOURCE_VIEW_DESC read;
+ depth_view->GetDesc(&read);
+ if (FAILED(d3d->CreateTexture2D(&copy, NULL, &Depth))
+ || FAILED(d3d->CreateShaderResourceView(Depth, &read, &DepthView))) {
+ drop(DepthView);
+ drop(Depth);
+ }
+ }
+ if (Depth != NULL) {
+ context->CopyResource(Depth, depth);
+ DepthSource = source;
+ }
+ depth->Release();
+ }
+ HaveDepth = DepthSource != NULL;
+}
+
+void DX11BackendClass::WaterResources::Release()
+{
+ drop(White);
+ drop(WhiteTexture);
+ drop(ClampLinear);
+ drop(ClampPoint);
+ drop(WrapLinear);
+ drop(Constants);
+ for (ID3D11Buffer *& buffer : Packets) {
+ drop(buffer);
+ }
+ PacketsHeld = false;
+ drop(ColourView);
+ drop(Colour);
+ drop(DepthView);
+ drop(Depth);
+ ColourSource = NULL;
+ DepthSource = NULL;
+ ColourStale = true;
+ for (OceanSurface & surface : Initial) {
+ drop(surface);
+ }
+ for (unsigned set = 0; set < 2; ++set) {
+ for (OceanSurface & surface : Ping[set]) {
+ drop(surface);
+ }
+ }
+ for (OceanSurface & surface : Fields) {
+ drop(surface);
+ }
+ drop(Twiddles);
+ drop(OceanVertex);
+ for (ID3D11PixelShader *& program : OceanPixels) {
+ drop(program);
+ }
+ drop(OceanConstants);
+ drop(OceanPoint);
+ drop(OceanLinear);
+ drop(NoCull);
+ for (std::map<std::string, ID3D11VertexShader *>::iterator entry = VertexPrograms.begin();
+ entry != VertexPrograms.end(); ++entry) {
+ drop(entry->second);
+ }
+ VertexPrograms.clear();
+ // A new device may take what this one refused.
+ Made = false;
+ Refused = false;
+ OceanFailed = false;
+ OceanReady = false;
+ OceanStatus = "not asked for";
+ DrawVertex = NULL;
+ Fft = false;
+ memset(Textures, 0, sizeof(Textures));
+}
+
+DX11BackendClass::WaterResources * DX11BackendClass::Create_Water()
+{
+ return new WaterResources;
+}
+
+void DX11BackendClass::Destroy_Water(WaterResources * water)
+{
+ delete water;
+}
+
+void DX11BackendClass::Set_Water_Constants(unsigned first_register, const float * values, unsigned count)
+{
+ memcpy(Water->Registers[first_register], values, sizeof(float) * 4 * count);
+}
+
+void DX11BackendClass::Set_Water_Texture(unsigned stage, ID3D11ShaderResourceView * texture)
+{
+ if (stage < DX11_WATER_STAGES) {
+ Water->Textures[stage] = texture;
+ }
+}
+
+void DX11BackendClass::Water_Scene_Changed(ID3D11Resource * target)
+{
+ // A filter target cleared mid-frame leaves the scene's copy as it was, as on the SDL device
+ // (Invalidate_Water_Snapshots); clearing the copied target itself makes it old.
+ // ponytail: one copy, keyed by its target; a frame drawing water into A, B, then A again takes A
+ // a second time with the first water in it, where SDL keeps a copy per target.
+ if (target == NULL || target == Water->ColourSource) {
+ Water->ColourStale = true;
+ }
+}
+
+void DX11BackendClass::Release_Water()
+{
+ Water->Release();
+}
+
+std::string DX11BackendClass::Water_Report() const
+{
+ char line[256];
+ snprintf(line, sizeof(line), "%llu Modern draws, %llu displaced by the ocean (%llu field updates); ocean %s",
+ Water->Draws, Water->DisplacedDraws, Water->OceanUpdates, Water->OceanStatus.c_str());
+ return line;
+}
+
+bool DX11BackendClass::Prepare_Water()
+{
+ if (!Water->Make(Device->Get_Device())) {
+ return false;
+ }
+ WaterResources & water = *Water;
+ ++water.Draws;
+ water.Fft = false;
+ water.DrawVertex = NULL;
+ const float (*registers)[4] = water.Registers;
+ // Open sea with its optical context and height correction is displaced on the GPU. A sampled
+ // ocean that cannot be made leaves the analytic CPU surface the patch was built with.
+ if (PixelProgram == ENGINE_SHADER_WATER_TRAPEZOID && VertexProgram == ENGINE_SHADER_NONE
+ && RenderStates.Get_Render_State(D3DRS_LIGHTING) == FALSE
+ && registers[6][2] > 0.5f && registers[6][3] > 0.5f
+ && water.Prepare_Ocean(*this, Device->Get_Device(), Device->Get_Context(),
+ registers[1][0] * WaterFftSampling::TimeScale)) {
+ VertexPipelineDescription description;
+ Build_Vertex_Description(description);
+ const std::string key = VertexShader_Key(description);
+ std::map<std::string, ID3D11VertexShader *>::iterator found = water.VertexPrograms.find(key);
+ if (found == water.VertexPrograms.end()) {
+ ID3D11VertexShader * program = NULL;
+ std::string hlsl;
+ std::vector<unsigned char> code;
+ if (DX11Water_Ocean_Vertex_Program(description, hlsl)
+ && Compile_Program(hlsl, "water vertex", "vs_5_0", code)) {
+ Device->Get_Device()->CreateVertexShader(&code[0], code.size(), NULL, &program);
+ }
+ found = water.VertexPrograms.insert(std::make_pair(key, program)).first;
+ }
+ water.DrawVertex = found->second;
+ water.Fft = water.DrawVertex != NULL;
+ }
+
+ ID3D11RenderTargetView * const view = (CurrentTarget != NULL) ? CurrentTarget : Device->Get_Scene_View();
+ ID3D11Resource * source = CurrentTargetResource;
+ if (CurrentTarget == NULL) {
+ view->GetResource(&source);
+ source->Release(); // the device holds the scene target for as long as it lives
+ }
+ water.Take_Scene(*Device, source, view, CurrentTarget == NULL || CurrentDepth == Device->Get_Depth_Stencil_View());
+ return true;
+}
+
+void DX11BackendClass::Bind_Water()
+{
+ WaterResources & water = *Water;
+ ID3D11DeviceContext * const context = Device->Get_Context();
+ const float (*registers)[4] = water.Registers;
+
+ ID3D11ShaderResourceView * const history = water.Textures[14];
+ D3D11_TEXTURE2D_DESC atlas;
+ const bool foam = history != NULL && WaterConstants::FoamHistoryRegisters(registers)
+ && view_texture(history, atlas) && (atlas.BindFlags & D3D11_BIND_RENDER_TARGET) == 0
+ && WaterConstants::FoamHistoryAtlas(registers, atlas.Width, atlas.Height);
+
+ const WaterConstants::Camera camera = { View, Projection, float(ViewportX), float(ViewportY),
+ float(ViewportWidth), float(ViewportHeight), 0.0f, 1.0f };
+ WaterConstants::Block block;
+ WaterConstants::Fill(registers, camera, foam, block);
+ RenderStates.Get_Texture_Factor(block.TextureFactor);
+ const DWORD fog_colour = RenderStates.Get_Render_State(D3DRS_FOGCOLOR);
+ block.FogColour[0] = float((fog_colour >> 16) & 0xff) / 255.0f;
+ block.FogColour[1] = float((fog_colour >> 8) & 0xff) / 255.0f;
+ block.FogColour[2] = float(fog_colour & 0xff) / 255.0f;
+ block.FogColour[3] = float((fog_colour >> 24) & 0xff) / 255.0f;
+ block.AlphaReference[0] = float(RenderStates.Get_Render_State(D3DRS_ALPHAREF) & 0xff);
+ if (water.Fft && Textures[2] == NULL) {
+ block.TerrainParameters[3] = 0.0f;
+ }
+ block.SceneParameters[0] = water.HaveColour ? 1.0f : 0.0f;
+ block.SceneParameters[1] = 1.0f / float(water.TargetWidth);
+ block.SceneParameters[2] = 1.0f / float(water.TargetHeight);
+ block.SceneParameters[3] = water.HaveDepth ? 1.0f : 0.0f;
+ block.FftParameters[0] = water.Fft ? 1.0f : 0.0f;
+ WaterConstants::VisualBlock visual;
+ WaterConstants::FillVisual(block, registers, visual);
+ upload(context, water.Constants, &visual, sizeof(visual));
+ const float (*packets)[4] = registers + WaterHullVisualLayout::PacketRegister;
+ if (!water.PacketsHeld || memcmp(water.HeldPackets, packets, sizeof(water.HeldPackets)) != 0) {
+ bool uploaded = true;
+ for (unsigned index = 0; index < WaterHullVisualLayout::BlockCount; ++index) {
+ uploaded = upload(context, water.Packets[index], packets + WaterHullVisualLayout::BlockOffset(index),
+ WaterHullVisualLayout::BlockRegisters(index) * 16) && uploaded;
+ }
+ memcpy(water.HeldPackets, packets, sizeof(water.HeldPackets));
+ water.PacketsHeld = uploaded;
+ }
+ ID3D11Buffer * const blocks[1 + WaterHullVisualLayout::BlockCount] = {
+ water.Constants, water.Packets[0], water.Packets[1], water.Packets[2] };
+ context->PSSetConstantBuffers(0, 1 + WaterHullVisualLayout::BlockCount, blocks);
+
+ // A stage with nothing bound reads white, as on the SDL device, where Direct3D 11 reads zero.
+ ID3D11ShaderResourceView * views[DX11_WATER_STAGES];
+ ID3D11SamplerState * samplers[DX11_WATER_STAGES];
+ for (unsigned stage = 0; stage < DX11_WATER_STAGES; ++stage) {
+ const bool own = stage < DX11_BACKEND_TEXTURE_STAGES;
+ ID3D11ShaderResourceView * const bound = own ? Bound.Textures[stage] : water.Textures[stage];
+ views[stage] = bound != NULL ? bound : water.White;
+ samplers[stage] = own ? Bound.Samplers[stage] : water.ClampLinear;
+ }
+ views[5] = water.HaveColour ? water.ColourView : water.White;
+ views[6] = water.HaveDepth ? water.DepthView : water.White;
+ views[14] = foam ? history : water.White;
+ for (unsigned map = 0; map < Spectrum::Maps; ++map) {
+ views[8 + map] = water.Fft ? water.Fields[map].View : water.White;
+ samplers[8 + map] = water.Fft ? water.OceanLinear : water.ClampLinear;
+ }
+ // The terrain's heights, the scene's depth and the bed: the sampling the SDL device fixes for
+ // them whatever the engine's stage states say.
+ samplers[2] = water.ClampLinear;
+ samplers[6] = water.ClampPoint;
+ samplers[7] = water.WrapLinear;
+ context->PSSetShaderResources(0, DX11_WATER_STAGES, views);
+ context->PSSetSamplers(0, DX11_WATER_STAGES, samplers);
+
+ if (water.Fft) {
+ ++water.DisplacedDraws;
+ context->VSSetShader(water.DrawVertex, NULL, 0);
+ context->VSSetConstantBuffers(1, 1, &water.Constants);
+ ID3D11ShaderResourceView * const vertex_views[4] = { water.Fields[0].View, water.Fields[2].View,
+ water.Fields[4].View, Textures[2] != NULL ? Textures[2] : water.White };
+ ID3D11SamplerState * const vertex_samplers[4] = { water.OceanLinear, water.OceanLinear,
+ water.OceanLinear, water.ClampLinear };
+ context->VSSetShaderResources(0, 4, vertex_views);
+ context->VSSetSamplers(0, 4, vertex_samplers);
+ }
+
+ // The shader refracts and attenuates the bed itself; the Classic feather through destination
+ // alpha would blend the unattenuated bed in a second time.
+ if (PixelProgram == ENGINE_SHADER_WATER_TRAPEZOID
+ && RenderStates.Get_Render_State(D3DRS_ALPHABLENDENABLE) != FALSE
+ && RenderStates.Get_Render_State(D3DRS_SRCBLEND) == D3DBLEND_DESTALPHA
+ && RenderStates.Get_Render_State(D3DRS_DESTBLEND) == D3DBLEND_INVDESTALPHA) {
+ D3D11_BLEND_DESC description;
+ RenderStates.Build_Blend_Description(description);
+ description.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
+ description.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
+ BlendStateMap::const_iterator existing = BlendStates.find(description);
+ ID3D11BlendState * state = (existing != BlendStates.end()) ? existing->second : NULL;
+ if (state == NULL && SUCCEEDED(Device->Get_Device()->CreateBlendState(&description, &state))) {
+ BlendStates[description] = state;
+ }
+ if (state != NULL) {
+ context->OMSetBlendState(state, NULL, 0xffffffff);
+ }
+ }
+}
+
+void DX11BackendClass::Unbind_Water()
+{
+ ID3D11DeviceContext * const context = Device->Get_Context();
+ ID3D11ShaderResourceView * const none[DX11_WATER_STAGES] = {};
+ // Nothing the water read stays bound: the ocean's maps are drawn into again next frame.
+ context->PSSetShaderResources(DX11_BACKEND_TEXTURE_STAGES, DX11_WATER_STAGES - DX11_BACKEND_TEXTURE_STAGES,
+ none + DX11_BACKEND_TEXTURE_STAGES);
+ if (Water->Fft) {
+ context->VSSetShaderResources(0, 4, none);
+ }
+ Forget_Bindings();
+}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11water.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11water.h
new file mode 100644
index 000000000..9e4e3afd5
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11water.h
@@ -0,0 +1,34 @@
+/*
+** The Modern water on Direct3D 11: the text its programs are made from. The draw itself is
+** DX11BackendClass's (dx11water.cpp holds that half of the class), because a water draw is one of
+** the backend's draws with fifteen stages, four constant blocks and, over open sea, a displaced
+** vertex half and the GPU ocean bound beside what the generators give it.
+**
+** Distributed under the repository's GPL-3.0 terms; see LICENSE.md.
+*/
+
+#ifndef DX11WATER_H
+#define DX11WATER_H
+
+#include "ffvertex.h"
+#include "Platform/WaterHullVisualLayout.h"
+
+#include <string>
+
+// The registers W3DWater sets for a Modern draw, c0 to the last hull packet.
+const unsigned DX11_WATER_REGISTERS = WaterHullVisualLayout::PixelRegisterCount;
+// The stages the Modern text samples, t0 to t14; the backend's own four are the first of them.
+const unsigned DX11_WATER_STAGES = 15;
+// The ocean field's passes: the spectrum at the time asked for, one butterfly, the final sign.
+const unsigned DX11_WATER_OCEAN_PASSES = 3;
+
+// The fixed-function vertex program for this state, wrapped so the ocean's maps displace it
+// (WaterFftSampling::WrapVertex). False for a lit description, which the water never draws with.
+bool DX11Water_Ocean_Vertex_Program(const VertexPipelineDescription & description, std::string & hlsl);
+
+// One of the ocean's pixel passes (WaterFftSpectrum.h), with the SDL GPU register spaces taken out
+// for shader model 5, and the full-screen triangle every pass draws.
+std::string DX11Water_Ocean_Pass_Program(unsigned pass);
+const char * DX11Water_Ocean_Pass_Vertex_Program();
+
+#endif // DX11WATER_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
index e53beb1e8..207640e4a 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
@@ -516,6 +516,11 @@ public:
static void Set_DX8_Texture_Stage_State(unsigned stage, D3DTEXTURESTAGESTATETYPE state, unsigned value);
static void Set_DX8_Texture_Stage_State(unsigned stage, D3DSAMPLERSTATETYPE state, unsigned value);
static void Set_DX8_Texture(unsigned int stage, IDirect3DBaseTexture9* texture);
+ // What the wrapper last set, which a deferred Direct3D 9 device (Defer_D3D9_State) may not hold yet.
+ // False while Invalidate_Cached_Render_States has left the state unknown.
+ static bool Get_DX8_Texture_Stage_State(unsigned stage, D3DTEXTURESTAGESTATETYPE state, unsigned & value)
+ { value = TextureStageStates[stage][state]; return value != 0x12345678; }
+ static IDirect3DBaseTexture9* Get_DX8_Texture(unsigned stage) { return Textures[stage]; }
static void Set_Light_Environment(LightEnvironmentClass* light_env);
static LightEnvironmentClass* Get_Light_Environment() { return Light_Environment; }
static void Set_Fog(bool enable, const Vector3 &color, float start, float end);
@@ -1426,6 +1431,7 @@ WWINLINE void DX8Wrapper::Set_DX8_Texture(unsigned int stage, IDirect3DBaseTextu
{
if (stage >= MAX_TEXTURE_STAGES)
{ DX8CALL(SetTexture(stage, texture));
+ Direct3D11_Mirror_Texture(stage, texture);
return;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
index 9da9b4a92..720e99d20 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
@@ -678,8 +678,9 @@ WaterRefractionSample waterRefractedScene(float2 originalPixel, float2 offset,
// discontinuously changes absorption and also contaminates neighbouring derivatives.
bool nearestValid = waterRefractionHit(nearestTexel, world, opticalWorld, view, nearestHit);
[branch] if (nearestValid) {
- float4 validWeights = float4(0, 0, 0, 0);
- validWeights[nearest] = weights[nearest];
+ // A mask rather than validWeights[nearest]: FXC cannot write a vector at a runtime index,
+ // and DXC's HLSL 2021 takes no vector ternary.
+ float4 validWeights = weights * float4(int4(0, 1, 2, 3) == nearest);
bool completeFootprint = true;
[unroll] for (int i = 0; i < 4; ++i) {
[branch] if (i != nearest && weights[i] > 0.0) {
@@ -1332,9 +1333,10 @@ bool EngineShader_Pixel_Program(EngineShaderProgram program,
hlsl.clear();
return false;
}
+ const bool modern_water = EngineShader_Is_Modern_Water(program);
if (target == COMBINER_SHADER_TARGET_SDL3_GPU) {
#if defined(__linux__)
- if (program == ENGINE_SHADER_WATER_TRAPEZOID || program == ENGINE_SHADER_WATER_RIVER) {
+ if (modern_water) {
write_modern_water(hlsl, program == ENGINE_SHADER_WATER_RIVER);
if (!CombinerShader_Append_Pixel_Pipeline(pipeline, hlsl)) return false;
hlsl += " return current;\n}\n";
@@ -1344,6 +1346,14 @@ bool EngineShader_Pixel_Program(EngineShaderProgram program,
return write_engine_pixel_program(program, pipeline, hlsl, EngineShader_Paints_Ground(program))
&& SDL3_Shader_Retarget(hlsl, false);
}
+ // Direct3D 11 draws the Modern water from the same text, bound by dx11water.cpp. The Classic
+ // style registers the classic names, whose transcription is the one this target always wrote.
+ if (modern_water) {
+ write_modern_water(hlsl, program == ENGINE_SHADER_WATER_RIVER);
+ if (!CombinerShader_Append_Pixel_Pipeline(pipeline, hlsl)) return false;
+ hlsl += " return current;\n}\n";
+ return true;
+ }
return write_engine_pixel_program(program, pipeline, hlsl, true);
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h
index 89acc26d4..54755db02 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h
@@ -99,6 +99,13 @@ bool EngineShader_Pixel_Program(EngineShaderProgram program,
// the trees are not among them: both have shadows of their own.
bool EngineShader_Paints_Ground(EngineShaderProgram program);
+// The two programs the Modern water style draws with: the plain names, which W3DWater registers
+// only under that style. Their text reads the water's own constant block and fifteen stages.
+inline bool EngineShader_Is_Modern_Water(EngineShaderProgram program)
+{
+ return program == ENGINE_SHADER_WATER_TRAPEZOID || program == ENGINE_SHADER_WATER_RIVER;
+}
+
// 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/Tests/test_dx11backend.cpp b/GeneralsMD/Code/Tests/test_dx11backend.cpp
index 0886673bc..5beb77173 100644
--- a/GeneralsMD/Code/Tests/test_dx11backend.cpp
+++ b/GeneralsMD/Code/Tests/test_dx11backend.cpp
@@ -29,8 +29,11 @@
#include "dx11backend.h"
#include "dx11resource.h"
+#include "dx11water.h"
#include "Platform/HazardCloudCore.h"
+#include "Platform/WaterConstants.h"
+#include <math.h>
#include <stdio.h>
#include <string.h>
#include <vector>
@@ -1188,3 +1191,132 @@ TEST(dx11backend_the_hazard_cloud_programs_compile_at_shader_model_5)
}
backend.Shutdown();
}
+
+// The fixed-function vertex state the modern ocean patch draws with: an unlit XYZNDUV2 vertex,
+// four stages (the base, the mirror's projection, the camera space noise and the shroud), fog.
+static VertexPipelineDescription water_vertex_description()
+{
+ VertexPipelineDescription description;
+ memset(&description, 0, sizeof(description));
+ description.FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX2;
+ description.ColourVertexEnabled = true;
+ description.DiffuseMaterialSource = D3DMCS_COLOR1;
+ description.StageCount = 4;
+ description.Stages[1].TextureCoordinateIndex = 1;
+ description.Stages[2].TextureCoordinateIndex = D3DTSS_TCI_CAMERASPACEPOSITION;
+ description.Stages[2].TextureTransformFlags = D3DTTFF_COUNT2;
+ description.Stages[3].TextureCoordinateIndex = D3DTSS_TCI_CAMERASPACEPOSITION;
+ description.Stages[3].TextureTransformFlags = D3DTTFF_COUNT2;
+ description.FogEnabled = true;
+ description.FogVertexMode = D3DFOG_LINEAR;
+ return description;
+}
+
+// The Modern water's text is the SDL GPU backend's too. Its two surfaces, the displaced ocean's
+// vertex half and the FFT passes all have to come through the compiler at shader model 5 (the
+// surfaces write a dynamically indexed array, which shader model 4 refuses) and be taken by the
+// device, or the water draws nothing with Modern selected.
+TEST(dx11backend_the_modern_water_programs_compile_at_shader_model_5)
+{
+ DX11DeviceClass device;
+ CHECK(device.Create_Offscreen());
+ DX11BackendClass backend;
+ CHECK(backend.Initialise(&device));
+
+ PixelPipelineDescription pipeline;
+ memset(&pipeline, 0, sizeof(pipeline));
+ pipeline.FogEnabled = true;
+ struct Program { std::string source; const char * profile; const char * name; };
+ std::vector<Program> programs;
+ for (const EngineShaderProgram water : { ENGINE_SHADER_WATER_TRAPEZOID, ENGINE_SHADER_WATER_RIVER }) {
+ Program program = { std::string(), "ps_5_0", EngineShader_Name(water) };
+ CHECK(EngineShader_Pixel_Program(water, pipeline, program.source));
+ programs.push_back(program);
+ }
+ Program ocean = { std::string(), "vs_5_0", "water vertex" };
+ CHECK(DX11Water_Ocean_Vertex_Program(water_vertex_description(), ocean.source));
+ programs.push_back(ocean);
+ for (unsigned pass = 0; pass < DX11_WATER_OCEAN_PASSES; ++pass) {
+ const Program fft = { DX11Water_Ocean_Pass_Program(pass), "ps_5_0", "ocean pass" };
+ programs.push_back(fft);
+ }
+ const Program fullscreen = { DX11Water_Ocean_Pass_Vertex_Program(), "vs_5_0", "ocean vertex" };
+ programs.push_back(fullscreen);
+
+ for (const Program & program : programs) {
+ std::vector<unsigned char> code;
+ const bool vertex = program.profile[0] == 'v';
+ const unsigned started = GetTickCount();
+ const bool compiled = backend.Compile_Program(program.source, program.name, program.profile, code);
+ printf(" %s: %s in %u ms\n", program.name, compiled ? "compiled" : "refused",
+ GetTickCount() - started);
+ if (!compiled) {
+ printf(" %s\n", backend.First_Compiler_Error());
+ }
+ CHECK(compiled);
+ if (!compiled) {
+ continue;
+ }
+ ID3D11DeviceChild * made = NULL;
+ const HRESULT result = vertex
+ ? device.Get_Device()->CreateVertexShader(&code[0], code.size(), NULL, (ID3D11VertexShader **)&made)
+ : device.Get_Device()->CreatePixelShader(&code[0], code.size(), NULL, (ID3D11PixelShader **)&made);
+ CHECK(SUCCEEDED(result));
+ if (made != NULL) {
+ made->Release();
+ }
+ }
+ backend.Shutdown();
+}
+
+// The block the Modern water's two stages read, built from W3DWater's registers and the draw's
+// camera. A camera standing at (10, 20, 30) has to come back out of the inverted view, the
+// registers land in their fields, a river draw drops the hulls, and the foam atlas is read only
+// when stage 14 holds one.
+TEST(dx11backend_the_modern_water_constants_are_built_from_the_registers)
+{
+ static float registers[DX11_WATER_REGISTERS][4];
+ memset(registers, 0, sizeof(registers));
+ const float time = 12.5f;
+ const float hulls = 3.0f;
+ registers[1][0] = time;
+ registers[6][2] = 1.0f;
+ registers[7][0] = hulls;
+ registers[88][0] = 100.0f;
+ registers[88][2] = 0.01f;
+ registers[88][3] = 0.01f;
+ registers[89][0] = 1.0f;
+ registers[89][2] = 4.0f;
+ registers[WaterHullVisualLayout::MetadataRegister][3] = 1.0f;
+
+ const float x = 10.0f, y = 20.0f, z = 30.0f;
+ const float view[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -x, -y, -z, 1 };
+ const float projection[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, -1, 0 };
+ const WaterConstants::Camera camera = { view, projection, 0.0f, 0.0f, 800.0f, 600.0f, 0.0f, 1.0f };
+
+ CHECK(WaterConstants::FoamHistoryRegisters(registers));
+ CHECK(WaterConstants::FoamHistoryAtlas(registers, 64, 64));
+ WaterConstants::Block block;
+ WaterConstants::Fill(registers, camera, true, block);
+ CHECK(fabsf(block.CameraPosition[0] - x) < 0.001f);
+ CHECK(fabsf(block.CameraPosition[1] - y) < 0.001f);
+ CHECK(fabsf(block.CameraPosition[2] - z) < 0.001f);
+ CHECK(block.WaterParameters[0] == time);
+ CHECK(block.OpticalParameters[2] == 1.0f);
+ CHECK(block.HullParameters[0] == hulls);
+ CHECK(block.FoamHistoryArea[0] == 100.0f);
+ CHECK(block.Viewport[0] == 0.5f && block.Viewport[2] == 800.0f);
+ WaterConstants::VisualBlock visual;
+ WaterConstants::FillVisual(block, registers, visual);
+ CHECK(visual.VisualHullMeta[0][3] == 1.0f);
+
+ WaterConstants::Fill(registers, camera, false, block);
+ CHECK(block.FoamHistoryArea[0] == 0.0f);
+
+ registers[1][1] = 1.0f;
+ CHECK(!WaterConstants::FoamHistoryRegisters(registers));
+ WaterConstants::Fill(registers, camera, false, block);
+ CHECK(block.HullParameters[0] == 0.0f);
+ WaterConstants::FillVisual(block, registers, visual);
+ CHECK(visual.VisualHullMeta[0][3] == 0.0f);
+}
diff --git a/GeneralsMD/Code/Tests/test_engineshader.cpp b/GeneralsMD/Code/Tests/test_engineshader.cpp
index 1bd8a0735..62b70bf68 100644
--- a/GeneralsMD/Code/Tests/test_engineshader.cpp
+++ b/GeneralsMD/Code/Tests/test_engineshader.cpp
@@ -122,7 +122,7 @@ TEST(engineshader_keeps_the_two_halves_apart)
TEST(engineshader_adds_the_sparkles_and_then_shrouds_the_trapezoid_water)
{
std::string hlsl;
- CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID, plain_pipeline(), hlsl));
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_CLASSIC_TRAPEZOID, plain_pipeline(), hlsl));
CHECK(contains(hlsl, "float4 current = saturate(input.Diffuse * texel0);"));
CHECK(contains(hlsl, "current.rgb = saturate(texel1.rgb * texel2.rgb + current.rgb);"));
CHECK(contains(hlsl, "current.rgb = saturate(current.rgb * texel3.rgb);"));
@@ -133,7 +133,7 @@ TEST(engineshader_adds_the_sparkles_and_then_shrouds_the_trapezoid_water)
TEST(engineshader_darkens_only_the_river_waters_sparkles_by_the_vertex_alpha)
{
std::string hlsl;
- CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_RIVER, plain_pipeline(), hlsl));
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_CLASSIC_RIVER, plain_pipeline(), hlsl));
CHECK(contains(hlsl, "current.rgb = saturate(input.Diffuse.rgb * texel0.rgb);"));
CHECK(contains(hlsl, "current.a = saturate(texel0.a * texel3.a);"));
CHECK(contains(hlsl, "sparkle = saturate(sparkle * input.Diffuse.a);"));
@@ -173,10 +173,28 @@ TEST(engineshader_writes_the_alpha_test_and_the_fog_into_a_water_program)
pipeline.AlphaTestEnabled = true;
pipeline.AlphaFunction = D3DCMP_GREATEREQUAL;
- std::string hlsl;
- CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID, pipeline, hlsl));
- CHECK(contains(hlsl, "lerp(FogColour.rgb, current.rgb, saturate(input.Fog))"));
- CHECK(contains(hlsl, "AlphaReference"));
+ const EngineShaderProgram programs[] = { ENGINE_SHADER_WATER_CLASSIC_TRAPEZOID,
+ ENGINE_SHADER_WATER_TRAPEZOID, ENGINE_SHADER_WATER_RIVER };
+ for (const EngineShaderProgram program : programs) {
+ std::string hlsl;
+ CHECK(EngineShader_Pixel_Program(program, pipeline, hlsl));
+ CHECK(contains(hlsl, "lerp(FogColour.rgb, current.rgb, saturate(input.Fog))"));
+ CHECK(contains(hlsl, "AlphaReference"));
+ }
+}
+
+// The Modern names are the Modern text on Direct3D 11 as well, and the Classic names keep the
+// transcription that target always wrote, so a Classic frame compiles exactly what it did.
+TEST(engineshader_writes_modern_water_only_for_the_modern_names)
+{
+ std::string modern, classic;
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID, plain_pipeline(), modern));
+ CHECK(contains(modern, "Texture14 : register(t14)"));
+ CHECK(contains(modern, "cbuffer WaterVisualBlock2 : register(b3)"));
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_CLASSIC_TRAPEZOID, plain_pipeline(), classic));
+ CHECK(!contains(classic, "Texture4"));
+ CHECK(EngineShader_Is_Modern_Water(ENGINE_SHADER_WATER_RIVER));
+ CHECK(!EngineShader_Is_Modern_Water(ENGINE_SHADER_WATER_CLASSIC_RIVER));
}
// lrp r0, v0.w, t1, t0 is t0 + v0.w * (t1 - t0), so the vertex alpha is the weight of the second
@@ -241,7 +259,7 @@ TEST(engineshader_leaves_the_roads_vertex_colour_until_last)
TEST(engineshader_declares_the_four_stages_the_water_samples)
{
std::string hlsl;
- CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_RIVER, plain_pipeline(), hlsl));
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_CLASSIC_RIVER, plain_pipeline(), hlsl));
for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {
char sampler[64];
snprintf(sampler, sizeof(sampler), "Texture%u.Sample(Sampler%u, input.TexCoord%u)",
@@ -379,13 +397,14 @@ TEST(engineshader_writes_programs_the_compiler_accepts)
pipeline.AlphaFunction = D3DCMP_GREATER;
std::string trapezoid;
- CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID, pipeline, trapezoid));
- CHECK(compiles(compile, trapezoid, EngineShader_Name(ENGINE_SHADER_WATER_TRAPEZOID),
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_CLASSIC_TRAPEZOID, pipeline, trapezoid));
+ CHECK(compiles(compile, trapezoid, EngineShader_Name(ENGINE_SHADER_WATER_CLASSIC_TRAPEZOID),
PIXEL_PROFILE));
std::string river;
- CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_RIVER, pipeline, river));
- CHECK(compiles(compile, river, EngineShader_Name(ENGINE_SHADER_WATER_RIVER), PIXEL_PROFILE));
+ CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_CLASSIC_RIVER, pipeline, river));
+ CHECK(compiles(compile, river, EngineShader_Name(ENGINE_SHADER_WATER_CLASSIC_RIVER),
+ PIXEL_PROFILE));
std::string reflection;
CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_REFLECTION, pipeline, reflection));
diff --git a/GeneralsMD/Code/Tests/test_shader_sdl.cpp b/GeneralsMD/Code/Tests/test_shader_sdl.cpp
index 0f84d3ddf..3223dfd88 100644
--- a/GeneralsMD/Code/Tests/test_shader_sdl.cpp
+++ b/GeneralsMD/Code/Tests/test_shader_sdl.cpp
@@ -282,8 +282,8 @@ TEST(runtime_bed_material_is_tileable_deterministic_and_has_distinct_relief)
TEST(classic_water_uses_the_original_program_and_separate_cache_identity)
{
- // D3D11 retains the original transcription. Classic on SDL must be exactly that
- // program after binding retargeting, including fog/alpha-test variants.
+ // D3D11's Classic names keep the original transcription. Classic on SDL must be exactly
+ // that program after binding retargeting, including fog/alpha-test variants.
for (unsigned river=0; river<2; ++river) for (unsigned state=0; state<4; ++state) {
const auto original=river?ENGINE_SHADER_WATER_RIVER:ENGINE_SHADER_WATER_TRAPEZOID;
const auto classic=river?ENGINE_SHADER_WATER_CLASSIC_RIVER:ENGINE_SHADER_WATER_CLASSIC_TRAPEZOID;
@@ -292,7 +292,7 @@ TEST(classic_water_uses_the_original_program_and_separate_cache_identity)
pipeline.AlphaTestEnabled=(state&2)!=0;
pipeline.AlphaFunction=FF_CMP_GREATEREQUAL;
std::string expected,actual,modern;
- CHECK(EngineShader_Pixel_Program(original,pipeline,expected,COMBINER_SHADER_TARGET_D3D11));
+ CHECK(EngineShader_Pixel_Program(classic,pipeline,expected,COMBINER_SHADER_TARGET_D3D11));
CHECK(SDL3_Shader_Retarget(expected,false));
CHECK(EngineShader_Pixel_Program(classic,pipeline,actual,COMBINER_SHADER_TARGET_SDL3_GPU));
CHECK(actual==expected);