LCOV - code coverage report
Current view: top level - source/simulation2/components - CCmpTemplateManager.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 63 98 64.3 %
Date: 2026-12-02 01:21:50 Functions: 14 20 70.0 %

          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 "ICmpTemplateManager.h"
      21             : 
      22             : #include "ps/CLogger.h"
      23             : #include "ps/TemplateLoader.h"
      24             : #include "ps/XML/RelaxNG.h"
      25             : #include "simulation2/MessageTypes.h"
      26             : #include "simulation2/serialization/SerializeTemplates.h"
      27             : #include "simulation2/serialization/SerializedTypes.h"
      28             : #include "simulation2/system/Component.h"
      29             : #include "simulation2/system/Entity.h"
      30             : #include "simulation2/system/Message.h"
      31             : 
      32             : #include <algorithm>
      33             : #include <cstddef>
      34             : #include <map>
      35             : #include <string>
      36             : #include <utility>
      37             : #include <vector>
      38             : 
      39          15 : class CCmpTemplateManager final : public ICmpTemplateManager
      40             : {
      41             : public:
      42         137 :     static void ClassInit(CComponentManager& componentManager)
      43             :     {
      44         137 :         componentManager.SubscribeGloballyToMessageType(MT_Destroy);
      45             :     }
      46             : 
      47          30 :     DEFAULT_COMPONENT_ALLOCATOR(TemplateManager)
      48             : 
      49         137 :     static std::string GetSchema()
      50             :     {
      51         274 :         return "<a:component type='system'/><empty/>";
      52             :     }
      53             : 
      54          15 :     void Init(const CParamNode&) override
      55             :     {
      56          15 :         m_DisableValidation = false;
      57             : 
      58          15 :         m_Validator.LoadGrammar(GetSimContext().GetComponentManager().GenerateSchema());
      59             :         // TODO: handle errors loading the grammar here?
      60             :         // TODO: support hotloading changes to the grammar
      61          15 :     }
      62             : 
      63          15 :     void Deinit() override
      64             :     {
      65          15 :     }
      66             : 
      67          19 :     void Serialize(ISerializer& serialize) override
      68             :     {
      69          19 :         std::map<std::string, std::vector<entity_id_t>> templateMap;
      70             : 
      71        1124 :         for (const std::pair<const entity_id_t, std::string>& templateEnt : m_LatestTemplates)
      72        1105 :             if (!ENTITY_IS_LOCAL(templateEnt.first))
      73        1087 :                 templateMap[templateEnt.second].push_back(templateEnt.first);
      74             : 
      75          19 :         Serializer(serialize, "templates", templateMap);
      76          19 :     }
      77             : 
      78           1 :     void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override
      79             :     {
      80           1 :         Init(paramNode);
      81             : 
      82           1 :         std::map<std::string, std::vector<entity_id_t>> templateMap;
      83           1 :         Serializer(deserialize, "templates", templateMap);
      84           2 :         for (const std::pair<const std::string, std::vector<entity_id_t>>& mapEl : templateMap)
      85           2 :             for (entity_id_t id : mapEl.second)
      86           2 :                 m_LatestTemplates[id] = mapEl.first;
      87           1 :     }
      88             : 
      89          32 :     void HandleMessage(const CMessage& msg, bool /*global*/) override
      90             :     {
      91          32 :         switch (msg.GetType())
      92             :         {
      93          32 :         case MT_Destroy:
      94          32 :         {
      95          32 :             const CMessageDestroy& msgData = static_cast<const CMessageDestroy&> (msg);
      96             : 
      97             :             // Clean up m_LatestTemplates so it doesn't record any data for destroyed entities
      98          32 :             m_LatestTemplates.erase(msgData.entity);
      99             : 
     100             :             break;
     101             :         }
     102             :         }
     103          32 :     }
     104             : 
     105           1 :     void DisableValidation() override
     106             :     {
     107           1 :         m_DisableValidation = true;
     108           1 :     }
     109             : 
     110             :     const CParamNode* LoadTemplate(entity_id_t ent, const std::string& templateName) override;
     111             : 
     112             :     const CParamNode* GetTemplate(const std::string& templateName) override;
     113             : 
     114             :     const CParamNode* GetTemplateWithoutValidation(const std::string& templateName) override;
     115             : 
     116             :     bool TemplateExists(const std::string& templateName) const override;
     117             : 
     118             :     const CParamNode* LoadLatestTemplate(entity_id_t ent) override;
     119             : 
     120             :     std::string GetCurrentTemplateName(entity_id_t ent) const override;
     121             : 
     122             :     std::vector<std::string> FindAllTemplates(bool includeActors) const override;
     123             : 
     124             :     std::vector<std::vector<std::wstring>> GetCivData() override;
     125             : 
     126             :     std::vector<std::string> FindUsedTemplates() const override;
     127             : 
     128             :     std::vector<entity_id_t> GetEntitiesUsingTemplate(const std::string& templateName) const override;
     129             : 
     130             : private:
     131             :     // Template loader
     132             :     CTemplateLoader m_templateLoader;
     133             : 
     134             :     // Entity template XML validator
     135             :     RelaxNGValidator m_Validator;
     136             : 
     137             :     // Disable validation, for test cases
     138             :     bool m_DisableValidation;
     139             : 
     140             :     // Map from template name to schema validation status.
     141             :     // (Some files, e.g. inherited parent templates, may not be valid themselves but we still need to load
     142             :     // them and use them; we only reject invalid templates that were requested directly by GetTemplate/etc)
     143             :     std::map<std::string, bool> m_TemplateSchemaValidity;
     144             : 
     145             :     // Remember the template used by each entity, so we can return them
     146             :     // again for deserialization.
     147             :     std::map<entity_id_t, std::string> m_LatestTemplates;
     148             : };
     149             : 
     150         274 : REGISTER_COMPONENT_TYPE(TemplateManager)
     151             : 
     152         245 : const CParamNode* CCmpTemplateManager::LoadTemplate(entity_id_t ent, const std::string& templateName)
     153             : {
     154         245 :     m_LatestTemplates[ent] = templateName;
     155             : 
     156         245 :     return GetTemplate(templateName);
     157             : }
     158             : 
     159        7710 : const CParamNode* CCmpTemplateManager::GetTemplate(const std::string& templateName)
     160             : {
     161        7710 :     const CParamNode& fileData = m_templateLoader.GetTemplateFileData(templateName);
     162        7710 :     if (!fileData.IsOk())
     163             :         return NULL;
     164             : 
     165        7697 :     if (!m_DisableValidation)
     166             :     {
     167             :         // Compute validity, if it's not computed before
     168        7689 :         if (m_TemplateSchemaValidity.find(templateName) == m_TemplateSchemaValidity.end())
     169             :         {
     170        7493 :             m_TemplateSchemaValidity[templateName] = m_Validator.Validate(templateName, fileData.ToXMLString());
     171             : 
     172             :             // Show error on the first failure to validate the template
     173        7493 :             if (!m_TemplateSchemaValidity[templateName])
     174           4 :                 LOGERROR("Failed to validate entity template '{}'", templateName);
     175             :         }
     176             :         // Refuse to return invalid templates
     177        7689 :         if (!m_TemplateSchemaValidity[templateName])
     178             :             return NULL;
     179             :     }
     180             : 
     181        7695 :     const CParamNode& templateRoot = fileData.GetOnlyChild();
     182        7695 :     if (!templateRoot.IsOk())
     183             :     {
     184             :         // The validator should never let this happen
     185           0 :         LOGERROR("Invalid root element in entity template '{}'", templateName);
     186           0 :         return NULL;
     187             :     }
     188             : 
     189             :     return &templateRoot;
     190             : }
     191             : 
     192           0 : const CParamNode* CCmpTemplateManager::GetTemplateWithoutValidation(const std::string& templateName)
     193             : {
     194           0 :     const CParamNode& templateRoot = m_templateLoader.GetTemplateFileData(templateName).GetOnlyChild();
     195           0 :     if (!templateRoot.IsOk())
     196           0 :         return NULL;
     197             : 
     198             :     return &templateRoot;
     199             : }
     200             : 
     201           0 : bool CCmpTemplateManager::TemplateExists(const std::string& templateName) const
     202             : {
     203           0 :     return m_templateLoader.TemplateExists(templateName);
     204             : }
     205             : 
     206           1 : const CParamNode* CCmpTemplateManager::LoadLatestTemplate(entity_id_t ent)
     207             : {
     208           2 :     std::map<entity_id_t, std::string>::const_iterator it = m_LatestTemplates.find(ent);
     209           1 :     if (it == m_LatestTemplates.end())
     210             :         return NULL;
     211           1 :     return LoadTemplate(ent, it->second);
     212             : }
     213             : 
     214         270 : std::string CCmpTemplateManager::GetCurrentTemplateName(entity_id_t ent) const
     215             : {
     216         270 :     std::map<entity_id_t, std::string>::const_iterator it = m_LatestTemplates.find(ent);
     217         270 :     if (it == m_LatestTemplates.end())
     218           0 :         return "";
     219         270 :     return it->second;
     220             : }
     221             : 
     222           1 : std::vector<std::string> CCmpTemplateManager::FindAllTemplates(bool includeActors) const
     223             : {
     224           1 :     ETemplatesType templatesType = includeActors ? ALL_TEMPLATES : SIMULATION_TEMPLATES;
     225           2 :     return m_templateLoader.FindTemplates("", true, templatesType);
     226             : }
     227             : 
     228           0 : std::vector<std::vector<std::wstring>> CCmpTemplateManager::GetCivData()
     229             : {
     230           0 :     std::vector<std::vector<std::wstring>> data;
     231             : 
     232           0 :     std::vector<std::string> names = m_templateLoader.FindTemplatesUnrestricted("special/players/", false);
     233           0 :     data.reserve(names.size());
     234           0 :     for (const std::string& name : names)
     235             :     {
     236           0 :         const CParamNode& identity = GetTemplate(name)->GetChild("Identity");
     237           0 :         data.push_back(std::vector<std::wstring> {
     238           0 :             identity.GetChild("Civ").ToWString(),
     239           0 :             identity.GetChild("GenericName").ToWString()
     240           0 :         });
     241             :     }
     242           0 :     return data;
     243           0 : }
     244             : 
     245           0 : std::vector<std::string> CCmpTemplateManager::FindUsedTemplates() const
     246             : {
     247           0 :     std::vector<std::string> usedTemplates;
     248           0 :     for (const std::pair<const entity_id_t, std::string>& p : m_LatestTemplates)
     249           0 :         if (std::find(usedTemplates.begin(), usedTemplates.end(), p.second) == usedTemplates.end())
     250           0 :             usedTemplates.push_back(p.second);
     251           0 :     return usedTemplates;
     252           0 : }
     253             : 
     254             : /**
     255             :  * Get the list of entities using the specified template
     256             :  */
     257           0 : std::vector<entity_id_t> CCmpTemplateManager::GetEntitiesUsingTemplate(const std::string& templateName) const
     258             : {
     259           0 :     std::vector<entity_id_t> entities;
     260           0 :     for (const std::pair<const entity_id_t, std::string>& p : m_LatestTemplates)
     261           0 :         if (p.second == templateName)
     262           0 :             entities.push_back(p.first);
     263             : 
     264           0 :     return entities;
     265           0 : }

Generated by: LCOV version 1.16