LCOV - code coverage report
Current view: top level - source/renderer - WaterManager.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 87 653 13.3 %
Date: 2026-12-03 01:19:39 Functions: 6 21 28.6 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "WaterManager.h"
      21             : 
      22             : #include "graphics/Camera.h"
      23             : #include "graphics/ShaderManager.h"
      24             : #include "graphics/ShaderTechnique.h"
      25             : #include "graphics/ShaderTechniquePtr.h"
      26             : #include "graphics/Terrain.h"
      27             : #include "graphics/TextureManager.h"
      28             : #include "lib/code_annotation.h"
      29             : #include "lib/debug.h"
      30             : #include "lib/path.h"
      31             : #include "lib/secure_crt.h"
      32             : #include "maths/BoundingBoxAligned.h"
      33             : #include "maths/Frustum.h"
      34             : #include "maths/MathUtil.h"
      35             : #include "maths/Vector2D.h"
      36             : #include "maths/Vector3D.h"
      37             : #include "ps/CStrIntern.h"
      38             : #include "ps/CStrInternStatic.h"
      39             : #include "ps/Game.h"
      40             : #include "ps/World.h"
      41             : #include "renderer/PostprocManager.h"
      42             : #include "renderer/Renderer.h"
      43             : #include "renderer/RenderingOptions.h"
      44             : #include "renderer/SceneRenderer.h"
      45             : #include "renderer/VertexBuffer.h"
      46             : #include "renderer/backend/Backend.h"
      47             : #include "renderer/backend/Format.h"
      48             : #include "renderer/backend/IBuffer.h"
      49             : #include "renderer/backend/IDevice.h"
      50             : #include "renderer/backend/IDeviceCommandContext.h"
      51             : #include "renderer/backend/IFramebuffer.h"
      52             : #include "renderer/backend/IShaderProgram.h"
      53             : #include "renderer/backend/ITexture.h"
      54             : #include "renderer/backend/Sampler.h"
      55             : 
      56             : #include <algorithm>
      57             : #include <array>
      58             : #include <bit>
      59             : #include <climits>
      60             : #include <cmath>
      61             : #include <cstdint>
      62             : #include <cstdlib>
      63             : #include <deque>
      64             : #include <set>
      65             : #include <utility>
      66             : 
      67             : struct CoastalPoint
      68             : {
      69           0 :     CoastalPoint(int idx, CVector2D pos) : index(idx), position(pos) {};
      70             :     int index;
      71             :     CVector2D position;
      72             : };
      73             : 
      74           0 : struct SWavesVertex
      75             : {
      76             :     // vertex position
      77             :     CVector3D m_BasePosition;
      78             :     CVector3D m_ApexPosition;
      79             :     CVector3D m_SplashPosition;
      80             :     CVector3D m_RetreatPosition;
      81             : 
      82             :     CVector2D m_PerpVect;
      83             :     float m_UV[2];
      84             : };
      85             : cassert(sizeof(SWavesVertex) == 64);
      86             : 
      87           0 : struct WaveObject
      88             : {
      89             :     CVertexBufferManager::Handle m_VBVertices;
      90             :     CBoundingBoxAligned m_AABB;
      91             :     size_t m_Width;
      92             :     float m_TimeDiff;
      93             : };
      94             : 
      95          10 : WaterManager::WaterManager(Renderer::Backend::IDevice* device)
      96          10 :     : m_Device(device)
      97             : {
      98             :     // water
      99          10 :     m_RenderWater = false; // disabled until textures are successfully loaded
     100          10 :     m_WaterHeight = 5.0f;
     101             : 
     102          10 :     m_RefTextureSize = 0;
     103             : 
     104          10 :     m_WaterTexTimer = 0.0;
     105             : 
     106          10 :     m_WindAngle = 0.0f;
     107          10 :     m_Waviness = 8.0f;
     108          10 :     m_WaterColor = CColor(0.3f, 0.35f, 0.7f, 1.0f);
     109          10 :     m_WaterTint = CColor(0.28f, 0.3f, 0.59f, 1.0f);
     110          10 :     m_Murkiness = 0.45f;
     111          10 :     m_RepeatPeriod = 16.0f;
     112             : 
     113          10 :     m_WaterEffects = true;
     114          10 :     m_WaterFancyEffects = false;
     115          10 :     m_WaterRealDepth = false;
     116          10 :     m_WaterRefraction = false;
     117          10 :     m_WaterReflection = false;
     118          10 :     m_WaterType = L"ocean";
     119             : 
     120          10 :     m_NeedsReloading = false;
     121          10 :     m_NeedInfoUpdate = true;
     122             : 
     123          10 :     m_MapSize = 0;
     124             : 
     125          10 :     m_updatei0 = 0;
     126          10 :     m_updatej0 = 0;
     127          10 :     m_updatei1 = 0;
     128          10 :     m_updatej1 = 0;
     129          10 : }
     130             : 
     131        1220 : WaterManager::~WaterManager()
     132             : {
     133             :     // Cleanup if the caller messed up
     134          10 :     UnloadWaterTextures();
     135             : 
     136          10 :     m_ShoreWaves.clear();
     137          10 :     m_ShoreWavesVBIndices.Reset();
     138             : 
     139          10 :     m_DistanceHeightmap.reset();
     140          10 :     m_WindStrength.reset();
     141             : 
     142          10 :     m_FancyEffectsFramebuffer.reset();
     143          10 :     m_FancyEffectsOccludersFramebuffer.reset();
     144          10 :     m_RefractionFramebuffer.reset();
     145          10 :     m_ReflectionFramebuffer.reset();
     146             : 
     147          10 :     m_FancyTexture.reset();
     148          10 :     m_FancyTextureDepth.reset();
     149          10 :     m_ReflFboDepthTexture.reset();
     150          10 :     m_RefrFboDepthTexture.reset();
     151        1240 : }
     152             : 
     153          10 : void WaterManager::Initialize()
     154             : {
     155          10 :     const uint32_t stride = sizeof(SWavesVertex);
     156             : 
     157          10 :     const std::array<Renderer::Backend::SVertexAttributeFormat, 6> attributes{{
     158             :         {Renderer::Backend::VertexAttributeStream::POSITION,
     159             :             Renderer::Backend::Format::R32G32B32_SFLOAT,
     160             :             offsetof(SWavesVertex, m_BasePosition), stride,
     161             :             Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
     162             :         {Renderer::Backend::VertexAttributeStream::NORMAL,
     163             :             Renderer::Backend::Format::R32G32_SFLOAT,
     164             :             offsetof(SWavesVertex, m_PerpVect), stride,
     165             :             Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
     166             :         {Renderer::Backend::VertexAttributeStream::UV0,
     167             :             Renderer::Backend::Format::R32G32_SFLOAT,
     168             :             offsetof(SWavesVertex, m_UV), stride,
     169             :             Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
     170             : 
     171             :         {Renderer::Backend::VertexAttributeStream::UV1,
     172             :             Renderer::Backend::Format::R32G32B32_SFLOAT,
     173             :             offsetof(SWavesVertex, m_ApexPosition), stride,
     174             :             Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
     175             :         {Renderer::Backend::VertexAttributeStream::UV2,
     176             :             Renderer::Backend::Format::R32G32B32_SFLOAT,
     177             :             offsetof(SWavesVertex, m_SplashPosition), stride,
     178             :             Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
     179             :         {Renderer::Backend::VertexAttributeStream::UV3,
     180             :             Renderer::Backend::Format::R32G32B32_SFLOAT,
     181             :             offsetof(SWavesVertex, m_RetreatPosition), stride,
     182             :             Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
     183             :     }};
     184          10 :     m_ShoreVertexInputLayout = g_Renderer.GetVertexInputLayout(attributes);
     185          10 : }
     186             : 
     187             : ///////////////////////////////////////////////////////////////////
     188             : // Progressive load of water textures
     189           0 : int WaterManager::LoadWaterTextures()
     190             : {
     191             :     // TODO: this doesn't need to be progressive-loading any more
     192             :     // (since texture loading is async now)
     193             : 
     194           0 :     wchar_t pathname[PATH_MAX];
     195             : 
     196             :     // Load diffuse grayscale images (for non-fancy water)
     197           0 :     for (size_t i = 0; i < ARRAY_SIZE(m_WaterTexture); ++i)
     198             :     {
     199           0 :         swprintf_s(pathname, ARRAY_SIZE(pathname), L"art/textures/animated/water/default/diffuse%02d.dds", (int)i+1);
     200           0 :         CTextureProperties textureProps(pathname);
     201           0 :         textureProps.SetAddressMode(
     202             :             Renderer::Backend::Sampler::AddressMode::REPEAT);
     203             : 
     204           0 :         CTexturePtr texture = g_Renderer.GetTextureManager().CreateTexture(textureProps);
     205           0 :         texture->Prefetch();
     206           0 :         m_WaterTexture[i] = texture;
     207           0 :     }
     208             : 
     209           0 :     m_RenderWater = true;
     210             : 
     211             :     // Load normalmaps (for fancy water)
     212           0 :     ReloadWaterNormalTextures();
     213             : 
     214             :     // Load CoastalWaves
     215           0 :     {
     216           0 :         CTextureProperties textureProps(L"art/textures/terrain/types/water/coastalWave.png");
     217           0 :         textureProps.SetAddressMode(
     218             :             Renderer::Backend::Sampler::AddressMode::REPEAT);
     219           0 :         CTexturePtr texture = g_Renderer.GetTextureManager().CreateTexture(textureProps);
     220           0 :         texture->Prefetch();
     221           0 :         m_WaveTex = texture;
     222           0 :     }
     223             : 
     224             :     // Load Foam
     225           0 :     {
     226           0 :         CTextureProperties textureProps(L"art/textures/terrain/types/water/foam.png");
     227           0 :         textureProps.SetAddressMode(
     228             :             Renderer::Backend::Sampler::AddressMode::REPEAT);
     229           0 :         CTexturePtr texture = g_Renderer.GetTextureManager().CreateTexture(textureProps);
     230           0 :         texture->Prefetch();
     231           0 :         m_FoamTex = texture;
     232           0 :     }
     233             : 
     234           0 :     RecreateOrLoadTexturesIfNeeded();
     235             : 
     236           0 :     return 0;
     237             : }
     238             : 
     239          10 : void WaterManager::CreateViewSizeDependentObjects(const uint32_t, const uint32_t)
     240             : {
     241          10 :     RecreateOrLoadTexturesIfNeeded();
     242          10 : }
     243             : 
     244           0 : void WaterManager::DestroyViewSizeDependentObjects()
     245             : {
     246           0 :     m_ReflectionFramebuffer.reset();
     247           0 :     m_ReflectionTexture.reset();
     248           0 :     m_ReflFboDepthTexture.reset();
     249             : 
     250           0 :     m_ReflectionFramebufferInitialized = false;
     251             : 
     252           0 :     m_RefractionFramebuffer.reset();
     253           0 :     m_RefractionTexture.reset();
     254           0 :     m_RefrFboDepthTexture.reset();
     255             : 
     256           0 :     m_RefractionFramebufferInitialized = false;
     257             : 
     258           0 :     m_FancyEffectsFramebuffer.reset();
     259           0 :     m_FancyEffectsOccludersFramebuffer.reset();
     260           0 :     m_FancyTexture.reset();
     261           0 :     m_FancyTextureDepth.reset();
     262           0 : }
     263             : 
     264          10 : void WaterManager::RecreateOrLoadTexturesIfNeeded()
     265             : {
     266             :     // Use screen-sized textures for minimum artifacts.
     267          10 :     const size_t newRefTextureSize = std::bit_ceil(static_cast<uint32_t>(g_Renderer.GetHeight()));
     268             : 
     269          10 :     if (m_RefTextureSize != newRefTextureSize)
     270             :     {
     271          10 :         m_ReflectionFramebuffer.reset();
     272          10 :         m_ReflectionTexture.reset();
     273          10 :         m_ReflFboDepthTexture.reset();
     274             : 
     275          10 :         m_RefractionFramebuffer.reset();
     276          10 :         m_RefractionTexture.reset();
     277          10 :         m_RefrFboDepthTexture.reset();
     278             : 
     279          10 :         m_RefTextureSize = newRefTextureSize;
     280             :     }
     281             : 
     282          10 :     const Renderer::Backend::Format depthFormat =
     283          10 :         m_Device->GetPreferredDepthStencilFormat(
     284             :             Renderer::Backend::ITexture::Usage::SAMPLED |
     285             :                 Renderer::Backend::ITexture::Usage::DEPTH_STENCIL_ATTACHMENT,
     286             :             true, false);
     287             : 
     288          10 :     Renderer::Backend::Format framebufferColorFormat{
     289          10 :         g_Renderer.GetPostprocManager().IsEnabled()
     290          10 :         ? g_Renderer.GetPostprocManager().GetFramebufferColorFormat()
     291          10 :         : Renderer::Backend::Format::R8G8B8A8_UNORM};
     292             : 
     293             :     // Create reflection textures.
     294          10 :     const bool needsReflectionTextures =
     295          10 :         g_RenderingOptions.GetWaterEffects() &&
     296           0 :         g_RenderingOptions.GetWaterReflection();
     297           0 :     if (needsReflectionTextures && !m_ReflectionTexture)
     298             :     {
     299           0 :         m_ReflectionTexture = m_Device->CreateTexture2D("WaterReflectionTexture",
     300             :             Renderer::Backend::ITexture::Usage::SAMPLED |
     301             :                 Renderer::Backend::ITexture::Usage::COLOR_ATTACHMENT,
     302           0 :             framebufferColorFormat, m_RefTextureSize, m_RefTextureSize,
     303           0 :             Renderer::Backend::Sampler::MakeDefaultSampler(
     304             :                 Renderer::Backend::Sampler::Filter::LINEAR,
     305           0 :                 Renderer::Backend::Sampler::AddressMode::MIRRORED_REPEAT));
     306             : 
     307           0 :         m_ReflFboDepthTexture = m_Device->CreateTexture2D("WaterReflectionDepthTexture",
     308             :             Renderer::Backend::ITexture::Usage::SAMPLED |
     309             :                 Renderer::Backend::ITexture::Usage::DEPTH_STENCIL_ATTACHMENT,
     310           0 :             depthFormat, m_RefTextureSize, m_RefTextureSize,
     311           0 :             Renderer::Backend::Sampler::MakeDefaultSampler(
     312             :                 Renderer::Backend::Sampler::Filter::NEAREST,
     313           0 :                 Renderer::Backend::Sampler::AddressMode::REPEAT));
     314             : 
     315           0 :         Renderer::Backend::SColorAttachment colorAttachment{};
     316           0 :         colorAttachment.texture = m_ReflectionTexture.get();
     317           0 :         colorAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::CLEAR;
     318           0 :         colorAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::STORE;
     319           0 :         colorAttachment.clearColor = CColor{0.5f, 0.5f, 1.0f, 0.0f};
     320             : 
     321           0 :         Renderer::Backend::SDepthStencilAttachment depthStencilAttachment{};
     322           0 :         depthStencilAttachment.texture = m_ReflFboDepthTexture.get();
     323           0 :         depthStencilAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::CLEAR;
     324           0 :         depthStencilAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::STORE;
     325             : 
     326           0 :         m_ReflectionFramebuffer = m_Device->CreateFramebuffer("ReflectionFramebuffer",
     327           0 :             &colorAttachment, &depthStencilAttachment);
     328           0 :         if (!m_ReflectionFramebuffer)
     329             :         {
     330           0 :             g_RenderingOptions.SetWaterReflection(false);
     331           0 :             UpdateQuality();
     332             :         }
     333           0 :         m_ReflectionFramebufferInitialized = false;
     334             :     }
     335             : 
     336             :     // Create refraction textures.
     337          10 :     const bool needsRefractionTextures =
     338          10 :         g_RenderingOptions.GetWaterEffects() &&
     339           0 :         g_RenderingOptions.GetWaterRefraction();
     340           0 :     if (needsRefractionTextures && !m_RefractionTexture)
     341             :     {
     342           0 :         m_RefractionTexture = m_Device->CreateTexture2D("WaterRefractionTexture",
     343             :             Renderer::Backend::ITexture::Usage::SAMPLED |
     344             :                 Renderer::Backend::ITexture::Usage::COLOR_ATTACHMENT,
     345           0 :             framebufferColorFormat, m_RefTextureSize, m_RefTextureSize,
     346           0 :             Renderer::Backend::Sampler::MakeDefaultSampler(
     347             :                 Renderer::Backend::Sampler::Filter::LINEAR,
     348           0 :                 Renderer::Backend::Sampler::AddressMode::MIRRORED_REPEAT));
     349             : 
     350           0 :         m_RefrFboDepthTexture = m_Device->CreateTexture2D("WaterRefractionDepthTexture",
     351             :             Renderer::Backend::ITexture::Usage::SAMPLED |
     352             :                 Renderer::Backend::ITexture::Usage::DEPTH_STENCIL_ATTACHMENT,
     353           0 :             depthFormat, m_RefTextureSize, m_RefTextureSize,
     354           0 :             Renderer::Backend::Sampler::MakeDefaultSampler(
     355             :                 Renderer::Backend::Sampler::Filter::NEAREST,
     356           0 :                 Renderer::Backend::Sampler::AddressMode::REPEAT));
     357             : 
     358           0 :         Renderer::Backend::SColorAttachment colorAttachment{};
     359           0 :         colorAttachment.texture = m_RefractionTexture.get();
     360           0 :         colorAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::CLEAR;
     361           0 :         colorAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::STORE;
     362           0 :         colorAttachment.clearColor = CColor{1.0f, 0.0f, 0.0f, 0.0f};
     363             : 
     364           0 :         Renderer::Backend::SDepthStencilAttachment depthStencilAttachment{};
     365           0 :         depthStencilAttachment.texture = m_RefrFboDepthTexture.get();
     366           0 :         depthStencilAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::CLEAR;
     367           0 :         depthStencilAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::STORE;
     368             : 
     369           0 :         m_RefractionFramebuffer = m_Device->CreateFramebuffer("RefractionFramebuffer",
     370           0 :             &colorAttachment, &depthStencilAttachment);
     371           0 :         if (!m_RefractionFramebuffer)
     372             :         {
     373           0 :             g_RenderingOptions.SetWaterRefraction(false);
     374           0 :             UpdateQuality();
     375             :         }
     376           0 :         m_RefractionFramebufferInitialized = false;
     377             :     }
     378             : 
     379          10 :     const float scale{g_Renderer.GetPostprocManager().IsEnabled()
     380          10 :         ? g_Renderer.GetPostprocManager().GetScale() : 1.0f};
     381          10 :     const uint32_t newWidth{static_cast<uint32_t>(g_Renderer.GetWidth() * scale)};
     382          10 :     const uint32_t newHeight{static_cast<uint32_t>(g_Renderer.GetHeight() * scale)};
     383          10 :     if (m_FancyTexture && (m_FancyTexture->GetWidth() != newWidth || m_FancyTexture->GetHeight() != newHeight))
     384             :     {
     385           0 :         m_FancyEffectsFramebuffer.reset();
     386           0 :         m_FancyEffectsOccludersFramebuffer.reset();
     387           0 :         m_FancyTexture.reset();
     388           0 :         m_FancyTextureDepth.reset();
     389             :     }
     390             : 
     391             :     // Create the Fancy Effects textures.
     392          10 :     const bool needsFancyTextures =
     393          10 :         g_RenderingOptions.GetWaterEffects() &&
     394           0 :         g_RenderingOptions.GetWaterFancyEffects();
     395           0 :     if (needsFancyTextures && !m_FancyTexture)
     396             :     {
     397           0 :         m_FancyTexture = m_Device->CreateTexture2D("WaterFancyTexture",
     398             :             Renderer::Backend::ITexture::Usage::SAMPLED |
     399             :                 Renderer::Backend::ITexture::Usage::COLOR_ATTACHMENT,
     400             :             Renderer::Backend::Format::R8G8B8A8_UNORM, newWidth, newHeight,
     401           0 :             Renderer::Backend::Sampler::MakeDefaultSampler(
     402             :                 Renderer::Backend::Sampler::Filter::LINEAR,
     403           0 :                 Renderer::Backend::Sampler::AddressMode::REPEAT));
     404             : 
     405           0 :         m_FancyTextureDepth = m_Device->CreateTexture2D("WaterFancyDepthTexture",
     406             :             Renderer::Backend::ITexture::Usage::DEPTH_STENCIL_ATTACHMENT,
     407             :             depthFormat, newWidth, newHeight,
     408           0 :             Renderer::Backend::Sampler::MakeDefaultSampler(
     409             :                 Renderer::Backend::Sampler::Filter::LINEAR,
     410           0 :                 Renderer::Backend::Sampler::AddressMode::REPEAT));
     411             : 
     412           0 :         Renderer::Backend::SColorAttachment colorAttachment{};
     413           0 :         colorAttachment.texture = m_FancyTexture.get();
     414           0 :         colorAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::CLEAR;
     415           0 :         colorAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::STORE;
     416           0 :         colorAttachment.clearColor = CColor{0.0f, 0.0f, 0.0f, 0.0f};
     417             : 
     418           0 :         Renderer::Backend::SDepthStencilAttachment depthStencilAttachment{};
     419           0 :         depthStencilAttachment.texture = m_FancyTextureDepth.get();
     420           0 :         depthStencilAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::CLEAR;
     421             :         // We need to store depth for later rendering occluders.
     422           0 :         depthStencilAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::STORE;
     423             : 
     424           0 :         m_FancyEffectsFramebuffer = m_Device->CreateFramebuffer("FancyEffectsFramebuffer",
     425           0 :             &colorAttachment, &depthStencilAttachment);
     426             : 
     427           0 :         Renderer::Backend::SColorAttachment occludersColorAttachment{};
     428           0 :         occludersColorAttachment.texture = m_FancyTexture.get();
     429           0 :         occludersColorAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::LOAD;
     430           0 :         occludersColorAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::STORE;
     431           0 :         occludersColorAttachment.clearColor = CColor{0.0f, 0.0f, 0.0f, 0.0f};
     432             : 
     433           0 :         Renderer::Backend::SDepthStencilAttachment occludersDepthStencilAttachment{};
     434           0 :         occludersDepthStencilAttachment.texture = m_FancyTextureDepth.get();
     435           0 :         occludersDepthStencilAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::LOAD;
     436           0 :         occludersDepthStencilAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::DONT_CARE;
     437             : 
     438           0 :         m_FancyEffectsOccludersFramebuffer = m_Device->CreateFramebuffer("FancyEffectsOccludersFramebuffer",
     439           0 :             &occludersColorAttachment, &occludersDepthStencilAttachment);
     440           0 :         if (!m_FancyEffectsFramebuffer || !m_FancyEffectsOccludersFramebuffer)
     441             :         {
     442           0 :             g_RenderingOptions.SetWaterRefraction(false);
     443           0 :             UpdateQuality();
     444             :         }
     445             :     }
     446          10 : }
     447             : 
     448           0 : void WaterManager::ReloadWaterNormalTextures()
     449             : {
     450           0 :     wchar_t pathname[PATH_MAX];
     451           0 :     for (size_t i = 0; i < ARRAY_SIZE(m_NormalMap); ++i)
     452             :     {
     453           0 :         swprintf_s(pathname, ARRAY_SIZE(pathname), L"art/textures/animated/water/%ls/normal00%02d.png", m_WaterType.c_str(), static_cast<int>(i) + 1);
     454           0 :         CTextureProperties textureProps(pathname);
     455           0 :         textureProps.SetAddressMode(
     456             :             Renderer::Backend::Sampler::AddressMode::REPEAT);
     457           0 :         textureProps.SetAnisotropicFilter(true);
     458             : 
     459           0 :         CTexturePtr texture = g_Renderer.GetTextureManager().CreateTexture(textureProps);
     460           0 :         texture->Prefetch();
     461           0 :         m_NormalMap[i] = texture;
     462           0 :     }
     463           0 : }
     464             : 
     465             : ///////////////////////////////////////////////////////////////////
     466             : // Unload water textures
     467          10 : void WaterManager::UnloadWaterTextures()
     468             : {
     469         610 :     for (size_t i = 0; i < ARRAY_SIZE(m_WaterTexture); i++)
     470         600 :         m_WaterTexture[i].reset();
     471             : 
     472         610 :     for (size_t i = 0; i < ARRAY_SIZE(m_NormalMap); i++)
     473         600 :         m_NormalMap[i].reset();
     474             : 
     475          10 :     m_RefractionFramebuffer.reset();
     476          10 :     m_ReflectionFramebuffer.reset();
     477          10 :     m_ReflectionTexture.reset();
     478          10 :     m_RefractionTexture.reset();
     479          10 : }
     480             : 
     481             : template<bool Transpose>
     482           0 : static inline void ComputeDirection(float* distanceMap, const std::uint16_t* heightmap, float waterHeight,
     483             :     size_t SideSize, size_t maxLevel)
     484             : {
     485             : #define ABOVEWATER(x, z) (HEIGHT_SCALE * heightmap[z*SideSize + x] >= waterHeight)
     486             : #define UPDATELOOKAHEAD \
     487             :     for (; lookahead <= id2+maxLevel && lookahead < SideSize && \
     488             :            ((!Transpose && !ABOVEWATER(lookahead, id1)) || (Transpose && !ABOVEWATER(id1, lookahead))); ++lookahead)
     489             :     // Algorithm:
     490             :     // We want to know the distance to the closest shore point. Go through each line/column,
     491             :     // keep track of when we encountered the last shore point and how far ahead the next one is.
     492           0 :     for (size_t id1 = 0; id1 < SideSize; ++id1)
     493             :     {
     494           0 :         size_t id2 = 0;
     495           0 :         const size_t& x = Transpose ? id1 : id2;
     496           0 :         const size_t& z = Transpose ? id2 : id1;
     497             : 
     498           0 :         size_t level = ABOVEWATER(x, z) ? 0 : maxLevel;
     499           0 :         size_t lookahead = (size_t)(level > 0);
     500             : 
     501           0 :         UPDATELOOKAHEAD;
     502             : 
     503             :         // start moving
     504           0 :         for (; id2 < SideSize; ++id2)
     505             :         {
     506             :             // update current level
     507           0 :             if (ABOVEWATER(x, z))
     508           0 :                 level = 0;
     509             :             else
     510           0 :                 level = std::min(level+1, maxLevel);
     511             : 
     512             :             // move lookahead
     513           0 :             if (lookahead == id2)
     514           0 :                 ++lookahead;
     515           0 :             UPDATELOOKAHEAD;
     516             : 
     517             :             // This is the important bit: set the distance to either:
     518             :             // - the distance to the previous shore point (level)
     519             :             // - the distance to the next shore point (lookahead-id2)
     520           0 :             distanceMap[z*SideSize + x] = std::min(distanceMap[z*SideSize + x], (float)std::min(lookahead-id2, level));
     521             :         }
     522             :     }
     523             : #undef ABOVEWATER
     524             : #undef UPDATELOOKAHEAD
     525           0 : }
     526             : 
     527             : ///////////////////////////////////////////////////////////////////
     528             : // Calculate our binary heightmap from the terrain heightmap.
     529           0 : void WaterManager::RecomputeDistanceHeightmap()
     530             : {
     531           0 :     const CTerrain& terrain = g_Game->GetWorld()->GetTerrain();
     532           0 :     if (!terrain.GetHeightMap())
     533             :         return;
     534             : 
     535           0 :     size_t SideSize = m_MapSize;
     536             : 
     537             :     // we want to look ahead some distance, but not too much (less efficient and not interesting). This is our lookahead.
     538           0 :     const size_t maxLevel = 5;
     539             : 
     540           0 :     if (!m_DistanceHeightmap)
     541             :     {
     542           0 :         m_DistanceHeightmap = std::make_unique<float[]>(SideSize * SideSize);
     543           0 :         std::fill(m_DistanceHeightmap.get(), m_DistanceHeightmap.get() + SideSize * SideSize, static_cast<float>(maxLevel));
     544             :     }
     545             : 
     546             :     // Create a manhattan-distance heightmap.
     547             :     // This could be refined to only be done near the coast itself, but it's probably not necessary.
     548             : 
     549           0 :     const std::uint16_t* const heightmap = terrain.GetHeightMap();
     550             : 
     551           0 :     ComputeDirection<false>(m_DistanceHeightmap.get(), heightmap, m_WaterHeight, SideSize, maxLevel);
     552           0 :     ComputeDirection<true>(m_DistanceHeightmap.get(), heightmap, m_WaterHeight, SideSize, maxLevel);
     553             : }
     554             : 
     555             : // This requires m_DistanceHeightmap to be defined properly.
     556           0 : void WaterManager::CreateWaveMeshes()
     557             : {
     558           0 :     if (m_MapSize == 0)
     559           0 :         return;
     560             : 
     561           0 :     const CTerrain& terrain = g_Game->GetWorld()->GetTerrain();
     562           0 :     if (!terrain.GetHeightMap())
     563             :         return;
     564             : 
     565           0 :     m_ShoreWaves.clear();
     566           0 :     m_ShoreWavesVBIndices.Reset();
     567             : 
     568           0 :     if (m_Waviness < 5.0f && m_WaterType != L"ocean")
     569             :         return;
     570             : 
     571           0 :     size_t SideSize = m_MapSize;
     572             : 
     573             :     // First step: get the points near the coast.
     574           0 :     std::set<int> CoastalPointsSet;
     575           0 :     for (size_t z = 1; z < SideSize-1; ++z)
     576           0 :         for (size_t x = 1; x < SideSize-1; ++x)
     577             :             // get the points not on the shore but near it, ocean-side
     578           0 :             if (m_DistanceHeightmap[z*m_MapSize + x] > 0.5f && m_DistanceHeightmap[z*m_MapSize + x] < 1.5f)
     579           0 :                 CoastalPointsSet.insert((z)*SideSize + x);
     580             : 
     581             :     // Second step: create chains out of those coastal points.
     582           0 :     static const int around[8][2] = { { -1,-1 }, { -1,0 }, { -1,1 }, { 0,1 }, { 1,1 }, { 1,0 }, { 1,-1 }, { 0,-1 } };
     583             : 
     584           0 :     std::vector<std::deque<CoastalPoint> > CoastalPointsChains;
     585           0 :     while (!CoastalPointsSet.empty())
     586             :     {
     587           0 :         int index = *(CoastalPointsSet.begin());
     588           0 :         int x = index % SideSize;
     589           0 :         int y = (index - x ) / SideSize;
     590             : 
     591           0 :         std::deque<CoastalPoint> Chain;
     592             : 
     593           0 :         Chain.push_front(CoastalPoint(index,CVector2D(x*4,y*4)));
     594             : 
     595             :         // Erase us.
     596           0 :         CoastalPointsSet.erase(CoastalPointsSet.begin());
     597             : 
     598             :         // We're our starter points. At most we can have 2 points close to us.
     599             :         // We'll pick the first one and look for its neighbors (he can only have one new)
     600             :         // Up until we either reach the end of the chain, or ourselves.
     601             :         // Then go down the other direction if there is any.
     602           0 :         int neighbours[2] = { -1, -1 };
     603           0 :         int nbNeighb = 0;
     604           0 :         for (int i = 0; i < 8; ++i)
     605             :         {
     606           0 :             if (CoastalPointsSet.count(x + around[i][0] + (y + around[i][1])*SideSize))
     607             :             {
     608           0 :                 if (nbNeighb < 2)
     609           0 :                     neighbours[nbNeighb] = x + around[i][0] + (y + around[i][1])*SideSize;
     610           0 :                 ++nbNeighb;
     611             :             }
     612             :         }
     613           0 :         if (nbNeighb > 2)
     614           0 :             continue;
     615             : 
     616           0 :         for (int i = 0; i < 2; ++i)
     617             :         {
     618           0 :             if (neighbours[i] == -1)
     619           0 :                 continue;
     620             :             // Move to our neighboring point
     621           0 :             int xx = neighbours[i] % SideSize;
     622           0 :             int yy = (neighbours[i] - xx ) / SideSize;
     623           0 :             int indexx = xx + yy*SideSize;
     624           0 :             int endedChain = false;
     625             : 
     626           0 :             if (i == 0)
     627           0 :                 Chain.push_back(CoastalPoint(indexx,CVector2D(xx*4,yy*4)));
     628             :             else
     629           0 :                 Chain.push_front(CoastalPoint(indexx,CVector2D(xx*4,yy*4)));
     630             : 
     631             :             // If there's a loop we'll be the "other" neighboring point already so check for that.
     632             :             // We'll readd at the end/front the other one to have full squares.
     633           0 :             if (CoastalPointsSet.count(indexx) == 0)
     634             :                 break;
     635             : 
     636           0 :             CoastalPointsSet.erase(indexx);
     637             : 
     638             :             // Start checking from there.
     639           0 :             while(!endedChain)
     640             :             {
     641           0 :                 bool found = false;
     642           0 :                 nbNeighb = 0;
     643           0 :                 for (int p = 0; p < 8; ++p)
     644             :                 {
     645           0 :                     if (CoastalPointsSet.count(xx+around[p][0] + (yy + around[p][1])*SideSize))
     646             :                     {
     647           0 :                         if (nbNeighb >= 2)
     648             :                         {
     649             :                             CoastalPointsSet.erase(xx + yy*SideSize);
     650             :                             continue;
     651             :                         }
     652           0 :                         ++nbNeighb;
     653             :                         // We've found a new point around us.
     654             :                         // Move there
     655           0 :                         xx = xx + around[p][0];
     656           0 :                         yy = yy + around[p][1];
     657           0 :                         indexx = xx + yy*SideSize;
     658           0 :                         if (i == 0)
     659           0 :                             Chain.push_back(CoastalPoint(indexx,CVector2D(xx*4,yy*4)));
     660             :                         else
     661           0 :                             Chain.push_front(CoastalPoint(indexx,CVector2D(xx*4,yy*4)));
     662           0 :                         CoastalPointsSet.erase(xx + yy*SideSize);
     663           0 :                         found = true;
     664           0 :                         break;
     665             :                     }
     666             :                 }
     667           0 :                 if (!found)
     668           0 :                     endedChain = true;
     669             :             }
     670             :         }
     671           0 :         if (Chain.size() > 10)
     672           0 :             CoastalPointsChains.push_back(Chain);
     673           0 :     }
     674             : 
     675             :     // (optional) third step: Smooth chains out.
     676             :     // This is also really dumb.
     677           0 :     for (size_t i = 0; i < CoastalPointsChains.size(); ++i)
     678             :     {
     679             :         // Bump 1 for smoother.
     680           0 :         for (int p = 0; p < 3; ++p)
     681             :         {
     682           0 :             for (size_t j = 1; j < CoastalPointsChains[i].size()-1; ++j)
     683             :             {
     684           0 :                 CVector2D realPos = CoastalPointsChains[i][j-1].position + CoastalPointsChains[i][j+1].position;
     685             : 
     686           0 :                 CoastalPointsChains[i][j].position = (CoastalPointsChains[i][j].position + realPos/2.0f)/2.0f;
     687             :             }
     688             :         }
     689             :     }
     690             : 
     691             :     // Fourth step: create waves themselves, using those chains. We basically create subchains.
     692           0 :     std::uint16_t waveSizes = 14;   // maximal size in width.
     693             : 
     694             :     // Construct indices buffer (we can afford one for all of them)
     695           0 :     std::vector<std::uint16_t> water_indices;
     696           0 :     for (std::uint16_t a = 0; a < waveSizes - 1; ++a)
     697             :     {
     698           0 :         for (std::uint16_t rect = 0; rect < 7; ++rect)
     699             :         {
     700           0 :             water_indices.push_back(a * 9 + rect);
     701           0 :             water_indices.push_back(a * 9 + 9 + rect);
     702           0 :             water_indices.push_back(a * 9 + 1 + rect);
     703           0 :             water_indices.push_back(a * 9 + 9 + rect);
     704           0 :             water_indices.push_back(a * 9 + 10 + rect);
     705           0 :             water_indices.push_back(a * 9 + 1 + rect);
     706             :         }
     707             :     }
     708             :     // Generic indexes, max-length
     709           0 :     m_ShoreWavesVBIndices = g_Renderer.GetVertexBufferManager().AllocateChunk(
     710             :         sizeof(std::uint16_t), water_indices.size(),
     711             :         Renderer::Backend::IBuffer::Type::INDEX,
     712             :         Renderer::Backend::IBuffer::Usage::TRANSFER_DST,
     713           0 :         nullptr, CVertexBufferManager::Group::WATER);
     714           0 :     m_ShoreWavesVBIndices->m_Owner->UpdateChunkVertices(m_ShoreWavesVBIndices.Get(), &water_indices[0]);
     715             : 
     716           0 :     float diff = (rand() % 50) / 5.0f;
     717             : 
     718           0 :     std::vector<SWavesVertex> vertices, reversed;
     719           0 :     for (size_t i = 0; i < CoastalPointsChains.size(); ++i)
     720             :     {
     721           0 :         for (size_t j = 0; j < CoastalPointsChains[i].size()-waveSizes; ++j)
     722             :         {
     723           0 :             if (CoastalPointsChains[i].size()- 1 - j < waveSizes)
     724             :                 break;
     725             : 
     726           0 :             std::uint16_t width = waveSizes;
     727             : 
     728             :             // First pass to get some parameters out.
     729             :             float outmost = 0.0f;   // how far to move on the shore.
     730             :             float avgDepth = 0.0f;
     731             :             int sign = 1;
     732             :             CVector2D firstPerp(0,0), perp(0,0), lastPerp(0,0);
     733           0 :             for (std::uint16_t a = 0; a < waveSizes; ++a)
     734             :             {
     735           0 :                 lastPerp = perp;
     736           0 :                 perp = CVector2D(0,0);
     737           0 :                 int nb = 0;
     738           0 :                 CVector2D pos = CoastalPointsChains[i][j+a].position;
     739           0 :                 CVector2D posPlus;
     740           0 :                 CVector2D posMinus;
     741           0 :                 if (a > 0)
     742             :                 {
     743           0 :                     ++nb;
     744           0 :                     posMinus = CoastalPointsChains[i][j+a-1].position;
     745           0 :                     perp += pos-posMinus;
     746             :                 }
     747           0 :                 if (a < waveSizes-1)
     748             :                 {
     749           0 :                     ++nb;
     750           0 :                     posPlus = CoastalPointsChains[i][j+a+1].position;
     751           0 :                     perp += posPlus-pos;
     752             :                 }
     753           0 :                 perp /= nb;
     754           0 :                 perp = CVector2D(-perp.Y,perp.X).Normalized();
     755             : 
     756           0 :                 if (a == 0)
     757           0 :                     firstPerp = perp;
     758             : 
     759           0 :                 if ( a > 1 && perp.Dot(lastPerp) < 0.90f && perp.Dot(firstPerp) < 0.70f)
     760             :                 {
     761           0 :                     width = a+1;
     762           0 :                     break;
     763             :                 }
     764             : 
     765           0 :                 if (terrain.GetExactGroundLevel(pos.X+perp.X*1.5f, pos.Y+perp.Y*1.5f)
     766           0 :                     > m_WaterHeight)
     767           0 :                     sign = -1;
     768             : 
     769           0 :                 avgDepth += terrain.GetExactGroundLevel(pos.X+sign*perp.X*20.0f,
     770           0 :                     pos.Y+sign*perp.Y*20.0f) - m_WaterHeight;
     771             : 
     772           0 :                 float localOutmost = -2.0f;
     773           0 :                 while (localOutmost < 0.0f)
     774             :                 {
     775           0 :                     const float depth = terrain.GetExactGroundLevel(
     776           0 :                         pos.X+sign*perp.X*localOutmost,
     777           0 :                         pos.Y+sign*perp.Y*localOutmost) - m_WaterHeight;
     778           0 :                     if (depth < 0.0f || depth > 0.6f)
     779           0 :                         localOutmost += 0.2f;
     780             :                     else
     781             :                         break;
     782             :                 }
     783             : 
     784           0 :                 outmost += localOutmost;
     785             :             }
     786           0 :             if (width < 5)
     787             :             {
     788           0 :                 j += 6;
     789           0 :                 continue;
     790             :             }
     791             : 
     792           0 :             outmost /= width;
     793             : 
     794           0 :             if (outmost > -0.5f)
     795             :             {
     796           0 :                 j += 3;
     797           0 :                 continue;
     798             :             }
     799           0 :             outmost = -2.5f + outmost * m_Waviness/10.0f;
     800             : 
     801           0 :             avgDepth /= width;
     802             : 
     803           0 :             if (avgDepth > -1.3f)
     804             :             {
     805           0 :                 j += 3;
     806           0 :                 continue;
     807             :             }
     808             :             // we passed the checks, we can create a wave of size "width".
     809             : 
     810           0 :             std::unique_ptr<WaveObject> shoreWave = std::make_unique<WaveObject>();
     811           0 :             vertices.clear();
     812           0 :             vertices.reserve(9 * width);
     813             : 
     814           0 :             shoreWave->m_Width = width;
     815           0 :             shoreWave->m_TimeDiff = diff;
     816           0 :             diff += (rand() % 100) / 25.0f + 4.0f;
     817             : 
     818           0 :             for (std::uint16_t a = 0; a < width; ++a)
     819             :             {
     820           0 :                 perp = CVector2D(0,0);
     821           0 :                 int nb = 0;
     822           0 :                 CVector2D pos = CoastalPointsChains[i][j+a].position;
     823           0 :                 CVector2D posPlus;
     824           0 :                 CVector2D posMinus;
     825           0 :                 if (a > 0)
     826             :                 {
     827           0 :                     ++nb;
     828           0 :                     posMinus = CoastalPointsChains[i][j+a-1].position;
     829           0 :                     perp += pos-posMinus;
     830             :                 }
     831           0 :                 if (a < waveSizes-1)
     832             :                 {
     833           0 :                     ++nb;
     834           0 :                     posPlus = CoastalPointsChains[i][j+a+1].position;
     835           0 :                     perp += posPlus-pos;
     836             :                 }
     837           0 :                 perp /= nb;
     838           0 :                 perp = CVector2D(-perp.Y,perp.X).Normalized();
     839             : 
     840           0 :                 SWavesVertex point[9];
     841             : 
     842           0 :                 float baseHeight = 0.04f;
     843             : 
     844           0 :                 float halfWidth = (width-1.0f)/2.0f;
     845           0 :                 float sideNess = sqrtf(Clamp( (halfWidth - fabsf(a - halfWidth)) / 3.0f, 0.0f, 1.0f));
     846             : 
     847           0 :                 point[0].m_UV[0] = a; point[0].m_UV[1] = 8;
     848           0 :                 point[1].m_UV[0] = a; point[1].m_UV[1] = 7;
     849           0 :                 point[2].m_UV[0] = a; point[2].m_UV[1] = 6;
     850           0 :                 point[3].m_UV[0] = a; point[3].m_UV[1] = 5;
     851           0 :                 point[4].m_UV[0] = a; point[4].m_UV[1] = 4;
     852           0 :                 point[5].m_UV[0] = a; point[5].m_UV[1] = 3;
     853           0 :                 point[6].m_UV[0] = a; point[6].m_UV[1] = 2;
     854           0 :                 point[7].m_UV[0] = a; point[7].m_UV[1] = 1;
     855           0 :                 point[8].m_UV[0] = a; point[8].m_UV[1] = 0;
     856             : 
     857           0 :                 point[0].m_PerpVect = perp;
     858           0 :                 point[1].m_PerpVect = perp;
     859           0 :                 point[2].m_PerpVect = perp;
     860           0 :                 point[3].m_PerpVect = perp;
     861           0 :                 point[4].m_PerpVect = perp;
     862           0 :                 point[5].m_PerpVect = perp;
     863           0 :                 point[6].m_PerpVect = perp;
     864           0 :                 point[7].m_PerpVect = perp;
     865           0 :                 point[8].m_PerpVect = perp;
     866             : 
     867           0 :                 static const float perpT1[9] = { 6.0f, 6.05f, 6.1f, 6.2f, 6.3f, 6.4f, 6.5f, 6.6f, 9.7f };
     868           0 :                 static const float perpT2[9] = { 2.0f, 2.1f,  2.2f, 2.3f, 2.4f, 3.0f, 3.3f, 3.6f, 9.5f };
     869           0 :                 static const float perpT3[9] = { 1.1f, 0.7f, -0.2f, 0.0f, 0.6f, 1.3f, 2.2f, 3.6f, 9.0f };
     870           0 :                 static const float perpT4[9] = { 2.0f, 2.1f,  1.2f, 1.5f, 1.7f, 1.9f, 2.7f, 3.8f, 9.0f };
     871             : 
     872           0 :                 static const float heightT1[9] = { 0.0f, 0.2f, 0.5f, 0.8f, 0.9f, 0.85f, 0.6f, 0.2f, 0.0 };
     873           0 :                 static const float heightT2[9] = { -0.8f, -0.4f, 0.0f, 0.1f, 0.1f, 0.03f, 0.0f, 0.0f, 0.0 };
     874           0 :                 static const float heightT3[9] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0 };
     875             : 
     876           0 :                 for (size_t t = 0; t < 9; ++t)
     877             :                 {
     878           0 :                     const float terrHeight = 0.05f + terrain.GetExactGroundLevel(
     879           0 :                         pos.X+sign*perp.X*(perpT1[t]+outmost),
     880           0 :                                                                             pos.Y+sign*perp.Y*(perpT1[t]+outmost));
     881           0 :                     point[t].m_BasePosition = CVector3D(pos.X+sign*perp.X*(perpT1[t]+outmost), baseHeight + heightT1[t]*sideNess + std::max(m_WaterHeight,terrHeight),
     882             :                                                         pos.Y+sign*perp.Y*(perpT1[t]+outmost));
     883             :                 }
     884           0 :                 for (size_t t = 0; t < 9; ++t)
     885             :                 {
     886           0 :                     const float terrHeight = 0.05f + terrain.GetExactGroundLevel(
     887           0 :                         pos.X+sign*perp.X*(perpT2[t]+outmost),
     888           0 :                                                                             pos.Y+sign*perp.Y*(perpT2[t]+outmost));
     889           0 :                     point[t].m_ApexPosition = CVector3D(pos.X+sign*perp.X*(perpT2[t]+outmost), baseHeight + heightT1[t]*sideNess + std::max(m_WaterHeight,terrHeight),
     890             :                                                         pos.Y+sign*perp.Y*(perpT2[t]+outmost));
     891             :                 }
     892           0 :                 for (size_t t = 0; t < 9; ++t)
     893             :                 {
     894           0 :                     const float terrHeight = 0.05f + terrain.GetExactGroundLevel(
     895           0 :                         pos.X+sign*perp.X*(perpT3[t]+outmost*sideNess),
     896           0 :                                                                             pos.Y+sign*perp.Y*(perpT3[t]+outmost*sideNess));
     897           0 :                     point[t].m_SplashPosition = CVector3D(pos.X+sign*perp.X*(perpT3[t]+outmost*sideNess), baseHeight + heightT2[t]*sideNess + std::max(m_WaterHeight,terrHeight), pos.Y+sign*perp.Y*(perpT3[t]+outmost*sideNess));
     898             :                 }
     899           0 :                 for (size_t t = 0; t < 9; ++t)
     900             :                 {
     901           0 :                     const float terrHeight = 0.05f + terrain.GetExactGroundLevel(
     902           0 :                         pos.X+sign*perp.X*(perpT4[t]+outmost),
     903           0 :                                                                             pos.Y+sign*perp.Y*(perpT4[t]+outmost));
     904           0 :                     point[t].m_RetreatPosition = CVector3D(pos.X+sign*perp.X*(perpT4[t]+outmost), baseHeight + heightT3[t]*sideNess + std::max(m_WaterHeight,terrHeight),
     905             :                                                            pos.Y+sign*perp.Y*(perpT4[t]+outmost));
     906             :                 }
     907             : 
     908           0 :                 vertices.push_back(point[8]);
     909           0 :                 vertices.push_back(point[7]);
     910           0 :                 vertices.push_back(point[6]);
     911           0 :                 vertices.push_back(point[5]);
     912           0 :                 vertices.push_back(point[4]);
     913           0 :                 vertices.push_back(point[3]);
     914           0 :                 vertices.push_back(point[2]);
     915           0 :                 vertices.push_back(point[1]);
     916           0 :                 vertices.push_back(point[0]);
     917             : 
     918           0 :                 shoreWave->m_AABB += point[8].m_SplashPosition;
     919           0 :                 shoreWave->m_AABB += point[8].m_BasePosition;
     920           0 :                 shoreWave->m_AABB += point[0].m_SplashPosition;
     921           0 :                 shoreWave->m_AABB += point[0].m_BasePosition;
     922           0 :                 shoreWave->m_AABB += point[4].m_ApexPosition;
     923             :             }
     924             : 
     925           0 :             if (sign == 1)
     926             :             {
     927             :                 // Let's do some fancy reversing.
     928           0 :                 reversed.clear();
     929           0 :                 reversed.reserve(vertices.size());
     930           0 :                 for (int a = width - 1; a >= 0; --a)
     931             :                 {
     932           0 :                     for (size_t t = 0; t < 9; ++t)
     933           0 :                         reversed.push_back(vertices[a * 9 + t]);
     934             :                 }
     935           0 :                 std::swap(vertices, reversed);
     936             :             }
     937           0 :             j += width/2-1;
     938             : 
     939           0 :             shoreWave->m_VBVertices = g_Renderer.GetVertexBufferManager().AllocateChunk(
     940             :                 sizeof(SWavesVertex), vertices.size(),
     941             :                 Renderer::Backend::IBuffer::Type::VERTEX,
     942             :                 Renderer::Backend::IBuffer::Usage::TRANSFER_DST,
     943           0 :                 nullptr, CVertexBufferManager::Group::WATER);
     944           0 :             shoreWave->m_VBVertices->m_Owner->UpdateChunkVertices(shoreWave->m_VBVertices.Get(), &vertices[0]);
     945             : 
     946           0 :             m_ShoreWaves.emplace_back(std::move(shoreWave));
     947           0 :         }
     948             :     }
     949           0 : }
     950             : 
     951           0 : void WaterManager::RenderWaves(
     952             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
     953             :     const CFrustum& frustrum)
     954             : {
     955           0 :     if (!m_WaterFancyEffects)
     956           0 :         return;
     957             : 
     958           0 :     m_WaveTex->UploadBackendTextureIfNeeded(deviceCommandContext);
     959           0 :     m_FoamTex->UploadBackendTextureIfNeeded(deviceCommandContext);
     960             : 
     961           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Render Waves");
     962             : 
     963           0 :     Renderer::Backend::IFramebuffer* framebuffer =
     964           0 :         m_FancyEffectsFramebuffer.get();
     965           0 :     deviceCommandContext->BeginFramebufferPass(framebuffer);
     966           0 :     Renderer::Backend::IDeviceCommandContext::Rect viewportRect{};
     967           0 :     viewportRect.width = framebuffer->GetWidth();
     968           0 :     viewportRect.height = framebuffer->GetHeight();
     969           0 :     deviceCommandContext->SetViewports(1, &viewportRect);
     970             : 
     971           0 :     CShaderTechniquePtr tech = g_Renderer.GetShaderManager().LoadEffect(str_water_waves);
     972           0 :     deviceCommandContext->SetGraphicsPipelineState(
     973             :         tech->GetGraphicsPipelineState());
     974           0 :     deviceCommandContext->BeginPass();
     975           0 :     Renderer::Backend::IShaderProgram* shader = tech->GetShader();
     976             : 
     977           0 :     deviceCommandContext->SetTexture(
     978           0 :         shader->GetBindingSlot(str_waveTex), m_WaveTex->GetBackendTexture());
     979           0 :     deviceCommandContext->SetTexture(
     980           0 :         shader->GetBindingSlot(str_foamTex), m_FoamTex->GetBackendTexture());
     981             : 
     982           0 :     deviceCommandContext->SetUniform(
     983           0 :         shader->GetBindingSlot(str_time), static_cast<float>(m_WaterTexTimer));
     984           0 :     const CMatrix3D transform =
     985           0 :         g_Renderer.GetSceneRenderer().GetViewCamera().GetViewProjection();
     986           0 :     deviceCommandContext->SetUniform(
     987           0 :         shader->GetBindingSlot(str_transform), transform.AsFloatArray());
     988             : 
     989           0 :     for (size_t a = 0; a < m_ShoreWaves.size(); ++a)
     990             :     {
     991           0 :         if (!frustrum.IsBoxVisible(m_ShoreWaves[a]->m_AABB))
     992           0 :             continue;
     993             : 
     994           0 :         CVertexBuffer::VBChunk* VBchunk = m_ShoreWaves[a]->m_VBVertices.Get();
     995           0 :         ENSURE(!VBchunk->m_Owner->GetBuffer()->IsDynamic());
     996           0 :         ENSURE(!m_ShoreWavesVBIndices->m_Owner->GetBuffer()->IsDynamic());
     997             : 
     998           0 :         const uint32_t stride = sizeof(SWavesVertex);
     999           0 :         const uint32_t firstVertexOffset = VBchunk->m_Index * stride;
    1000             : 
    1001           0 :         deviceCommandContext->SetVertexInputLayout(m_ShoreVertexInputLayout);
    1002             : 
    1003           0 :         deviceCommandContext->SetUniform(
    1004           0 :             shader->GetBindingSlot(str_translation), m_ShoreWaves[a]->m_TimeDiff);
    1005           0 :         deviceCommandContext->SetUniform(
    1006           0 :             shader->GetBindingSlot(str_width), static_cast<float>(m_ShoreWaves[a]->m_Width));
    1007             : 
    1008           0 :         deviceCommandContext->SetVertexBuffer(
    1009           0 :             0, VBchunk->m_Owner->GetBuffer(), firstVertexOffset);
    1010           0 :         deviceCommandContext->SetIndexBuffer(m_ShoreWavesVBIndices->m_Owner->GetBuffer());
    1011             : 
    1012           0 :         const uint32_t indexCount = (m_ShoreWaves[a]->m_Width - 1) * (7 * 6);
    1013           0 :         deviceCommandContext->DrawIndexed(m_ShoreWavesVBIndices->m_Index, indexCount, 0);
    1014             : 
    1015           0 :         g_Renderer.GetStats().m_DrawCalls++;
    1016           0 :         g_Renderer.GetStats().m_WaterTris += indexCount / 3;
    1017             :     }
    1018           0 :     deviceCommandContext->EndPass();
    1019           0 :     deviceCommandContext->EndFramebufferPass();
    1020           0 : }
    1021             : 
    1022           0 : void WaterManager::RecomputeWaterData()
    1023             : {
    1024           0 :     if (!m_MapSize)
    1025             :         return;
    1026             : 
    1027           0 :     RecomputeDistanceHeightmap();
    1028           0 :     RecomputeWindStrength();
    1029           0 :     CreateWaveMeshes();
    1030             : }
    1031             : 
    1032             : ///////////////////////////////////////////////////////////////////
    1033             : // Calculate the strength of the wind at a given point on the map.
    1034           0 : void WaterManager::RecomputeWindStrength()
    1035             : {
    1036           0 :     if (m_MapSize <= 0)
    1037           0 :         return;
    1038             : 
    1039           0 :     if (!m_WindStrength)
    1040           0 :         m_WindStrength = std::make_unique<float[]>(m_MapSize * m_MapSize);
    1041             : 
    1042           0 :     const CTerrain& terrain = g_Game->GetWorld()->GetTerrain();
    1043           0 :     if (!terrain.GetHeightMap())
    1044             :         return;
    1045             : 
    1046           0 :     CVector2D windDir = CVector2D(cos(m_WindAngle), sin(m_WindAngle));
    1047             : 
    1048           0 :     int stepSize = 10;
    1049           0 :     ssize_t windX = -round(stepSize * windDir.X);
    1050           0 :     ssize_t windY = -round(stepSize * windDir.Y);
    1051             : 
    1052           0 :     struct SWindPoint {
    1053           0 :         SWindPoint(size_t x, size_t y, float strength) : X(x), Y(y), windStrength(strength) {}
    1054             :         ssize_t X;
    1055             :         ssize_t Y;
    1056             :         float windStrength;
    1057             :     };
    1058             : 
    1059           0 :     std::vector<SWindPoint> startingPoints;
    1060           0 :     std::vector<std::pair<int, int>> movement; // Every increment, move each starting point by all of these.
    1061             : 
    1062             :     // Compute starting points (one or two edges of the map) and how much to move each computation increment.
    1063           0 :     if (fabs(windDir.X) < 0.01f)
    1064             :     {
    1065           0 :         movement.emplace_back(0, windY > 0.f ? 1 : -1);
    1066           0 :         startingPoints.reserve(m_MapSize);
    1067           0 :         size_t start = windY > 0 ? 0 : m_MapSize - 1;
    1068           0 :         for (size_t x = 0; x < m_MapSize; ++x)
    1069           0 :             startingPoints.emplace_back(x, start, 0.f);
    1070             :     }
    1071           0 :     else if (fabs(windDir.Y) < 0.01f)
    1072             :     {
    1073           0 :         movement.emplace_back(windX > 0.f ? 1 : - 1, 0);
    1074           0 :         startingPoints.reserve(m_MapSize);
    1075           0 :         size_t start = windX > 0 ? 0 : m_MapSize - 1;
    1076           0 :         for (size_t z = 0; z < m_MapSize; ++z)
    1077           0 :             startingPoints.emplace_back(start, z, 0.f);
    1078             :     }
    1079             :     else
    1080             :     {
    1081           0 :         startingPoints.reserve(m_MapSize * 2);
    1082             :         // Points along X.
    1083           0 :         size_t start = windY > 0 ? 0 : m_MapSize - 1;
    1084           0 :         for (size_t x = 0; x < m_MapSize; ++x)
    1085           0 :             startingPoints.emplace_back(x, start, 0.f);
    1086             :         // Points along Z, avoid repeating the corner point.
    1087           0 :         start = windX > 0 ? 0 : m_MapSize - 1;
    1088           0 :         if (windY > 0)
    1089           0 :             for (size_t z = 1; z < m_MapSize; ++z)
    1090           0 :                 startingPoints.emplace_back(start, z, 0.f);
    1091             :         else
    1092           0 :             for (size_t z = 0; z < m_MapSize-1; ++z)
    1093           0 :                 startingPoints.emplace_back(start, z, 0.f);
    1094             : 
    1095             :         // Compute movement array.
    1096           0 :         movement.reserve(std::max(std::abs(windX),std::abs(windY)));
    1097           0 :         while (windX != 0 || windY != 0)
    1098             :         {
    1099           0 :             std::pair<ssize_t, ssize_t> move = {
    1100           0 :                 windX == 0 ? 0 : windX > 0 ? +1 : -1,
    1101           0 :                 windY == 0 ? 0 : windY > 0 ? +1 : -1
    1102           0 :             };
    1103           0 :             windX -= move.first;
    1104           0 :             windY -= move.second;
    1105           0 :             movement.push_back(move);
    1106             :         }
    1107             :     }
    1108             : 
    1109             :     // We have all starting points ready, move them all until the map is covered.
    1110           0 :     for (SWindPoint& point : startingPoints)
    1111             :     {
    1112             :         // Starting velocity is 1.0 unless in shallow water.
    1113           0 :         m_WindStrength[point.Y * m_MapSize + point.X] = 1.f;
    1114           0 :         const float depth = m_WaterHeight - terrain.GetVertexGroundLevel(point.X, point.Y);
    1115           0 :         if (depth > 0.f && depth < 2.f)
    1116           0 :             m_WindStrength[point.Y * m_MapSize + point.X] = depth / 2.f;
    1117           0 :         point.windStrength = m_WindStrength[point.Y * m_MapSize + point.X];
    1118             : 
    1119           0 :         bool onMap = true;
    1120           0 :         while (onMap)
    1121           0 :             for (size_t step = 0; step < movement.size(); ++step)
    1122             :             {
    1123             :                 // Move wind speed towards the mean.
    1124           0 :                 point.windStrength = 0.15f + point.windStrength * 0.85f;
    1125             : 
    1126             :                 // Adjust speed based on height difference, a positive height difference slowly increases speed (simulate venturi effect)
    1127             :                 // and a lower height reduces speed (wind protection from hills/...)
    1128           0 :                 const float heightDiff = std::max(m_WaterHeight, terrain.GetVertexGroundLevel(
    1129           0 :                     point.X + movement[step].first, point.Y + movement[step].second)) -
    1130           0 :                     std::max(m_WaterHeight, terrain.GetVertexGroundLevel(point.X, point.Y));
    1131           0 :                 if (heightDiff > 0.f)
    1132           0 :                     point.windStrength = std::min(2.f, point.windStrength + std::min(4.f, heightDiff) / 40.f);
    1133             :                 else
    1134           0 :                     point.windStrength = std::max(0.f, point.windStrength + std::max(-4.f, heightDiff) / 5.f);
    1135             : 
    1136           0 :                 point.X += movement[step].first;
    1137           0 :                 point.Y += movement[step].second;
    1138             : 
    1139           0 :                 if (point.X < 0 || point.X >= static_cast<ssize_t>(m_MapSize) || point.Y < 0 || point.Y >= static_cast<ssize_t>(m_MapSize))
    1140             :                 {
    1141           0 :                     onMap = false;
    1142           0 :                     break;
    1143             :                 }
    1144           0 :                 m_WindStrength[point.Y * m_MapSize + point.X] = point.windStrength;
    1145             :             }
    1146             :     }
    1147             :     // TODO: should perhaps blur a little, or change the above code to incorporate neighboring tiles a bit.
    1148           0 : }
    1149             : 
    1150             : ////////////////////////////////////////////////////////////////////////
    1151             : // TODO: This will always recalculate for now
    1152           0 : void WaterManager::SetMapSize(size_t size)
    1153             : {
    1154             :     // TODO: Im' blindly trusting the user here.
    1155           0 :     m_MapSize = size;
    1156           0 :     m_NeedInfoUpdate = true;
    1157           0 :     m_updatei0 = 0;
    1158           0 :     m_updatei1 = size;
    1159           0 :     m_updatej0 = 0;
    1160           0 :     m_updatej1 = size;
    1161             : 
    1162           0 :     m_DistanceHeightmap.reset();
    1163           0 :     m_WindStrength.reset();
    1164           0 : }
    1165             : 
    1166             : ////////////////////////////////////////////////////////////////////////
    1167             : // This will set the bools properly
    1168           0 : void WaterManager::UpdateQuality()
    1169             : {
    1170           0 :     if (g_RenderingOptions.GetWaterEffects() != m_WaterEffects)
    1171             :     {
    1172           0 :         m_WaterEffects = g_RenderingOptions.GetWaterEffects();
    1173           0 :         m_NeedsReloading = true;
    1174             :     }
    1175           0 :     if (g_RenderingOptions.GetWaterFancyEffects() != m_WaterFancyEffects)
    1176             :     {
    1177           0 :         m_WaterFancyEffects = g_RenderingOptions.GetWaterFancyEffects();
    1178           0 :         m_NeedsReloading = true;
    1179             :     }
    1180           0 :     if (g_RenderingOptions.GetWaterRealDepth() != m_WaterRealDepth)
    1181             :     {
    1182           0 :         m_WaterRealDepth = g_RenderingOptions.GetWaterRealDepth();
    1183           0 :         m_NeedsReloading = true;
    1184             :     }
    1185           0 :     if (g_RenderingOptions.GetWaterRefraction() != m_WaterRefraction)
    1186             :     {
    1187           0 :         m_WaterRefraction = g_RenderingOptions.GetWaterRefraction();
    1188           0 :         m_NeedsReloading = true;
    1189             :     }
    1190           0 :     if (g_RenderingOptions.GetWaterReflection() != m_WaterReflection)
    1191             :     {
    1192           0 :         m_WaterReflection = g_RenderingOptions.GetWaterReflection();
    1193           0 :         m_NeedsReloading = true;
    1194             :     }
    1195           0 : }
    1196             : 
    1197           0 : bool WaterManager::WillRenderFancyWater() const
    1198             : {
    1199           0 :     return m_RenderWater && g_RenderingOptions.GetWaterEffects();
    1200             : }
    1201             : 
    1202           0 : size_t WaterManager::GetCurrentTextureIndex(const double& period) const
    1203             : {
    1204           0 :     ENSURE(period > 0.0);
    1205           0 :     return static_cast<size_t>(m_WaterTexTimer * ARRAY_SIZE(m_WaterTexture) / period) % ARRAY_SIZE(m_WaterTexture);
    1206             : }
    1207             : 
    1208           0 : size_t WaterManager::GetNextTextureIndex(const double& period) const
    1209             : {
    1210           0 :     ENSURE(period > 0.0);
    1211           0 :     return (GetCurrentTextureIndex(period) + 1) % ARRAY_SIZE(m_WaterTexture);
    1212             : }

Generated by: LCOV version 1.16