LCOV - code coverage report
Current view: top level - source/renderer - VertexBuffer.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 77 120 64.2 %
Date: 2026-12-03 01:19:39 Functions: 8 14 57.1 %

          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 "VertexBuffer.h"
      21             : 
      22             : #include "lib/debug.h"
      23             : #include "renderer/Renderer.h"
      24             : #include "renderer/backend/IDevice.h"
      25             : #include "renderer/backend/IDeviceCommandContext.h"
      26             : 
      27             : #include <algorithm>
      28             : #include <cstring>
      29             : #include <iterator>
      30             : 
      31             : // Absolute maximum (bytewise) size of each GL vertex buffer object.
      32             : // Make it large enough for the maximum feasible mesh size (64K vertexes,
      33             : // 64 bytes per vertex in InstancingModelRenderer).
      34             : // TODO: measure what influence this has on performance
      35             : constexpr std::size_t MAX_VB_SIZE_BYTES = 4 * 1024 * 1024;
      36             : 
      37          10 : CVertexBuffer::CVertexBuffer(
      38             :     Renderer::Backend::IDevice* device, const char* name, const size_t vertexSize,
      39          10 :     const Renderer::Backend::IBuffer::Type type, const uint32_t usage)
      40          10 :     : CVertexBuffer(device, name, vertexSize, type, usage, MAX_VB_SIZE_BYTES)
      41             : {
      42          10 : }
      43             : 
      44          10 : CVertexBuffer::CVertexBuffer(
      45             :     Renderer::Backend::IDevice* device, const char* name, const size_t vertexSize,
      46             :     const Renderer::Backend::IBuffer::Type type, const uint32_t usage,
      47          10 :     const size_t maximumBufferSize)
      48          10 :     : m_VertexSize(vertexSize), m_HasNeededChunks(false)
      49             : {
      50          10 :     size_t size = maximumBufferSize;
      51             : 
      52          10 :     if (type == Renderer::Backend::IBuffer::Type::VERTEX)
      53             :     {
      54             :         // We want to store 16-bit indices to any vertex in a buffer, so the
      55             :         // buffer must never be bigger than vertexSize*64K bytes since we can
      56             :         // address at most 64K of them with 16-bit indices
      57           0 :         size = std::min(size, vertexSize * 65536);
      58             :     }
      59          10 :     else if (type == Renderer::Backend::IBuffer::Type::INDEX)
      60             :     {
      61          10 :         ENSURE(vertexSize == sizeof(std::uint16_t));
      62             :     }
      63             : 
      64             :     // store max/free vertex counts
      65          10 :     m_MaxVertices = m_FreeVertices = size / vertexSize;
      66             : 
      67          20 :     m_Buffer = device->CreateBuffer(
      68          10 :         name, type, m_MaxVertices * m_VertexSize, usage);
      69             : 
      70             :     // create sole free chunk
      71          10 :     VBChunk* chunk = new VBChunk;
      72          10 :     chunk->m_Owner = this;
      73          10 :     chunk->m_Count = m_FreeVertices;
      74          10 :     chunk->m_Index = 0;
      75          10 :     m_FreeList.emplace_back(chunk);
      76          10 : }
      77             : 
      78          10 : CVertexBuffer::~CVertexBuffer()
      79             : {
      80             :     // Must have released all chunks before destroying the buffer
      81          10 :     ENSURE(m_AllocList.empty());
      82             : 
      83          10 :     m_Buffer.reset();
      84             : 
      85          20 :     for (VBChunk* const& chunk : m_FreeList)
      86          10 :         delete chunk;
      87          20 : }
      88             : 
      89          10 : bool CVertexBuffer::CompatibleVertexType(
      90             :     const size_t vertexSize, const Renderer::Backend::IBuffer::Type type,
      91             :     const uint32_t usage) const
      92             : {
      93          10 :     ENSURE(m_Buffer);
      94          10 :     return type == m_Buffer->GetType() && usage == m_Buffer->GetUsage() && vertexSize == m_VertexSize;
      95             : }
      96             : 
      97             : ///////////////////////////////////////////////////////////////////////////////
      98             : // Allocate: try to allocate a buffer of given number of vertices (each of
      99             : // given size), with the given type, and using the given texture - return null
     100             : // if no free chunks available
     101          10 : CVertexBuffer::VBChunk* CVertexBuffer::Allocate(
     102             :     const size_t vertexSize, const size_t numberOfVertices,
     103             :     const Renderer::Backend::IBuffer::Type type, const uint32_t usage,
     104             :     void* backingStore)
     105             : {
     106             :     // check this is the right kind of buffer
     107          10 :     if (!CompatibleVertexType(vertexSize, type, usage))
     108             :         return nullptr;
     109             : 
     110          10 :     if (UseStreaming(usage))
     111           0 :         ENSURE(backingStore != nullptr);
     112             : 
     113             :     // quick check there's enough vertices spare to allocate
     114          10 :     if (numberOfVertices > m_FreeVertices)
     115             :         return nullptr;
     116             : 
     117             :     // trawl free list looking for first free chunk with enough space
     118          10 :     std::vector<VBChunk*>::iterator best_iter = m_FreeList.end();
     119          20 :     for (std::vector<VBChunk*>::iterator iter = m_FreeList.begin(); iter != m_FreeList.end(); ++iter)
     120             :     {
     121          10 :         if (numberOfVertices == (*iter)->m_Count)
     122             :         {
     123             :             best_iter = iter;
     124             :             break;
     125             :         }
     126          10 :         else if (numberOfVertices < (*iter)->m_Count && (best_iter == m_FreeList.end() || (*best_iter)->m_Count < (*iter)->m_Count))
     127             :             best_iter = iter;
     128             :     }
     129             : 
     130             :     // We could not find a large enough chunk.
     131          10 :     if (best_iter == m_FreeList.end())
     132             :         return nullptr;
     133             : 
     134          10 :     VBChunk* chunk = *best_iter;
     135          10 :     m_FreeList.erase(best_iter);
     136          10 :     m_FreeVertices -= chunk->m_Count;
     137             : 
     138          10 :     chunk->m_BackingStore = backingStore;
     139          10 :     chunk->m_Dirty = false;
     140          10 :     chunk->m_Needed = false;
     141             : 
     142             :     // split chunk into two; - allocate a new chunk using all unused vertices in the
     143             :     // found chunk, and add it to the free list
     144          10 :     if (chunk->m_Count > numberOfVertices)
     145             :     {
     146          10 :         VBChunk* newchunk = new VBChunk;
     147          10 :         newchunk->m_Owner = this;
     148          10 :         newchunk->m_Count = chunk->m_Count - numberOfVertices;
     149          10 :         newchunk->m_Index = chunk->m_Index + numberOfVertices;
     150          10 :         m_FreeList.emplace_back(newchunk);
     151          10 :         m_FreeVertices += newchunk->m_Count;
     152             : 
     153             :         // resize given chunk
     154          10 :         chunk->m_Count = numberOfVertices;
     155             :     }
     156             : 
     157             :     // return found chunk
     158          10 :     m_AllocList.push_back(chunk);
     159             :     return chunk;
     160             : }
     161             : 
     162             : ///////////////////////////////////////////////////////////////////////////////
     163             : // Release: return given chunk to this buffer
     164          10 : void CVertexBuffer::Release(VBChunk* chunk)
     165             : {
     166             :     // Update total free count before potentially modifying this chunk's count
     167          10 :     m_FreeVertices += chunk->m_Count;
     168             : 
     169          10 :     m_AllocList.erase(std::find(m_AllocList.begin(), m_AllocList.end(), chunk));
     170             : 
     171             :     // Sorting O(nlogn) shouldn't be too far from O(n) by performance, because
     172             :     // the container is partly sorted already.
     173          10 :     std::sort(
     174             :         m_FreeList.begin(), m_FreeList.end(),
     175           0 :         [](const VBChunk* chunk1, const VBChunk* chunk2) -> bool
     176             :         {
     177           0 :             return chunk1->m_Index < chunk2->m_Index;
     178             :         });
     179             : 
     180             :     // Coalesce with any free-list items that are adjacent to this chunk;
     181             :     // merge the found chunk with the new one, and remove the old one
     182             :     // from the list.
     183          10 :     for (std::vector<VBChunk*>::iterator iter = m_FreeList.begin(); iter != m_FreeList.end();)
     184             :     {
     185          10 :         if ((*iter)->m_Index == chunk->m_Index + chunk->m_Count
     186          10 :          || (*iter)->m_Index + (*iter)->m_Count == chunk->m_Index)
     187             :         {
     188          10 :             chunk->m_Index = std::min(chunk->m_Index, (*iter)->m_Index);
     189          10 :             chunk->m_Count += (*iter)->m_Count;
     190          10 :             delete *iter;
     191          10 :             iter = m_FreeList.erase(iter);
     192          10 :             if (!m_FreeList.empty() && iter != m_FreeList.begin())
     193           0 :                 iter = std::prev(iter);
     194             :         }
     195             :         else
     196             :         {
     197          20 :             ++iter;
     198             :         }
     199             :     }
     200             : 
     201          10 :     m_FreeList.emplace_back(chunk);
     202          10 : }
     203             : 
     204             : ///////////////////////////////////////////////////////////////////////////////
     205             : // UpdateChunkVertices: update vertex data for given chunk
     206          10 : void CVertexBuffer::UpdateChunkVertices(VBChunk* chunk, void* data)
     207             : {
     208          10 :     ENSURE(m_Buffer);
     209          10 :     if (UseStreaming(m_Buffer->GetUsage()))
     210             :     {
     211             :         // The backend buffer is now out of sync with the backing store.
     212           0 :         chunk->m_Dirty = true;
     213             : 
     214             :         // Sanity check: Make sure the caller hasn't tried to reallocate
     215             :         // their backing store.
     216           0 :         ENSURE(data == chunk->m_BackingStore);
     217             :     }
     218             :     else
     219             :     {
     220          10 :         ENSURE(data);
     221          10 :         g_Renderer.GetDeviceCommandContext()->UploadBufferRegion(
     222          10 :             m_Buffer.get(), data, chunk->m_Index * m_VertexSize, chunk->m_Count * m_VertexSize);
     223             :     }
     224          10 : }
     225             : 
     226           0 : void CVertexBuffer::UploadIfNeeded(
     227             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
     228             : {
     229           0 :     if (UseStreaming(m_Buffer->GetUsage()))
     230             :     {
     231           0 :         if (!m_HasNeededChunks)
     232             :             return;
     233             : 
     234             :         // If any chunks are out of sync with the current backend buffer, and are
     235             :         // needed for rendering this frame, we'll need to re-upload the backend buffer.
     236           0 :         bool needUpload = false;
     237           0 :         for (VBChunk* const& chunk : m_AllocList)
     238             :         {
     239           0 :             if (chunk->m_Dirty && chunk->m_Needed)
     240             :             {
     241             :                 needUpload = true;
     242             :                 break;
     243             :             }
     244             :         }
     245             : 
     246           0 :         if (needUpload)
     247             :         {
     248           0 :             deviceCommandContext->UploadBuffer(m_Buffer.get(), [&](std::uint8_t* mappedData)
     249             :             {
     250             : #ifndef NDEBUG
     251             :                 // To help detect bugs where PrepareForRendering() was not called,
     252             :                 // force all not-needed data to 0, so things won't get rendered
     253             :                 // with undefined (but possibly still correct-looking) data.
     254             :                 memset(mappedData, 0, m_MaxVertices * m_VertexSize);
     255             : #endif
     256             : 
     257             :                 // Copy only the chunks we need. (This condition is helpful when
     258             :                 // the backend buffer contains data for every unit in the world,
     259             :                 // but only a handful are visible on screen and we don't need to
     260             :                 // bother copying the rest.)
     261           0 :                 for (VBChunk* const& chunk : m_AllocList)
     262           0 :                     if (chunk->m_Needed)
     263           0 :                         std::memcpy(mappedData + chunk->m_Index * m_VertexSize, chunk->m_BackingStore, chunk->m_Count * m_VertexSize);
     264           0 :             });
     265             : 
     266             :             // Anything we just uploaded is clean; anything else is dirty
     267             :             // since the rest of the backend buffer content is now undefined
     268           0 :             for (VBChunk* const& chunk : m_AllocList)
     269             :             {
     270           0 :                 if (chunk->m_Needed)
     271             :                 {
     272           0 :                     chunk->m_Dirty = false;
     273           0 :                     chunk->m_Needed = false;
     274             :                 }
     275             :                 else
     276           0 :                     chunk->m_Dirty = true;
     277             :             }
     278             :         }
     279             :         else
     280             :         {
     281             :             // Reset the flags for the next phase.
     282           0 :             for (VBChunk* const& chunk : m_AllocList)
     283           0 :                 chunk->m_Needed = false;
     284             :         }
     285             : 
     286           0 :         m_HasNeededChunks = false;
     287             :     }
     288             : }
     289             : 
     290           0 : size_t CVertexBuffer::GetBytesReserved() const
     291             : {
     292           0 :     return MAX_VB_SIZE_BYTES;
     293             : }
     294             : 
     295           0 : size_t CVertexBuffer::GetBytesAllocated() const
     296             : {
     297           0 :     return (m_MaxVertices - m_FreeVertices) * m_VertexSize;
     298             : }
     299             : 
     300           0 : void CVertexBuffer::DumpStatus() const
     301             : {
     302           0 :     debug_printf("freeverts = %d\n", static_cast<int>(m_FreeVertices));
     303             : 
     304           0 :     size_t maxSize = 0;
     305           0 :     for (VBChunk* const& chunk : m_FreeList)
     306             :     {
     307           0 :         debug_printf("free chunk %p: size=%d\n", static_cast<void *>(chunk), static_cast<int>(chunk->m_Count));
     308           0 :         maxSize = std::max(chunk->m_Count, maxSize);
     309             :     }
     310           0 :     debug_printf("max size = %d\n", static_cast<int>(maxSize));
     311           0 : }
     312             : 
     313          40 : bool CVertexBuffer::UseStreaming(const uint32_t usage)
     314             : {
     315          20 :     return usage & Renderer::Backend::IBuffer::Usage::DYNAMIC;
     316             : }
     317             : 
     318           0 : void CVertexBuffer::PrepareForRendering(VBChunk* chunk)
     319             : {
     320           0 :     chunk->m_Needed = true;
     321           0 :     m_HasNeededChunks = true;
     322           0 : }

Generated by: LCOV version 1.16