LCOV - code coverage report
Current view: top level - source/graphics - TerrainTextureManager.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 12 135 8.9 %
Date: 2026-12-03 01:19:39 Functions: 3 13 23.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 "TerrainTextureManager.h"
      21             : 
      22             : #include "graphics/TerrainProperties.h"
      23             : #include "graphics/TerrainTextureEntry.h"
      24             : #include "lib/alignment.h"
      25             : #include "lib/allocators/shared_ptr.h"
      26             : #include "lib/debug.h"
      27             : #include "lib/file/vfs/vfs.h"
      28             : #include "lib/file/vfs/vfs_util.h"
      29             : #include "lib/path.h"
      30             : #include "lib/status.h"
      31             : #include "lib/tex/tex.h"
      32             : #include "maths/MathUtil.h"
      33             : #include "ps/CLogger.h"
      34             : #include "ps/Filesystem.h"
      35             : #include "ps/XMB/XMBStorage.h"
      36             : #include "ps/XML/Xeromyces.h"
      37             : #include "renderer/backend/Format.h"
      38             : #include "renderer/backend/IDevice.h"
      39             : #include "renderer/backend/IDeviceCommandContext.h"
      40             : #include "renderer/backend/Sampler.h"
      41             : 
      42             : #include <algorithm>
      43             : #include <bit>
      44             : #include <cstdint>
      45             : #include <utility>
      46             : #include <vector>
      47             : 
      48             : class CFileInfo;
      49             : 
      50          10 : CTerrainTextureManager::CTerrainTextureManager(Renderer::Backend::IDevice* device)
      51          10 :     : m_Device(device)
      52             : {
      53          20 :     if (!VfsDirectoryExists(L"art/terrains/"))
      54             :         return;
      55           0 :     if (!g_Xeromyces.AddValidator(g_VFS, "terrain", "art/terrains/terrain.rng"))
      56           0 :         LOGERROR("CTerrainTextureManager: failed to load grammar file 'art/terrains/terrain.rng'");
      57           0 :     if (!g_Xeromyces.AddValidator(g_VFS, "terrain_texture", "art/terrains/terrain_texture.rng"))
      58           0 :         LOGERROR("CTerrainTextureManager: failed to load grammar file 'art/terrains/terrain_texture.rng'");
      59           0 : }
      60             : 
      61          10 : CTerrainTextureManager::~CTerrainTextureManager()
      62             : {
      63          10 :     UnloadTerrainTextures();
      64             : 
      65          10 :     for (std::pair<const VfsPath, TerrainAlpha>& ta : m_TerrainAlphas)
      66           0 :         ta.second.m_CompositeAlphaMap.reset();
      67          10 : }
      68             : 
      69          10 : void CTerrainTextureManager::UnloadTerrainTextures()
      70             : {
      71          10 :     m_TextureEntries.clear();
      72          10 :     m_TerrainGroups.clear();
      73             : 
      74          10 :     m_LastGroupIndex = 0;
      75          10 : }
      76             : 
      77           0 : CTerrainTextureEntry* CTerrainTextureManager::FindTexture(const CStr& tag_)
      78             : {
      79           0 :     CStr tag = tag_.BeforeLast("."); // Strip extension
      80             : 
      81           0 :     for (const auto& textureEntry : m_TextureEntries)
      82           0 :         if (textureEntry->GetTag() == tag)
      83           0 :             return textureEntry.get();
      84             : 
      85           0 :     LOGWARNING("CTerrainTextureManager: Couldn't find terrain {} using fallback texture", tag);
      86             : 
      87             :     // If the texture is not found, return a default texture.
      88             :     // This is a fallback texture, so it should not be used in the editor.
      89           0 :     std::unique_ptr<CTerrainTextureEntry> fallback{std::make_unique<CTerrainTextureEntry>(tag)};
      90           0 :     return m_TextureEntries.emplace_back(std::move(fallback)).get();
      91           0 : }
      92             : 
      93           0 : void CTerrainTextureManager::AddTexture(const CTerrainPropertiesPtr& props, const VfsPath& path)
      94             : {
      95           0 :     m_TextureEntries.emplace_back(std::make_unique<CTerrainTextureEntry>(props, path));
      96           0 : }
      97             : 
      98             : struct AddTextureCallbackData
      99             : {
     100             :     CTerrainTextureManager* self;
     101             :     CTerrainPropertiesPtr props;
     102             : };
     103             : 
     104           0 : static Status AddTextureDirCallback(const VfsPath& pathname, const uintptr_t cbData)
     105             : {
     106           0 :     AddTextureCallbackData& data = *(AddTextureCallbackData*)cbData;
     107           0 :     VfsPath path = pathname / L"terrains.xml";
     108           0 :     if (!VfsFileExists(path))
     109           0 :         LOGMESSAGE("'{}' does not exist. Using previous properties.", path.string8());
     110             :     else
     111           0 :         data.props = CTerrainProperties::FromXML(data.props, path);
     112             : 
     113           0 :     return INFO::OK;
     114           0 : }
     115             : 
     116           0 : static Status AddTextureCallback(const VfsPath& pathname, const CFileInfo&, const uintptr_t cbData)
     117             : {
     118           0 :     AddTextureCallbackData& data = *(AddTextureCallbackData*)cbData;
     119           0 :     if (pathname.Basename() != L"terrains")
     120           0 :         data.self->AddTexture(data.props, pathname);
     121             : 
     122           0 :     return INFO::OK;
     123             : }
     124             : 
     125           0 : PS::Loader::Task CTerrainTextureManager::LoadTerrainTextures()
     126             : {
     127             :     vfs::ForEachFileContext context{VfsPath{L"art/terrains/"}};
     128             :     AddTextureCallbackData data{this, std::make_shared<CTerrainProperties>(CTerrainPropertiesPtr())};
     129             :     while (true)
     130             :     {
     131             :         vfs::ForEachFileNext(context, g_VFS, AddTextureCallback,
     132             :             reinterpret_cast<uintptr_t>(&data), L"*.xml", vfs::DIR_RECURSIVE,
     133             :             AddTextureDirCallback, reinterpret_cast<uintptr_t>(&data));
     134             : 
     135             :         if (context.empty())
     136             :             co_return 0;
     137             : 
     138             :         // We don't know exact number so just using a rough approximation of the
     139             :         // current number.
     140             :         const size_t totalApproximateAmountOfTextures{1000};
     141             :         co_yield Clamp<int>(m_TextureEntries.size() * 90 / totalApproximateAmountOfTextures, 10, 100);
     142             :     }
     143           0 : }
     144             : 
     145           0 : CTerrainGroup* CTerrainTextureManager::FindGroup(const CStr& name)
     146             : {
     147           0 :     TerrainGroupMap::const_iterator it = m_TerrainGroups.find(name);
     148           0 :     if (it != m_TerrainGroups.end())
     149           0 :         return it->second.get();
     150             :     else
     151           0 :         return m_TerrainGroups.insert_or_assign(name, std::make_unique<CTerrainGroup>(name, ++m_LastGroupIndex)).first->second.get();
     152             : }
     153             : 
     154             : // LoadAlphaMaps: load the 14 default alpha maps, pack them into one composite texture and
     155             : // calculate the coordinate of each alphamap within this packed texture.
     156             : CTerrainTextureManager::TerrainAlphaMap::iterator
     157           0 : CTerrainTextureManager::LoadAlphaMap(const VfsPath& alphaMapType)
     158             : {
     159           0 :     const std::wstring key = L"(alpha map composite" + alphaMapType.string() + L")";
     160             : 
     161           0 :     CTerrainTextureManager::TerrainAlphaMap::iterator it = m_TerrainAlphas.find(alphaMapType);
     162             : 
     163           0 :     if (it != g_TexMan.m_TerrainAlphas.end())
     164           0 :         return it;
     165             : 
     166           0 :     m_TerrainAlphas[alphaMapType] = TerrainAlpha();
     167           0 :     it = m_TerrainAlphas.find(alphaMapType);
     168             : 
     169           0 :     TerrainAlpha& result = it->second;
     170             : 
     171             :     //
     172             :     // load all textures and store Handle in array
     173             :     //
     174           0 :     Tex textures[NUM_ALPHA_MAPS] = {};
     175           0 :     const VfsPath path = VfsPath("art/textures/terrain/alphamaps") / alphaMapType;
     176             : 
     177           0 :     const wchar_t* fnames[NUM_ALPHA_MAPS] =
     178             :     {
     179             :         L"blendcircle.png",
     180             :         L"blendlshape.png",
     181             :         L"blendedge.png",
     182             :         L"blendedgecorner.png",
     183             :         L"blendedgetwocorners.png",
     184             :         L"blendfourcorners.png",
     185             :         L"blendtwooppositecorners.png",
     186             :         L"blendlshapecorner.png",
     187             :         L"blendtwocorners.png",
     188             :         L"blendcorner.png",
     189             :         L"blendtwoedges.png",
     190             :         L"blendthreecorners.png",
     191             :         L"blendushape.png",
     192             :         L"blendbad.png"
     193             :     };
     194           0 :     size_t base = 0;    // texture width/height (see below)
     195             :     // For convenience, we require all alpha maps to be of the same BPP.
     196           0 :     size_t bpp = 0;
     197           0 :     for (size_t i = 0; i < NUM_ALPHA_MAPS; ++i)
     198             :     {
     199             :         // note: these individual textures can be discarded afterwards;
     200             :         // we cache the composite.
     201           0 :         std::shared_ptr<std::uint8_t> fileData;
     202           0 :         size_t fileSize;
     203           0 :         if (g_VFS->LoadFile(path / fnames[i], fileData, fileSize) != INFO::OK ||
     204           0 :             textures[i].decode(fileData, fileSize) != INFO::OK)
     205             :         {
     206           0 :             m_TerrainAlphas.erase(it);
     207           0 :             LOGERROR("Failed to load alphamap: {}", alphaMapType.string8());
     208             : 
     209           0 :             const VfsPath standard("standard");
     210           0 :             if (path != standard)
     211           0 :                 return LoadAlphaMap(standard);
     212           0 :             return m_TerrainAlphas.end();
     213           0 :         }
     214             : 
     215             :         // Get its size and make sure they are all equal.
     216             :         // (the packing algo assumes this).
     217           0 :         if (textures[i].m_Width != textures[i].m_Height)
     218           0 :             DEBUG_DISPLAY_ERROR(L"Alpha maps are not square");
     219             :         // .. first iteration: establish size
     220           0 :         if (i == 0)
     221             :         {
     222           0 :             base = textures[i].m_Width;
     223           0 :             bpp = textures[i].m_Bpp;
     224             :         }
     225             :         // .. not first: make sure texture size matches
     226           0 :         else if (base != textures[i].m_Width || bpp != textures[i].m_Bpp)
     227           0 :             DEBUG_DISPLAY_ERROR(L"Alpha maps are not identically sized (including pixel depth)");
     228           0 :     }
     229             : 
     230             :     //
     231             :     // copy each alpha map (tile) into one buffer, arrayed horizontally.
     232             :     //
     233           0 :     const size_t tileWidth = 2 + base + 2;  // 2 pixel border (avoids bilinear filtering artifacts)
     234           0 :     const size_t totalWidth = std::bit_ceil(tileWidth * NUM_ALPHA_MAPS);
     235           0 :     const size_t totalHeight = base; ENSURE(std::has_single_bit(totalHeight));
     236           0 :     std::shared_ptr<std::uint8_t> data;
     237           0 :     AllocateAligned(data, totalWidth * totalHeight, maxSectorSize);
     238             :     // for each tile on row
     239           0 :     for (size_t i = 0; i < NUM_ALPHA_MAPS; ++i)
     240             :     {
     241             :         // get src of copy
     242           0 :         std::uint8_t* src = textures[i].get_data();
     243           0 :         ENSURE(src);
     244             : 
     245           0 :         const size_t srcStep = bpp / 8;
     246             : 
     247             :         // get destination of copy
     248           0 :         std::uint8_t* dst = data.get() + (i * tileWidth);
     249             : 
     250             :         // for each row of image
     251           0 :         for (size_t j = 0; j < base; ++j)
     252             :         {
     253             :             // duplicate first pixel
     254           0 :             *dst++ = *src;
     255           0 :             *dst++ = *src;
     256             : 
     257             :             // copy a row
     258           0 :             for (size_t k = 0; k < base; ++k)
     259             :             {
     260           0 :                 *dst++ = *src;
     261           0 :                 src += srcStep;
     262             :             }
     263             : 
     264             :             // duplicate last pixel
     265           0 :             *dst++ = *(src - srcStep);
     266           0 :             *dst++ = *(src - srcStep);
     267             : 
     268             :             // advance write pointer for next row
     269           0 :             dst += totalWidth - tileWidth;
     270             :         }
     271             : 
     272           0 :         result.m_AlphaMapCoords[i].u0 = static_cast<float>(i * tileWidth + 2) / totalWidth;
     273           0 :         result.m_AlphaMapCoords[i].u1 = static_cast<float>((i + 1) * tileWidth - 2) / totalWidth;
     274           0 :         result.m_AlphaMapCoords[i].v0 = 0.0f;
     275           0 :         result.m_AlphaMapCoords[i].v1 = 1.0f;
     276             :     }
     277             : 
     278           0 :     for (size_t i = 0; i < NUM_ALPHA_MAPS; ++i)
     279           0 :         textures[i].free();
     280             : 
     281             :     // Enable the following to save a png of the generated texture
     282             :     // in the public/ directory, for debugging.
     283             : #if 0
     284             :     Tex t;
     285             :     ignore_result(t.wrap(totalWidth, totalHeight, 8, TEX_GREY, data, 0));
     286             : 
     287             :     const VfsPath filename("blendtex.png");
     288             : 
     289             :     DynArray da;
     290             :     RETURN_STATUS_IF_ERR(tex_encode(&t, filename.Extension(), &da));
     291             : 
     292             :     // write to disk
     293             :     //Status ret = INFO::OK;
     294             :     {
     295             :         std::shared_ptr<std::uint8_t> file = DummySharedPtr(da.base);
     296             :         const ssize_t bytes_written = g_VFS->CreateFile(filename, file, da.pos);
     297             :         if (bytes_written > 0)
     298             :             ENSURE(bytes_written == (ssize_t)da.pos);
     299             :         //else
     300             :         //  ret = (Status)bytes_written;
     301             :     }
     302             : 
     303             :     ignore_result(da_free(&da));
     304             : #endif
     305             : 
     306           0 :     result.m_CompositeAlphaMap = m_Device->CreateTexture2D("CompositeAlphaMap",
     307             :         Renderer::Backend::ITexture::Usage::TRANSFER_DST |
     308             :             Renderer::Backend::ITexture::Usage::SAMPLED,
     309             :         Renderer::Backend::Format::A8_UNORM, totalWidth, totalHeight,
     310           0 :         Renderer::Backend::Sampler::MakeDefaultSampler(
     311             :             Renderer::Backend::Sampler::Filter::LINEAR,
     312           0 :             Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE));
     313             : 
     314           0 :     result.m_CompositeDataToUpload = std::move(data);
     315             : 
     316           0 :     m_AlphaMapsToUpload.emplace_back(it);
     317             : 
     318           0 :     return it;
     319           0 : }
     320             : 
     321           0 : void CTerrainTextureManager::UploadResourcesIfNeeded(
     322             :     Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
     323             : {
     324           0 :     for (const CTerrainTextureManager::TerrainAlphaMap::iterator& it : m_AlphaMapsToUpload)
     325             :     {
     326           0 :         TerrainAlpha& alphaMap = it->second;
     327           0 :         if (!alphaMap.m_CompositeDataToUpload)
     328           0 :             continue;
     329             :         // Upload the composite texture.
     330           0 :         Renderer::Backend::ITexture* texture = alphaMap.m_CompositeAlphaMap.get();
     331           0 :         deviceCommandContext->UploadTexture(
     332           0 :             texture, Renderer::Backend::Format::A8_UNORM, alphaMap.m_CompositeDataToUpload.get(),
     333           0 :             texture->GetWidth() * texture->GetHeight());
     334           0 :         alphaMap.m_CompositeDataToUpload.reset();
     335             :     }
     336             : 
     337           0 :     m_AlphaMapsToUpload.clear();
     338           0 : }
     339             : 
     340           0 : void CTerrainGroup::AddTerrain(CTerrainTextureEntry* pTerrain)
     341             : {
     342           0 :     m_Terrains.push_back(pTerrain);
     343           0 : }
     344             : 
     345           0 : void CTerrainGroup::RemoveTerrain(CTerrainTextureEntry* pTerrain)
     346             : {
     347           0 :     std::vector<CTerrainTextureEntry*>::iterator it = find(m_Terrains.begin(), m_Terrains.end(), pTerrain);
     348           0 :     if (it != m_Terrains.end())
     349           0 :         m_Terrains.erase(it);
     350           0 : }

Generated by: LCOV version 1.16