LCOV - code coverage report
Current view: top level - source/simulation2/helpers - Grid.h (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 122 141 86.5 %
Date: 2026-11-23 23:00:22 Functions: 26 34 76.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             : #ifndef INCLUDED_GRID
      19             : #define INCLUDED_GRID
      20             : 
      21             : #include "lib/code_annotation.h"
      22             : #include "lib/code_generation.h"
      23             : #include "lib/debug.h"
      24             : #include "simulation2/serialization/SerializeTemplates.h"
      25             : #include "simulation2/system/Component.h"
      26             : 
      27             : #include <algorithm>
      28             : #include <cstring>
      29             : #include <new>
      30             : #include <type_traits>
      31             : #include <utility>
      32             : 
      33             : #ifdef NDEBUG
      34             : #define GRID_BOUNDS_DEBUG 0
      35             : #else
      36             : #define GRID_BOUNDS_DEBUG 1
      37             : #endif
      38             : 
      39             : /**
      40             :  * Basic 2D array, intended for storing tile data, plus support for lazy updates
      41             :  * by ICmpObstructionManager.
      42             :  * @c T must be a POD type that can be initialised with 0s.
      43             :  */
      44             : template<typename T>
      45             : class Grid
      46             : {
      47             :     friend struct SerializeHelper<Grid<T>>;
      48             : public:
      49          12 :     Grid() : m_W(0), m_H(0), m_Data(NULL)
      50             :     {
      51             :     }
      52             : 
      53          92 :     Grid(std::uint16_t w, std::uint16_t h) : m_W(w), m_H(h), m_Data(NULL)
      54             :     {
      55          92 :         resize(w, h);
      56          89 :     }
      57             : 
      58        2085 :     Grid(const Grid& g) : m_W(0), m_H(0), m_Data(NULL)
      59             :     {
      60        2085 :         *this = g;
      61        2085 :     }
      62             : 
      63             :     using value_type = T;
      64             : public:
      65             : 
      66             :     // Ensure that o and this are the same size before calling.
      67       18768 :     Grid& operator=(const Grid& g)
      68             :     {
      69       18768 :         if (this == &g)
      70             :             return *this;
      71             : 
      72       18768 :         if (m_W == g.m_W && m_H == g.m_H)
      73             :         {
      74             :             if constexpr (std::is_trivially_copyable_v<T>)
      75       15629 :                 memcpy(m_Data, g.m_Data, m_W*m_H*sizeof(T));
      76             :             else
      77           0 :                 std::copy(g.m_Data, g.m_Data + m_H*m_W, &m_Data[0]);
      78       15629 :             return *this;
      79             :         }
      80             : 
      81        3139 :         m_W = g.m_W;
      82        3139 :         m_H = g.m_H;
      83        3139 :         SAFE_ARRAY_DELETE(m_Data);
      84        3139 :         if (g.m_Data)
      85             :         {
      86      269059 :             m_Data = new T[m_W * m_H];
      87             :             if constexpr (std::is_trivially_copyable_v<T>)
      88        2098 :                 memcpy(m_Data, g.m_Data, m_W*m_H*sizeof(T));
      89             :             else
      90        1041 :                 std::copy(g.m_Data, g.m_Data + m_H*m_W, &m_Data[0]);
      91             :         }
      92             :         return *this;
      93             :     }
      94             : 
      95         186 :     void swap(Grid& g)
      96             :     {
      97         186 :         std::swap(m_Data, g.m_Data);
      98         186 :         std::swap(m_H, g.m_H);
      99         186 :         std::swap(m_W, g.m_W);
     100         186 :     }
     101             : 
     102       18796 :     ~Grid()
     103             :     {
     104      292173 :         SAFE_ARRAY_DELETE(m_Data);
     105       17808 :     }
     106             : 
     107             :     // Ensure that o and this are the same size before calling.
     108             : 
     109       18738 :     bool operator==(const Grid& g) const
     110             :     {
     111       37476 :         if (!compare_sizes(&g))
     112             :             return false;
     113             : 
     114             :         if constexpr (std::is_standard_layout_v<T> && std::is_trivial_v<T>)
     115       17697 :             return memcmp(m_Data, g.m_Data, m_W*m_H*sizeof(T)) == 0;
     116             :         else
     117        1041 :             return std::equal(&m_Data[0], &m_Data[m_W*m_H], g.m_Data);
     118             :     }
     119        2082 :     bool operator!=(const Grid& g) const { return !(*this==g); }
     120             : 
     121       10887 :     bool blank() const
     122             :     {
     123       10887 :         return m_W == 0 && m_H == 0;
     124             :     }
     125             : 
     126      126889 :     std::uint16_t width() const { return m_W; };
     127      126881 :     std::uint16_t height() const { return m_H; };
     128             : 
     129          63 :     bool any_set_in_square(int i0, int j0, int i1, int j1) const
     130             :     {
     131             :         if constexpr (std::is_standard_layout_v<T> && std::is_trivial_v<T>)
     132             :         {
     133             : #if GRID_BOUNDS_DEBUG
     134             :             ENSURE(i0 >= 0 && j0 >= 0 && i1 <= m_W && j1 <= m_H);
     135             : #endif
     136        2913 :             for (int j = j0; j < j1; ++j)
     137             :             {
     138             :                 int sum = 0;
     139      222768 :                 for (int i = i0; i < i1; ++i)
     140      219888 :                     sum += m_Data[j*m_W + i];
     141        2880 :                 if (sum > 0)
     142             :                     return true;
     143             :             }
     144             :             return false;
     145             :         }
     146             :         else
     147             :         {
     148             :             static_assert(!std::is_same<T, T>::value, "Not implemented.");
     149             :             return false; // Fix warnings.
     150             :         }
     151             :     }
     152             : 
     153             :     // Reset the data to its default-constructed value (usually 0), not changing size.
     154        3487 :     void reset()
     155             :     {
     156        3487 :         if (m_Data) {
     157             :             if constexpr (std::is_standard_layout_v<T> && std::is_trivial_v<T>)
     158        2413 :                 memset(m_Data, 0, m_W*m_H*sizeof(T));
     159             :             else
     160        2110 :                 std::fill(&m_Data[0], &m_Data[m_H*m_W], T{});
     161             :         }
     162        3487 :     }
     163             : 
     164             :     // Clear the grid setting the size to 0 and freeing any data.
     165       16832 :     void clear()
     166             :     {
     167       16832 :         resize(0, 0);
     168             :     }
     169             : 
     170       20103 :     void resize(std::uint16_t w, std::uint16_t h)
     171             :     {
     172      287751 :         SAFE_ARRAY_DELETE(m_Data);
     173       20103 :         m_W = w;
     174       20103 :         m_H = h;
     175             : 
     176       20103 :         if (!m_W && !m_H)
     177             :             return;
     178             : 
     179      278298 :         m_Data = new T[m_W * m_H];
     180        3271 :         ENSURE(m_Data);
     181        3271 :         reset();
     182             :     }
     183             : 
     184             :     // Add two grids of the same size
     185             :     void add(const Grid& g)
     186             :     {
     187             : #if GRID_BOUNDS_DEBUG
     188             :         ENSURE(g.m_W == m_W && g.m_H == m_H);
     189             : #endif
     190             :         for (int i=0; i < m_H*m_W; ++i)
     191             :             m_Data[i] += g.m_Data[i];
     192             :     }
     193             : 
     194           0 :     void bitwise_or(const Grid& g)
     195             :     {
     196           0 :         if (this == &g)
     197             :             return;
     198             : 
     199             : #if GRID_BOUNDS_DEBUG
     200             :         ENSURE(g.m_W == m_W && g.m_H == m_H);
     201             : #endif
     202           0 :         for (int i = 0; i < m_H*m_W; ++i)
     203           0 :             m_Data[i] |= g.m_Data[i];
     204             :     }
     205             : 
     206    21527235 :     void set(int i, int j, const T& value)
     207             :     {
     208             : #if GRID_BOUNDS_DEBUG
     209             :         ENSURE(0 <= i && i < m_W && 0 <= j && j < m_H);
     210             : #endif
     211    13313230 :         m_Data[j*m_W + i] = value;
     212      334058 :     }
     213             : 
     214        1603 :     T& operator[](std::pair<std::uint16_t, std::uint16_t> coords) { return get(coords.first, coords.second); }
     215             :     T& get(std::pair<std::uint16_t, std::uint16_t> coords) { return get(coords.first, coords.second); }
     216             : 
     217        1527 :     T& operator[](std::pair<std::uint16_t, std::uint16_t> coords) const { return get(coords.first, coords.second); }
     218             :     T& get(std::pair<std::uint16_t, std::uint16_t> coords) const { return get(coords.first, coords.second); }
     219             : 
     220   406623212 :     T& get(int i, int j)
     221             :     {
     222             : #if GRID_BOUNDS_DEBUG
     223             :         ENSURE(0 <= i && i < m_W && 0 <= j && j < m_H);
     224             : #endif
     225   402109774 :         return m_Data[j*m_W + i];
     226             :     }
     227             : 
     228     2164331 :     T& get(int i, int j) const
     229             :     {
     230             : #if GRID_BOUNDS_DEBUG
     231             :         ENSURE(0 <= i && i < m_W && 0 <= j && j < m_H);
     232             : #endif
     233     2164331 :         return m_Data[j*m_W + i];
     234             :     }
     235             : 
     236             :     template<typename U>
     237       19119 :     bool compare_sizes(const Grid<U>* g) const
     238             :     {
     239       19113 :         return g && m_W == g->m_W && m_H == g->m_H;
     240             :     }
     241             : 
     242             :     std::uint16_t m_W, m_H;
     243             :     T* m_Data;
     244             : };
     245             : 
     246             : 
     247             : /**
     248             :  * Serialize a grid, applying a simple RLE compression that is assumed efficient.
     249             :  */
     250             : template<typename T>
     251             : struct SerializeHelper<Grid<T>>
     252             : {
     253          37 :     void operator()(ISerializer& serialize, const char* name, Grid<T>& value)
     254             :     {
     255          37 :         size_t len = value.m_H * value.m_W;
     256          37 :         serialize.NumberU16_Unbounded("width", value.m_W);
     257          37 :         serialize.NumberU16_Unbounded("height", value.m_H);
     258          37 :         if (len == 0)
     259          37 :             return;
     260          37 :         std::uint32_t count = 1;
     261          37 :         T prevVal = value.m_Data[0];
     262      680856 :         for (size_t i = 1; i < len; ++i)
     263             :         {
     264      680819 :             if (prevVal == value.m_Data[i])
     265             :             {
     266      671856 :                 count++;
     267      671856 :                 continue;
     268             :             }
     269        8963 :             serialize.NumberU32_Unbounded("#", count);
     270        8963 :             Serializer(serialize, name, prevVal);
     271        8963 :             count = 1;
     272        8963 :             prevVal = value.m_Data[i];
     273             :         }
     274          37 :         serialize.NumberU32_Unbounded("#", count);
     275          37 :         Serializer(serialize, name, prevVal);
     276             :     }
     277             : 
     278           0 :     void operator()(IDeserializer& deserialize, const char* name, Grid<T>& value)
     279             :     {
     280             :         std::uint16_t w, h;
     281           0 :         deserialize.NumberU16_Unbounded("width", w);
     282           0 :         deserialize.NumberU16_Unbounded("height", h);
     283           0 :         std::uint32_t len = h * w;
     284           0 :         value.resize(w, h);
     285           0 :         for (size_t i = 0; i < len;)
     286             :         {
     287             :             std::uint32_t count;
     288           0 :             deserialize.NumberU32_Unbounded("#", count);
     289             :             T el;
     290           0 :             Serializer(deserialize, name, el);
     291           0 :             std::fill(&value.m_Data[i], &value.m_Data[i+count], el);
     292           0 :             i += count;
     293             :         }
     294           0 :     }
     295             : };
     296             : 
     297             : 
     298             : /**
     299             :  * Similar to Grid, except optimised for sparse usage (the grid is subdivided into
     300             :  * buckets whose contents are only initialised on demand, to save on memset cost).
     301             :  */
     302             : template<typename T>
     303             : class SparseGrid
     304             : {
     305             :     NONCOPYABLE(SparseGrid);
     306             : 
     307             :     enum { BucketBits = 4, BucketSize = 1 << BucketBits };
     308             : 
     309       17983 :     T* GetBucket(int i, int j)
     310             :     {
     311       17983 :         size_t b = (j >> BucketBits) * m_BW + (i >> BucketBits);
     312       17983 :         if (!m_Data[b])
     313             :         {
     314      526882 :             m_Data[b] = new T[BucketSize*BucketSize]();
     315             :         }
     316       17977 :         return m_Data[b];
     317             :     }
     318             : 
     319             : public:
     320         954 :     SparseGrid(std::uint16_t w, std::uint16_t h) : m_W(w), m_H(h), m_DirtyID(0)
     321             :     {
     322         954 :         ENSURE(m_W && m_H);
     323             : 
     324         954 :         m_BW = static_cast<std::uint16_t>((m_W + BucketSize-1) >> BucketBits);
     325         954 :         m_BH = static_cast<std::uint16_t>((m_H + BucketSize-1) >> BucketBits);
     326             : 
     327     2136762 :         m_Data = new T*[m_BW*m_BH]();
     328         954 :     }
     329             : 
     330         950 :     ~SparseGrid()
     331             :     {
     332         950 :         reset();
     333         954 :         SAFE_ARRAY_DELETE(m_Data);
     334         954 :     }
     335             : 
     336         950 :     void reset()
     337             :     {
     338     1931786 :         for (size_t i = 0; i < (size_t)(m_BW*m_BH); ++i)
     339     1930832 :             SAFE_ARRAY_DELETE(m_Data[i]);
     340             : 
     341             :         // Reset m_Data by value-constructing in place with placement new.
     342     2175930 :         m_Data = new (m_Data) T*[m_BW*m_BH]();
     343         954 :     }
     344             : 
     345           0 :     void set(int i, int j, const T& value)
     346             :     {
     347             : #if GRID_BOUNDS_DEBUG
     348             :         ENSURE(0 <= i && i < m_W && 0 <= j && j < m_H);
     349             : #endif
     350           0 :         GetBucket(i, j)[(j % BucketSize)*BucketSize + (i % BucketSize)] = value;
     351             :     }
     352             : 
     353         953 :     T& get(int i, int j)
     354             :     {
     355             : #if GRID_BOUNDS_DEBUG
     356             :         ENSURE(0 <= i && i < m_W && 0 <= j && j < m_H);
     357             : #endif
     358       16178 :         return GetBucket(i, j)[(j % BucketSize)*BucketSize + (i % BucketSize)];
     359             :     }
     360             : 
     361             :     std::uint16_t m_W, m_H;
     362             :     std::uint16_t m_BW, m_BH;
     363             :     T** m_Data;
     364             : 
     365             :     size_t m_DirtyID; // if this is < the id maintained by ICmpObstructionManager then it needs to be updated
     366             : };
     367             : 
     368             : /**
     369             :  * Structure holding grid dirtiness informations, for clever updates.
     370             :  */
     371          19 : struct GridUpdateInformation
     372             : {
     373             :     bool dirty;
     374             :     bool globallyDirty;
     375             :     Grid<std::uint8_t> dirtinessGrid;
     376             : 
     377             :     /**
     378             :      * Update the information with additionnal needed updates, then erase the source of additions.
     379             :      * This can usually be optimized through a careful memory management.
     380             :      */
     381         192 :     void MergeAndClear(GridUpdateInformation& b)
     382             :     {
     383         192 :         ENSURE(dirtinessGrid.compare_sizes(&b.dirtinessGrid));
     384             : 
     385         192 :         bool wasDirty = dirty;
     386             : 
     387         192 :         dirty |= b.dirty;
     388         192 :         globallyDirty |= b.globallyDirty;
     389             : 
     390             :         // If the current grid is useless, swap it
     391         192 :         if (!wasDirty)
     392         186 :             dirtinessGrid.swap(b.dirtinessGrid);
     393             :         // If the new grid isn't used, don't bother updating it
     394           6 :         else if (dirty && !globallyDirty)
     395           0 :             dirtinessGrid.bitwise_or(b.dirtinessGrid);
     396             : 
     397         384 :         b.Clean();
     398         192 :     }
     399             : 
     400             :     /**
     401             :      * Mark everything as clean
     402             :      */
     403         199 :     void Clean()
     404             :     {
     405         199 :         dirty = false;
     406         199 :         globallyDirty = false;
     407         199 :         dirtinessGrid.reset();
     408             :     }
     409             : };
     410             : 
     411             : #endif // INCLUDED_GRID

Generated by: LCOV version 1.16