Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(w3ddevice): draw volumetric hazard clouds on direct3d 11
Olcay Seygan35f86aed500c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5b02b449a..83ba719fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,9 +17,10 @@ found and fixed — EA's own, not port damage.**- 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.-## Volumetric hazard clouds on Linux and macOS+## Volumetric hazard clouds-- Options has a Cloud Style box. Volumetric draws toxin, anthrax and nuclear fields as moving smoke at the size and for the time the hazard really lasts: low smoke hugs the ground and curls around infantry walking through it, and a nuclear field fades in across its whole width with dark billows and embers rising through the heat shimmer. The damage is exactly what it was. Classic stays the default until the cost in a big battle is measured, and on Windows the box is hidden.+- Options has a Cloud Style box. Volumetric draws toxin, anthrax and nuclear fields as moving smoke at the size and for the time the hazard really lasts: low smoke hugs the ground and curls around infantry walking through it, and a nuclear field fades in across its whole width with dark billows and embers rising through the heat shimmer. The damage is exactly what it was. Classic stays the default until the cost in a big battle is measured.+- Windows draws them too, on the default renderer, and so do Linux and macOS. The Direct3D 9 renderer and the Classic graphics setting keep the original puddles whatever the box says, and turning heat effects off takes the shimmer off a nuclear field as well. A cloud that only drifts redraws its smoke twenty times a second rather than every frame, and the second match of a session no longer stalls on the first toxin shell while the clouds' shaders are built again.## A rank ladder for every armydiff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex 0b5a09a19..4aee42da3 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -1830,8 +1830,6 @@ GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrameSunShadow.cppGameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cppGameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cppGameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.h-GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.cpp-GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.hGameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cppGameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.hGameEngineDevice/Source/PosixDevice/Render/SdlProgramCache.cpp@@ -1856,6 +1854,7 @@ GameEngineDevice/Source/W3DDevice/Common/Thing/W3DModuleFactory.cppGameEngineDevice/Source/W3DDevice/Common/Thing/W3DThingFactory.cppGameEngineDevice/Source/W3DDevice/Common/W3DConvert.cppGameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp+GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cppGameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDebrisDraw.cppGameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDefaultDraw.cppGameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp@@ -1894,7 +1893,9 @@ GameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameFont.cppGameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindow.cppGameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindowManager.cppGameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp+GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cppGameEngineDevice/Source/W3DDevice/GameClient/HazardCloudFlow.cpp+GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cppGameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cppGameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cppGameEngineDevice/Source/W3DDevice/GameClient/Shaders/MotionBlur.nvv@@ -1985,6 +1986,7 @@ Libraries/Include/Platform/D3D9PosixMath.hLibraries/Include/Platform/DoubleClickTime.hLibraries/Include/Platform/EngineShaderName.hLibraries/Include/Platform/HazardCloud.h+Libraries/Include/Platform/HazardCloudCore.hLibraries/Include/Platform/HazardCloudFlow.hLibraries/Include/Platform/HazardCloudPolicy.hLibraries/Include/Platform/IsWindows9x.h@@ -1998,7 +2000,6 @@ Libraries/Include/Platform/PosixD3D9/d3d9caps.hLibraries/Include/Platform/PosixD3D9/d3d9types.hLibraries/Include/Platform/RenderTypes.hLibraries/Include/Platform/RendererName.h-Libraries/Include/Platform/SdlHazardCloud.hLibraries/Include/Platform/SleepMilliseconds.hLibraries/Include/Platform/StrdupAsWindows.hLibraries/Include/Platform/SunShadow.hdiff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex 65770f14d..f1532fecb 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -1515,8 +1515,9 @@ if(ZH_PLATFORM_POSIX)# has its own WebBrowser off Windows (B5).list(FILTER W3DDEVICE_SOURCES EXCLUDE REGEX "/W3DDevice/GameClient/W3DWebBrowser\\.cpp$")# The neutral cloud core is in W3DDevice on every platform. SDL supplies the- # POSIX factory below; the no-backend factory is compiled only without it.- list(FILTER W3DDEVICE_SOURCES EXCLUDE REGEX "/HazardCloudUnsupported\\.cpp$")+ # POSIX factory below; the no-backend factory is compiled only without it, and+ # the Direct3D 11 backend only on Windows.+ list(FILTER W3DDEVICE_SOURCES EXCLUDE REGEX "/(HazardCloudUnsupported|DX11HazardCloud)\\.cpp$")# ---- the movies (V1): Windows' Bink player and its Bink API on FFmpeg, the same two files -------------# FFmpeg is built from the tarball Tools/vendor.sh keeps, into the build tree, with the Bink demuxer@@ -1585,7 +1586,6 @@ if(ZH_PLATFORM_POSIX)# the SDL GPU cloud backend and its runtime capability query.target_sources(w3ddevice PRIVATE${ZH_POSIX_RENDER_DIR}/SdlHazardCloud.cpp- ${ZH_POSIX_RENDER_DIR}/SdlHazardCloudShader.cpp${ZH_POSIX_RENDER_DIR}/SdlHazardCloudEmbers.cpp)set_target_properties(w3ddevice PROPERTIES CXX_STANDARD 17)target_include_directories(w3ddevice PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Include@@ -1690,6 +1690,9 @@ list(FILTER GAMEENGINEDEVICE_SOURCES EXCLUDE REGEX "/Source/PosixDevice/")# SdlDevice is the same for SDL3 (C2, C3), built below as sdldevice, never on Windows either; the glob# above took it in, and W2's first MSVC build found no SDL3 to compile it against.list(FILTER GAMEENGINEDEVICE_SOURCES EXCLUDE REGEX "/Source/SdlDevice/")+# The hazard clouds' backend here is Direct3D 11's (DX11HazardCloud.cpp); the no-backend entry points+# are for the tests that link no device.+list(FILTER GAMEENGINEDEVICE_SOURCES EXCLUDE REGEX "/HazardCloudUnsupported\\.cpp$")# Sound and video are the game's own. Miles and Bink were binary-only, and the DLLs the retail# game ships are 32-bit, so there is nothing for a 64-bit exe to bind to: what it links instead is# those two APIs written over XAudio2 and FFmpeg. FFmpeg decodes binkvideo and binkaudio natively,@@ -2180,6 +2183,8 @@ target_include_directories(test_hazard_cloud_policy PRIVATE ${CMAKE_CURRENT_SOUR# device, on every platform (including builds that use the SDL backend in game).target_sources(test_hazard_cloud_policy PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cpp${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudFlow.cpp${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp)@@ -2262,6 +2267,11 @@ add_lib_test(test_dx11pipeline dx11device dx11state dx11layout ffshader ffvertexadd_lib_test(test_dx11resource dx11resource dx11device)add_lib_test(test_engineshader engineshader)add_lib_test(test_dx11backend dx11backend)+# The hazard clouds' text, which the backend compiles for DX11HazardCloud.cpp.+target_sources(test_dx11backend PRIVATE+ ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cpp)+target_include_directories(test_dx11backend PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Include)+set_target_properties(test_dx11backend PROPERTIES CXX_STANDARD 17)add_lib_test(test_dx11post dx11post dx11device user32)add_lib_test(test_dx11twin dx11twin dx11device)add_lib_test(test_dx11texture dx11texture dx11device user32)diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cppindex 6af5a7075..50fe93bca 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp@@ -1,14 +1,12 @@// Shared world-space hazard clouds; game and isolated preview use one renderer.// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.#include "PreRTS.h"-#include "Platform/SdlHazardCloud.h"-#include "SdlHazardCloudShader.h"+#include "Platform/HazardCloudCore.h"#include "SdlHazardCloudEmbers.h"#include "WW3D2/dx8wrapper.h"#include "WW3D2/sdl3shadercompile.h"#include "PosixDevice9.h"#include "SdlGpuFrame.h"-#include "SdlRenderMatrix.h"#include "SdlResourceMirror.h"#include <SDL3/SDL.h>#include <algorithm>@@ -22,20 +20,18 @@namespace SdlHazardCloud {namespace {-const float Steps = 96.0f;-const float MaximumDisplacement = 18.0f;-const unsigned MaximumBodies = 32;+using namespace HazardCloud;+const SDL_GPUTextureFormat LowTargetFormat = SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT;const SDL_GPUTextureUsageFlags LowTargetUsage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER;const SDL_GPUTextureFormat DensityTargetFormat = SDL_GPU_TEXTUREFORMAT_R16_FLOAT;-const unsigned CacheSlices = 24;-const unsigned CacheColumns = 6;-const unsigned CacheRows = CacheSlices / CacheColumns;struct FieldCache {SdlTarget density = {};SdlTarget lighting = {};unsigned side = 0;};+// Kept from the first layer until HazardCloud::ReleaseDevice, so a new map's+// first hazard compiles nothing.struct SharedResources {SdlGpuFrame *frame = nullptr;SDL_GPUDevice *gpu = nullptr;@@ -59,19 +55,12 @@ struct SharedResources {};SharedResources shared;-unsigned cacheSide(const FieldState &field)-{- const float extent = 2.0f * (field.radius + field.fringe + MaximumDisplacement);- const unsigned samples = static_cast<unsigned>(std::clamp(std::ceil(extent / 2.0f) + 1.0f, 32.0f, 512.0f));- return (samples + 15u) & ~15u;-}-void releaseShared(bool deviceAlive){if (deviceAlive && shared.frame && shared.gpu) {if (shared.lowTarget.Colour) shared.frame->Release_After_Batch(shared.lowTarget.Colour, nullptr);if (shared.heatBackground.Colour) shared.frame->Release_After_Batch(shared.heatBackground.Colour, nullptr);- // Last layer only: pipelines cannot retire through Release_After_Batch.+ // Pipelines cannot retire through Release_After_Batch.shared.frame->Flush();SDL_WaitForGPUIdle(shared.gpu);SdlHazardCloudEmbers::shutdown();@@ -96,77 +85,75 @@ void releaseShared(bool deviceAlive)}shared = {};}-} // namespace-struct Layer::Impl {- FieldState fieldStates[2] = {};- unsigned fieldCount = 0;- float sourceTravel[2] = {}, sourceAge[2] = {}, peakDensity[2] = {};- float simulationTime = 0;- bool hasSimulationTime = false;- bool initialized = false;- bool interactionEnabled = true;- bool heatEnabled = true;- bool flowDirty = true;- bool failed = false;- bool explicitDomain = false;- unsigned renderedFrames = 0;- unsigned flowUploads = 0;- uint64_t flowUsedBatch = ~uint64_t(0);- std::vector<Body> bodies;- HazardCloudFlow::Flow flow;- std::array<Palette, 4> palettes = {{defaultPalette(0), defaultPalette(1), defaultPalette(2), defaultPalette(3)}};+bool sharedDeviceAlive()+{+ PosixDevice9 *device = dynamic_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());+ return device && shared.frame && device->Get_Gpu() == shared.frame;+}++class Layer final : public LayerCore {+public:+ ~Layer() override { shutdown(); }+ bool initialize() override;+ bool render(const Camera &camera) override;+ std::uint64_t estimatedCacheBytes() const override;+ void shutdown() override;++private:+ bool makeResources();+ bool makeFlowTexture();+ bool resizeLowTarget(unsigned width, unsigned height);+ bool prepareHeatBackground(const SdlTarget &target);+ void captureHeatBackground(const SdlTarget &target);+ void retireCache(FieldCache &cache);+ bool resizeFieldCache(unsigned index);+ void bindCachedTextures(SdlRecordedDraw &draw, bool density);+ bool prepareCaches(Uniforms &uniforms, SDL_GPUTexture *sceneDepth,+ uint32_t vertexOffset, const SdlTarget &restoreTarget);+ bool uploadTerrain();+ void bindTerrain(SdlRecordedDraw &draw);+ bool uploadFlow();+ bool resolveSceneTarget(PosixDevice9 *device, SdlTarget &target);+SdlGpuFrame *frame = nullptr;SDL_GPUDevice *gpu = nullptr;SDL_GPUTexture *flowTexture = nullptr;SDL_GPUTexture *terrainTexture = nullptr;- std::vector<float> terrainPixels = std::vector<float>(TerrainGridSide * TerrainGridSide * 2, 0.0f);- bool terrainEnabled[2] = {};- float terrainMin[2] = {}, terrainMax[2] = {};- bool terrainDirty = false;+ uint64_t flowUsedBatch = ~uint64_t(0);FieldCache fieldCaches[2];- SdlHazardCloudUniforms cachedInputs = {};- bool cachedInputsValid = false;- unsigned cachedFlowUploads = 0;- unsigned cacheUpdates = 0;- unsigned cacheBakes = 0;--void fail(const char *reason)-{- if (!failed) std::fprintf(stderr, "hazard-cloud: volumetric renderer FAIL: %s\n", reason);- failed = true;-}+};-bool makeResources()+bool Layer::makeResources(){std::vector<unsigned char> spirv;std::string log;- if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudVertexShader(), true, spirv, log)+ if (!SDL3_Compile_HLSL_To_SPIRV(vertexShader(), true, spirv, log)|| !(shared.vertexShader = SDL3_Create_Shader(gpu, spirv, true, log))) {fail(("vertex shader: " + log).c_str());return false;}- if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudPixelShader(false), false, spirv, log)+ if (!SDL3_Compile_HLSL_To_SPIRV(pixelShader(Pass::Volume, true), false, spirv, log)|| !(shared.pixelShader = SDL3_Create_Shader(gpu, spirv, false, log))) {fail(("volume shader: " + log).c_str());return false;}- if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudPixelShader(true), false, spirv, log)+ if (!SDL3_Compile_HLSL_To_SPIRV(pixelShader(Pass::Composite, true), false, spirv, log)|| !(shared.compositePixelShader = SDL3_Create_Shader(gpu, spirv, false, log))) {fail(("volume composite shader: " + log).c_str());return false;}- if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudHeatShader(), false, spirv, log)+ if (!SDL3_Compile_HLSL_To_SPIRV(pixelShader(Pass::Heat, true), false, spirv, log)|| !(shared.heatPixelShader = SDL3_Create_Shader(gpu, spirv, false, log))) {fail(("volume heat shader: " + log).c_str());return false;}- if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudCacheShader(false), false, spirv, log)+ if (!SDL3_Compile_HLSL_To_SPIRV(pixelShader(Pass::Density, true), false, spirv, log)|| !(shared.densityPixelShader = SDL3_Create_Shader(gpu, spirv, false, log))) {fail(("volume density cache shader: " + log).c_str());return false;}- if (!SDL3_Compile_HLSL_To_SPIRV(SdlHazardCloudCacheShader(true), false, spirv, log)+ if (!SDL3_Compile_HLSL_To_SPIRV(pixelShader(Pass::Lighting, true), false, spirv, log)|| !(shared.lightingPixelShader = SDL3_Create_Shader(gpu, spirv, false, log))) {fail(("volume lighting cache shader: " + log).c_str());return false;@@ -245,7 +232,7 @@ bool makeResources()return true;}-bool makeFlowTexture()+bool Layer::makeFlowTexture(){const SDL_GPUTextureFormat flowFormat = SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;const SDL_GPUTextureUsageFlags flowUsage = SDL_GPU_TEXTUREUSAGE_SAMPLER;@@ -268,7 +255,7 @@ bool makeFlowTexture()return true;}-bool resizeLowTarget(unsigned width, unsigned height)+bool Layer::resizeLowTarget(unsigned width, unsigned height){const unsigned lowWidth = width / 2 + width % 2;const unsigned lowHeight = height / 2 + height % 2;@@ -290,7 +277,7 @@ bool resizeLowTarget(unsigned width, unsigned height)return true;}-bool prepareHeatBackground(const SdlTarget &target)+bool Layer::prepareHeatBackground(const SdlTarget &target){if (!shared.heatBackground.Colour || shared.heatBackground.Width != target.Width || shared.heatBackground.Height != target.Height) {SDL_GPUTextureCreateInfo description = {};@@ -309,7 +296,7 @@ bool prepareHeatBackground(const SdlTarget &target)return true;}-void captureHeatBackground(const SdlTarget &target)+void Layer::captureHeatBackground(const SdlTarget &target){// Capture the actual scene at this draw, not a possibly earlier pre-water// snapshot. The queued blit separates attachment writes from shader reads;@@ -318,20 +305,16 @@ void captureHeatBackground(const SdlTarget &target)frame->Record_Blit(target.Colour, rectangle, shared.heatBackground.Colour, rectangle, false);}-void retireCache(FieldCache &cache)+void Layer::retireCache(FieldCache &cache){if (cache.density.Colour) frame->Release_After_Batch(cache.density.Colour, nullptr);if (cache.lighting.Colour) frame->Release_After_Batch(cache.lighting.Colour, nullptr);cache = {};}-bool resizeFieldCache(unsigned index)+bool Layer::resizeFieldCache(unsigned index){- const FieldState &field = fieldStates[index];- const float extent = 2.0f * (field.radius + field.fringe + MaximumDisplacement);- // Include both domain boundaries, retain at most two world units between- // grid nodes, and round the dimension up to a small allocation granularity.- const unsigned side = cacheSide(field);+ const unsigned side = cacheSide(fieldStates[index]);FieldCache &cache = fieldCaches[index];if (cache.side == side && cache.density.Colour && cache.lighting.Colour) return true;SDL_GPUTextureCreateInfo description = {};@@ -355,11 +338,11 @@ bool resizeFieldCache(unsigned index)cache.density = { density, nullptr, description.width, description.height };cache.lighting = { lighting, nullptr, description.width, description.height };cache.side = side;- cachedInputsValid = false;+ invalidateBake();return true;}-void bindCachedTextures(SdlRecordedDraw &draw, bool density)+void Layer::bindCachedTextures(SdlRecordedDraw &draw, bool density){for (unsigned i = 0; i < 2; ++i) {SDL_GPUTexture *texture = density ? fieldCaches[i].density.Colour : fieldCaches[i].lighting.Colour;@@ -370,37 +353,23 @@ void bindCachedTextures(SdlRecordedDraw &draw, bool density)}}-bool prepareCaches(SdlHazardCloudUniforms &uniforms, SDL_GPUTexture *sceneDepth,- uint32_t vertexOffset, const SdlTarget &restoreTarget)+bool Layer::prepareCaches(Uniforms &uniforms, SDL_GPUTexture *sceneDepth,+ uint32_t vertexOffset, const SdlTarget &restoreTarget){- bool active[2] = {};float *grids[] = { uniforms.Cache0, uniforms.Cache1 };for (unsigned i = 0; i < fieldCount; ++i) {- const FieldState &field = fieldStates[i];- active[i] = field.radius > 0.001f && field.height > 0.002f && field.density > 0.00001f;- if (!active[i]) continue;+ if (!fieldActive(i)) continue;if (!resizeFieldCache(i)) return false;grids[i][0] = grids[i][1] = static_cast<float>(fieldCaches[i].side);grids[i][2] = static_cast<float>(CacheSlices);grids[i][3] = static_cast<float>(CacheColumns);}- // Exclude all view-dependent values from the cache key. Orbiting, zooming,- // resizing or drawing a paused frame can reuse the same world-space volume.- SdlHazardCloudUniforms inputs = uniforms;- std::fill(inputs.WorldFromClip, inputs.WorldFromClip + 16, 0.0f);- std::fill(inputs.CameraPosition, inputs.CameraPosition + 4, 0.0f);- std::fill(inputs.Viewport, inputs.Viewport + 4, 0.0f);- inputs.Scene[0] = inputs.Scene[1] = inputs.Scene[2] = 0;- inputs.Settings[1] = inputs.Settings[3] = 0;- std::fill(inputs.CachePass, inputs.CachePass + 4, 0.0f);- if (cachedInputsValid && cachedFlowUploads == flowUploads- && std::memcmp(&inputs, &cachedInputs, sizeof(inputs)) == 0) return true;+ if (!takeBake(uniforms)) return true;- bool rebuilt = false;for (unsigned i = 0; i < fieldCount; ++i) {- if (!active[i]) continue;+ if (!fieldActive(i)) continue;const FieldCache &cache = fieldCaches[i];- SdlHazardCloudUniforms bake = uniforms;+ Uniforms bake = uniforms;bake.CachePass[0] = static_cast<float>(i);SdlRecordedDraw draw = {};draw.Pipeline = shared.densityPipeline;@@ -441,18 +410,12 @@ bool prepareCaches(SdlHazardCloudUniforms &uniforms, SDL_GPUTexture *sceneDepth,frame->Set_Target(cache.lighting);frame->Clear_Back_Buffer(true, false, false, 0, 1.0f, 0);frame->Record_Draw(draw);- ++cacheBakes;- rebuilt = true;}frame->Set_Target(restoreTarget);- cachedInputs = inputs;- cachedFlowUploads = flowUploads;- cachedInputsValid = true;- if (rebuilt) ++cacheUpdates;return true;}-bool uploadTerrain()+bool Layer::uploadTerrain(){if (!terrainEnabled[0] && !terrainEnabled[1]) return true;if (!terrainTexture) {@@ -482,11 +445,11 @@ bool uploadTerrain()std::memcpy(frame->Upload_Space(bytes, offset), terrainPixels.data(), bytes);frame->Queue_Texture_Upload(terrainTexture, 0, TerrainGridSide * 2, TerrainGridSide, offset);terrainDirty = false;- cachedInputsValid = false;+ invalidateBake();return true;}-void bindTerrain(SdlRecordedDraw &draw)+void Layer::bindTerrain(SdlRecordedDraw &draw){draw.SamplerCount = 7;draw.Textures[5] = flowTexture;@@ -495,9 +458,9 @@ void bindTerrain(SdlRecordedDraw &draw)draw.Samplers[6] = shared.flowSampler;}-bool uploadFlow()+bool Layer::uploadFlow(){- if (!flowDirty) return true;+ if (!flowNeedsUpload()) return true;if (!flow.valid()) {fail("interaction simulation produced invalid state");return false;@@ -513,12 +476,11 @@ bool uploadFlow()uint32_t offset = 0;std::memcpy(frame->Upload_Space(bytes, offset), flow.data(), bytes);frame->Queue_Texture_Upload(flowTexture, 0, flow.width(), flow.height(), offset);- flowDirty = false;- ++flowUploads;+ flowUploaded();return true;}-bool resolveSceneTarget(PosixDevice9 *device, SdlTarget &target)+bool Layer::resolveSceneTarget(PosixDevice9 *device, SdlTarget &target){IDirect3DSurface9 *current = nullptr, *back = nullptr, *depth = nullptr;device->GetRenderTarget(0, ¤t);@@ -571,68 +533,9 @@ bool resolveSceneTarget(PosixDevice9 *device, SdlTarget &target)return true;}-void heatScissor(const float viewProjection[16], const D3DVIEWPORT9 &viewport,- const SdlTarget &target, int32_t rectangle[4])+bool Layer::render(const Camera &camera){- const float left = static_cast<float>(std::min(viewport.X, target.Width));- const float top = static_cast<float>(std::min(viewport.Y, target.Height));- const float right = left + std::min(viewport.Width, target.Width - static_cast<unsigned>(left));- const float bottom = top + std::min(viewport.Height, target.Height - static_cast<unsigned>(top));- rectangle[0] = static_cast<int32_t>(left);- rectangle[1] = static_cast<int32_t>(top);- rectangle[2] = static_cast<int32_t>(right - left);- rectangle[3] = static_cast<int32_t>(bottom - top);- float minX = 1.0e30f, minY = 1.0e30f, maxX = -1.0e30f, maxY = -1.0e30f;- bool found = false;- for (unsigned i = 0; i < fieldCount; ++i) {- const FieldState &field = fieldStates[i];- if (field.palette < 0.5f || field.palette >= 1.5f || field.radius <= 0.001f- || field.height <= 0.002f || field.density <= 0.00001f) continue;- found = true;- const float radius = field.radius + field.fringe + MaximumDisplacement;- for (unsigned corner = 0; corner < 8; ++corner) {- const float world[4] = {- field.ground.x + (corner & 1 ? radius : -radius),- field.ground.y + (corner & 2 ? radius : -radius),- (terrainEnabled[i] ? (corner & 4 ? terrainMax[i] : terrainMin[i]) : field.ground.z)- + (corner & 4 ? field.height * 2.6f : 0.0f), 1.0f- };- float clip[4] = {};- for (unsigned column = 0; column < 4; ++column)- for (unsigned row = 0; row < 4; ++row)- clip[column] += world[row] * viewProjection[row * 4 + column];- // A box crossing the near plane cannot be bounded by projecting- // only its corners. Keep the full viewport for that unusual view.- if (!std::isfinite(clip[0]) || !std::isfinite(clip[1])- || !std::isfinite(clip[2]) || !std::isfinite(clip[3])- || clip[3] <= 0.00001f || clip[2] <= 0.00001f) return;- const float x = viewport.X + 0.5f + (clip[0] / clip[3] + 1.0f) * viewport.Width * 0.5f;- const float y = viewport.Y + 0.5f + (1.0f - clip[1] / clip[3]) * viewport.Height * 0.5f;- minX = std::min(minX, x); maxX = std::max(maxX, x);- minY = std::min(minY, y); maxY = std::max(maxY, y);- }- }- if (!found) { rectangle[2] = rectangle[3] = 0; return; }- // Two pixels of conservative rasterization slack keep the projected- // envelope intact at viewport edges and odd framebuffer dimensions.- const float boundedLeft = std::clamp(std::floor(minX) - 2.0f, left, right);- const float boundedTop = std::clamp(std::floor(minY) - 2.0f, top, bottom);- const float boundedRight = std::clamp(std::ceil(maxX) + 2.0f, left, right);- const float boundedBottom = std::clamp(std::ceil(maxY) + 2.0f, top, bottom);- rectangle[0] = static_cast<int32_t>(boundedLeft);- rectangle[1] = static_cast<int32_t>(boundedTop);- rectangle[2] = static_cast<int32_t>(std::max(0.0f, boundedRight - boundedLeft));- rectangle[3] = static_cast<int32_t>(std::max(0.0f, boundedBottom - boundedTop));-}--bool renderVolume()-{- if (!initialized || failed || !fieldCount) return false;- bool active = false;- for (unsigned i = 0; i < fieldCount; ++i)- active = active || (fieldStates[i].radius > 0.001f && fieldStates[i].height > 0.002f- && fieldStates[i].density > 0.00001f);- if (!active) return false;+ if (!initialized || failed || !anyFieldActive()) return false;PosixDevice9 *device = static_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());if (!device || device->Get_Gpu() != frame) {fail("the preview graphics device was replaced");@@ -640,7 +543,7 @@ bool renderVolume()}// The scene's normal pass can target an intermediate texture. Resolve that// actual colour/depth pair, rather than assuming it is the final back buffer.- // Reflection and custom passes are excluded by the Render callback below.+ // Reflection and custom passes are excluded by the caller.SdlTarget target;if (!resolveSceneTarget(device, target)) return false;if (!resizeLowTarget(target.Width, target.Height)) return false;@@ -654,96 +557,9 @@ bool renderVolume()fail("sampleable scene depth is unavailable; volume clipping cannot run");return false;}- D3DMATRIX view, projection;- D3DVIEWPORT9 viewport;- if (device->GetTransform(D3DTS_VIEW, &view) != D3D_OK- || device->GetTransform(D3DTS_PROJECTION, &projection) != D3D_OK- || device->GetViewport(&viewport) != D3D_OK || !viewport.Width || !viewport.Height) {- fail("could not read the scene camera");- return false;- }- SdlHazardCloudUniforms uniforms = {};- float viewProjection[16], inverseView[16];- multiply(&view._11, &projection._11, viewProjection);- if (!render_inverse(viewProjection, uniforms.WorldFromClip)- || !render_inverse(&view._11, inverseView)) {- fail("scene camera has a singular transform");- return false;- }- const float depthRange = viewport.MaxZ - viewport.MinZ;- if (depthRange <= 1.0e-8f) {- fail("scene camera has an empty depth range");- return false;- }- for (unsigned column = 0; column < 4; ++column) {- const float row = uniforms.WorldFromClip[8 + column] / depthRange;- uniforms.WorldFromClip[12 + column] -= viewport.MinZ * row;- uniforms.WorldFromClip[8 + column] = row;- }- for (unsigned i = 0; i < 3; ++i) uniforms.CameraPosition[i] = inverseView[12 + i];- uniforms.CameraPosition[3] = 1;- uniforms.Viewport[0] = static_cast<float>(viewport.X) + 0.5f;- uniforms.Viewport[1] = static_cast<float>(viewport.Y) + 0.5f;- uniforms.Viewport[2] = static_cast<float>(viewport.Width);- uniforms.Viewport[3] = static_cast<float>(viewport.Height);- uniforms.Scene[0] = 1.0f / target.Width;- uniforms.Scene[1] = 1.0f / target.Height;- uniforms.Scene[2] = 1;- uniforms.Scene[3] = simulationTime;- float *fields[] = { uniforms.Field0, uniforms.Field1 };- float *shapes[] = { uniforms.Shape0, uniforms.Shape1 };- float *sources[] = { uniforms.Source0, uniforms.Source1 };- bool hotField = false;- for (unsigned i = 0; i < fieldCount; ++i) {- const FieldState &field = fieldStates[i];- hotField = hotField || (field.palette >= 0.5f && field.palette < 1.5f- && field.radius > 0.001f && field.height > 0.002f && field.density > 0.00001f);- fields[i][0] = field.ground.x;- fields[i][1] = field.ground.y;- fields[i][2] = field.ground.z + field.height * 0.5f;- fields[i][3] = field.radius;- shapes[i][0] = field.height * 0.5f;- shapes[i][1] = field.density;- shapes[i][2] = field.palette;- shapes[i][3] = field.formation;- uniforms.Footprints[i] = field.fringe;- sources[i][0] = field.release;- sources[i][1] = sourceTravel[i];- sources[i][2] = peakDensity[i] > 0.0001f- ? std::max(0.0f, 1.0f - field.density / peakDensity[i]) : 0.0f;- sources[i][3] = sourceAge[i];- }- float *terrain[] = { uniforms.Terrain0, uniforms.Terrain1 };- for (unsigned i = 0; i < 2; ++i) {- terrain[i][0] = terrainMin[i];- terrain[i][1] = terrainMax[i];- terrain[i][2] = terrainEnabled[i] ? 1.0f : 0.0f;- }- uniforms.Settings[0] = static_cast<float>(fieldCount);- // Keep palette values in the cache key: live edits must refresh lighting- // even while the source, infantry and simulation clock are paused.- for (unsigned i = 0; i < 4; ++i) {- const auto &palette = palettes[i];- uniforms.PaletteMain[i][0] = palette.main.r;- uniforms.PaletteMain[i][1] = palette.main.g;- uniforms.PaletteMain[i][2] = palette.main.b;- uniforms.PaletteMain[i][3] = palette.brightness;- uniforms.PaletteShadow[i][0] = palette.shadow.r;- uniforms.PaletteShadow[i][1] = palette.shadow.g;- uniforms.PaletteShadow[i][2] = palette.shadow.b;- uniforms.PaletteShadow[i][3] = 1.0f - palette.transparency;- }- // Visible hot-air refraction only for the warm nuclear palette.- // This is a preview material control; it never changes a gameplay hazard.- uniforms.Settings[1] = heatEnabled && hotField ? 10.0f : 0.0f;- uniforms.Settings[2] = 1;- uniforms.Settings[3] = Steps;- uniforms.Interaction[0] = flow.domainMinX();- uniforms.Interaction[1] = flow.domainMinY();- uniforms.Interaction[2] = 1.0f / (flow.domainMaxX() - flow.domainMinX());- uniforms.Interaction[3] = 1.0f / (flow.domainMaxY() - flow.domainMinY());- uniforms.FlowSettings[0] = interactionEnabled ? 1.0f : 0.0f;- uniforms.FlowSettings[1] = MaximumDisplacement;+ Uniforms uniforms;+ float viewProjection[16];+ if (!buildUniforms(camera, target.Width, target.Height, uniforms, viewProjection)) return false;// Complete all potentially failing material allocations before recording// a visible scene draw. The adapter can safely fall back to classic clouds.@@ -792,19 +608,21 @@ bool renderVolume()draw.Textures[2] = shared.lowTarget.Colour;draw.Samplers[2] = shared.depthSampler;std::copy(uniforms.Viewport, uniforms.Viewport + 4, draw.Viewport);- draw.Viewport[4] = viewport.MinZ;- draw.Viewport[5] = viewport.MaxZ;- draw.Scissor[0] = static_cast<int32_t>(viewport.X);- draw.Scissor[1] = static_cast<int32_t>(viewport.Y);- draw.Scissor[2] = std::min(viewport.Width, target.Width - std::min(viewport.X, target.Width));- draw.Scissor[3] = std::min(viewport.Height, target.Height - std::min(viewport.Y, target.Height));+ draw.Viewport[4] = camera.minZ;+ draw.Viewport[5] = camera.maxZ;+ draw.Scissor[0] = static_cast<int32_t>(camera.x);+ draw.Scissor[1] = static_cast<int32_t>(camera.y);+ draw.Scissor[2] = std::min(camera.width, target.Width - std::min(camera.x, target.Width));+ draw.Scissor[3] = std::min(camera.height, target.Height - std::min(camera.y, target.Height));frame->Set_Target(target);frame->Record_Draw(draw);SdlHazardCloudEmbers::render(frame, target, sceneDepth, viewProjection, draw.Viewport,fieldStates, fieldCount, simulationTime, terrainTexture, terrainEnabled);if (uniforms.Settings[1] > 0) {SdlRecordedDraw heatDraw = draw;- heatScissor(viewProjection, viewport, target, heatDraw.Scissor);+ int scissor[4];+ heatScissor(viewProjection, camera, target.Width, target.Height, scissor);+ std::copy(scissor, scissor + 4, heatDraw.Scissor);if (heatDraw.Scissor[2] > 0 && heatDraw.Scissor[3] > 0) {// Include the smoke and embers in the refraction. Warping only the// background makes heat disappear under a dense cloud's opacity.@@ -819,122 +637,11 @@ bool renderVolume()flowUsedBatch = frame->Batch();// Recorded state is private to this draw. The next engine draw rebinds its// own pipeline, samplers and uniforms without any D3D9 state restoration.- ++renderedFrames;+ ++renderedFrameCount;return true;}-void setFields(const FieldState *values, unsigned count)-{- if (count > 2 || (count && !values)) {- fail("invalid cloud lifecycle field list");- return;- }- for (unsigned i = 0; i < count; ++i) {- const FieldState &field = values[i];- if (!std::isfinite(field.ground.x) || !std::isfinite(field.ground.y)- || !std::isfinite(field.ground.z) || !std::isfinite(field.radius)- || !std::isfinite(field.height) || !std::isfinite(field.density)- || !std::isfinite(field.palette) || !std::isfinite(field.formation)- || !std::isfinite(field.release) || !std::isfinite(field.fringe)- || field.fringe < 0 || field.radius < 0 || field.height < 0- || field.density < 0 || field.palette < 0 || field.palette > 3- || field.formation < 0 || field.formation > 1 || field.release < 0 || field.release > 1) {- fail("invalid cloud lifecycle field state");- return;- }- }- if (!explicitDomain && count) {- float minX = values[0].ground.x, maxX = minX;- float minY = values[0].ground.y, maxY = minY;- for (unsigned i = 0; i < count; ++i) {- const float radius = std::max(1.0f, values[i].radius + values[i].fringe + MaximumDisplacement);- minX = std::min(minX, values[i].ground.x - radius);- maxX = std::max(maxX, values[i].ground.x + radius);- minY = std::min(minY, values[i].ground.y - radius);- maxY = std::max(maxY, values[i].ground.y + radius);- }- if (flow.domainMinX() != minX || flow.domainMaxX() != maxX- || flow.domainMinY() != minY || flow.domainMaxY() != maxY) {- flow.setDomain(minX, minY, maxX, maxY);- flowDirty = true;- }- }- fieldCount = count;- for (unsigned i = 0; i < count; ++i) {- fieldStates[i] = values[i];- peakDensity[i] = std::max(peakDensity[i], values[i].density);- }-}--void reset()-{- flow.reset();- flowDirty = true;- for (unsigned i = 0; i < 2; ++i) {- sourceTravel[i] = sourceAge[i] = peakDensity[i] = 0;- }-}--void setBodies(const Body *values, unsigned count)-{- if (count > MaximumBodies || (count && !values)) {- fail("invalid infantry interaction body list");- return;- }- for (unsigned i = 0; i < count; ++i) {- const Body &body = values[i];- if (!std::isfinite(body.x) || !std::isfinite(body.y) || !std::isfinite(body.z)- || !std::isfinite(body.vx) || !std::isfinite(body.vy)- || !std::isfinite(body.radius) || !std::isfinite(body.height)- || body.radius <= 0 || body.height <= 0) {- fail("invalid infantry interaction body");- return;- }- }- if (count) bodies.assign(values, values + count);- else bodies.clear();-}--void setInteractionEnabled(bool value)-{- if (interactionEnabled == value) return;- interactionEnabled = value;- flow.reset();- flowDirty = true;-}---void setHeatEnabled(bool value) { heatEnabled = value; }--void update(float timeSeconds)-{- if (!std::isfinite(timeSeconds) || timeSeconds < 0) {- fail("invalid simulation time");- return;- }- const float elapsed = hasSimulationTime ? timeSeconds - simulationTime : 0.0f;- simulationTime = timeSeconds;- hasSimulationTime = true;- if (elapsed < 0) {- reset();- } else if (elapsed > 0 && !failed) {- for (unsigned i = 0; i < fieldCount; ++i) {- sourceAge[i] += elapsed;- sourceTravel[i] += elapsed * fieldStates[i].release * 22.0f;- }- // Appearance only controls drawing. Keep the same wake history while- // the original effects are shown, so toggling back is an in-place A/B.- if (interactionEnabled) {- flow.step(elapsed, bodies.empty() ? nullptr : bodies.data(),- static_cast<unsigned>(bodies.size()));- if (!flow.valid()) fail("interaction simulation produced invalid state");- flowDirty = true;- }- }-}---bool initialize()+bool Layer::initialize(){if (initialized) return !failed;if (!HazardCloud::Supported()) return false;@@ -944,13 +651,17 @@ bool initialize()fail("an SDL graphics device is required");return false;}- if (shared.users && (shared.frame != frame || shared.gpu != gpu)) {- fail("existing cloud layers belong to a different graphics device");- frame = nullptr;- gpu = nullptr;- return false;+ if (shared.gpu && (shared.frame != frame || shared.gpu != gpu)) {+ if (shared.users) {+ fail("existing cloud layers belong to a different graphics device");+ frame = nullptr;+ gpu = nullptr;+ return false;+ }+ // The device was replaced without a ReleaseDevice; its objects went with it.+ releaseShared(false);}- if (!shared.users) {+ if (!shared.gpu) {shared.frame = frame;shared.gpu = gpu;if (!makeResources()) {@@ -968,7 +679,7 @@ bool initialize()return true;}-void shutdown()+void Layer::shutdown(){if (!initialized) return;PosixDevice9 *device = static_cast<PosixDevice9 *>(DX8Wrapper::_Get_D3D_Device());@@ -980,99 +691,24 @@ void shutdown()}for (FieldCache &cache : fieldCaches) cache = {};flowTexture = terrainTexture = nullptr;- terrainDirty = terrainEnabled[0] || terrainEnabled[1];initialized = false;if (shared.users) --shared.users;- if (!shared.users) releaseShared(alive);frame = nullptr;gpu = nullptr;- cachedInputsValid = false;- cachedInputs = {};- cachedFlowUploads = cacheUpdates = cacheBakes = 0;- renderedFrames = flowUploads = 0;flowUsedBatch = ~uint64_t(0);- flowDirty = true;- hasSimulationTime = false;- bodies.clear();- reset();+ resetCounters();}-};-Layer::Layer() : impl(new Impl) {}-Layer::~Layer() { shutdown(); delete impl; }-bool Layer::initialize() { return impl->initialize(); }-void Layer::setFields(const FieldState *fields, unsigned count) { impl->setFields(fields, count); }-void Layer::setBodies(const Body *bodies, unsigned count) { impl->setBodies(bodies, count); }-void Layer::setFlowDomain(float minX, float minY, float maxX, float maxY)-{- impl->flow.setDomain(minX, minY, maxX, maxY);- impl->explicitDomain = true;- impl->flowDirty = true;- if (!impl->flow.valid()) impl->fail("invalid interaction simulation domain");-}-void Layer::setTerrain(unsigned index, const float *heights)-{- if (index >= 2) { impl->fail("invalid terrain field index"); return; }- if (!heights) {- impl->terrainEnabled[index] = false;- impl->terrainMin[index] = impl->terrainMax[index] = 0;- return;- }- float minimum = heights[0], maximum = heights[0];- for (unsigned i = 0; i < TerrainGridSide * TerrainGridSide; ++i) {- if (!std::isfinite(heights[i]) || std::abs(heights[i]) > 100000.0f) {- impl->fail("invalid terrain height");- return;- }- minimum = std::min(minimum, heights[i]);- maximum = std::max(maximum, heights[i]);- }- bool changed = !impl->terrainEnabled[index];- for (unsigned y = 0; y < TerrainGridSide; ++y) {- float *destination = impl->terrainPixels.data() + y * TerrainGridSide * 2 + index * TerrainGridSide;- const float *source = heights + y * TerrainGridSide;- changed = changed || std::memcmp(destination, source, TerrainGridSide * sizeof(float)) != 0;- std::copy(source, source + TerrainGridSide, destination);- }- impl->terrainEnabled[index] = true;- impl->terrainMin[index] = minimum;- impl->terrainMax[index] = maximum;- impl->terrainDirty = impl->terrainDirty || changed;-}-void Layer::setPalette(unsigned index, const Palette &palette)-{- const float values[] = { palette.main.r, palette.main.g, palette.main.b,- palette.shadow.r, palette.shadow.g, palette.shadow.b, palette.brightness, palette.transparency };- if (index >= 4) { impl->fail("invalid palette index"); return; }- for (unsigned i = 0; i < 8; ++i)- if (!std::isfinite(values[i]) || values[i] < 0 || values[i] > (i == 6 ? 2 : 1)) {- impl->fail("invalid palette value");- return;- }- impl->palettes[index] = palette;-}-void Layer::setInteractionEnabled(bool value) { impl->setInteractionEnabled(value); }-bool Layer::isInteractionEnabled() const { return impl->interactionEnabled; }-void Layer::setHeatEnabled(bool value) { impl->setHeatEnabled(value); }-bool Layer::isHeatEnabled() const { return impl->heatEnabled; }-void Layer::update(float seconds) { impl->update(seconds); }-void Layer::reset() { impl->reset(); }-bool Layer::render() { return impl->renderVolume(); }-bool Layer::valid() const { return impl->initialized && !impl->failed && impl->flow.valid(); }-unsigned Layer::activeBodies() const { return impl->flow.activeBodies(); }-float Layer::maxDisturbance() const { return impl->flow.maxDisturbance(); }-unsigned Layer::interactionUploads() const { return impl->flowUploads; }-unsigned Layer::renderedFrames() const { return impl->renderedFrames; }std::uint64_t Layer::estimatedCacheBytes() const{- std::uint64_t result = impl->flowTexture ? 192u * 96u * 4u * sizeof(float) : 0;- if (impl->terrainTexture) result += TerrainGridSide * TerrainGridSide * 2u * sizeof(float);- for (const FieldCache &cache : impl->fieldCaches)+ std::uint64_t result = flowTexture ? 192u * 96u * 4u * sizeof(float) : 0;+ if (terrainTexture) result += TerrainGridSide * TerrainGridSide * 2u * sizeof(float);+ for (const FieldCache &cache : fieldCaches)result += std::uint64_t(cache.side) * cache.side * CacheSlices * 10u;return result;}-void Layer::shutdown() { impl->shutdown(); }+} // namespace} // namespace SdlHazardCloudnamespace HazardCloud {@@ -1097,4 +733,9 @@ std::unique_ptr<Layer> CreateLayer()return std::make_unique<SdlHazardCloud::Layer>();}+void ReleaseDevice()+{+ if (SdlHazardCloud::shared.gpu) SdlHazardCloud::releaseShared(SdlHazardCloud::sharedDeviceAlive());+}+} // namespace HazardClouddiff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cppindex 5aa275f24..ee7640702 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp@@ -2,7 +2,7 @@// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.#include "PreRTS.h"#include "SdlHazardCloudEmbers.h"-#include "Platform/HazardCloud.h"+#include "Platform/HazardCloudCore.h"#include "WW3D2/sdl3shadercompile.h"#include "SdlGpuFrame.h"@@ -17,9 +17,6 @@namespace SdlHazardCloudEmbers {namespace {-constexpr unsigned MinimumEmbers = 24;-constexpr unsigned MaximumEmbers = 96;-constexpr float ReferenceEmberRadius = 250.0f;SDL_GPUDevice *gpu = nullptr;SDL_GPUShader *vertexShader = nullptr;SDL_GPUShader *pixelShader = nullptr;@@ -28,16 +25,6 @@ SDL_GPUSampler *depthSampler = nullptr;bool failed = false;unsigned renderedFrames = 0;-struct VertexConstants {- float viewProjection[16];- float viewport[4];- float field[4];- float shape[4];- float scene[4];- float terrain[4]; // enabled, field index, sampled domain radius, reserved-};-static_assert(sizeof(VertexConstants) == 144, "ember shader constant layout");-bool fail(const char *reason){if (!failed) std::fprintf(stderr, "hazard-cloud: nuclear embers FAIL: %s\n", reason);@@ -45,143 +32,15 @@ bool fail(const char *reason)return false;}-const char *vertexSource = R"HLSL(-Texture2D<float> TerrainHeight : register(t0, space0);-SamplerState TerrainSampler : register(s0, space0);-cbuffer EmberConstants : register(b0, space1)-{- row_major float4x4 ViewProjection;- float4 Viewport;- float4 Field;- float4 Shape;- float4 Scene;- float4 Terrain;-};-struct EmberVertex {- float4 position : SV_Position;- float2 local : TEXCOORD0;- float2 glow : TEXCOORD1;-};-float emberHash(float seed)-{- float3 p = frac(float3(seed, seed + 1.0, seed + 2.0) * 0.1031);- p += dot(p, p.yzx + 33.33);- return frac((p.x + p.y) * p.z);-}-float emberGround(float2 world)-{- if (Terrain.x < 0.5) return Field.z;- uint width, height;- TerrainHeight.GetDimensions(width, height);- float side = float(height);- float2 uv = saturate((world - Field.xy) / max(Terrain.z * 2.0, 0.001) + 0.5);- float2 texel = uv * (side - 1.0);- float2 lower = floor(texel), upper = min(lower + 1.0, side - 1.0);- float2 weight = frac(texel);- float2 a = (lower + float2(Terrain.y * side, 0) + 0.5) / float2(width, height);- float2 b = (upper + float2(Terrain.y * side, 0) + 0.5) / float2(width, height);- float low = lerp(TerrainHeight.SampleLevel(TerrainSampler, a, 0),- TerrainHeight.SampleLevel(TerrainSampler, float2(b.x, a.y), 0), weight.x);- float high = lerp(TerrainHeight.SampleLevel(TerrainSampler, float2(a.x, b.y), 0),- TerrainHeight.SampleLevel(TerrainSampler, b, 0), weight.x);- return lerp(low, high, weight.y);-}-EmberVertex main(uint vertex : SV_VertexID)-{- uint particle = vertex / 6;- uint corner = vertex % 6;- float2 local;- if (corner == 0 || corner == 3) local = float2(-1, -1);- else if (corner == 1) local = float2(1, -1);- else if (corner == 2 || corner == 4) local = float2(1, 1);- else local = float2(-1, 1);-- float seed = float(particle) * 13.61 + Field.x * 0.21 + Field.y * 0.37;- float random = emberHash(seed + 7.0);- float lifetime = 3.4 + emberHash(seed + 2.0) * 2.8;- float age = frac(Scene.x / lifetime + emberHash(seed + 19.0));- // One anchor per equal-area radial stratum, separated by the golden angle.- // Slight jitter breaks the spiral's regularity without random clustering.- // Field.w includes the cloud's visual fringe. Its whole footprint ignites- // together; formation controls opacity rather than moving sparks outward.- float rotation = emberHash(Field.x * 0.21 + Field.y * 0.37 + 3.0) * 6.2831853;- float angle = float(particle) * 2.39996323 + rotation- + (emberHash(seed + 11.0) - 0.5) * 0.12;- float stratum = (float(particle) + 0.35 + emberHash(seed + 1.0) * 0.30) / max(Scene.y, 1.0);- float radius = sqrt(stratum) * Field.w;- float2 origin = Field.xy + float2(cos(angle), sin(angle)) * radius;- float2 drift = float2(sin(age * 5.0 + seed), cos(age * 4.0 + seed * 0.7));- drift *= (2.0 + random * 5.0) * age;- drift += float2(3.0, -1.0) * age * age;- float height = Shape.x * (0.36 + age * (1.8 + random * 0.6));- float3 world = float3(origin + drift, emberGround(origin + drift) + height);- float4 clip = mul(float4(world, 1), ViewProjection);- float4 upClip = mul(float4(world + float3(0, 0, 1), 1), ViewProjection);- float2 up = (upClip.xy / max(upClip.w, 0.0001) - clip.xy / max(clip.w, 0.0001))- * Viewport.zw * float2(0.5, -0.5);- up = dot(up, up) > 0.00001 ? normalize(up) : float2(0, -1);- float2 across = float2(-up.y, up.x);- // The bright core is roughly 1-2 pixels across at the default view, with- // a softer orange halo and a short tail pointing down its rising path.- float zoom = clamp(sqrt(max(Viewport.z * Viewport.w, 1.0) / 1024000.0), 0.8, 1.7);- float2 extent = float2(2.3 + random * 1.1, 3.0 + random * 2.5) * zoom;- float2 pixelOffset = across * local.x * extent.x + up * local.y * extent.y;- clip.xy += pixelOffset * float2(2, -2) / max(Viewport.zw, float2(1, 1)) * clip.w;- float fade = smoothstep(0.0, 0.14, age) * (1.0 - smoothstep(0.58, 1.0, age));- fade *= saturate(Shape.y * 1.6) * smoothstep(0.02, 0.28, Shape.z);- fade *= lerp(0.58, 1.0, random) * lerp(0.55, 1.0, smoothstep(0.5, 1.1, height / Shape.x));- // Keep the outer annulus legible. Only the last few percent of outward- // drift die away, so the soft cloud fringe does not become a hard spark ring.- float edgeRadius = length(world.xy - Field.xy) / max(Field.w, 0.001);- fade *= (1.0 - 0.40 * smoothstep(0.88, 1.0, edgeRadius))- * (1.0 - smoothstep(1.0, 1.055, edgeRadius));- EmberVertex output;- output.position = clip;- output.local = local;- output.glow = float2(fade, random);- return output;-}-)HLSL";--const char *pixelSource = R"HLSL(-Texture2D<float> SceneDepth : register(t0, space2);-SamplerState DepthSampler : register(s0, space2);-cbuffer EmberPixelConstants : register(b0, space3) { float4 Scene; };-struct EmberVertex {- float4 position : SV_Position;- float2 local : TEXCOORD0;- float2 glow : TEXCOORD1;-};-float4 main(EmberVertex input) : SV_Target-{- float depth = SceneDepth.SampleLevel(DepthSampler, input.position.xy * Scene.xy, 0);- // Use the same captured opaque depth as the volume: terrain and infantry- // hide sparks behind them, while this pass never writes the scene depth.- clip(depth - input.position.z + 0.0000005);- float2 corePoint = (input.local - float2(0, 0.30)) * float2(1, 1.6);- float squared = dot(corePoint, corePoint);- float core = exp2(-squared * 12.0);- float halo = exp2(-squared * 3.0);- float tail = (1.0 - smoothstep(0.10, 0.34, abs(input.local.x)))- * smoothstep(-1.0, -0.30, input.local.y)- * (1.0 - smoothstep(-0.18, 0.30, input.local.y));- float edge = (1.0 - smoothstep(0.80, 1.0, abs(input.local.x)))- * (1.0 - smoothstep(0.85, 1.0, abs(input.local.y)));- float3 warm = lerp(float3(1.0, 0.21, 0.025), float3(1.0, 0.43, 0.08), input.glow.y);- float3 light = float3(1.0, 0.80, 0.43) * core * 0.95 + warm * (halo * 0.30 + tail * 0.17);- return float4(light * input.glow.x * edge, 0);-}-)HLSL";-bool makeResources(SdlGpuFrame *frame, const SdlTarget &target){gpu = frame->Device();std::vector<unsigned char> spirv;std::string log;- if (!SDL3_Compile_HLSL_To_SPIRV(vertexSource, true, spirv, log)+ if (!SDL3_Compile_HLSL_To_SPIRV(HazardCloud::emberVertexShader(true), true, spirv, log)|| !(vertexShader = SDL3_Create_Shader(gpu, spirv, true, log)))return fail(("vertex shader: " + log).c_str());- if (!SDL3_Compile_HLSL_To_SPIRV(pixelSource, false, spirv, log)+ if (!SDL3_Compile_HLSL_To_SPIRV(HazardCloud::emberPixelShader(true), false, spirv, log)|| !(pixelShader = SDL3_Create_Shader(gpu, spirv, false, log)))return fail(("pixel shader: " + log).c_str());SDL_GPUColorTargetDescription colour = {};@@ -228,9 +87,7 @@ bool prepare(SdlGpuFrame *frame, const SdlTarget &target,if (failed || !frame || !frame->Device() || !target.Colour || !target.Depth|| fieldCount > 2 || (fieldCount && !fields)) return false;for (unsigned i = 0; i < fieldCount; ++i) {- const auto &field = fields[i];- if (field.palette < 0.5f || field.palette >= 1.5f || field.density <= 0.00001f- || field.radius <= 0.001f || field.height <= 0.002f || field.formation <= 0.02f) continue;+ if (!HazardCloud::emberField(fields[i])) continue;if (!pipeline && !makeResources(frame, target)) return false;if (gpu != frame->Device()) return fail("the graphics device was replaced");}@@ -249,34 +106,13 @@ bool render(SdlGpuFrame *frame, const SdlTarget &target, SDL_GPUTexture *sceneDereturn fail("invalid rendering inputs");bool active = false;for (unsigned i = 0; i < fieldCount; ++i) {- const auto &field = fields[i];- if (field.palette < 0.5f || field.palette >= 1.5f || field.density <= 0.00001f- || field.radius <= 0.001f || field.height <= 0.002f || field.formation <= 0.02f) continue;+ if (!HazardCloud::emberField(fields[i])) continue;if (!pipeline && !makeResources(frame, target)) return false;if (gpu != frame->Device()) return fail("the preview graphics device was replaced");- const float footprintRadius = field.radius + field.fringe;- const float areaRatio = footprintRadius * footprintRadius- / (ReferenceEmberRadius * ReferenceEmberRadius);- // Match particle density to visible area: 64 at the comparison size,- // fewer for cannon residue and at most 96 for the large missile field.- const unsigned emberCount = static_cast<unsigned>(std::clamp(- std::round(64.0f * areaRatio / 8.0f) * 8.0f,- static_cast<float>(MinimumEmbers), static_cast<float>(MaximumEmbers)));- VertexConstants constants = {};- std::copy(viewProjection, viewProjection + 16, constants.viewProjection);- std::copy(viewport, viewport + 4, constants.viewport);- constants.field[0] = field.ground.x;- constants.field[1] = field.ground.y;- constants.field[2] = field.ground.z;- constants.field[3] = footprintRadius;- constants.shape[0] = field.height;- constants.shape[1] = field.density;- constants.shape[2] = field.formation;- constants.scene[0] = timeSeconds;- constants.scene[1] = static_cast<float>(emberCount);- constants.terrain[0] = terrainTexture && terrainEnabled && terrainEnabled[i] ? 1.0f : 0.0f;- constants.terrain[1] = static_cast<float>(i);- constants.terrain[2] = footprintRadius + 18.0f;+ HazardCloud::EmberConstants constants;+ const unsigned emberCount = HazardCloud::emberConstants(fields[i], i,+ terrainTexture && terrainEnabled && terrainEnabled[i], viewProjection, viewport,+ timeSeconds, constants);const float pixelConstants[4] = { 1.0f / target.Width, 1.0f / target.Height, 0, 0 };SdlRecordedDraw draw = {};draw.Pipeline = pipeline;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.hdeleted file mode 100644index 4f9ffa389..000000000--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.h+++ /dev/null@@ -1,40 +0,0 @@-// Shared GPU material for preview and production hazard clouds.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#ifndef SDL_HAZARD_CLOUD_SHADER_H-#define SDL_HAZARD_CLOUD_SHADER_H--#include <string>--// Matches the fragment shader's b0 exactly; all matrices retain the renderer's-// row-major convention. The preview and game use the same constant contract.-struct SdlHazardCloudUniforms {- float WorldFromClip[16];- float CameraPosition[4];- float Viewport[4]; // origin including half pixel, width, height- float Scene[4]; // inverse target size, depth available, seconds- float Field0[4]; // world centre XYZ, horizontal radius- float Field1[4];- float Shape0[4]; // half height, density gain, palette, formation- float Shape1[4];- float Footprints[4]; // field 0/1 fringe beyond hazard radius, reserved ZW- float Source0[4]; // release, outward travel, dissipation, source age- float Source1[4];- float Settings[4]; // active fields, nuclear heat pixels, enabled, maximum steps- float Interaction[4]; // world origin XY, inverse world width/height- float FlowSettings[4]; // enabled, maximum displacement, reserved, reserved- float Cache0[4]; // voxel counts XYZ, atlas slice columns- float Cache1[4];- float CachePass[4]; // field index for cache construction, reserved YZW- float PaletteMain[4][4]; // per-palette main RGB, overall brightness- float PaletteShadow[4][4]; // per-palette shadow RGB, optical thickness multiplier- float Terrain0[4]; // minimum ground Z, maximum ground Z, enabled, reserved- float Terrain1[4];-};-static_assert(sizeof(SdlHazardCloudUniforms) == 480, "hazard volume uniform layout");--std::string SdlHazardCloudVertexShader();-std::string SdlHazardCloudPixelShader(bool composite = false);-std::string SdlHazardCloudCacheShader(bool lighting);-std::string SdlHazardCloudHeatShader();--#endifdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cppnew file mode 100644index 000000000..8014aa2ba--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cpp@@ -0,0 +1,577 @@+// Direct3D 11 backend for the volumetric hazard clouds: the same passes the SDL+// GPU backend records, drawn on the context between two of the backend's draws.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "Platform/HazardCloudCore.h"+#include "Common/Debug.h"+#include "dx11backend.h"+#include "dx11device.h"+#include "dx11runtime.h"++#include <d3d11.h>+#include <algorithm>+#include <cstring>+#include <string>+#include <vector>++namespace {+using namespace HazardCloud;++const DXGI_FORMAT LowFormat = DXGI_FORMAT_R16G16B16A16_FLOAT;+const DXGI_FORMAT DensityFormat = DXGI_FORMAT_R16_FLOAT;+const DXGI_FORMAT FlowFormat = DXGI_FORMAT_R32G32B32A32_FLOAT;+const DXGI_FORMAT TerrainFormat = DXGI_FORMAT_R32_FLOAT;+const unsigned PassCount = 5;+// The texture and sampler slots the cloud text declares (t0-t6, s0-s6).+const unsigned Slots = 7;++template <class T> void drop(T *&object)+{+ if (object) {+ object->Release();+ object = nullptr;+ }+}++struct Surface {+ ID3D11Texture2D *texture = nullptr;+ ID3D11RenderTargetView *target = nullptr;+ ID3D11ShaderResourceView *view = nullptr;+ unsigned width = 0, height = 0;+};++void drop(Surface &surface)+{+ drop(surface.view);+ drop(surface.target);+ drop(surface.texture);+ surface.width = surface.height = 0;+}++bool make(ID3D11Device *device, Surface &surface, unsigned width, unsigned height, DXGI_FORMAT format,+ bool renderTarget)+{+ if (surface.texture && surface.width == width && surface.height == height) return true;+ drop(surface);+ D3D11_TEXTURE2D_DESC description = {};+ description.Width = width;+ description.Height = height;+ description.MipLevels = 1;+ description.ArraySize = 1;+ description.Format = format;+ description.SampleDesc.Count = 1;+ description.Usage = D3D11_USAGE_DEFAULT;+ description.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0);+ if (FAILED(device->CreateTexture2D(&description, nullptr, &surface.texture))+ || FAILED(device->CreateShaderResourceView(surface.texture, nullptr, &surface.view))+ || (renderTarget && FAILED(device->CreateRenderTargetView(surface.texture, nullptr, &surface.target)))) {+ drop(surface);+ return false;+ }+ surface.width = width;+ surface.height = height;+ return true;+}++bool upload(ID3D11DeviceContext *context, ID3D11Buffer *buffer, const void *data, size_t bytes)+{+ D3D11_MAPPED_SUBRESOURCE mapped;+ if (FAILED(context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;+ std::memcpy(mapped.pData, data, bytes);+ context->Unmap(buffer, 0);+ return true;+}++// Programs, states and the screen-sized targets every layer shares, made with+// the first layer and kept until ReleaseDevice.+struct Shared {+ ID3D11Device *device = nullptr;+ bool refused = false;+ ID3D11VertexShader *fullscreen = nullptr;+ ID3D11PixelShader *pixel[PassCount] = {};+ ID3D11VertexShader *emberVertex = nullptr;+ ID3D11PixelShader *emberPixel = nullptr;+ ID3D11SamplerState *point = nullptr;+ ID3D11SamplerState *linear = nullptr;+ ID3D11BlendState *premultiplied = nullptr;+ ID3D11BlendState *additive = nullptr;+ ID3D11RasterizerState *rasterizer = nullptr;+ ID3D11Buffer *constants = nullptr;+ ID3D11Buffer *emberConstants = nullptr;+ ID3D11Buffer *emberPixelConstants = nullptr;+ Surface low;+ // A copy of the scene for the heat haze to bend, at the scene's size and format.+ ID3D11Texture2D *heat = nullptr;+ ID3D11ShaderResourceView *heatView = nullptr;+};+Shared shared;++void releaseShared()+{+ drop(shared.fullscreen);+ for (ID3D11PixelShader *&program : shared.pixel) drop(program);+ drop(shared.emberVertex);+ drop(shared.emberPixel);+ drop(shared.point);+ drop(shared.linear);+ drop(shared.premultiplied);+ drop(shared.additive);+ drop(shared.rasterizer);+ drop(shared.constants);+ drop(shared.emberConstants);+ drop(shared.emberPixelConstants);+ drop(shared.low);+ drop(shared.heatView);+ drop(shared.heat);+ shared = Shared();+}++bool compile(DX11BackendClass *backend, ID3D11Device *device, const std::string &source,+ const char *name, bool vertex, void **program)+{+ std::vector<unsigned char> code;+ if (!backend->Compile_Program(source, name, vertex ? "vs_5_0" : "ps_5_0", code)) {+ DEBUG_LOG(("HAZARDCLOUD: %s did not compile: %s\n", name, backend->First_Compiler_Error()));+ return false;+ }+ return vertex+ ? SUCCEEDED(device->CreateVertexShader(code.data(), code.size(), nullptr, (ID3D11VertexShader **)program))+ : SUCCEEDED(device->CreatePixelShader(code.data(), code.size(), nullptr, (ID3D11PixelShader **)program));+}++bool makeShared(DX11BackendClass *backend, ID3D11Device *device)+{+ if (shared.device == device) return !shared.refused;+ releaseShared();+ shared.device = device;+ static const char *const names[PassCount] = {+ "hazardcloud volume", "hazardcloud composite", "hazardcloud density", "hazardcloud lighting",+ "hazardcloud heat" };+ bool made = compile(backend, device, vertexShader(), "hazardcloud fullscreen", true, (void **)&shared.fullscreen)+ && compile(backend, device, emberVertexShader(false), "hazardcloud embers", true, (void **)&shared.emberVertex)+ && compile(backend, device, emberPixelShader(false), "hazardcloud embers", false, (void **)&shared.emberPixel);+ for (unsigned pass = 0; made && pass < PassCount; ++pass)+ made = compile(backend, device, pixelShader(static_cast<Pass>(pass), false), names[pass], false,+ (void **)&shared.pixel[pass]);++ D3D11_SAMPLER_DESC sampler = {};+ sampler.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;+ sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;+ sampler.ComparisonFunc = D3D11_COMPARISON_NEVER;+ sampler.MaxLOD = D3D11_FLOAT32_MAX;+ made = made && SUCCEEDED(device->CreateSamplerState(&sampler, &shared.point));+ sampler.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;+ made = made && SUCCEEDED(device->CreateSamplerState(&sampler, &shared.linear));++ // Premultiplied radiance over the scene, for the composite and the heat; the+ // embers add light and leave the scene's alpha alone.+ D3D11_BLEND_DESC blend = {};+ D3D11_RENDER_TARGET_BLEND_DESC &target = blend.RenderTarget[0];+ target.BlendEnable = TRUE;+ target.SrcBlend = target.SrcBlendAlpha = D3D11_BLEND_ONE;+ target.DestBlend = target.DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;+ target.BlendOp = target.BlendOpAlpha = D3D11_BLEND_OP_ADD;+ target.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;+ made = made && SUCCEEDED(device->CreateBlendState(&blend, &shared.premultiplied));+ target.DestBlend = D3D11_BLEND_ONE;+ target.SrcBlendAlpha = D3D11_BLEND_ZERO;+ target.DestBlendAlpha = D3D11_BLEND_ONE;+ made = made && SUCCEEDED(device->CreateBlendState(&blend, &shared.additive));++ D3D11_RASTERIZER_DESC rasterizer = {};+ rasterizer.FillMode = D3D11_FILL_SOLID;+ rasterizer.CullMode = D3D11_CULL_NONE;+ rasterizer.DepthClipEnable = TRUE;+ rasterizer.ScissorEnable = TRUE;+ made = made && SUCCEEDED(device->CreateRasterizerState(&rasterizer, &shared.rasterizer));++ D3D11_BUFFER_DESC buffer = {};+ buffer.Usage = D3D11_USAGE_DYNAMIC;+ buffer.BindFlags = D3D11_BIND_CONSTANT_BUFFER;+ buffer.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;+ buffer.ByteWidth = sizeof(Uniforms);+ made = made && SUCCEEDED(device->CreateBuffer(&buffer, nullptr, &shared.constants));+ buffer.ByteWidth = sizeof(EmberConstants);+ made = made && SUCCEEDED(device->CreateBuffer(&buffer, nullptr, &shared.emberConstants));+ buffer.ByteWidth = 16;+ made = made && SUCCEEDED(device->CreateBuffer(&buffer, nullptr, &shared.emberPixelConstants));+ if (!made) {+ DEBUG_LOG(("HAZARDCLOUD: the Direct3D 11 device refused the cloud programs; Classic clouds stay\n"));+ releaseShared();+ shared.device = device;+ shared.refused = true;+ }+ return made;+}++// The heat's copy of the scene, remade when the scene's size or format changes.+bool makeHeatCopy(ID3D11Device *device, ID3D11RenderTargetView *scene, ID3D11Resource *resource)+{+ D3D11_TEXTURE2D_DESC description;+ static_cast<ID3D11Texture2D *>(resource)->GetDesc(&description);+ if (shared.heat) {+ D3D11_TEXTURE2D_DESC held;+ shared.heat->GetDesc(&held);+ if (held.Width == description.Width && held.Height == description.Height && held.Format == description.Format)+ return true;+ drop(shared.heatView);+ drop(shared.heat);+ }+ description.BindFlags = D3D11_BIND_SHADER_RESOURCE;+ description.MiscFlags = 0;+ description.Usage = D3D11_USAGE_DEFAULT;+ description.CPUAccessFlags = 0;+ D3D11_RENDER_TARGET_VIEW_DESC written;+ scene->GetDesc(&written);+ D3D11_SHADER_RESOURCE_VIEW_DESC view = {};+ view.Format = written.Format;+ view.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;+ view.Texture2D.MipLevels = 1;+ if (FAILED(device->CreateTexture2D(&description, nullptr, &shared.heat))+ || FAILED(device->CreateShaderResourceView(shared.heat, &view, &shared.heatView))) {+ drop(shared.heatView);+ drop(shared.heat);+ return false;+ }+ return true;+}++bool supports(ID3D11Device *device, DXGI_FORMAT format, UINT wanted)+{+ UINT support = 0;+ return SUCCEEDED(device->CheckFormatSupport(format, &support)) && (support & wanted) == wanted;+}++class DX11Layer final : public LayerCore {+public:+ ~DX11Layer() override { shutdown(); }+ bool initialize() override;+ bool render(const Camera &camera) override;+ std::uint64_t estimatedCacheBytes() const override;+ void shutdown() override;++private:+ struct FieldCache {+ Surface density, lighting;+ unsigned side = 0;+ };+ bool refuse(const char *reason);+ bool prepareCaches(Uniforms &uniforms);+ void bake(ID3D11DeviceContext *context, ID3D11ShaderResourceView *depth, const Uniforms &uniforms);+ void unbindViews(ID3D11DeviceContext *context);+ void bindViews(ID3D11DeviceContext *context, ID3D11ShaderResourceView *const views[Slots]);++ Surface flowTexture, terrainTexture;+ FieldCache caches[2];+};++bool DX11Layer::refuse(const char *reason)+{+ if (!failed) DEBUG_LOG(("HAZARDCLOUD: Direct3D 11 clouds stopped: %s\n", reason));+ fail(reason);+ return false;+}++bool DX11Layer::initialize()+{+ if (initialized) return !failed;+ DX11DeviceClass *device = Direct3D11_Device();+ DX11BackendClass *backend = Direct3D11_Backend();+ if (!Supported() || !device || !backend) return false;+ failed = false;+ if (!makeShared(backend, device->Get_Device())) return false;+ if (!make(device->Get_Device(), flowTexture, flow.width(), flow.height(), FlowFormat, false))+ return refuse("the interaction texture was refused");+ initialized = true;+ if (!explicitDomain && !fieldCount) flow.setDomain(-400, -220, 400, 220);+ flowDirty = true;+ return true;+}++void DX11Layer::shutdown()+{+ if (!initialized) return;+ drop(flowTexture);+ drop(terrainTexture);+ for (FieldCache &cache : caches) {+ drop(cache.density);+ drop(cache.lighting);+ cache.side = 0;+ }+ initialized = false;+ resetCounters();+}++std::uint64_t DX11Layer::estimatedCacheBytes() const+{+ std::uint64_t result = flowTexture.texture ? 192u * 96u * 4u * sizeof(float) : 0;+ if (terrainTexture.texture) result += TerrainGridSide * TerrainGridSide * 2u * sizeof(float);+ for (const FieldCache &cache : caches)+ result += std::uint64_t(cache.side) * cache.side * CacheSlices * 10u;+ return result;+}++bool DX11Layer::prepareCaches(Uniforms &uniforms)+{+ float *grids[] = { uniforms.Cache0, uniforms.Cache1 };+ for (unsigned i = 0; i < fieldCount; ++i) {+ if (!fieldActive(i)) continue;+ const unsigned side = cacheSide(fieldStates[i]);+ FieldCache &cache = caches[i];+ if (cache.side != side) {+ if (!make(shared.device, cache.density, side * CacheColumns, side * CacheRows, DensityFormat, true)+ || !make(shared.device, cache.lighting, side * CacheColumns, side * CacheRows, LowFormat, true))+ return refuse("the cloud atlases were refused");+ cache.side = side;+ invalidateBake();+ }+ grids[i][0] = grids[i][1] = static_cast<float>(side);+ grids[i][2] = static_cast<float>(CacheSlices);+ grids[i][3] = static_cast<float>(CacheColumns);+ }+ return true;+}++void DX11Layer::unbindViews(ID3D11DeviceContext *context)+{+ ID3D11ShaderResourceView *const none[Slots] = {};+ context->PSSetShaderResources(0, Slots, none);+}++void DX11Layer::bindViews(ID3D11DeviceContext *context, ID3D11ShaderResourceView *const views[Slots])+{+ context->PSSetShaderResources(0, Slots, views);+}++void DX11Layer::bake(ID3D11DeviceContext *context, ID3D11ShaderResourceView *depth, const Uniforms &uniforms)+{+ const float clear[4] = {};+ for (unsigned i = 0; i < fieldCount; ++i) {+ if (!fieldActive(i)) continue;+ const FieldCache &cache = caches[i];+ Uniforms pass = uniforms;+ pass.CachePass[0] = static_cast<float>(i);+ upload(context, shared.constants, &pass, sizeof(pass));+ const D3D11_VIEWPORT viewport = { 0, 0, float(cache.density.width), float(cache.density.height), 0, 1 };+ const D3D11_RECT all = { 0, 0, LONG(cache.density.width), LONG(cache.density.height) };+ context->RSSetViewports(1, &viewport);+ context->RSSetScissorRects(1, &all);++ unbindViews(context);+ context->OMSetRenderTargets(1, &cache.density.target, nullptr);+ context->ClearRenderTargetView(cache.density.target, clear);+ ID3D11ShaderResourceView *const densityViews[Slots] = {+ depth, flowTexture.view, nullptr, nullptr, nullptr, nullptr, terrainTexture.view };+ bindViews(context, densityViews);+ context->PSSetShader(shared.pixel[int(Pass::Density)], nullptr, 0);+ context->Draw(3, 0);++ // Switching the target ends the density pass before the light reads it.+ unbindViews(context);+ context->OMSetRenderTargets(1, &cache.lighting.target, nullptr);+ context->ClearRenderTargetView(cache.lighting.target, clear);+ ID3D11ShaderResourceView *const lightViews[Slots] = {+ depth, flowTexture.view, flowTexture.view, caches[0].density.view, caches[1].density.view, nullptr,+ terrainTexture.view };+ bindViews(context, lightViews);+ context->PSSetShader(shared.pixel[int(Pass::Lighting)], nullptr, 0);+ context->Draw(3, 0);+ }+}++bool DX11Layer::render(const Camera &camera)+{+ if (!initialized || failed || !anyFieldActive()) return false;+ DX11BackendClass *backend = Direct3D11_Backend();+ DX11DeviceClass *device = Direct3D11_Device();+ if (!backend || !device || device->Get_Device() != shared.device)+ return refuse("the Direct3D 11 device was replaced");+ // A mirror or the sun's map: Classic draws there. A screen filter's texture+ // carries the scene's depth, so the clouds go into it.+ ID3D11RenderTargetView *scene = backend->Scene_Target();+ if (!scene) return false;+ ID3D11DeviceContext *context = device->Get_Context();+ ID3D11ShaderResourceView *depth = device->Get_Depth_Texture();+ if (!depth) return refuse("the scene has no readable depth");+ ID3D11Resource *sceneResource = nullptr;+ scene->GetResource(&sceneResource);+ D3D11_TEXTURE2D_DESC sceneDescription;+ static_cast<ID3D11Texture2D *>(sceneResource)->GetDesc(&sceneDescription);+ sceneResource->Release(); // the device's own view keeps it alive+ const unsigned width = sceneDescription.Width, height = sceneDescription.Height;++ Uniforms uniforms;+ float viewProjection[16];+ if (!buildUniforms(camera, width, height, uniforms, viewProjection)) return false;+ if (!make(shared.device, shared.low, width / 2 + width % 2, height / 2 + height % 2, LowFormat, true))+ return refuse("the half resolution target was refused");+ const bool heat = uniforms.Settings[1] > 0;+ if (heat && !makeHeatCopy(shared.device, scene, sceneResource))+ return refuse("the heat haze's copy of the scene was refused");+ if ((terrainEnabled[0] || terrainEnabled[1]) && !terrainTexture.texture) {+ if (!make(shared.device, terrainTexture, TerrainGridSide * 2, TerrainGridSide, TerrainFormat, false))+ return refuse("the terrain height texture was refused");+ terrainDirty = true;+ }+ if (!prepareCaches(uniforms)) return false;++ // Everything below binds on the context behind the backend's back. What it+ // expects to find again is put back at the end, and it forgets the rest.+ // The backend never turns the scissor on, so only the viewport needs keeping.+ D3D11_VIEWPORT savedViewport;+ UINT viewportCount = 1;+ context->RSGetViewports(&viewportCount, &savedViewport);++ if (flowNeedsUpload()) {+ if (!flow.valid()) return refuse("interaction simulation produced invalid state");+ context->UpdateSubresource(flowTexture.texture, 0, nullptr, flow.data(),+ UINT(flow.width() * 4 * sizeof(float)), 0);+ flowUploaded();+ }+ if (terrainDirty && terrainTexture.texture) {+ context->UpdateSubresource(terrainTexture.texture, 0, nullptr, terrainPixels.data(),+ UINT(TerrainGridSide * 2 * sizeof(float)), 0);+ terrainDirty = false;+ invalidateBake();+ }++ ID3D11SamplerState *const samplers[Slots] = {+ shared.point, shared.point, shared.point, shared.linear, shared.linear, shared.linear, shared.point };+ context->IASetInputLayout(nullptr);+ context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);+ context->VSSetShader(shared.fullscreen, nullptr, 0);+ context->RSSetState(shared.rasterizer);+ context->OMSetDepthStencilState(nullptr, 0);+ context->OMSetBlendState(nullptr, nullptr, 0xffffffff);+ context->PSSetSamplers(0, Slots, samplers);+ context->PSSetConstantBuffers(0, 1, &shared.constants);+ if (takeBake(uniforms)) bake(context, depth, uniforms);++ // The volume at half resolution, unblended.+ upload(context, shared.constants, &uniforms, sizeof(uniforms));+ const float clear[4] = {};+ const D3D11_VIEWPORT lowViewport = { 0, 0, float(shared.low.width), float(shared.low.height), 0, 1 };+ const D3D11_RECT lowRect = { 0, 0, LONG(shared.low.width), LONG(shared.low.height) };+ context->RSSetViewports(1, &lowViewport);+ context->RSSetScissorRects(1, &lowRect);+ unbindViews(context);+ context->OMSetRenderTargets(1, &shared.low.target, nullptr);+ context->ClearRenderTargetView(shared.low.target, clear);+ ID3D11ShaderResourceView *const volumeViews[Slots] = {+ depth, flowTexture.view, nullptr, caches[0].lighting.view, caches[1].lighting.view, nullptr,+ terrainTexture.view };+ bindViews(context, volumeViews);+ context->PSSetShader(shared.pixel[int(Pass::Volume)], nullptr, 0);+ context->Draw(3, 0);++ // Up into the scene over the camera's viewport. The depth is read as a+ // texture, so no depth buffer is bound and nothing tests against it.+ const D3D11_VIEWPORT sceneViewport = { float(camera.x), float(camera.y), float(camera.width),+ float(camera.height), camera.minZ, camera.maxZ };+ const LONG right = LONG((std::min)(camera.x + camera.width, width));+ const LONG bottom = LONG((std::min)(camera.y + camera.height, height));+ const D3D11_RECT sceneRect = { LONG(camera.x), LONG(camera.y), right, bottom };+ context->RSSetViewports(1, &sceneViewport);+ context->RSSetScissorRects(1, &sceneRect);+ unbindViews(context);+ context->OMSetRenderTargets(1, &scene, nullptr);+ ID3D11ShaderResourceView *const compositeViews[Slots] = {+ depth, flowTexture.view, shared.low.view, caches[0].lighting.view, caches[1].lighting.view, nullptr,+ terrainTexture.view };+ bindViews(context, compositeViews);+ context->OMSetBlendState(shared.premultiplied, nullptr, 0xffffffff);+ context->PSSetShader(shared.pixel[int(Pass::Composite)], nullptr, 0);+ context->Draw(3, 0);++ // The embers, projected the way the scene is: half a pixel over, as the+ // backend's own viewport sits for Direct3D 9's pixel centres.+ const D3D11_VIEWPORT emberViewport = { float(camera.x) + 0.5f, float(camera.y) + 0.5f, float(camera.width),+ float(camera.height), camera.minZ, camera.maxZ };+ bool embers = false;+ for (unsigned i = 0; i < fieldCount; ++i) {+ if (!emberField(fieldStates[i])) continue;+ EmberConstants constants;+ const unsigned count = emberConstants(fieldStates[i], i, terrainEnabled[i] && terrainTexture.view,+ viewProjection, uniforms.Viewport, simulationTime, constants);+ if (!embers) {+ const float pixelConstants[4] = { 1.0f / width, 1.0f / height, 0, 0 };+ upload(context, shared.emberPixelConstants, pixelConstants, sizeof(pixelConstants));+ context->RSSetViewports(1, &emberViewport);+ context->VSSetShader(shared.emberVertex, nullptr, 0);+ context->VSSetConstantBuffers(0, 1, &shared.emberConstants);+ context->VSSetShaderResources(0, 1, &terrainTexture.view);+ context->VSSetSamplers(0, 1, &shared.point);+ context->PSSetShader(shared.emberPixel, nullptr, 0);+ context->PSSetConstantBuffers(0, 1, &shared.emberPixelConstants);+ context->OMSetBlendState(shared.additive, nullptr, 0xffffffff);+ embers = true;+ }+ upload(context, shared.emberConstants, &constants, sizeof(constants));+ context->Draw(count * 6, 0);+ }+ if (embers) {+ ID3D11ShaderResourceView *const none = nullptr;+ context->VSSetShaderResources(0, 1, &none);+ context->VSSetShader(shared.fullscreen, nullptr, 0);+ context->RSSetViewports(1, &sceneViewport);+ context->PSSetConstantBuffers(0, 1, &shared.constants);+ context->OMSetBlendState(shared.premultiplied, nullptr, 0xffffffff);+ }++ // The nuclear heat bends the scene as it stands now, smoke and embers in it.+ if (heat) {+ int rectangle[4];+ heatScissor(viewProjection, camera, width, height, rectangle);+ if (rectangle[2] > 0 && rectangle[3] > 0) {+ const D3D11_RECT heatRect = { rectangle[0], rectangle[1], rectangle[0] + rectangle[2],+ rectangle[1] + rectangle[3] };+ context->RSSetScissorRects(1, &heatRect);+ ID3D11Resource *source = nullptr;+ scene->GetResource(&source);+ context->CopyResource(shared.heat, source);+ source->Release();+ ID3D11ShaderResourceView *const heatViews[Slots] = {+ depth, flowTexture.view, shared.low.view, caches[0].lighting.view, caches[1].lighting.view,+ shared.heatView, terrainTexture.view };+ bindViews(context, heatViews);+ context->PSSetShader(shared.pixel[int(Pass::Heat)], nullptr, 0);+ context->Draw(3, 0);+ }+ }++ unbindViews(context);+ ID3D11DepthStencilView *sceneDepth = device->Get_Depth_Stencil_View();+ context->OMSetRenderTargets(1, &scene, sceneDepth);+ context->RSSetViewports(viewportCount, &savedViewport);+ backend->Forget_Bindings();+ if (renderedFrameCount++ == 0)+ DEBUG_LOG(("HAZARDCLOUD: Direct3D 11 cloud drawn, palette %d, radius %.0f, %u bakes so far\n",+ int(fieldStates[0].palette + 0.5f), fieldStates[0].radius, bakes()));+ return true;+}++} // namespace++namespace HazardCloud {++bool Supported()+{+ DX11DeviceClass *device = Direct3D11_Device();+ if (!Direct3D11_Present_Is_Enabled() || !Direct3D11_Backend() || !device || !device->Get_Device()+ || !device->Get_Depth_Texture() || device->Get_Device()->GetFeatureLevel() < D3D_FEATURE_LEVEL_11_0)+ return false;+ ID3D11Device *d3d = device->Get_Device();+ const UINT sampled = D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_SHADER_SAMPLE;+ const UINT drawn = sampled | D3D11_FORMAT_SUPPORT_RENDER_TARGET;+ return supports(d3d, LowFormat, drawn) && supports(d3d, DensityFormat, drawn)+ && supports(d3d, FlowFormat, sampled) && supports(d3d, TerrainFormat, sampled);+}++std::unique_ptr<Layer> CreateLayer()+{+ if (!Supported()) return nullptr;+ return std::make_unique<DX11Layer>();+}++void ReleaseDevice() { releaseShared(); }++} // namespace HazardClouddiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cppindex aa3e21260..62071e745 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cpp@@ -1,6 +1,6 @@// Backend-neutral hazard cloud palette and allocation policy.// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#include "Platform/HazardCloud.h"+#include "Platform/HazardCloudCore.h"#include <algorithm>#include <array>@@ -17,15 +17,17 @@ constexpr std::array<Palette, 4> approved = {{{{0.839999974f, 0.629999995f, 1.0f}, {0.192156866f, 0.0470588244f, 0.235294119f}, 1.32000005f, 0.74000001f},}};+} // namespace++// Include both domain boundaries, keep at most two world units between grid+// nodes, and round the dimension up to a small allocation granularity.unsigned cacheSide(const FieldState &field){- const float extent = 2.0f * (field.radius + field.fringe + 18.0f);+ const float extent = 2.0f * (field.radius + field.fringe + MaximumDisplacement);const unsigned samples = static_cast<unsigned>(std::clamp(std::ceil(extent / 2.0f) + 1.0f, 32.0f, 512.0f));return (samples + 15u) & ~15u;}-} // namespace-const Palette &defaultPalette(unsigned index) { return approved[index < 4 ? index : 0]; }std::uint64_t Layer::estimateCacheBytes(const FieldState *fields, unsigned count)diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cppnew file mode 100644index 000000000..a2447971e--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cpp@@ -0,0 +1,466 @@+// The device-free half of the hazard cloud layers, shared by every backend.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "Platform/HazardCloudCore.h"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstring>+#include <initializer_list>++namespace HazardCloud {+namespace {++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;+ }+}++// Visual-only inverse for reconstructing render positions from depth. Double+// intermediates keep distant camera translations stable.+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) std::swap(rows[c][k], rows[pivot][k]);+ 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] = static_cast<float>(rows[r][c + 4]);+ return true;+}++constexpr unsigned MinimumEmbers = 24;+constexpr unsigned MaximumEmbers = 96;+constexpr float ReferenceEmberRadius = 250.0f;++} // namespace++bool emberField(const FieldState &field)+{+ return field.palette >= 0.5f && field.palette < 1.5f && field.density > 0.00001f+ && field.radius > 0.001f && field.height > 0.002f && field.formation > 0.02f;+}++unsigned emberConstants(const FieldState &field, unsigned index, bool terrain,+ const float viewProjection[16], const float viewport[4],+ float timeSeconds, EmberConstants &constants)+{+ const float footprintRadius = field.radius + field.fringe;+ const float areaRatio = footprintRadius * footprintRadius+ / (ReferenceEmberRadius * ReferenceEmberRadius);+ // Match particle density to visible area: 64 at the comparison size,+ // fewer for cannon residue and at most 96 for the large missile field.+ const unsigned count = static_cast<unsigned>(std::clamp(+ std::round(64.0f * areaRatio / 8.0f) * 8.0f,+ static_cast<float>(MinimumEmbers), static_cast<float>(MaximumEmbers)));+ constants = {};+ std::copy(viewProjection, viewProjection + 16, constants.viewProjection);+ std::copy(viewport, viewport + 4, constants.viewport);+ constants.field[0] = field.ground.x;+ constants.field[1] = field.ground.y;+ constants.field[2] = field.ground.z;+ constants.field[3] = footprintRadius;+ constants.shape[0] = field.height;+ constants.shape[1] = field.density;+ constants.shape[2] = field.formation;+ constants.scene[0] = timeSeconds;+ constants.scene[1] = static_cast<float>(count);+ constants.terrain[0] = terrain ? 1.0f : 0.0f;+ constants.terrain[1] = static_cast<float>(index);+ constants.terrain[2] = footprintRadius + MaximumDisplacement;+ return count;+}++void LayerCore::fail(const char *reason)+{+ if (!failed) std::fprintf(stderr, "hazard-cloud: volumetric renderer FAIL: %s\n", reason);+ failed = true;+}++bool LayerCore::fieldActive(unsigned index) const+{+ const FieldState &field = fieldStates[index];+ return index < fieldCount && field.radius > 0.001f && field.height > 0.002f && field.density > 0.00001f;+}++bool LayerCore::anyFieldActive() const+{+ for (unsigned i = 0; i < fieldCount; ++i)+ if (fieldActive(i)) return true;+ return false;+}++void LayerCore::setFields(const FieldState *values, unsigned count)+{+ if (count > 2 || (count && !values)) {+ fail("invalid cloud lifecycle field list");+ return;+ }+ for (unsigned i = 0; i < count; ++i) {+ const FieldState &field = values[i];+ if (!std::isfinite(field.ground.x) || !std::isfinite(field.ground.y)+ || !std::isfinite(field.ground.z) || !std::isfinite(field.radius)+ || !std::isfinite(field.height) || !std::isfinite(field.density)+ || !std::isfinite(field.palette) || !std::isfinite(field.formation)+ || !std::isfinite(field.release) || !std::isfinite(field.fringe)+ || field.fringe < 0 || field.radius < 0 || field.height < 0+ || field.density < 0 || field.palette < 0 || field.palette > 3+ || field.formation < 0 || field.formation > 1 || field.release < 0 || field.release > 1) {+ fail("invalid cloud lifecycle field state");+ return;+ }+ }+ if (!explicitDomain && count) {+ float minX = values[0].ground.x, maxX = minX;+ float minY = values[0].ground.y, maxY = minY;+ for (unsigned i = 0; i < count; ++i) {+ const float radius = (std::max)(1.0f, values[i].radius + values[i].fringe + MaximumDisplacement);+ minX = (std::min)(minX, values[i].ground.x - radius);+ maxX = (std::max)(maxX, values[i].ground.x + radius);+ minY = (std::min)(minY, values[i].ground.y - radius);+ maxY = (std::max)(maxY, values[i].ground.y + radius);+ }+ if (flow.domainMinX() != minX || flow.domainMaxX() != maxX+ || flow.domainMinY() != minY || flow.domainMaxY() != maxY) {+ flow.setDomain(minX, minY, maxX, maxY);+ flowDirty = true;+ }+ }+ fieldCount = count;+ for (unsigned i = 0; i < count; ++i) {+ fieldStates[i] = values[i];+ peakDensity[i] = (std::max)(peakDensity[i], values[i].density);+ }+}++void LayerCore::reset()+{+ flow.reset();+ flowDirty = true;+ for (unsigned i = 0; i < 2; ++i) sourceTravel[i] = sourceAge[i] = peakDensity[i] = 0;+}++void LayerCore::setBodies(const Body *values, unsigned count)+{+ if (count > MaximumBodies || (count && !values)) {+ fail("invalid infantry interaction body list");+ return;+ }+ for (unsigned i = 0; i < count; ++i) {+ const Body &body = values[i];+ if (!std::isfinite(body.x) || !std::isfinite(body.y) || !std::isfinite(body.z)+ || !std::isfinite(body.vx) || !std::isfinite(body.vy)+ || !std::isfinite(body.radius) || !std::isfinite(body.height)+ || body.radius <= 0 || body.height <= 0) {+ fail("invalid infantry interaction body");+ return;+ }+ }+ if (count) bodies.assign(values, values + count);+ else bodies.clear();+}++void LayerCore::setFlowDomain(float minX, float minY, float maxX, float maxY)+{+ flow.setDomain(minX, minY, maxX, maxY);+ explicitDomain = true;+ flowDirty = true;+ if (!flow.valid()) fail("invalid interaction simulation domain");+}++void LayerCore::setTerrain(unsigned index, const float *heights)+{+ if (index >= 2) { fail("invalid terrain field index"); return; }+ if (!heights) {+ terrainEnabled[index] = false;+ terrainMin[index] = terrainMax[index] = 0;+ return;+ }+ float minimum = heights[0], maximum = heights[0];+ for (unsigned i = 0; i < TerrainGridSide * TerrainGridSide; ++i) {+ if (!std::isfinite(heights[i]) || std::abs(heights[i]) > 100000.0f) {+ fail("invalid terrain height");+ return;+ }+ minimum = (std::min)(minimum, heights[i]);+ maximum = (std::max)(maximum, heights[i]);+ }+ bool changed = !terrainEnabled[index];+ for (unsigned y = 0; y < TerrainGridSide; ++y) {+ float *destination = terrainPixels.data() + y * TerrainGridSide * 2 + index * TerrainGridSide;+ const float *source = heights + y * TerrainGridSide;+ changed = changed || std::memcmp(destination, source, TerrainGridSide * sizeof(float)) != 0;+ std::copy(source, source + TerrainGridSide, destination);+ }+ terrainEnabled[index] = true;+ terrainMin[index] = minimum;+ terrainMax[index] = maximum;+ terrainDirty = terrainDirty || changed;+}++void LayerCore::setPalette(unsigned index, const Palette &palette)+{+ const float values[] = { palette.main.r, palette.main.g, palette.main.b,+ palette.shadow.r, palette.shadow.g, palette.shadow.b, palette.brightness, palette.transparency };+ if (index >= 4) { fail("invalid palette index"); return; }+ for (unsigned i = 0; i < 8; ++i)+ if (!std::isfinite(values[i]) || values[i] < 0 || values[i] > (i == 6 ? 2 : 1)) {+ fail("invalid palette value");+ return;+ }+ palettes[index] = palette;+}++void LayerCore::setInteractionEnabled(bool value)+{+ if (interactionEnabled == value) return;+ interactionEnabled = value;+ flow.reset();+ flowDirty = true;+}++void LayerCore::update(float timeSeconds)+{+ if (!std::isfinite(timeSeconds) || timeSeconds < 0) {+ fail("invalid simulation time");+ return;+ }+ const float elapsed = hasSimulationTime ? timeSeconds - simulationTime : 0.0f;+ simulationTime = timeSeconds;+ hasSimulationTime = true;+ if (elapsed < 0) {+ reset();+ } else if (elapsed > 0 && !failed) {+ for (unsigned i = 0; i < fieldCount; ++i) {+ sourceAge[i] += elapsed;+ sourceTravel[i] += elapsed * fieldStates[i].release * 22.0f;+ }+ // Appearance only controls drawing. Keep the same wake history while+ // the original effects are shown, so toggling back is an in-place A/B.+ // A grid with nothing stirring it and nothing left to heal stays as it+ // is, so a quiet cloud uploads nothing and rebakes only as it ages.+ bool stirring = false;+ for (const Body &body : bodies)+ stirring = stirring || body.vx * body.vx + body.vy * body.vy > 0.02f * 0.02f;+ if (interactionEnabled && (stirring || flow.maxDisturbance() > 0.0f)) {+ flow.step(elapsed, bodies.empty() ? nullptr : bodies.data(),+ static_cast<unsigned>(bodies.size()));+ if (!flow.valid()) fail("interaction simulation produced invalid state");+ // Healed to under a fiftieth of a world unit: put it at rest.+ if (!stirring && flow.maxDisturbance() < 0.001f) flow.reset();+ flowDirty = true;+ }+ }+}++bool LayerCore::buildUniforms(const Camera &camera, unsigned targetWidth, unsigned targetHeight,+ Uniforms &uniforms, float viewProjection[16])+{+ if (!camera.width || !camera.height || !targetWidth || !targetHeight) {+ fail("the scene camera has an empty viewport");+ return false;+ }+ uniforms = {};+ float inverseView[16];+ multiply(camera.view, camera.projection, viewProjection);+ if (!inverse(viewProjection, uniforms.WorldFromClip) || !inverse(camera.view, inverseView)) {+ fail("scene camera has a singular transform");+ return false;+ }+ const float depthRange = camera.maxZ - camera.minZ;+ if (depthRange <= 1.0e-8f) {+ fail("scene camera has an empty depth range");+ return false;+ }+ for (unsigned column = 0; column < 4; ++column) {+ const float row = uniforms.WorldFromClip[8 + column] / depthRange;+ uniforms.WorldFromClip[12 + column] -= camera.minZ * row;+ uniforms.WorldFromClip[8 + column] = row;+ }+ for (unsigned i = 0; i < 3; ++i) uniforms.CameraPosition[i] = inverseView[12 + i];+ uniforms.CameraPosition[3] = 1;+ uniforms.Viewport[0] = static_cast<float>(camera.x) + 0.5f;+ uniforms.Viewport[1] = static_cast<float>(camera.y) + 0.5f;+ uniforms.Viewport[2] = static_cast<float>(camera.width);+ uniforms.Viewport[3] = static_cast<float>(camera.height);+ uniforms.Scene[0] = 1.0f / targetWidth;+ uniforms.Scene[1] = 1.0f / targetHeight;+ uniforms.Scene[2] = 1;+ uniforms.Scene[3] = simulationTime;+ float *fields[] = { uniforms.Field0, uniforms.Field1 };+ float *shapes[] = { uniforms.Shape0, uniforms.Shape1 };+ float *sources[] = { uniforms.Source0, uniforms.Source1 };+ bool hotField = false;+ for (unsigned i = 0; i < fieldCount; ++i) {+ const FieldState &field = fieldStates[i];+ hotField = hotField || (field.palette >= 0.5f && field.palette < 1.5f && fieldActive(i));+ fields[i][0] = field.ground.x;+ fields[i][1] = field.ground.y;+ fields[i][2] = field.ground.z + field.height * 0.5f;+ fields[i][3] = field.radius;+ shapes[i][0] = field.height * 0.5f;+ shapes[i][1] = field.density;+ shapes[i][2] = field.palette;+ shapes[i][3] = field.formation;+ uniforms.Footprints[i] = field.fringe;+ sources[i][0] = field.release;+ sources[i][1] = sourceTravel[i];+ sources[i][2] = peakDensity[i] > 0.0001f+ ? (std::max)(0.0f, 1.0f - field.density / peakDensity[i]) : 0.0f;+ sources[i][3] = sourceAge[i];+ }+ float *terrain[] = { uniforms.Terrain0, uniforms.Terrain1 };+ for (unsigned i = 0; i < 2; ++i) {+ terrain[i][0] = terrainMin[i];+ terrain[i][1] = terrainMax[i];+ terrain[i][2] = terrainEnabled[i] ? 1.0f : 0.0f;+ }+ uniforms.Settings[0] = static_cast<float>(fieldCount);+ for (unsigned i = 0; i < 4; ++i) {+ const Palette &palette = palettes[i];+ uniforms.PaletteMain[i][0] = palette.main.r;+ uniforms.PaletteMain[i][1] = palette.main.g;+ uniforms.PaletteMain[i][2] = palette.main.b;+ uniforms.PaletteMain[i][3] = palette.brightness;+ uniforms.PaletteShadow[i][0] = palette.shadow.r;+ uniforms.PaletteShadow[i][1] = palette.shadow.g;+ uniforms.PaletteShadow[i][2] = palette.shadow.b;+ uniforms.PaletteShadow[i][3] = 1.0f - palette.transparency;+ }+ // Visible hot-air refraction only for the warm nuclear palette.+ uniforms.Settings[1] = heatEnabled && hotField ? 10.0f : 0.0f;+ uniforms.Settings[2] = 1;+ uniforms.Settings[3] = Steps;+ uniforms.Interaction[0] = flow.domainMinX();+ uniforms.Interaction[1] = flow.domainMinY();+ uniforms.Interaction[2] = 1.0f / (flow.domainMaxX() - flow.domainMinX());+ uniforms.Interaction[3] = 1.0f / (flow.domainMaxY() - flow.domainMinY());+ uniforms.FlowSettings[0] = interactionEnabled ? 1.0f : 0.0f;+ uniforms.FlowSettings[1] = MaximumDisplacement;+ return true;+}++bool LayerCore::takeBake(const Uniforms &uniforms)+{+ // Nothing the camera does reaches the atlases: orbiting, zooming, resizing+ // or drawing a paused frame reuses the same world-space volume.+ Uniforms inputs = uniforms;+ std::fill(inputs.WorldFromClip, inputs.WorldFromClip + 16, 0.0f);+ std::fill(inputs.CameraPosition, inputs.CameraPosition + 4, 0.0f);+ std::fill(inputs.Viewport, inputs.Viewport + 4, 0.0f);+ std::fill(inputs.Scene, inputs.Scene + 4, 0.0f);+ inputs.Settings[1] = inputs.Settings[3] = 0;+ std::fill(inputs.CachePass, inputs.CachePass + 4, 0.0f);+ const long long tick = static_cast<long long>(std::floor(simulationTime * BakesPerSecond));+ bool bake = !cachedInputsValid;+ if (!bake && (cachedFlowUploads != flowUploads+ || std::memcmp(&inputs, &cachedInputs, sizeof(inputs)) != 0)) {+ // What a cloud does on its own as it ages: its density, its formation+ // front and its source history. Anything else that differs is a change+ // the next frame has to show.+ Uniforms structure = inputs, cachedStructure = cachedInputs;+ for (Uniforms *u : { &structure, &cachedStructure }) {+ u->Shape0[1] = u->Shape0[3] = u->Shape1[1] = u->Shape1[3] = 0;+ std::fill(u->Source0, u->Source0 + 4, 0.0f);+ std::fill(u->Source1, u->Source1 + 4, 0.0f);+ }+ bake = std::memcmp(&structure, &cachedStructure, sizeof(structure)) != 0+ || tick != cachedBakeTick;+ }+ if (!bake) return false;+ cachedInputs = inputs;+ cachedFlowUploads = flowUploads;+ cachedBakeTick = tick;+ cachedInputsValid = true;+ ++cacheBakes;+ return true;+}++void LayerCore::heatScissor(const float viewProjection[16], const Camera &camera,+ unsigned targetWidth, unsigned targetHeight, int rectangle[4]) const+{+ const float left = static_cast<float>((std::min)(camera.x, targetWidth));+ const float top = static_cast<float>((std::min)(camera.y, targetHeight));+ const float right = left + (std::min)(camera.width, targetWidth - static_cast<unsigned>(left));+ const float bottom = top + (std::min)(camera.height, targetHeight - static_cast<unsigned>(top));+ rectangle[0] = static_cast<int>(left);+ rectangle[1] = static_cast<int>(top);+ rectangle[2] = static_cast<int>(right - left);+ rectangle[3] = static_cast<int>(bottom - top);+ float minX = 1.0e30f, minY = 1.0e30f, maxX = -1.0e30f, maxY = -1.0e30f;+ bool found = false;+ for (unsigned i = 0; i < fieldCount; ++i) {+ const FieldState &field = fieldStates[i];+ if (field.palette < 0.5f || field.palette >= 1.5f || !fieldActive(i)) continue;+ found = true;+ const float radius = field.radius + field.fringe + MaximumDisplacement;+ for (unsigned corner = 0; corner < 8; ++corner) {+ const float world[4] = {+ field.ground.x + (corner & 1 ? radius : -radius),+ field.ground.y + (corner & 2 ? radius : -radius),+ (terrainEnabled[i] ? (corner & 4 ? terrainMax[i] : terrainMin[i]) : field.ground.z)+ + (corner & 4 ? field.height * 2.6f : 0.0f), 1.0f+ };+ float clip[4] = {};+ for (unsigned column = 0; column < 4; ++column)+ for (unsigned row = 0; row < 4; ++row)+ clip[column] += world[row] * viewProjection[row * 4 + column];+ // A box crossing the near plane cannot be bounded by projecting+ // only its corners. Keep the full viewport for that unusual view.+ if (!std::isfinite(clip[0]) || !std::isfinite(clip[1])+ || !std::isfinite(clip[2]) || !std::isfinite(clip[3])+ || clip[3] <= 0.00001f || clip[2] <= 0.00001f) return;+ const float x = camera.x + 0.5f + (clip[0] / clip[3] + 1.0f) * camera.width * 0.5f;+ const float y = camera.y + 0.5f + (1.0f - clip[1] / clip[3]) * camera.height * 0.5f;+ minX = (std::min)(minX, x); maxX = (std::max)(maxX, x);+ minY = (std::min)(minY, y); maxY = (std::max)(maxY, y);+ }+ }+ if (!found) { rectangle[2] = rectangle[3] = 0; return; }+ // Two pixels of conservative rasterization slack keep the projected+ // envelope intact at viewport edges and odd framebuffer dimensions.+ const float boundedLeft = std::clamp(std::floor(minX) - 2.0f, left, right);+ const float boundedTop = std::clamp(std::floor(minY) - 2.0f, top, bottom);+ const float boundedRight = std::clamp(std::ceil(maxX) + 2.0f, left, right);+ const float boundedBottom = std::clamp(std::ceil(maxY) + 2.0f, top, bottom);+ rectangle[0] = static_cast<int>(boundedLeft);+ rectangle[1] = static_cast<int>(boundedTop);+ rectangle[2] = static_cast<int>((std::max)(0.0f, boundedRight - boundedLeft));+ rectangle[3] = static_cast<int>((std::max)(0.0f, boundedBottom - boundedTop));+}++void LayerCore::resetCounters()+{+ cachedInputsValid = false;+ cachedInputs = {};+ cachedFlowUploads = cacheBakes = 0;+ cachedBakeTick = 0;+ renderedFrameCount = flowUploads = 0;+ flowDirty = true;+ hasSimulationTime = false;+ terrainDirty = terrainEnabled[0] || terrainEnabled[1];+ bodies.clear();+ reset();+}++} // namespace HazardClouddiff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cppsimilarity index 82%rename from GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.cpprename to GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cppindex 07e356f28..57edda403 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudShader.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudShader.cpp@@ -1,19 +1,22 @@-// Shared bounded world-space density integrated along each camera ray.+// Shared bounded world-space density integrated along each camera ray, and the+// nuclear embers drawn over it. One text for every backend.// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#include "SdlHazardCloudShader.h"+#include "Platform/HazardCloudCore.h"-std::string SdlHazardCloudVertexShader()-{- return R"HLSL(-float4 main(uint vertex : SV_VertexID) : SV_Position+namespace HazardCloud {+namespace {++// ", spaceN" out of every register(): SDL GPU's resource sets, which FXC refuses.+std::string withSpaces(std::string source, bool registerSpaces){- float2 uv = float2((vertex << 1) & 2, vertex & 2);- return float4(uv * float2(2, -2) + float2(-1, 1), 0, 1);-}-)HLSL";+ if (registerSpaces) return source;+ for (std::size_t at = source.find(", space"); at != std::string::npos; at = source.find(", space", at))+ source.erase(at, 8);+ return source;}-static std::string cloudShader(int pass)+// The text is cut into several literals: MSVC refuses one longer than 16 KB (C2026).+std::string cloudShader(int pass){return std::string(pass == 1 ? "#define CLOUD_COMPOSITE 1\n" : "#define CLOUD_COMPOSITE 0\n")+ "#define CLOUD_HEAT_PASS " + std::to_string(pass == 4 ? 1 : 0) + "\n"@@ -197,6 +200,7 @@ float volumeBillows(float2 p, float h, float erosion)return largest * 0.55 + total * 0.45;}+)HLSL" R"HLSL(// The hazard radius controls readable coverage. The separate soft fringe matches// the original renderer's textured puddles, which extend beyond their centres.float volumeDensity(float3 world, float4 field, float4 shape, float4 source, float fringe, float identity)@@ -342,6 +346,7 @@ void volumeSample(float3 world, float4 field, float4 shape, float4 source, floatlight += coefficients.rgb;}+)HLSL" R"HLSL(#if CLOUD_CACHE_PASSfloat4 volumeBuildCache(float2 pixel){@@ -502,6 +507,7 @@ float2 volumeFullPixel(float2 lowPixel)return min(floor(lowPixel) * 2.0 + 1.5, round(1.0 / Scene.xy) - 0.5);}+)HLSL" R"HLSL(#if CLOUD_COMPOSITE || CLOUD_HEAT_PASSfloat volumeDepthSlope(float2 pixel, float depth, float2 axis, float maximumStep){@@ -631,6 +637,7 @@ float4 volumeHeatColour(float2 pixel, float depth, float3 opaqueWorld, float2 sl}#endif+)HLSL" R"HLSL(float4 main(float4 position : SV_Position) : SV_Target{#if CLOUD_HEAT_PASS@@ -695,17 +702,156 @@ float4 main(float4 position : SV_Position) : SV_Target)HLSL";}-std::string SdlHazardCloudPixelShader(bool composite)+// Sparse nuclear embers. No assets, gameplay particles or damage are involved.+const char *emberVertexSource = R"HLSL(+Texture2D<float> TerrainHeight : register(t0, space0);+SamplerState TerrainSampler : register(s0, space0);+cbuffer EmberConstants : register(b0, space1){- return cloudShader(composite ? 1 : 0);+ row_major float4x4 ViewProjection;+ float4 Viewport;+ float4 Field;+ float4 Shape;+ float4 Scene;+ float4 Terrain;+};+struct EmberVertex {+ float4 position : SV_Position;+ float2 local : TEXCOORD0;+ float2 glow : TEXCOORD1;+};+float emberHash(float seed)+{+ float3 p = frac(float3(seed, seed + 1.0, seed + 2.0) * 0.1031);+ p += dot(p, p.yzx + 33.33);+ return frac((p.x + p.y) * p.z);+}+float emberGround(float2 world)+{+ if (Terrain.x < 0.5) return Field.z;+ uint width, height;+ TerrainHeight.GetDimensions(width, height);+ float side = float(height);+ float2 uv = saturate((world - Field.xy) / max(Terrain.z * 2.0, 0.001) + 0.5);+ float2 texel = uv * (side - 1.0);+ float2 lower = floor(texel), upper = min(lower + 1.0, side - 1.0);+ float2 weight = frac(texel);+ float2 a = (lower + float2(Terrain.y * side, 0) + 0.5) / float2(width, height);+ float2 b = (upper + float2(Terrain.y * side, 0) + 0.5) / float2(width, height);+ float low = lerp(TerrainHeight.SampleLevel(TerrainSampler, a, 0),+ TerrainHeight.SampleLevel(TerrainSampler, float2(b.x, a.y), 0), weight.x);+ float high = lerp(TerrainHeight.SampleLevel(TerrainSampler, float2(a.x, b.y), 0),+ TerrainHeight.SampleLevel(TerrainSampler, b, 0), weight.x);+ return lerp(low, high, weight.y);}+EmberVertex main(uint vertex : SV_VertexID)+{+ uint particle = vertex / 6;+ uint corner = vertex % 6;+ float2 local;+ if (corner == 0 || corner == 3) local = float2(-1, -1);+ else if (corner == 1) local = float2(1, -1);+ else if (corner == 2 || corner == 4) local = float2(1, 1);+ else local = float2(-1, 1);++ float seed = float(particle) * 13.61 + Field.x * 0.21 + Field.y * 0.37;+ float random = emberHash(seed + 7.0);+ float lifetime = 3.4 + emberHash(seed + 2.0) * 2.8;+ float age = frac(Scene.x / lifetime + emberHash(seed + 19.0));+ // One anchor per equal-area radial stratum, separated by the golden angle.+ // Slight jitter breaks the spiral's regularity without random clustering.+ // Field.w includes the cloud's visual fringe. Its whole footprint ignites+ // together; formation controls opacity rather than moving sparks outward.+ float rotation = emberHash(Field.x * 0.21 + Field.y * 0.37 + 3.0) * 6.2831853;+ float angle = float(particle) * 2.39996323 + rotation+ + (emberHash(seed + 11.0) - 0.5) * 0.12;+ float stratum = (float(particle) + 0.35 + emberHash(seed + 1.0) * 0.30) / max(Scene.y, 1.0);+ float radius = sqrt(stratum) * Field.w;+ float2 origin = Field.xy + float2(cos(angle), sin(angle)) * radius;+ float2 drift = float2(sin(age * 5.0 + seed), cos(age * 4.0 + seed * 0.7));+ drift *= (2.0 + random * 5.0) * age;+ drift += float2(3.0, -1.0) * age * age;+ float height = Shape.x * (0.36 + age * (1.8 + random * 0.6));+ float3 world = float3(origin + drift, emberGround(origin + drift) + height);+ float4 clip = mul(float4(world, 1), ViewProjection);+ float4 upClip = mul(float4(world + float3(0, 0, 1), 1), ViewProjection);+ float2 up = (upClip.xy / max(upClip.w, 0.0001) - clip.xy / max(clip.w, 0.0001))+ * Viewport.zw * float2(0.5, -0.5);+ up = dot(up, up) > 0.00001 ? normalize(up) : float2(0, -1);+ float2 across = float2(-up.y, up.x);+ // The bright core is roughly 1-2 pixels across at the default view, with+ // a softer orange halo and a short tail pointing down its rising path.+ float zoom = clamp(sqrt(max(Viewport.z * Viewport.w, 1.0) / 1024000.0), 0.8, 1.7);+ float2 extent = float2(2.3 + random * 1.1, 3.0 + random * 2.5) * zoom;+ float2 pixelOffset = across * local.x * extent.x + up * local.y * extent.y;+ clip.xy += pixelOffset * float2(2, -2) / max(Viewport.zw, float2(1, 1)) * clip.w;+ float fade = smoothstep(0.0, 0.14, age) * (1.0 - smoothstep(0.58, 1.0, age));+ fade *= saturate(Shape.y * 1.6) * smoothstep(0.02, 0.28, Shape.z);+ fade *= lerp(0.58, 1.0, random) * lerp(0.55, 1.0, smoothstep(0.5, 1.1, height / Shape.x));+ // Keep the outer annulus legible. Only the last few percent of outward+ // drift die away, so the soft cloud fringe does not become a hard spark ring.+ float edgeRadius = length(world.xy - Field.xy) / max(Field.w, 0.001);+ fade *= (1.0 - 0.40 * smoothstep(0.88, 1.0, edgeRadius))+ * (1.0 - smoothstep(1.0, 1.055, edgeRadius));+ EmberVertex output;+ output.position = clip;+ output.local = local;+ output.glow = float2(fade, random);+ return output;+}+)HLSL";++const char *emberPixelSource = R"HLSL(+Texture2D<float> SceneDepth : register(t0, space2);+SamplerState DepthSampler : register(s0, space2);+cbuffer EmberPixelConstants : register(b0, space3) { float4 Scene; };+struct EmberVertex {+ float4 position : SV_Position;+ float2 local : TEXCOORD0;+ float2 glow : TEXCOORD1;+};+float4 main(EmberVertex input) : SV_Target+{+ float depth = SceneDepth.SampleLevel(DepthSampler, input.position.xy * Scene.xy, 0);+ // Use the same captured opaque depth as the volume: terrain and infantry+ // hide sparks behind them, while this pass never writes the scene depth.+ clip(depth - input.position.z + 0.0000005);+ float2 corePoint = (input.local - float2(0, 0.30)) * float2(1, 1.6);+ float squared = dot(corePoint, corePoint);+ float core = exp2(-squared * 12.0);+ float halo = exp2(-squared * 3.0);+ float tail = (1.0 - smoothstep(0.10, 0.34, abs(input.local.x)))+ * smoothstep(-1.0, -0.30, input.local.y)+ * (1.0 - smoothstep(-0.18, 0.30, input.local.y));+ float edge = (1.0 - smoothstep(0.80, 1.0, abs(input.local.x)))+ * (1.0 - smoothstep(0.85, 1.0, abs(input.local.y)));+ float3 warm = lerp(float3(1.0, 0.21, 0.025), float3(1.0, 0.43, 0.08), input.glow.y);+ float3 light = float3(1.0, 0.80, 0.43) * core * 0.95 + warm * (halo * 0.30 + tail * 0.17);+ return float4(light * input.glow.x * edge, 0);+}+)HLSL";-std::string SdlHazardCloudCacheShader(bool lighting)+} // namespace++std::string vertexShader(){- return cloudShader(lighting ? 3 : 2);+ return R"HLSL(+float4 main(uint vertex : SV_VertexID) : SV_Position+{+ float2 uv = float2((vertex << 1) & 2, vertex & 2);+ return float4(uv * float2(2, -2) + float2(-1, 1), 0, 1);+}+)HLSL";}-std::string SdlHazardCloudHeatShader()+std::string pixelShader(Pass pass, bool registerSpaces){- return cloudShader(4);+ const int number = pass == Pass::Composite ? 1 : pass == Pass::Density ? 2+ : pass == Pass::Lighting ? 3 : pass == Pass::Heat ? 4 : 0;+ return withSpaces(cloudShader(number), registerSpaces);}++std::string emberVertexShader(bool registerSpaces) { return withSpaces(emberVertexSource, registerSpaces); }+std::string emberPixelShader(bool registerSpaces) { return withSpaces(emberPixelSource, registerSpaces); }++} // namespace HazardClouddiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cppindex bbd1db647..278be1492 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HazardCloudUnsupported.cpp@@ -1,5 +1,5 @@-// Entry points for builds without a hazard cloud renderer backend.-// Replace this implementation when adding a Direct3D 11 backend.+// 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.// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.#include "Platform/HazardCloud.h"@@ -7,5 +7,6 @@ namespace HazardCloud {bool Supported() { return false; }std::unique_ptr<Layer> CreateLayer() { return nullptr; }+void ReleaseDevice() {}} // namespace HazardClouddiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cppindex 9bd9a1e3c..cc99ab84d 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp@@ -41,6 +41,7 @@#include "W3DDevice/GameClient/W3DDynamicLight.h"#include "W3DDevice/GameClient/W3DWater.h"#include "WW3D2/camera.h"+#include "WW3D2/ww3d.h"#include "W3DDevice/GameClient/W3DSmoothMotion.h"#include "WW3D2/dx8wrapper.h"#include "WW3D2/dx11runtime.h"@@ -715,9 +716,13 @@ static const Real FIELD_GAIN = 0.7f; ///< of the template's brightest colostatic const Int FIELD_FADE_IN = LOGICFRAMES_PER_SECOND / 2; ///< logic framesstatic const Int FIELD_FADE_OUT = 3 * LOGICFRAMES_PER_SECOND; ///< logic frames before the field object diesstatic const Int FIELD_FADE_GONE = FIELD_FADE_OUT; ///< logic frames, a field fogged over or whose object went early-// Stable until device resources are released. FieldKey ordering must never query-// a live device: changing its answer while keys exist would invalidate the map.+// Whether the fields are tracked the way the volumetric clouds need them: a+// backend that draws them, and the Volumetric style chosen. Classic keeps the+// retail keys, owner choice, grace and initial delay on every platform. Changed+// only at the sync point (fieldCloudsSupported), never in the render, because+// FieldKey ordering reads it and changing it while keys exist invalidates the map.static bool s_fieldCloudsSupported = false;+static bool s_fieldCloudCapability = false; ///< the device's answer, asked once per devicestatic bool s_fieldCloudCapabilityKnown = false;static bool fieldCloudsSupported();@@ -787,16 +792,19 @@ static unsigned s_fieldCollectionPass = 0;static bool fieldCloudsSupported(){if (!s_fieldCloudCapabilityKnown) {- const bool supported = HazardCloud::Supported();- // In particular, a previously unavailable device may now have a backend.- // Destroy keys before changing their comparator's mode.- if (supported != s_fieldCloudsSupported) {- s_fieldStates.clear();- s_fieldSystemOwners.clear();- }- s_fieldCloudsSupported = supported;+ s_fieldCloudCapability = HazardCloud::Supported();s_fieldCloudCapabilityKnown = true;}+ // The Classic graphics setting is the game's own picture, and its clouds.+ const bool volumetric = s_fieldCloudCapability && TheGlobalData+ && TheGlobalData->m_cloudStyle == 1 && !TheGlobalData->m_classicGraphics;+ // A new device, or the style switched: destroy keys before changing their+ // comparator's mode.+ if (volumetric != s_fieldCloudsSupported) {+ s_fieldStates.clear();+ s_fieldSystemOwners.clear();+ s_fieldCloudsSupported = volumetric;+ }return s_fieldCloudsSupported;}static Bool s_fieldSkipNextFadeIn = FALSE;@@ -951,7 +959,7 @@ bool isCloudMainPass()bool modernCloudsEnabled(){- return fieldCloudsSupported() && TheGlobalData && TheGlobalData->m_cloudStyle == 1 && isCloudMainPass();+ return s_fieldCloudsSupported && isCloudMainPass();}void releaseCloudLayers()@@ -964,7 +972,7 @@ void releaseCloudLayers()void beginCloudPass(unsigned now){- if (!fieldCloudsSupported() || !TheGlobalData || TheGlobalData->m_cloudStyle != 1) {+ if (!s_fieldCloudsSupported) {releaseCloudLayers();return;}@@ -1025,7 +1033,34 @@ bool updateCloudTerrain(CloudLayer &slot, const HazardCloud::FieldState &field,return true;}-bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float seconds, int now)+/** The camera the scene is drawn from, in the device's layout, from the camera itself: the+ * device's transforms can be whatever the last draw left until the next state flush. */+HazardCloud::Camera cloudCamera(CameraClass &camera)+{+ HazardCloud::Camera result;+ Matrix4x4 projection;+ camera.Get_D3D_Projection_Matrix(&projection);+ Matrix3D view;+ camera.Get_View_Matrix(&view);+ const Matrix4x4 d3dProjection = projection.Transpose();+ const Matrix4x4 d3dView = Matrix4x4(view).Transpose();+ memcpy(result.view, &d3dView, sizeof(result.view));+ memcpy(result.projection, &d3dProjection, sizeof(result.projection));+ // as CameraClass::Apply sets the device's viewport+ int width, height, bits;+ bool windowed;+ WW3D::Get_Render_Target_Resolution(width, height, bits, windowed);+ const ViewportClass &viewport = camera.Get_Viewport();+ result.x = (unsigned)(viewport.Min.X * (float)width);+ result.y = (unsigned)(viewport.Min.Y * (float)height);+ result.width = (unsigned)((viewport.Max.X - viewport.Min.X) * (float)width);+ result.height = (unsigned)((viewport.Max.Y - viewport.Min.Y) * (float)height);+ camera.Get_Depth_Range(&result.minZ, &result.maxZ);+ return result;+}++bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float seconds, int now,+ const HazardCloud::Camera &camera){if (!modernCloudsEnabled() || key.palette < 0) return false;if (s_cloudDraws >= MaxCloudLayers) return false;@@ -1123,9 +1158,10 @@ bool drawModernCloud(const FieldKey &key, FieldState &state, float fade, float sif (count < bodies.size()) bodies[count++] = body;}slot->renderer->setBodies(bodies.data(), count);+ slot->renderer->setHeatEnabled(TheGlobalData->m_useHeatEffects != FALSE);slot->renderer->update(seconds);slot->used = s_cloudPass;- if (!slot->renderer->render()) return false;+ if (!slot->renderer->render(camera)) return false;++s_cloudDraws;return true;}@@ -1280,14 +1316,13 @@ static void updateGroundFields( const std::vector<ParticleSystem *> &systems )if (obj) if (auto *life = static_cast<LifetimeUpdate *>(obj->findUpdateModule(key_cloudLife)))state.cloudDieFrame = Int(life->getDieFrame());}- if (TheGlobalData && TheGlobalData->m_cloudStyle == 1)- updateCloudBodies((unsigned)now);+ updateCloudBodies((unsigned)now);}}/** Lays the fields updateGroundFields found on the terrain into the field buffers; drawGroundFields* draws them. Returns the puddles laid. */-static Int collectGroundFields( const AABoxClass &view )+static Int collectGroundFields( const AABoxClass &view, CameraClass &sceneCamera ){const Int now = (Int)TheGameLogic->getFrame();// between the last two logic ticks, as the models are, so a pulse does not step at the logic rate@@ -1295,6 +1330,7 @@ static Int collectGroundFields( const AABoxClass &view )s_fieldPuddles.clear();s_fieldDraws.clear();beginCloudPass(now);+ const HazardCloud::Camera camera = cloudCamera( sceneCamera );Int laid = 0;for (std::map<FieldKey, FieldState>::iterator st = s_fieldStates.begin(); st != s_fieldStates.end(); ++st)@@ -1319,7 +1355,7 @@ static Int collectGroundFields( const AABoxClass &view )&& WWMath::Fabs( state.centre.y - view.Center.Y ) <= view.Extent.Y + reach&& (groundVolume || WWMath::Fabs( state.centre.z - view.Center.Z ) <= view.Extent.Z + reach);if (visible) {- if (drawModernCloud(key, state, fade, seconds, now)) {+ if (drawModernCloud(key, state, fade, seconds, now, camera)) {// Preserve the client's existing area-effect particle ceiling even// though the replacement does not build the old puddle geometry.const Real spread = state.radius / size;@@ -1660,7 +1696,9 @@ void W3DParticleSystemManager::reset()void W3DParticleSystemManager::invalidateGroundFields(bool fadeIn){- releaseCloudResources();+ // The layers' fields and wakes belong to the game that ended; the programs the+ // layers share stay, so the next map's first hazard compiles nothing.+ releaseCloudLayers();// Ground draw buffers are rebuilt by the next collect/draw; their texture// references are already released at the end of each draw. Only this map// persists the footprint after an emitter is removed or changes appearance.@@ -1672,6 +1710,7 @@ void W3DParticleSystemManager::invalidateGroundFields(bool fadeIn)void W3DParticleSystemManager::releaseCloudResources(){releaseCloudLayers();+ HazardCloud::ReleaseDevice();// Query the replacement device at the next sync point. The helper clears// keys before changing their ordering if support changed; unchanged support// retains field ages/owner bindings across a resize or device reset.@@ -1990,7 +2029,7 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)s_fieldIndex.clear();s_fieldChunks.clear();{- const Int puddles = collectGroundFields( bbox );+ const Int puddles = collectGroundFields( bbox, rinfo.Camera );// counted as field particles on purpose: past MaxFieldParticleCount the field systems keep// one particle each, and that one is all the steady pool needs from themm_fieldParticleCount += puddles;diff --git a/GeneralsMD/Code/Libraries/Include/Platform/HazardCloud.h b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloud.hindex 9eaa91a0e..a500d4246 100644--- a/GeneralsMD/Code/Libraries/Include/Platform/HazardCloud.h+++ b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloud.h@@ -34,6 +34,17 @@ struct Palette {// Stable user-approved palette, independent of preview files or game options.const Palette &defaultPalette(unsigned index);+// The scene camera a cloud is drawn from, handed over by the caller rather than+// read back from the device, whose transforms can be the last draw's until the+// next state flush. Matrices are row-major in the Direct3D layout (row vectors,+// world * view * projection); the viewport is in target pixels.+struct Camera {+ float view[16];+ float projection[16];+ unsigned x, y, width, height;+ float minZ, maxZ;+};+// Main render thread only. Owns up to two fields with independent density,// lighting and infantry-wake history. Pipelines and transient scene targets are// shared by all layers on the same device. No scene object is registered.@@ -67,7 +78,7 @@ public:// Call only in the main scene after opaque geometry/water. False means no// cloud scene draw was recorded, so the caller may draw classic effects.- virtual bool render() = 0;+ virtual bool render(const Camera &camera) = 0;virtual bool valid() const = 0;virtual unsigned activeBodies() const = 0;virtual float maxDisturbance() const = 0;@@ -84,11 +95,15 @@ public:virtual void shutdown() = 0;};-// A renderer backend (SDL GPU today, Direct3D 11 later) implements Layer and-// these two entry points. Supported() queries the current device at call time;-// false includes calls before a usable graphics device exists. CreateLayer()-// returns nullptr when unsupported; initialize() performs resource allocation.+// A renderer backend (SDL GPU, Direct3D 11) implements Layer and these entry+// points. Supported() queries the current device at call time; false includes+// calls before a usable graphics device exists. CreateLayer() returns nullptr+// when unsupported; initialize() performs resource allocation.bool Supported();std::unique_ptr<Layer> CreateLayer();+// The programs and targets every layer shares outlive the layers, so a new map's+// first hazard compiles nothing. Release them only when the device goes away+// (teardown, reset, resolution change), after every layer has been shut down.+void ReleaseDevice();} // namespace HazardClouddiff --git a/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudCore.h b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudCore.hnew file mode 100644index 000000000..126b7c894--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/HazardCloudCore.h@@ -0,0 +1,159 @@+// The device-free half of every hazard cloud backend: the field and wake state,+// the constants the shaders read, the shader text and when the caches rebake.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++#include "Platform/HazardCloud.h"+#include <array>+#include <cstdint>+#include <string>+#include <vector>++namespace HazardCloud {++constexpr float Steps = 96.0f;+constexpr float MaximumDisplacement = 18.0f;+constexpr unsigned MaximumBodies = 32;+constexpr unsigned CacheSlices = 24;+constexpr unsigned CacheColumns = 6;+constexpr unsigned CacheRows = CacheSlices / CacheColumns;+// How often a cloud that is only aging rebakes its density and light atlases.+// ponytail: a fixed rate; a wake behind running infantry steps at it too, raise+// it if that ever reads as stutter.+constexpr float BakesPerSecond = 20.0f;++// One atlas slice's side in voxels, the same for the estimate and the device.+unsigned cacheSide(const FieldState &field);++// Matches the cloud pixel shaders' b0 exactly; all matrices keep the renderer's+// row-major convention.+struct Uniforms {+ float WorldFromClip[16];+ float CameraPosition[4];+ float Viewport[4]; // origin including half pixel, width, height+ float Scene[4]; // inverse target size, depth available, seconds+ float Field0[4]; // world centre XYZ, horizontal radius+ float Field1[4];+ float Shape0[4]; // half height, density gain, palette, formation+ float Shape1[4];+ float Footprints[4]; // field 0/1 fringe beyond hazard radius, reserved ZW+ float Source0[4]; // release, outward travel, dissipation, source age+ float Source1[4];+ float Settings[4]; // active fields, nuclear heat pixels, enabled, maximum steps+ float Interaction[4]; // world origin XY, inverse world width/height+ float FlowSettings[4]; // enabled, maximum displacement, reserved, reserved+ float Cache0[4]; // voxel counts XYZ, atlas slice columns+ float Cache1[4];+ float CachePass[4]; // field index for cache construction, reserved YZW+ float PaletteMain[4][4]; // per-palette main RGB, overall brightness+ float PaletteShadow[4][4]; // per-palette shadow RGB, optical thickness multiplier+ float Terrain0[4]; // minimum ground Z, maximum ground Z, enabled, reserved+ float Terrain1[4];+};+static_assert(sizeof(Uniforms) == 480, "hazard volume uniform layout");++// The nuclear embers' vertex constants, b0 of the ember vertex shader.+struct EmberConstants {+ float viewProjection[16];+ float viewport[4];+ float field[4];+ float shape[4];+ float scene[4];+ float terrain[4]; // enabled, field index, sampled domain radius, reserved+};+static_assert(sizeof(EmberConstants) == 144, "ember shader constant layout");++// A field that shows embers: nuclear, visible and past the first of its formation.+bool emberField(const FieldState &field);+// The constants for one field's embers and how many billboards they draw.+unsigned emberConstants(const FieldState &field, unsigned index, bool terrain,+ const float viewProjection[16], const float viewport[4],+ float timeSeconds, EmberConstants &constants);++// HLSL text. SDL GPU wants explicit register spaces; FXC's shader model 5+// rejects them, so the Direct3D 11 backend asks for the text without.+enum class Pass { Volume, Composite, Density, Lighting, Heat };+std::string vertexShader();+std::string pixelShader(Pass pass, bool registerSpaces);+std::string emberVertexShader(bool registerSpaces);+std::string emberPixelShader(bool registerSpaces);++// Everything a backend keeps that needs no device. A backend derives from this+// and supplies initialize, render, estimatedCacheBytes and shutdown.+class LayerCore : public Layer {+public:+ void setFields(const FieldState *fields, unsigned count) override;+ void setBodies(const Body *bodies, unsigned count) override;+ void setFlowDomain(float minX, float minY, float maxX, float maxY) override;+ void setTerrain(unsigned fieldIndex, const float *heights) override;+ void setPalette(unsigned index, const Palette &palette) override;+ void setInteractionEnabled(bool enabled) override;+ bool isInteractionEnabled() const override { return interactionEnabled; }+ void setHeatEnabled(bool enabled) override { heatEnabled = enabled; }+ bool isHeatEnabled() const override { return heatEnabled; }+ void update(float timeSeconds) override;+ void reset() override;+ bool valid() const override { return initialized && !failed && flow.valid(); }+ unsigned activeBodies() const override { return flow.activeBodies(); }+ float maxDisturbance() const override { return flow.maxDisturbance(); }+ unsigned interactionUploads() const override { return flowUploads; }+ unsigned renderedFrames() const override { return renderedFrameCount; }++ // Whether the atlases have to be rebuilt for these constants, and if so the+ // constants are taken as baked. A view change never rebakes; a structural+ // change (palette, terrain, size, a new field) rebakes at once; a cloud that+ // only ages or stirs rebakes at most BakesPerSecond times a second.+ bool takeBake(const Uniforms &uniforms);+ unsigned bakes() const { return cacheBakes; }+ // Whether the wake grid changed since the device last uploaded it.+ bool flowNeedsUpload() const { return flowDirty; }++protected:+ void fail(const char *reason);+ bool fieldActive(unsigned index) const;+ bool anyFieldActive() const;+ // The cloud constants for this camera over a target of this size, and the+ // camera's world to clip matrix. False (and failed) for a singular camera.+ bool buildUniforms(const Camera &camera, unsigned targetWidth, unsigned targetHeight,+ Uniforms &uniforms, float viewProjection[16]);+ // The scissor that holds the nuclear heat, inside the camera's viewport;+ // width zero when no field is hot.+ void heatScissor(const float viewProjection[16], const Camera &camera,+ unsigned targetWidth, unsigned targetHeight, int rectangle[4]) const;+ // The device uploaded the wake grid; the next bake sees the new wakes.+ void flowUploaded() { flowDirty = false; ++flowUploads; }+ // Forget what was baked: new atlases, new terrain, a reset device.+ void invalidateBake() { cachedInputsValid = false; }+ void resetCounters();++ FieldState fieldStates[2] = {};+ unsigned fieldCount = 0;+ float sourceTravel[2] = {}, sourceAge[2] = {}, peakDensity[2] = {};+ float simulationTime = 0;+ bool hasSimulationTime = false;+ bool initialized = false;+ bool interactionEnabled = true;+ bool heatEnabled = true;+ bool flowDirty = true;+ bool failed = false;+ bool explicitDomain = false;+ unsigned renderedFrameCount = 0;+ unsigned flowUploads = 0;+ std::vector<Body> bodies;+ HazardCloudFlow::Flow flow;+ std::array<Palette, 4> palettes = {{defaultPalette(0), defaultPalette(1), defaultPalette(2), defaultPalette(3)}};+ // Both fields' grids side by side, TerrainGridSide * 2 wide.+ std::vector<float> terrainPixels = std::vector<float>(TerrainGridSide * TerrainGridSide * 2, 0.0f);+ bool terrainEnabled[2] = {};+ float terrainMin[2] = {}, terrainMax[2] = {};+ bool terrainDirty = false;++private:+ Uniforms cachedInputs = {};+ bool cachedInputsValid = false;+ unsigned cachedFlowUploads = 0;+ long long cachedBakeTick = 0;+ unsigned cacheBakes = 0;+};++} // namespace HazardClouddiff --git a/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloud.h b/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloud.hdeleted file mode 100644index 306c6a34d..000000000--- a/GeneralsMD/Code/Libraries/Include/Platform/SdlHazardCloud.h+++ /dev/null@@ -1,49 +0,0 @@-// SDL GPU implementation of the backend-neutral hazard cloud renderer.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#pragma once--#include "Platform/HazardCloud.h"--namespace SdlHazardCloud {--using HazardCloud::FieldState;-using HazardCloud::Body;-using HazardCloud::Color;-using HazardCloud::Palette;-using HazardCloud::TerrainGridSide;-using HazardCloud::defaultPalette;--class Layer final : public HazardCloud::Layer {-public:- Layer();- ~Layer() override;- Layer(const Layer &) = delete;- Layer &operator=(const Layer &) = delete;-- bool initialize() override;- void setFields(const FieldState *fields, unsigned count) override;- void setBodies(const Body *bodies, unsigned count) override;- void setFlowDomain(float minX, float minY, float maxX, float maxY) override;- void setTerrain(unsigned fieldIndex, const float *heights) override;- void setPalette(unsigned index, const Palette &palette) override;- void setInteractionEnabled(bool enabled) override;- bool isInteractionEnabled() const override;- void setHeatEnabled(bool enabled) override;- bool isHeatEnabled() const override;- void update(float timeSeconds) override;- void reset() override;- bool render() override;- bool valid() const override;- unsigned activeBodies() const override;- float maxDisturbance() const override;- unsigned interactionUploads() const override;- unsigned renderedFrames() const override;- std::uint64_t estimatedCacheBytes() const override;- void shutdown() override;--private:- struct Impl;- Impl *impl;-};--} // namespace SdlHazardClouddiff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cppindex 8ba375c93..fbf5b730a 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp@@ -1137,6 +1137,17 @@ bool DX11BackendClass::Draws_Into_Scene() constreturn CurrentTarget == NULL && !ShadowMapBound;}+ID3D11RenderTargetView * DX11BackendClass::Scene_Target() const+{+ if (ShadowMapBound) {+ return NULL;+ }+ if (CurrentTarget == NULL) {+ return Device->Get_Scene_View();+ }+ return CurrentDepth == Device->Get_Depth_Stencil_View() ? CurrentTarget : NULL;+}+/** The black and white view, the motion blur and the cross fade draw the whole scene into a targetof their own, and Draw_Effect refuses every look there; asked first, the scene keeps the heatvision and the disabled tint for those frames instead of drawing the object plain. */diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.hindex 82003ef3b..570c09ade 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h@@ -263,6 +263,10 @@ public:// Whether the draws are going into the scene's own target.bool Draws_Into_Scene() const;+ // Where the scene is going now: its own target, or a screen filter's texture drawn over the+ // scene's depth; NULL for a mirror or the sun's map.+ ID3D11RenderTargetView * Scene_Target() const;+// The scene's target, its depth and the draws' viewport bound again after a pass that bound// its own on the context mid-scene (the post chain's occlusion).void Resume_Scene();@@ -365,6 +369,11 @@ public:{ return (index < TargetTrace.size()) ? TargetTrace[index].c_str() : ""; }const char * First_Compiler_Error() const { return CompilerError.c_str(); }+ // A program for a pass of someone else's (the hazard clouds), compiled once and kept in the+ // shader cache with the generated ones, so a second run compiles nothing.+ bool Compile_Program(const std::string & source, const char * name, const char * profile,+ std::vector<unsigned char> & bytecode);+private:DX11BackendClass(const DX11BackendClass &);DX11BackendClass & operator=(const DX11BackendClass &);@@ -941,8 +950,6 @@ private:bool Any_Missing_Texture() const;void Dump_Program(const std::string & key, const std::string & vertex_hlsl,const std::string & pixel_hlsl);- bool Compile_Program(const std::string & source, const char * name, const char * profile,- std::vector<unsigned char> & bytecode);void Save_Shader_Cache() const;std::string CompilerError;diff --git a/GeneralsMD/Code/Tests/test_dx11backend.cpp b/GeneralsMD/Code/Tests/test_dx11backend.cppindex 88613d6d9..0886673bc 100644--- a/GeneralsMD/Code/Tests/test_dx11backend.cpp+++ b/GeneralsMD/Code/Tests/test_dx11backend.cpp@@ -29,6 +29,7 @@#include "dx11backend.h"#include "dx11resource.h"+#include "Platform/HazardCloudCore.h"#include <stdio.h>#include <string.h>@@ -1143,3 +1144,47 @@ TEST(dx11backend_the_smoke_map_holds_each_casters_three_sums)resource->Release();backend.Shutdown();}++// The volumetric hazard clouds' text is the SDL GPU backend's too, written for DXC. Every pass of+// it has to go through the compiler this backend uses at shader model 5, and the device has to take+// what comes out, or the clouds go Classic on the first hazard of the match.+TEST(dx11backend_the_hazard_cloud_programs_compile_at_shader_model_5)+{+ DX11DeviceClass device;+ CHECK(device.Create_Offscreen());+ DX11BackendClass backend;+ CHECK(backend.Initialise(&device));++ struct Program { std::string source; bool vertex; };+ const Program programs[] = {+ { HazardCloud::vertexShader(), true },+ { HazardCloud::pixelShader(HazardCloud::Pass::Volume, false), false },+ { HazardCloud::pixelShader(HazardCloud::Pass::Composite, false), false },+ { HazardCloud::pixelShader(HazardCloud::Pass::Density, false), false },+ { HazardCloud::pixelShader(HazardCloud::Pass::Lighting, false), false },+ { HazardCloud::pixelShader(HazardCloud::Pass::Heat, false), false },+ { HazardCloud::emberVertexShader(false), true },+ { HazardCloud::emberPixelShader(false), false },+ };+ for (const Program & program : programs) {+ std::vector<unsigned char> code;+ const bool compiled = backend.Compile_Program(program.source, "hazardcloud",+ program.vertex ? "vs_5_0" : "ps_5_0", code);+ if (!compiled) {+ printf(" %s\n", backend.First_Compiler_Error());+ }+ CHECK(compiled);+ if (!compiled) {+ continue;+ }+ ID3D11DeviceChild * made = NULL;+ const HRESULT result = program.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();+}diff --git a/GeneralsMD/Code/Tests/test_hazard_cloud_policy.cpp b/GeneralsMD/Code/Tests/test_hazard_cloud_policy.cppindex 1edf501ab..b0fe32576 100644--- a/GeneralsMD/Code/Tests/test_hazard_cloud_policy.cpp+++ b/GeneralsMD/Code/Tests/test_hazard_cloud_policy.cpp@@ -2,6 +2,7 @@#include "Platform/HazardCloudPolicy.h"#include "Platform/HazardCloud.h"#include "Platform/HazardCloudFlow.h"+#include "Platform/HazardCloudCore.h"#include <initializer_list>#include <limits>@@ -216,3 +217,92 @@ TEST(hazard_cloud_neutral_flow_advances_and_resets_without_a_renderer)break;}}++namespace {++// The device-free core with no device under it: what a backend would bake and upload.+class CoreProbe final : public HazardCloud::LayerCore {+public:+ bool initialize() override { initialized = true; return true; }+ bool render(const HazardCloud::Camera &) override { return false; }+ std::uint64_t estimatedCacheBytes() const override { return 0; }+ void shutdown() override {}+ using LayerCore::flowUploaded;+ bool bakesFrom(float cameraX)+ {+ // A perspective camera standing back from the field, moved sideways by cameraX.+ HazardCloud::Camera camera = {+ {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, cameraX, 0, 400, 1},+ {1, 0, 0, 0, 0, 1.7f, 0, 0, 0, 0, 1.001f, 1, 0, 0, -1.001f, 0},+ 0, 0, 1280, 720, 0, 1 };+ HazardCloud::Uniforms uniforms;+ float viewProjection[16];+ CHECK(buildUniforms(camera, 1280, 720, uniforms, viewProjection));+ return takeBake(uniforms);+ }+};++} // namespace++TEST(hazard_cloud_atlases_rebake_on_a_change_and_at_most_twenty_times_a_second)+{+ CoreProbe layer;+ layer.initialize();+ const HazardCloud::FieldState field = {{0, 0, 0}, 40, 18.61f, 1, 0, 1, 0, 10};+ layer.setFields(&field, 1);+ layer.update(1.0f);+ CHECK(layer.bakesFrom(0));+ CHECK(!layer.bakesFrom(0));+ CHECK(!layer.bakesFrom(50)); // the camera never reaches the atlases+ layer.update(1.01f); // aging inside one bake period+ CHECK(!layer.bakesFrom(0));+ layer.update(1.06f); // and into the next+ CHECK(layer.bakesFrom(0));+ HazardCloud::Palette palette = HazardCloud::defaultPalette(0);+ palette.brightness = 1.0f;+ layer.setPalette(0, palette); // a structural change shows on the next frame+ CHECK(layer.bakesFrom(0));+ HazardCloud::FieldState wider = field;+ wider.radius = 60;+ layer.setFields(&wider, 1);+ CHECK(layer.bakesFrom(0));+ CHECK_EQ(layer.bakes(), 4u);+}++TEST(hazard_cloud_quiet_wake_grid_uploads_nothing)+{+ CoreProbe layer;+ layer.initialize();+ const HazardCloud::FieldState field = {{0, 0, 0}, 40, 18.61f, 1, 0, 1, 0, 10};+ layer.setFields(&field, 1);+ CHECK(layer.flowNeedsUpload());+ layer.flowUploaded();+ float seconds = 1.0f;+ for (unsigned frame = 0; frame < 30; ++frame) layer.update(seconds += 1.0f / 60.0f);+ CHECK(!layer.flowNeedsUpload()); // no infantry, nothing to heal+ const HazardCloud::Body walker = {0, 0, 0, 30, 0, 3, 15};+ layer.setBodies(&walker, 1);+ for (unsigned frame = 0; frame < 10; ++frame) layer.update(seconds += 1.0f / 60.0f);+ CHECK(layer.flowNeedsUpload());+ CHECK(layer.maxDisturbance() > 0.0f);+ layer.flowUploaded();+ layer.setBodies(nullptr, 0);+ for (unsigned frame = 0; frame < 60 * 20 && layer.maxDisturbance() > 0.0f; ++frame)+ layer.update(seconds += 1.0f / 60.0f);+ CHECK_EQ(layer.maxDisturbance(), 0.0f); // healed, then put at rest+ layer.flowUploaded();+ layer.update(seconds += 1.0f / 60.0f);+ CHECK(!layer.flowNeedsUpload());+ CHECK(layer.valid());+}++TEST(hazard_cloud_shader_text_drops_register_spaces_only_for_direct3d_11)+{+ using HazardCloud::Pass;+ for (Pass pass : {Pass::Volume, Pass::Composite, Pass::Density, Pass::Lighting, Pass::Heat}) {+ CHECK(HazardCloud::pixelShader(pass, true).find(", space2)") != std::string::npos);+ CHECK(HazardCloud::pixelShader(pass, false).find(", space") == std::string::npos);+ }+ CHECK(HazardCloud::emberVertexShader(false).find(", space") == std::string::npos);+ CHECK(HazardCloud::emberPixelShader(false).find("register(b0)") != std::string::npos);+}