LCOV - code coverage report
Current view: top level - source/renderer - DecalRData.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 4 176 2.3 %
Date: 2026-12-03 01:19:39 Functions: 1 8 12.5 %

          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 "DecalRData.h"
      21             : 
      22             : #include "graphics/Color.h"
      23             : #include "graphics/Decal.h"
      24             : #include "graphics/Material.h"
      25             : #include "graphics/ShaderDefines.h"
      26             : #include "graphics/ShaderManager.h"
      27             : #include "graphics/ShaderTechnique.h"
      28             : #include "graphics/ShaderTechniquePtr.h"
      29             : #include "graphics/Terrain.h"
      30             : #include "graphics/TextureManager.h"
      31             : #include "lib/alignment.h"
      32             : #include "lib/debug.h"
      33             : #include "lib/posix/posix_types.h"
      34             : #include "maths/Matrix3D.h"
      35             : #include "ps/CLogger.h"
      36             : #include "ps/CStrIntern.h"
      37             : #include "ps/CStrInternStatic.h"
      38             : #include "ps/memory/AllocatorAdapter.h"
      39             : #include "ps/memory/LinearAllocator.h"
      40             : #include "ps/Profile.h"
      41             : #include "renderer/Renderer.h"
      42             : #include "renderer/TerrainRenderer.h"
      43             : #include "renderer/VertexBuffer.h"
      44             : #include "renderer/backend/Format.h"
      45             : #include "renderer/backend/IBuffer.h"
      46             : #include "renderer/backend/IDeviceCommandContext.h"
      47             : #include "renderer/backend/IShaderProgram.h"
      48             : #include "simulation2/components/ICmpWaterManager.h"
      49             : #include "simulation2/system/Component.h"
      50             : #include "simulation2/system/Entity.h"
      51             : 
      52             : #include <algorithm>
      53             : #include <array>
      54             : #include <cstddef>
      55             : #include <cstdint>
      56             : #include <memory>
      57             : #include <utility>
      58             : 
      59             : // TODO: Currently each decal is a separate CDecalRData. We might want to use
      60             : // lots of decals for special effects like shadows, footprints, etc, in which
      61             : // case we should probably redesign this to batch them all together for more
      62             : // efficient rendering.
      63             : 
      64             : namespace
      65             : {
      66             : 
      67           0 : struct SDecalBatch
      68             : {
      69             :     CDecalRData* decal;
      70             :     CStrIntern shaderEffect;
      71             :     CShaderDefines shaderDefines;
      72             :     CVertexBuffer::VBChunk* vertices;
      73             :     CVertexBuffer::VBChunk* indices;
      74             : };
      75             : 
      76             : struct SDecalBatchComparator
      77             : {
      78           0 :     bool operator()(const SDecalBatch& lhs, const SDecalBatch& rhs) const
      79             :     {
      80           0 :         if (lhs.shaderEffect != rhs.shaderEffect)
      81           0 :             return lhs.shaderEffect < rhs.shaderEffect;
      82           0 :         if (lhs.shaderDefines != rhs.shaderDefines)
      83           0 :             return lhs.shaderDefines < rhs.shaderDefines;
      84           0 :         const CMaterial& lhsMaterial = lhs.decal->GetDecal()->m_Decal.m_Material;
      85           0 :         const CMaterial& rhsMaterial = rhs.decal->GetDecal()->m_Decal.m_Material;
      86           0 :         if (lhsMaterial.GetDiffuseTexture() != rhsMaterial.GetDiffuseTexture())
      87           0 :             return lhsMaterial.GetDiffuseTexture() < rhsMaterial.GetDiffuseTexture();
      88           0 :         if (lhs.vertices->m_Owner != rhs.vertices->m_Owner)
      89           0 :             return lhs.vertices->m_Owner < rhs.vertices->m_Owner;
      90           0 :         if (lhs.indices->m_Owner != rhs.indices->m_Owner)
      91           0 :             return lhs.indices->m_Owner < rhs.indices->m_Owner;
      92           0 :         return lhs.decal < rhs.decal;
      93             :     }
      94             : };
      95             : 
      96             : } // anonymous namespace
      97             : 
      98             : // static
      99          10 : Renderer::Backend::IVertexInputLayout* CDecalRData::GetVertexInputLayout()
     100             : {
     101          10 :     const uint32_t stride = sizeof(SDecalVertex);
     102          10 :     const std::array<Renderer::Backend::SVertexAttributeFormat, 3> attributes{{
     103             :         {Renderer::Backend::VertexAttributeStream::POSITION,
     104             :             Renderer::Backend::Format::R32G32B32_SFLOAT,
     105             :             offsetof(SDecalVertex, m_Position), stride,
     106             :             Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
     107             :         {Renderer::Backend::VertexAttributeStream::NORMAL,
     108             :             Renderer::Backend::Format::R32G32B32_SFLOAT,
     109             :             offsetof(SDecalVertex, m_Normal), stride,
     110             :             Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
     111             :         {Renderer::Backend::VertexAttributeStream::UV0,
     112             :             Renderer::Backend::Format::R32G32_SFLOAT,
     113             :             offsetof(SDecalVertex, m_UV), stride,
     114             :             Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
     115             :     }};
     116          10 :     return g_Renderer.GetVertexInputLayout(attributes);
     117             : }
     118             : 
     119           0 : CDecalRData::CDecalRData(CModelDecal* decal, CSimulation2* simulation)
     120           0 :     : m_Decal(decal), m_Simulation(simulation)
     121             : {
     122           0 :     BuildVertexData();
     123           0 : }
     124             : 
     125           0 : CDecalRData::~CDecalRData() = default;
     126             : 
     127           0 : void CDecalRData::Update(CSimulation2* simulation)
     128             : {
     129           0 :     m_Simulation = simulation;
     130           0 :     if (m_UpdateFlags != 0)
     131             :     {
     132           0 :         BuildVertexData();
     133           0 :         m_UpdateFlags = 0;
     134             :     }
     135           0 : }
     136             : 
     137           0 : void CDecalRData::RenderDecals(
     138             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
     139             :     Renderer::Backend::IVertexInputLayout* vertexInputLayout,
     140             :     const std::vector<CDecalRData*>& decals, const CShaderDefines& context,
     141             :     ShadowMap* shadow, const CMaterial::Pass materialPass)
     142             : {
     143           0 :     PROFILE3("render terrain decals");
     144           0 :     GPU_SCOPED_LABEL(deviceCommandContext, "Render terrain decals");
     145             : 
     146           0 :     PS::Memory::ScopedLinearAllocator scopedLinearAllocator{g_Renderer.GetLinearAllocator()};
     147             : 
     148           0 :     using Batches = std::vector<SDecalBatch, PS::Memory::AllocatorAdapter<SDecalBatch, PS::Memory::ScopedLinearAllocator>>;
     149           0 :     Batches batches((Batches::allocator_type(scopedLinearAllocator)));
     150           0 :     batches.reserve(decals.size());
     151             : 
     152           0 :     CShaderDefines contextDecal = context;
     153           0 :     contextDecal.Add(str_DECAL, str_1);
     154             : 
     155           0 :     for (CDecalRData* decal : decals)
     156             :     {
     157           0 :         const CMaterial& material{decal->m_Decal->m_Decal.m_Material};
     158           0 :         const auto& shader{material.GetShader(materialPass)};
     159           0 :         if (shader.effect.empty())
     160             :         {
     161           0 :             LOGERROR("Terrain renderer failed to load shader effect.\n");
     162           0 :             continue;
     163           0 :         }
     164             : 
     165           0 :         if (material.GetSamplers().empty() || !decal->m_VBDecals || !decal->m_VBDecalsIndices)
     166           0 :             continue;
     167             : 
     168           0 :         SDecalBatch batch;
     169           0 :         batch.decal = decal;
     170           0 :         batch.shaderEffect = shader.effect;
     171           0 :         batch.shaderDefines = shader.defines;
     172           0 :         batch.vertices = decal->m_VBDecals.Get();
     173           0 :         batch.indices = decal->m_VBDecalsIndices.Get();
     174             : 
     175           0 :         batches.emplace_back(std::move(batch));
     176             :     }
     177             : 
     178           0 :     if (batches.empty())
     179           0 :         return;
     180             : 
     181           0 :     std::sort(batches.begin(), batches.end(), SDecalBatchComparator());
     182             : 
     183           0 :     CVertexBuffer* lastIB = nullptr;
     184           0 :     for (auto itTechBegin = batches.begin(), itTechEnd = batches.begin(); itTechBegin != batches.end(); itTechBegin = itTechEnd)
     185             :     {
     186           0 :         while (itTechEnd != batches.end() &&
     187           0 :             itTechBegin->shaderEffect == itTechEnd->shaderEffect &&
     188           0 :             itTechBegin->shaderDefines == itTechEnd->shaderDefines)
     189             :         {
     190           0 :             ++itTechEnd;
     191             :         }
     192             : 
     193           0 :         CShaderDefines defines = contextDecal;
     194           0 :         defines.SetMany(itTechBegin->shaderDefines);
     195             :         // TODO: move enabling blend to XML.
     196           0 :         CShaderTechniquePtr techBase{g_Renderer.GetShaderManager().LoadEffect([](const CStrIntern shaderEffect)
     197             :             {
     198           0 :                 if (shaderEffect == str_terrain_base)
     199           0 :                     return str_terrain_decal;
     200           0 :                 if (shaderEffect == str_terrain_base_reflections)
     201           0 :                     return str_terrain_decal_reflections;
     202           0 :                 if (shaderEffect == str_terrain_base_wireframe)
     203           0 :                     return str_terrain_decal_wireframe;
     204             :                 return shaderEffect;
     205           0 :             }(itTechBegin->shaderEffect), defines)};
     206           0 :         if (!techBase)
     207             :         {
     208           0 :             LOGERROR("Terrain renderer failed to load shader effect ({})\n",
     209             :                 itTechBegin->shaderEffect.string());
     210           0 :             continue;
     211           0 :         }
     212             : 
     213           0 :         const int numPasses = techBase->GetNumPasses();
     214           0 :         for (int pass = 0; pass < numPasses; ++pass)
     215             :         {
     216           0 :             deviceCommandContext->SetGraphicsPipelineState(
     217             :                 techBase->GetGraphicsPipelineState(pass));
     218           0 :             deviceCommandContext->BeginPass();
     219             : 
     220           0 :             Renderer::Backend::IShaderProgram* shader = techBase->GetShader(pass);
     221           0 :             TerrainRenderer::PrepareShader(deviceCommandContext, shader, shadow);
     222             : 
     223           0 :             CColor shadingColor(1.0f, 1.0f, 1.0f, 1.0f);
     224           0 :             const int32_t shadingColorBindingSlot =
     225           0 :                 shader->GetBindingSlot(str_shadingColor);
     226           0 :             deviceCommandContext->SetUniform(
     227           0 :                 shadingColorBindingSlot, shadingColor.AsFloatArray());
     228             : 
     229           0 :             CShaderUniforms currentStaticUniforms;
     230             : 
     231             :             CVertexBuffer* lastVB = nullptr;
     232           0 :             for (auto itDecal = itTechBegin; itDecal != itTechEnd; ++itDecal)
     233             :             {
     234           0 :                 SDecalBatch& batch = *itDecal;
     235           0 :                 CDecalRData* decal = batch.decal;
     236           0 :                 CMaterial& material = decal->m_Decal->m_Decal.m_Material;
     237             : 
     238           0 :                 const CMaterial::SamplersVector& samplers = material.GetSamplers();
     239           0 :                 for (const CMaterial::TextureSampler& sampler : samplers)
     240           0 :                     sampler.Sampler->UploadBackendTextureIfNeeded(deviceCommandContext);
     241           0 :                 for (const CMaterial::TextureSampler& sampler : samplers)
     242             :                 {
     243           0 :                     deviceCommandContext->SetTexture(
     244           0 :                         shader->GetBindingSlot(sampler.Name),
     245           0 :                         sampler.Sampler->GetBackendTexture());
     246             :                 }
     247             : 
     248           0 :                 if (currentStaticUniforms != material.GetStaticUniforms())
     249             :                 {
     250           0 :                     currentStaticUniforms = material.GetStaticUniforms();
     251           0 :                     material.GetStaticUniforms().BindUniforms(deviceCommandContext, shader);
     252             :                 }
     253             : 
     254             :                 // TODO: Need to handle floating decals correctly. In particular, we need
     255             :                 // to render non-floating before water and floating after water (to get
     256             :                 // the blending right), and we also need to apply the correct lighting in
     257             :                 // each case, which doesn't really seem possible with the current
     258             :                 // TerrainRenderer.
     259             :                 // Also, need to mark the decals as dirty when water height changes.
     260             : 
     261             :                 //  m_Decal->GetBounds().Render();
     262             : 
     263           0 :                 if (shadingColor != decal->m_Decal->GetShadingColor())
     264             :                 {
     265           0 :                     shadingColor = decal->m_Decal->GetShadingColor();
     266           0 :                     deviceCommandContext->SetUniform(
     267           0 :                         shadingColorBindingSlot, shadingColor.AsFloatArray());
     268             :                 }
     269             : 
     270           0 :                 if (lastVB != batch.vertices->m_Owner)
     271             :                 {
     272           0 :                     lastVB = batch.vertices->m_Owner;
     273           0 :                     ENSURE(!lastVB->GetBuffer()->IsDynamic());
     274             : 
     275           0 :                     deviceCommandContext->SetVertexInputLayout(vertexInputLayout);
     276             : 
     277           0 :                     deviceCommandContext->SetVertexBuffer(
     278           0 :                         0, batch.vertices->m_Owner->GetBuffer(), 0);
     279             :                 }
     280             : 
     281           0 :                 if (lastIB != batch.indices->m_Owner)
     282             :                 {
     283           0 :                     lastIB = batch.indices->m_Owner;
     284           0 :                     ENSURE(!lastIB->GetBuffer()->IsDynamic());
     285           0 :                     deviceCommandContext->SetIndexBuffer(batch.indices->m_Owner->GetBuffer());
     286             :                 }
     287             : 
     288           0 :                 deviceCommandContext->DrawIndexed(batch.indices->m_Index, batch.indices->m_Count, 0);
     289             : 
     290             :                 // bump stats
     291           0 :                 g_Renderer.m_Stats.m_DrawCalls++;
     292           0 :                 g_Renderer.m_Stats.m_TerrainTris += batch.indices->m_Count / 3;
     293             :             }
     294             : 
     295           0 :             deviceCommandContext->EndPass();
     296             :         }
     297           0 :     }
     298           0 : }
     299             : 
     300           0 : void CDecalRData::BuildVertexData()
     301             : {
     302           0 :     PROFILE("decal build");
     303             : 
     304           0 :     const SDecal& decal = m_Decal->m_Decal;
     305             : 
     306             :     // TODO: Currently this constructs an axis-aligned bounding rectangle around
     307             :     // the decal. It would be more efficient for rendering if we excluded tiles
     308             :     // that are outside the (non-axis-aligned) decal rectangle.
     309             : 
     310           0 :     ssize_t i0, j0, i1, j1;
     311           0 :     m_Decal->CalcVertexExtents(i0, j0, i1, j1);
     312             :     // Currently CalcVertexExtents might return empty rectangle, that means
     313             :     // we can't render it.
     314           0 :     if (i1 <= i0 || j1 <= j0)
     315             :     {
     316             :         // We have nothing to render.
     317           0 :         m_VBDecals.Reset();
     318           0 :         m_VBDecalsIndices.Reset();
     319           0 :         return;
     320             :     }
     321             : 
     322           0 :     CmpPtr<ICmpWaterManager> cmpWaterManager(*m_Simulation, SYSTEM_ENTITY);
     323             : 
     324           0 :     std::vector<SDecalVertex> vertices((i1 - i0 + 1) * (j1 - j0 + 1));
     325             : 
     326           0 :     for (ssize_t j = j0, idx = 0; j <= j1; ++j)
     327             :     {
     328           0 :         for (ssize_t i = i0; i <= i1; ++i, ++idx)
     329             :         {
     330           0 :             SDecalVertex& vertex = vertices[idx];
     331           0 :             m_Decal->m_Terrain->CalcPosition(i, j, vertex.m_Position);
     332             : 
     333           0 :             if (decal.m_Floating && cmpWaterManager)
     334             :             {
     335           0 :                 vertex.m_Position.Y = std::max(
     336           0 :                     vertex.m_Position.Y,
     337           0 :                     cmpWaterManager->GetExactWaterLevel(vertex.m_Position.X, vertex.m_Position.Z));
     338             :             }
     339             : 
     340           0 :             m_Decal->m_Terrain->CalcNormal(i, j, vertex.m_Normal);
     341             : 
     342             :             // Map from world space back into decal texture space.
     343           0 :             CVector3D inv = m_Decal->GetInvTransform().Transform(vertex.m_Position);
     344           0 :             vertex.m_UV.X = 0.5f + (inv.X - decal.m_OffsetX) / decal.m_SizeX;
     345             :             // Flip V to match our texture convention.
     346           0 :             vertex.m_UV.Y = 0.5f - (inv.Z - decal.m_OffsetZ) / decal.m_SizeZ;
     347             :         }
     348             :     }
     349             : 
     350           0 :     if (!m_VBDecals || m_VBDecals->m_Count != vertices.size())
     351             :     {
     352           0 :         m_VBDecals = g_Renderer.GetVertexBufferManager().AllocateChunk(
     353             :             sizeof(SDecalVertex), vertices.size(),
     354             :             Renderer::Backend::IBuffer::Type::VERTEX,
     355           0 :             Renderer::Backend::IBuffer::Usage::TRANSFER_DST);
     356             :     }
     357           0 :     m_VBDecals->m_Owner->UpdateChunkVertices(m_VBDecals.Get(), vertices.data());
     358             : 
     359           0 :     std::vector<std::uint16_t> indices((i1 - i0) * (j1 - j0) * 6);
     360             : 
     361           0 :     const ssize_t w = i1 - i0 + 1;
     362           0 :     auto itIdx = indices.begin();
     363           0 :     const size_t base = m_VBDecals->m_Index;
     364           0 :     for (ssize_t dj = 0; dj < j1 - j0; ++dj)
     365             :     {
     366           0 :         for (ssize_t di = 0; di < i1 - i0; ++di)
     367             :         {
     368           0 :             const bool dir = m_Decal->m_Terrain->GetTriangulationDir(i0 + di, j0 + dj);
     369           0 :             if (dir)
     370             :             {
     371           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 0) * w + (di + 0)) + base);
     372           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 0) * w + (di + 1)) + base);
     373           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 1) * w + (di + 0)) + base);
     374             : 
     375           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 0) * w + (di + 1)) + base);
     376           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 1) * w + (di + 1)) + base);
     377           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 1) * w + (di + 0)) + base);
     378             :             }
     379             :             else
     380             :             {
     381           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 0) * w + (di + 0)) + base);
     382           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 0) * w + (di + 1)) + base);
     383           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 1) * w + (di + 1)) + base);
     384             : 
     385           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 1) * w + (di + 1)) + base);
     386           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 1) * w + (di + 0)) + base);
     387           0 :                 *itIdx++ = static_cast<std::uint16_t>(((dj + 0) * w + (di + 0)) + base);
     388             :             }
     389             :         }
     390             :     }
     391             : 
     392             :     // Construct vertex buffer.
     393           0 :     if (!m_VBDecalsIndices || m_VBDecalsIndices->m_Count != indices.size())
     394             :     {
     395           0 :         m_VBDecalsIndices = g_Renderer.GetVertexBufferManager().AllocateChunk(
     396             :             sizeof(std::uint16_t), indices.size(),
     397             :             Renderer::Backend::IBuffer::Type::INDEX,
     398           0 :             Renderer::Backend::IBuffer::Usage::TRANSFER_DST);
     399             :     }
     400           0 :     m_VBDecalsIndices->m_Owner->UpdateChunkVertices(m_VBDecalsIndices.Get(), indices.data());
     401           0 : }

Generated by: LCOV version 1.16