LCOV - code coverage report
Current view: top level - source/graphics - MapReader.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 302 721 41.9 %
Date: 2026-12-03 01:19:39 Functions: 23 58 39.7 %

          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 "MapReader.h"
      21             : 
      22             : #include "graphics/Camera.h"
      23             : #include "graphics/Color.h"
      24             : #include "graphics/Entity.h"
      25             : #include "graphics/GameView.h"
      26             : #include "graphics/MapGenerator.h"
      27             : #include "graphics/MapIO.h"
      28             : #include "graphics/MiniPatch.h"
      29             : #include "graphics/Patch.h"
      30             : #include "graphics/Terrain.h"
      31             : #include "graphics/TerrainTextureEntry.h"
      32             : #include "graphics/TerrainTextureManager.h"
      33             : #include "lib/alignment.h"
      34             : #include "lib/code_annotation.h"
      35             : #include "lib/debug.h"
      36             : #include "lib/path.h"
      37             : #include "lib/timer.h"
      38             : #include "lib/utf8.h"
      39             : #include "maths/Fixed.h"
      40             : #include "maths/FixedVector3D.h"
      41             : #include "maths/MathUtil.h"
      42             : #include "maths/Matrix3D.h"
      43             : #include "maths/NUSpline.h"
      44             : #include "ps/CLogger.h"
      45             : #include "ps/Filesystem.h"
      46             : #include "ps/Future.h"
      47             : #include "ps/Loader.h"
      48             : #include "ps/Profiler2.h"
      49             : #include "ps/TaskManager.h"
      50             : #include "ps/World.h"
      51             : #include "ps/XMB/XMBData.h"
      52             : #include "ps/XML/Xeromyces.h"
      53             : #include "renderer/PostprocManager.h"
      54             : #include "renderer/SkyManager.h"
      55             : #include "renderer/WaterManager.h"
      56             : #include "scriptinterface/JSON.h"
      57             : #include "scriptinterface/Object.h"
      58             : #include "scriptinterface/Context.h"
      59             : #include "scriptinterface/Interface.h"
      60             : #include "scriptinterface/Request.h"
      61             : #include "scriptinterface/StructuredClone.h"
      62             : #include "simulation2/Simulation2.h"
      63             : #include "simulation2/components/ICmpCinemaManager.h"
      64             : #include "simulation2/components/ICmpGarrisonHolder.h"
      65             : #include "simulation2/components/ICmpObstruction.h"
      66             : #include "simulation2/components/ICmpOwnership.h"
      67             : #include "simulation2/components/ICmpPlayer.h"
      68             : #include "simulation2/components/ICmpPlayerManager.h"
      69             : #include "simulation2/components/ICmpPosition.h"
      70             : #include "simulation2/components/ICmpTerrain.h"
      71             : #include "simulation2/components/ICmpTurretHolder.h"
      72             : #include "simulation2/components/ICmpVisual.h"
      73             : #include "simulation2/components/ICmpWaterManager.h"
      74             : #include "simulation2/helpers/CinemaPath.h"
      75             : #include "simulation2/helpers/Position.h"
      76             : #include "simulation2/system/CmpPtr.h"
      77             : 
      78             : #include <algorithm>
      79             : #include <atomic>
      80             : #include <functional>
      81             : #include <js/PropertyAndElement.h>
      82             : #include <numeric>
      83             : #include <ranges>
      84             : #include <string>
      85             : #include <string_view>
      86             : #include <utility>
      87             : 
      88             : extern bool IsQuitRequested();
      89             : 
      90             : #if defined(_MSC_VER) && _MSC_VER > 1900
      91             : #pragma warning(disable: 4456) // Declaration hides previous local declaration.
      92             : #pragma warning(disable: 4458) // Declaration hides class member.
      93             : #endif
      94             : 
      95             : // TODO: Maybe this should be optimized depending on the map size.
      96             : constexpr int MAP_GENERATION_CONTEXT_SIZE{96 * MiB};
      97             : 
      98           3 : CMapReader::CMapReader() = default;
      99             : 
     100             : // LoadMap: try to load the map from given file; reinitialise the scene to new data if successful
     101           3 : void CMapReader::LoadMap(const VfsPath& pathname, const Script::Context& cx,  JS::HandleValue settings, CTerrain *pTerrain_,
     102             :                          WaterManager* pWaterMan_, SkyManager* pSkyMan_,
     103             :                          CLightEnv *pLightEnv_, CGameView *pGameView_, CCinemaManager* pCinema_, CTriggerManager* pTrigMan_, CPostprocManager* pPostproc_,
     104             :                          CSimulation2 *pSimulation2_, const CSimContext* pSimContext_, int playerID_, bool skipEntities)
     105             : {
     106           3 :     pTerrain = pTerrain_;
     107           3 :     pLightEnv = pLightEnv_;
     108           3 :     pGameView = pGameView_;
     109           3 :     pWaterMan = pWaterMan_;
     110           3 :     pSkyMan = pSkyMan_;
     111           3 :     pCinema = pCinema_;
     112           3 :     pTrigMan = pTrigMan_;
     113           3 :     pPostproc = pPostproc_;
     114           3 :     pSimulation2 = pSimulation2_;
     115           3 :     pSimContext = pSimContext_;
     116           3 :     m_PlayerID = playerID_;
     117           3 :     m_SkipEntities = skipEntities;
     118           3 :     m_StartingCameraTarget = INVALID_ENTITY;
     119           3 :     m_ScriptSettings.init(cx.GetGeneralJSContext(), settings);
     120             : 
     121           6 :     m_FilenameXml = pathname.ChangeExtension(L".xml");
     122             : 
     123             :     // In some cases (particularly tests) we don't want to bother storing a large
     124             :     // mostly-empty .pmp file, so we let the XML file specify basic terrain instead.
     125             :     // If there's an .xml file and no .pmp, then we're probably in this XML-only mode
     126           3 :     only_xml = false;
     127           3 :     if (!VfsFileExists(pathname) && VfsFileExists(m_FilenameXml))
     128             :     {
     129           3 :         only_xml = true;
     130             :     }
     131             : 
     132           3 :     file_format_version = CMapIO::FILE_VERSION; // default if there's no .pmp
     133             : 
     134           3 :     if (!only_xml)
     135             :     {
     136             :         // [25ms]
     137           0 :         unpacker.Read(pathname, "PSMP");
     138           0 :         file_format_version = unpacker.GetVersion();
     139             :     }
     140             : 
     141             :     // check oldest supported version
     142           3 :     if (file_format_version < FILE_READ_VERSION)
     143           0 :         throw PSERROR_Game_World_MapLoadFailed("Could not load terrain file - too old version!");
     144             : 
     145             :     // delete all existing entities
     146           3 :     if (pSimulation2)
     147           3 :         pSimulation2->ResetState();
     148             : 
     149             :     // reset post effects
     150           3 :     if (pPostproc)
     151           0 :         pPostproc->SetPostEffect(L"default");
     152             : 
     153             :     // load map or script settings script
     154           3 :     if (settings.isUndefined())
     155           0 :         PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     156             :         {
     157             :             co_return mapReader->LoadScriptSettings();
     158           0 :         }, this), L"CMapReader::LoadScriptSettings", 50);
     159             :     else
     160           6 :         PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     161             :         {
     162             :             co_return mapReader->LoadRMSettings();
     163           6 :         }, this), L"CMapReader::LoadRMSettings", 50);
     164             : 
     165             :     // load player settings script (must be done before reading map)
     166           6 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     167             :     {
     168             :         co_return mapReader->LoadPlayerSettings();
     169           6 :     }, this), L"CMapReader::LoadPlayerSettings", 50);
     170             : 
     171             :     // unpack the data
     172           3 :     if (!only_xml)
     173           0 :         PS::Loader::Register([this]
     174             :         {
     175           0 :             return UnpackTerrain();
     176             :         }, L"CMapReader::UnpackMap", 1200);
     177             : 
     178             :     // read the corresponding XML file
     179           6 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     180             :     {
     181             :         co_return mapReader->ReadXML();
     182           6 :     }, this), L"CMapReader::ReadXML", 50);
     183             : 
     184             :     // apply terrain data to the world
     185           6 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     186             :     {
     187             :         co_return mapReader->ApplyTerrainData();
     188           6 :     }, this), L"CMapReader::ApplyTerrainData", 5);
     189             : 
     190             :     // read entities
     191           6 :     PS::Loader::Register([this]
     192             :     {
     193           3 :         return ReadXMLEntities();
     194             :     }, L"CMapReader::ReadXMLEntities", 5800);
     195             : 
     196             :     // apply misc data to the world
     197           6 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     198             :     {
     199             :         co_return mapReader->ApplyData();
     200           6 :     }, this), L"CMapReader::ApplyData", 5);
     201             : 
     202             :     // load map settings script (must be done after reading map)
     203           6 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     204             :     {
     205             :         co_return mapReader->LoadMapSettings();
     206           6 :     }, this), L"CMapReader::LoadMapSettings", 5);
     207           3 : }
     208             : 
     209             : // LoadRandomMap: try to load the map data; reinitialise the scene to new data if successful
     210           0 : void CMapReader::LoadRandomMap(const CStrW& scriptFile, const Script::Context& cx, JS::HandleValue settings, CTerrain *pTerrain_,
     211             :                          WaterManager* pWaterMan_, SkyManager* pSkyMan_,
     212             :                          CLightEnv *pLightEnv_, CGameView *pGameView_, CCinemaManager* pCinema_, CTriggerManager* pTrigMan_, CPostprocManager* pPostproc_,
     213             :                          CSimulation2 *pSimulation2_, int playerID_)
     214             : {
     215           0 :     pSimulation2 = pSimulation2_;
     216           0 :     pSimContext = pSimulation2 ? &pSimulation2->GetSimContext() : NULL;
     217           0 :     m_ScriptSettings.init(cx.GetGeneralJSContext(), settings);
     218           0 :     pTerrain = pTerrain_;
     219           0 :     pLightEnv = pLightEnv_;
     220           0 :     pGameView = pGameView_;
     221           0 :     pWaterMan = pWaterMan_;
     222           0 :     pSkyMan = pSkyMan_;
     223           0 :     pCinema = pCinema_;
     224           0 :     pTrigMan = pTrigMan_;
     225           0 :     pPostproc = pPostproc_;
     226           0 :     m_PlayerID = playerID_;
     227           0 :     m_SkipEntities = false;
     228           0 :     m_StartingCameraTarget = INVALID_ENTITY;
     229             : 
     230             :     // delete all existing entities
     231           0 :     if (pSimulation2)
     232           0 :         pSimulation2->ResetState();
     233             : 
     234           0 :     only_xml = false;
     235             : 
     236             :     // copy random map settings (before entity creation)
     237           0 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     238             :     {
     239             :         co_return mapReader->LoadRMSettings();
     240           0 :     }, this), L"CMapReader::LoadRMSettings", 50);
     241             : 
     242             :     // load player settings script (must be done before reading map)
     243           0 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     244             :     {
     245             :         co_return mapReader->LoadPlayerSettings();
     246           0 :     }, this), L"CMapReader::LoadPlayerSettings", 50);
     247             : 
     248             :     // load map generator with random map script
     249           0 :     PS::Loader::Register([this, scriptFile]
     250             :     {
     251           0 :         return RunMapGeneration(scriptFile);
     252             :     }, L"CMapReader::RunMapGeneration", 20000);
     253             : 
     254             :     // parse RMS results into terrain structure
     255           0 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     256             :     {
     257             :         co_return mapReader->ParseTerrain();
     258           0 :     }, this), L"CMapReader::ParseTerrain", 500);
     259             : 
     260             :     // parse RMS results into environment settings
     261           0 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     262             :     {
     263             :         co_return mapReader->ParseEnvironment();
     264           0 :     }, this), L"CMapReader::ParseEnvironment", 5);
     265             : 
     266             :     // parse RMS results into camera settings
     267           0 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     268             :     {
     269             :         co_return mapReader->ParseCamera();
     270           0 :     }, this), L"CMapReader::ParseCamera", 5);
     271             : 
     272             :     // apply terrain data to the world
     273           0 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     274             :     {
     275             :         co_return mapReader->ApplyTerrainData();
     276           0 :     }, this), L"CMapReader::ApplyTerrainData", 5);
     277             : 
     278             :     // parse RMS results into entities
     279           0 :     PS::Loader::Register([this]
     280             :     {
     281           0 :         return ParseEntities();
     282             :     }, L"CMapReader::ParseEntities", 1010);
     283             : 
     284             :     // apply misc data to the world
     285           0 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     286             :     {
     287             :         co_return mapReader->ApplyData();
     288           0 :     }, this), L"CMapReader::ApplyData", 5);
     289             : 
     290             :     // load map settings script (must be done after reading map)
     291           0 :     PS::Loader::Register(std::bind_front([](CMapReader* mapReader) -> PS::Loader::Task
     292             :     {
     293             :         co_return mapReader->LoadMapSettings();
     294           0 :     }, this), L"CMapReader::LoadMapSettings", 5);
     295           0 : }
     296             : 
     297             : // UnpackTerrain: unpack the terrain from the end of the input data stream
     298             : //      - data: map size, heightmap, list of textures used by map, texture tile assignments
     299           0 : PS::Loader::Task CMapReader::UnpackTerrain()
     300             : {
     301             :     {
     302             :         m_PatchesPerSide = (ssize_t)unpacker.UnpackSize();
     303             : 
     304             :         // unpack heightmap [600us]
     305             :         size_t verticesPerSide = m_PatchesPerSide*PATCH_SIZE+1;
     306             :         m_Heightmap.resize(SQR(verticesPerSide));
     307             :         unpacker.UnpackRaw(&m_Heightmap[0], SQR(verticesPerSide) * sizeof(std::uint16_t));
     308             :     }
     309             : 
     310             :     // unpack # textures
     311             :     const std::size_t numTerrainTex{unpacker.UnpackSize()};
     312             :     m_TerrainTextures.reserve(numTerrainTex);
     313             : 
     314             :     // unpack texture names; find handle for each texture.
     315             :     // interruptible.
     316             :     for (std::size_t curTerrainTex{0}; curTerrainTex != numTerrainTex; ++curTerrainTex)
     317             :     {
     318             :         CStr texturename;
     319             :         unpacker.UnpackString(texturename);
     320             : 
     321             :         if (CTerrainTextureManager::IsInitialised())
     322             :         {
     323             :             CTerrainTextureEntry* texentry = g_TexMan.FindTexture(texturename);
     324             :             m_TerrainTextures.push_back(texentry);
     325             :         }
     326             : 
     327             :         co_yield 100 * (curTerrainTex + 1) / numTerrainTex;
     328             :     }
     329             : 
     330             :     // unpack tile data [3ms]
     331             :     ssize_t tilesPerSide = m_PatchesPerSide*PATCH_SIZE;
     332             :     m_Tiles.resize(size_t(SQR(tilesPerSide)));
     333             :     unpacker.UnpackRaw(&m_Tiles[0], sizeof(STileDesc)*m_Tiles.size());
     334             : 
     335             :     co_return 0;
     336           0 : }
     337             : 
     338           3 : int CMapReader::ApplyTerrainData()
     339             : {
     340           3 :     if (m_PatchesPerSide == 0)
     341             :     {
     342             :         // we'll probably crash when trying to use this map later
     343           0 :         throw PSERROR_Game_World_MapLoadFailed("Error loading map: no terrain data.\nCheck application log for details.");
     344             :     }
     345             : 
     346           3 :     if (!only_xml)
     347             :     {
     348             :         // initialise the terrain
     349           0 :         pTerrain->Initialize(m_PatchesPerSide, &m_Heightmap[0]);
     350             : 
     351           0 :         if (CTerrainTextureManager::IsInitialised())
     352             :         {
     353             :             // setup the textures on the minipatches
     354           0 :             STileDesc* tileptr = &m_Tiles[0];
     355           0 :             for (ssize_t j=0; j<m_PatchesPerSide; j++) {
     356           0 :                 for (ssize_t i=0; i<m_PatchesPerSide; i++) {
     357           0 :                     for (ssize_t m=0; m<PATCH_SIZE; m++) {
     358           0 :                         for (ssize_t k=0; k<PATCH_SIZE; k++) {
     359           0 :                             CMiniPatch& mp = pTerrain->GetPatch(i,j)->m_MiniPatches[m][k];    // can't fail
     360             : 
     361           0 :                             if (tileptr->m_Tex1Index >= m_TerrainTextures.size())
     362           0 :                                 throw PSERROR_Game_World_MapLoadFailed("Error loading map: terrain tile references an invalid texture index.\nCheck application log for details.");
     363             : 
     364           0 :                             mp.Tex = m_TerrainTextures[tileptr->m_Tex1Index];
     365           0 :                             mp.Priority = tileptr->m_Priority;
     366             : 
     367           0 :                             tileptr++;
     368             :                         }
     369             :                     }
     370             :                 }
     371             :             }
     372             :         }
     373             :     }
     374             : 
     375           3 :     CmpPtr<ICmpTerrain> cmpTerrain(*pSimContext, SYSTEM_ENTITY);
     376           3 :     if (cmpTerrain)
     377           3 :         cmpTerrain->ReloadTerrain();
     378             : 
     379           3 :     return 0;
     380             : }
     381             : 
     382             : // ApplyData: take all the input data, and rebuild the scene from it
     383           3 : int CMapReader::ApplyData()
     384             : {
     385             :     // copy over the lighting parameters
     386           3 :     if (pLightEnv)
     387           3 :         *pLightEnv = m_LightEnv;
     388             : 
     389           3 :     CmpPtr<ICmpPlayerManager> cmpPlayerManager(*pSimContext, SYSTEM_ENTITY);
     390             : 
     391           3 :     if (pGameView && cmpPlayerManager)
     392             :     {
     393             :         // Default to global camera (with constraints)
     394           0 :         pGameView->ResetCameraTarget(pGameView->GetCamera().GetFocus());
     395             : 
     396             :         // TODO: Starting rotation?
     397           0 :         CmpPtr<ICmpPlayer> cmpPlayer(*pSimContext, cmpPlayerManager->GetPlayerByID(m_PlayerID));
     398           0 :         if (cmpPlayer && cmpPlayer->HasStartingCamera())
     399             :         {
     400             :             // Use player starting camera
     401           0 :             CFixedVector3D pos = cmpPlayer->GetStartingCameraPos();
     402           0 :             pGameView->ResetCameraTarget(CVector3D(pos.X.ToFloat(), pos.Y.ToFloat(), pos.Z.ToFloat()));
     403             :         }
     404           0 :         else if (m_StartingCameraTarget != INVALID_ENTITY)
     405             :         {
     406             :             // Point camera at entity
     407           0 :             CmpPtr<ICmpPosition> cmpPosition(*pSimContext, m_StartingCameraTarget);
     408           0 :             if (cmpPosition)
     409             :             {
     410           0 :                 CFixedVector3D pos = cmpPosition->GetPosition();
     411           0 :                 pGameView->ResetCameraTarget(CVector3D(pos.X.ToFloat(), pos.Y.ToFloat(), pos.Z.ToFloat()));
     412             :             }
     413             :         }
     414             :     }
     415             : 
     416           3 :     return 0;
     417             : }
     418             : 
     419             : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     420             : 
     421             : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     422             : 
     423             : 
     424           3 : PSRETURN CMapSummaryReader::LoadMap(const VfsPath& pathname)
     425             : {
     426           3 :     VfsPath filename_xml = pathname.ChangeExtension(L".xml");
     427             : 
     428           3 :     CXeromyces xmb_file;
     429           3 :     if (xmb_file.Load(g_VFS, filename_xml, "scenario") != PSRETURN_OK)
     430           0 :         return PSRETURN_File_ReadFailed;
     431             : 
     432             :     // Define all the relevant elements used in the XML file
     433             :     #define EL(x) int el_##x = xmb_file.GetElementID(#x)
     434             :     #define AT(x) int at_##x = xmb_file.GetAttributeID(#x)
     435           3 :     EL(scenario);
     436           3 :     EL(scriptsettings);
     437             :     #undef AT
     438             :     #undef EL
     439             : 
     440           3 :     XMBElement root = xmb_file.GetRoot();
     441           3 :     ENSURE(root.GetNodeName() == el_scenario);
     442             : 
     443          42 :     for (XMBElement child : root.GetChildNodes())
     444             :     {
     445          18 :         int child_name = child.GetNodeName();
     446          18 :         if (child_name == el_scriptsettings)
     447             :         {
     448           3 :             m_ScriptSettings = child.GetText();
     449             :         }
     450             :     }
     451             : 
     452           3 :     return PSRETURN_OK;
     453           6 : }
     454             : 
     455           3 : void CMapSummaryReader::GetMapSettings(const Script::Interface& scriptInterface, JS::MutableHandleValue ret)
     456             : {
     457           3 :     Script::Request rq(scriptInterface);
     458             : 
     459           3 :     Script::CreateObject(rq, ret);
     460             : 
     461           3 :     if (m_ScriptSettings.empty())
     462           0 :         return;
     463             : 
     464           3 :     JS::RootedValue scriptSettingsVal(rq.cx);
     465           3 :     Script::ParseJSON(rq, m_ScriptSettings, &scriptSettingsVal);
     466           3 :     Script::SetProperty(rq, ret, "settings", scriptSettingsVal, false);
     467           3 : }
     468             : 
     469             : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     470             : 
     471             : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     472             : 
     473             : 
     474             : // Holds various state data while reading maps, so that loading can be
     475             : // interrupted (e.g. to update the progress display) then later resumed.
     476           6 : class CXMLReader
     477             : {
     478             :     NONCOPYABLE(CXMLReader);
     479             : public:
     480           3 :     CXMLReader(const VfsPath& xml_filename, CMapReader& mapReader)
     481           3 :         : m_MapReader(mapReader), nodes(NULL, 0, NULL)
     482             :     {
     483           3 :         Init(xml_filename);
     484           3 :     }
     485             : 
     486             :     CStr ReadScriptSettings();
     487             : 
     488             :     // read everything except for entities
     489             :     void ReadXML();
     490             : 
     491             :     CXeromyces xmb_file;
     492             :     XMBElementList nodes; // children of root
     493             : 
     494             :     void ReadEntities(XMBElement parent, CSimulation2& sim);
     495             : 
     496             : private:
     497             : 
     498             :     CMapReader& m_MapReader;
     499             : 
     500             :     int el_entity;
     501             :     int el_tracks;
     502             :     int el_template, el_player;
     503             :     int el_position, el_orientation, el_obstruction;
     504             :     int el_garrison;
     505             :     int el_turrets;
     506             :     int el_actor;
     507             :     int at_x;
     508             :     int at_y;
     509             :     int at_z;
     510             :     int at_group, at_group2;
     511             :     int at_angle;
     512             :     int at_uid;
     513             :     int at_seed;
     514             :     int at_turret;
     515             : 
     516             :     // maximum used entity ID, so we can safely allocate new ones
     517             :     entity_id_t max_uid;
     518             : 
     519             :     void Init(const VfsPath& xml_filename);
     520             : 
     521             :     void ReadTerrain(XMBElement parent);
     522             :     void ReadEnvironment(XMBElement parent);
     523             :     void ReadCamera(XMBElement parent);
     524             :     void ReadPaths(XMBElement parent);
     525             :     void ReadTriggers(XMBElement parent);
     526             : };
     527             : 
     528             : 
     529           3 : void CXMLReader::Init(const VfsPath& xml_filename)
     530             : {
     531           3 :     if (xmb_file.Load(g_VFS, xml_filename, "scenario") != PSRETURN_OK)
     532           0 :         throw PSERROR_Game_World_MapLoadFailed("Could not read map XML file!");
     533             : 
     534             :     // define the elements and attributes that are frequently used in the XML file,
     535             :     // so we don't need to do lots of string construction and comparison when
     536             :     // reading the data.
     537             :     // (Needs to be synchronised with the list in CXMLReader - ugh)
     538             : #define EL(x) el_##x = xmb_file.GetElementID(#x)
     539             : #define AT(x) at_##x = xmb_file.GetAttributeID(#x)
     540           3 :     EL(entity);
     541           3 :     EL(tracks);
     542           3 :     EL(template);
     543           3 :     EL(player);
     544           3 :     EL(position);
     545           3 :     EL(garrison);
     546           3 :     EL(turrets);
     547           3 :     EL(orientation);
     548           3 :     EL(obstruction);
     549           3 :     EL(actor);
     550           3 :     AT(x); AT(y); AT(z);
     551           3 :     AT(group); AT(group2);
     552           3 :     AT(angle);
     553           3 :     AT(uid);
     554           3 :     AT(seed);
     555           3 :     AT(turret);
     556             : #undef AT
     557             : #undef EL
     558             : 
     559           3 :     XMBElement root = xmb_file.GetRoot();
     560           6 :     ENSURE(xmb_file.GetElementStringView(root.GetNodeName()) == "Scenario");
     561           3 :     nodes = root.GetChildNodes();
     562             : 
     563             :     // Find the maximum entity ID, so we can safely allocate new IDs without conflicts
     564             : 
     565           3 :     max_uid = SYSTEM_ENTITY;
     566             : 
     567           3 :     XMBElement ents = nodes.GetFirstNamedItem(xmb_file.GetElementID("Entities"));
     568           6 :     for (XMBElement ent : ents.GetChildNodes())
     569             :     {
     570           0 :         CStr uid = ent.GetAttributes().GetNamedItem(at_uid);
     571           0 :         max_uid = std::max(max_uid, (entity_id_t)uid.ToUInt());
     572           0 :     }
     573           3 : }
     574             : 
     575             : 
     576           0 : CStr CXMLReader::ReadScriptSettings()
     577             : {
     578           0 :     XMBElement root = xmb_file.GetRoot();
     579           0 :     ENSURE(xmb_file.GetElementStringView(root.GetNodeName()) == "Scenario");
     580           0 :     nodes = root.GetChildNodes();
     581             : 
     582           0 :     XMBElement settings = nodes.GetFirstNamedItem(xmb_file.GetElementID("ScriptSettings"));
     583             : 
     584           0 :     return settings.GetText();
     585             : }
     586             : 
     587             : 
     588           3 : void CXMLReader::ReadTerrain(XMBElement parent)
     589             : {
     590             : #define AT(x) int at_##x = xmb_file.GetAttributeID(#x)
     591           3 :     AT(patches);
     592           3 :     AT(texture);
     593           3 :     AT(priority);
     594           3 :     AT(height);
     595             : #undef AT
     596             : 
     597           3 :     ssize_t patches = 9;
     598           3 :     CStr texture = "grass1_spring";
     599           3 :     int priority = 0;
     600           3 :     std::uint16_t height = 16384;
     601             : 
     602          30 :     for (XMBAttribute attr : parent.GetAttributes())
     603             :     {
     604          12 :         if (attr.Name == at_patches)
     605           3 :             patches = attr.Value.ToInt();
     606           9 :         else if (attr.Name == at_texture)
     607          15 :             texture = attr.Value;
     608           6 :         else if (attr.Name == at_priority)
     609           3 :             priority = attr.Value.ToInt();
     610           3 :         else if (attr.Name == at_height)
     611           3 :             height = static_cast<std::uint16_t>(attr.Value.ToInt());
     612          12 :     }
     613             : 
     614           3 :     m_MapReader.m_PatchesPerSide = patches;
     615             : 
     616             :     // Load the texture
     617           3 :     CTerrainTextureEntry* texentry = nullptr;
     618           3 :     if (CTerrainTextureManager::IsInitialised())
     619           0 :         texentry = g_TexMan.FindTexture(texture);
     620             : 
     621           3 :     m_MapReader.pTerrain->Initialize(patches, NULL);
     622             : 
     623             :     // Fill the heightmap
     624           3 :     std::uint16_t* heightmap = m_MapReader.pTerrain->GetHeightMap();
     625           3 :     ssize_t verticesPerSide = m_MapReader.pTerrain->GetVerticesPerSide();
     626      111750 :     for (ssize_t i = 0; i < SQR(verticesPerSide); ++i)
     627      111747 :         heightmap[i] = height;
     628             : 
     629             :     // Fill the texture map
     630          39 :     for (ssize_t pz = 0; pz < patches; ++pz)
     631             :     {
     632         468 :         for (ssize_t px = 0; px < patches; ++px)
     633             :         {
     634         432 :             CPatch* patch = m_MapReader.pTerrain->GetPatch(px, pz);  // can't fail
     635             : 
     636        7344 :             for (ssize_t z = 0; z < PATCH_SIZE; ++z)
     637             :             {
     638      117504 :                 for (ssize_t x = 0; x < PATCH_SIZE; ++x)
     639             :                 {
     640      110592 :                     patch->m_MiniPatches[z][x].Tex = texentry;
     641      110592 :                     patch->m_MiniPatches[z][x].Priority = priority;
     642             :                 }
     643             :             }
     644             :         }
     645             :     }
     646           3 : }
     647             : 
     648           3 : void CXMLReader::ReadEnvironment(XMBElement parent)
     649             : {
     650             : #define EL(x) int el_##x = xmb_file.GetElementID(#x)
     651             : #define AT(x) int at_##x = xmb_file.GetAttributeID(#x)
     652           3 :     EL(posteffect);
     653           3 :     EL(skyset);
     654           3 :     EL(suncolor);
     655           3 :     EL(sunelevation);
     656           3 :     EL(sunrotation);
     657           3 :     EL(ambientcolor);
     658           3 :     EL(water);
     659           3 :     EL(waterbody);
     660           3 :     EL(type);
     661           3 :     EL(color);
     662           3 :     EL(tint);
     663           3 :     EL(height);
     664           3 :     EL(waviness);
     665           3 :     EL(murkiness);
     666           3 :     EL(windangle);
     667           3 :     EL(fog);
     668           3 :     EL(fogcolor);
     669           3 :     EL(fogfactor);
     670           3 :     EL(fogthickness);
     671           3 :     EL(postproc);
     672           3 :     EL(brightness);
     673           3 :     EL(contrast);
     674           3 :     EL(saturation);
     675           3 :     EL(bloom);
     676           3 :     AT(r); AT(g); AT(b);
     677             : #undef AT
     678             : #undef EL
     679             : 
     680          54 :     for (XMBElement element : parent.GetChildNodes())
     681             :     {
     682          24 :         int element_name = element.GetNodeName();
     683             : 
     684          24 :         XMBAttributeList attrs = element.GetAttributes();
     685             : 
     686          24 :         if (element_name == el_skyset)
     687             :         {
     688           3 :             if (m_MapReader.pSkyMan)
     689           0 :                 m_MapReader.pSkyMan->SetSkySet(element.GetText().FromUTF8());
     690             :         }
     691          21 :         else if (element_name == el_suncolor)
     692             :         {
     693           9 :             m_MapReader.m_LightEnv.m_SunColor = RGBColor(
     694           6 :                 attrs.GetNamedItem(at_r).ToFloat(),
     695           6 :                 attrs.GetNamedItem(at_g).ToFloat(),
     696           6 :                 attrs.GetNamedItem(at_b).ToFloat());
     697             :         }
     698          18 :         else if (element_name == el_sunelevation)
     699             :         {
     700           3 :             m_MapReader.m_LightEnv.m_Elevation = attrs.GetNamedItem(at_angle).ToFloat();
     701             :         }
     702          15 :         else if (element_name == el_sunrotation)
     703             :         {
     704           3 :             m_MapReader.m_LightEnv.m_Rotation = attrs.GetNamedItem(at_angle).ToFloat();
     705             :         }
     706          12 :         else if (element_name == el_ambientcolor)
     707             :         {
     708           9 :             m_MapReader.m_LightEnv.m_AmbientColor = RGBColor(
     709           6 :                 attrs.GetNamedItem(at_r).ToFloat(),
     710           6 :                 attrs.GetNamedItem(at_g).ToFloat(),
     711           6 :                 attrs.GetNamedItem(at_b).ToFloat());
     712             :         }
     713           9 :         else if (element_name == el_fog)
     714             :         {
     715          27 :             for (XMBElement fog : element.GetChildNodes())
     716             :             {
     717           9 :                 int fog_element_name = fog.GetNodeName();
     718           9 :                 if (fog_element_name == el_fogcolor)
     719             :                 {
     720           3 :                     XMBAttributeList fogAttributes = fog.GetAttributes();
     721           9 :                     m_MapReader.m_LightEnv.m_FogColor = RGBColor(
     722           6 :                         fogAttributes.GetNamedItem(at_r).ToFloat(),
     723           6 :                         fogAttributes.GetNamedItem(at_g).ToFloat(),
     724           6 :                         fogAttributes.GetNamedItem(at_b).ToFloat());
     725             :                 }
     726           6 :                 else if (fog_element_name == el_fogfactor)
     727             :                 {
     728           3 :                     m_MapReader.m_LightEnv.m_FogFactor = fog.GetText().ToFloat();
     729             :                 }
     730           3 :                 else if (fog_element_name == el_fogthickness)
     731             :                 {
     732           3 :                     m_MapReader.m_LightEnv.m_FogMax = fog.GetText().ToFloat();
     733             :                 }
     734             :             }
     735             :         }
     736           6 :         else if (element_name == el_postproc)
     737             :         {
     738          39 :             for (XMBElement postproc : element.GetChildNodes())
     739             :             {
     740          15 :                 int post_element_name = postproc.GetNodeName();
     741          15 :                 if (post_element_name == el_brightness)
     742             :                 {
     743           3 :                     m_MapReader.m_LightEnv.m_Brightness = postproc.GetText().ToFloat();
     744             :                 }
     745          12 :                 else if (post_element_name == el_contrast)
     746             :                 {
     747           3 :                     m_MapReader.m_LightEnv.m_Contrast = postproc.GetText().ToFloat();
     748             :                 }
     749           9 :                 else if (post_element_name == el_saturation)
     750             :                 {
     751           3 :                     m_MapReader.m_LightEnv.m_Saturation = postproc.GetText().ToFloat();
     752             :                 }
     753           6 :                 else if (post_element_name == el_bloom)
     754             :                 {
     755           3 :                     m_MapReader.m_LightEnv.m_Bloom = postproc.GetText().ToFloat();
     756             :                 }
     757           3 :                 else if (post_element_name == el_posteffect)
     758             :                 {
     759           3 :                     if (m_MapReader.pPostproc)
     760           0 :                         m_MapReader.pPostproc->SetPostEffect(postproc.GetText().FromUTF8());
     761             :                 }
     762             :             }
     763             :         }
     764           3 :         else if (element_name == el_water)
     765             :         {
     766          15 :             for (XMBElement waterbody : element.GetChildNodes())
     767             :             {
     768           3 :                 ENSURE(waterbody.GetNodeName() == el_waterbody);
     769          51 :                 for (XMBElement waterelement : waterbody.GetChildNodes())
     770             :                 {
     771          21 :                     int water_element_name = waterelement.GetNodeName();
     772          21 :                     if (water_element_name == el_height)
     773             :                     {
     774           3 :                         CmpPtr<ICmpWaterManager> cmpWaterManager(*m_MapReader.pSimContext, SYSTEM_ENTITY);
     775           3 :                         ENSURE(cmpWaterManager);
     776           3 :                         cmpWaterManager->SetWaterLevel(entity_pos_t::FromString(waterelement.GetText()));
     777           3 :                         continue;
     778           3 :                     }
     779             : 
     780             :                     // The rest are purely graphical effects, and should be ignored if
     781             :                     // graphics are disabled
     782          18 :                     if (!m_MapReader.pWaterMan)
     783          18 :                         continue;
     784             : 
     785           0 :                     if (water_element_name == el_type)
     786             :                     {
     787           0 :                         if (waterelement.GetText() == "default")
     788           0 :                             m_MapReader.pWaterMan->m_WaterType = L"ocean";
     789             :                         else
     790           0 :                             m_MapReader.pWaterMan->m_WaterType =  waterelement.GetText().FromUTF8();
     791             :                     }
     792             : #define READ_COLOR(el, out) \
     793             :                     else if (water_element_name == el) \
     794             :                     { \
     795             :                         XMBAttributeList colorAttrs = waterelement.GetAttributes(); \
     796             :                         out = CColor( \
     797             :                             colorAttrs.GetNamedItem(at_r).ToFloat(), \
     798             :                             colorAttrs.GetNamedItem(at_g).ToFloat(), \
     799             :                             colorAttrs.GetNamedItem(at_b).ToFloat(), \
     800             :                             1.f); \
     801             :                     }
     802             : 
     803             : #define READ_FLOAT(el, out) \
     804             :                     else if (water_element_name == el) \
     805             :                     { \
     806             :                         out = waterelement.GetText().ToFloat(); \
     807             :                     } \
     808             : 
     809           0 :                     READ_COLOR(el_color, m_MapReader.pWaterMan->m_WaterColor)
     810           0 :                     READ_COLOR(el_tint, m_MapReader.pWaterMan->m_WaterTint)
     811           0 :                     READ_FLOAT(el_waviness, m_MapReader.pWaterMan->m_Waviness)
     812           0 :                     READ_FLOAT(el_murkiness, m_MapReader.pWaterMan->m_Murkiness)
     813           0 :                     READ_FLOAT(el_windangle, m_MapReader.pWaterMan->m_WindAngle)
     814             : 
     815             : #undef READ_FLOAT
     816             : #undef READ_COLOR
     817             : 
     818             :                     else
     819          21 :                         debug_warn(L"Invalid map XML data");
     820             :                 }
     821             : 
     822             :             }
     823             :         }
     824             :         else
     825          24 :             debug_warn(L"Invalid map XML data");
     826             :     }
     827             : 
     828           3 :     m_MapReader.m_LightEnv.CalculateSunDirection();
     829           3 : }
     830             : 
     831           3 : void CXMLReader::ReadCamera(XMBElement parent)
     832             : {
     833             :     // defaults if we don't find player starting camera
     834             : #define EL(x) int el_##x = xmb_file.GetElementID(#x)
     835             : #define AT(x) int at_##x = xmb_file.GetAttributeID(#x)
     836           3 :     EL(declination);
     837           3 :     EL(rotation);
     838           3 :     EL(position);
     839           3 :     AT(angle);
     840           3 :     AT(x); AT(y); AT(z);
     841             : #undef AT
     842             : #undef EL
     843             : 
     844           3 :     float declination = DEGTORAD(30.f), rotation = DEGTORAD(-45.f);
     845           3 :     CVector3D translation = CVector3D(100, 150, -100);
     846             : 
     847          24 :     for (XMBElement element : parent.GetChildNodes())
     848             :     {
     849           9 :         int element_name = element.GetNodeName();
     850             : 
     851           9 :         XMBAttributeList attrs = element.GetAttributes();
     852           9 :         if (element_name == el_declination)
     853             :         {
     854           3 :             declination = attrs.GetNamedItem(at_angle).ToFloat();
     855             :         }
     856           6 :         else if (element_name == el_rotation)
     857             :         {
     858           3 :             rotation = attrs.GetNamedItem(at_angle).ToFloat();
     859             :         }
     860           3 :         else if (element_name == el_position)
     861             :         {
     862           9 :             translation = CVector3D(
     863           6 :                 attrs.GetNamedItem(at_x).ToFloat(),
     864           6 :                 attrs.GetNamedItem(at_y).ToFloat(),
     865           6 :                 attrs.GetNamedItem(at_z).ToFloat());
     866             :         }
     867             :         else
     868           9 :             debug_warn(L"Invalid map XML data");
     869             :     }
     870             : 
     871           3 :     if (m_MapReader.pGameView)
     872             :     {
     873           0 :         CCamera camera{m_MapReader.pGameView->GetCamera()};
     874           0 :         camera.m_Orientation.SetXRotation(declination);
     875           0 :         camera.m_Orientation.RotateY(rotation);
     876           0 :         camera.m_Orientation.Translate(translation);
     877           0 :         camera.UpdateFrustum();
     878           0 :         m_MapReader.pGameView->SetCamera(camera);
     879           0 :     }
     880           3 : }
     881             : 
     882           3 : void CXMLReader::ReadPaths(XMBElement parent)
     883             : {
     884             :     #define EL(x) int el_##x = xmb_file.GetElementID(#x)
     885             :     #define AT(x) int at_##x = xmb_file.GetAttributeID(#x)
     886             : 
     887           3 :     EL(path);
     888           3 :     EL(rotation);
     889           3 :     EL(node);
     890           3 :     EL(position);
     891           3 :     EL(target);
     892           3 :     AT(name);
     893           3 :     AT(timescale);
     894           3 :     AT(orientation);
     895           3 :     AT(mode);
     896           3 :     AT(style);
     897           3 :     AT(x);
     898           3 :     AT(y);
     899           3 :     AT(z);
     900           3 :     AT(deltatime);
     901             : 
     902             : #undef EL
     903             : #undef AT
     904             : 
     905           3 :     CmpPtr<ICmpCinemaManager> cmpCinemaManager(*m_MapReader.pSimContext, SYSTEM_ENTITY);
     906           9 :     for (XMBElement element : parent.GetChildNodes())
     907             :     {
     908           0 :         int elementName = element.GetNodeName();
     909             : 
     910           0 :         if (elementName == el_path)
     911             :         {
     912           0 :             CCinemaData pathData;
     913           0 :             XMBAttributeList attrs = element.GetAttributes();
     914           0 :             CStrW pathName(attrs.GetNamedItem(at_name).FromUTF8());
     915           0 :             pathData.m_Name = pathName;
     916           0 :             pathData.m_Timescale = fixed::FromString(attrs.GetNamedItem(at_timescale));
     917           0 :             pathData.m_Orientation = attrs.GetNamedItem(at_orientation).FromUTF8();
     918           0 :             pathData.m_Mode = attrs.GetNamedItem(at_mode).FromUTF8();
     919           0 :             pathData.m_Style = attrs.GetNamedItem(at_style).FromUTF8();
     920             : 
     921           0 :             TNSpline positionSpline, targetSpline;
     922           0 :             fixed lastPositionTime = fixed::Zero();
     923           0 :             fixed lastTargetTime = fixed::Zero();
     924             : 
     925           0 :             for (XMBElement pathChild : element.GetChildNodes())
     926             :             {
     927           0 :                 elementName = pathChild.GetNodeName();
     928           0 :                 attrs = pathChild.GetAttributes();
     929             : 
     930             :                 // Load node data used for spline
     931           0 :                 if (elementName == el_node)
     932             :                 {
     933           0 :                     lastPositionTime += fixed::FromString(attrs.GetNamedItem(at_deltatime));
     934           0 :                     lastTargetTime += fixed::FromString(attrs.GetNamedItem(at_deltatime));
     935           0 :                     for (XMBElement nodeChild : pathChild.GetChildNodes())
     936             :                     {
     937           0 :                         elementName = nodeChild.GetNodeName();
     938           0 :                         attrs = nodeChild.GetAttributes();
     939             : 
     940           0 :                         if (elementName == el_position)
     941             :                         {
     942           0 :                             CFixedVector3D position(fixed::FromString(attrs.GetNamedItem(at_x)),
     943           0 :                                 fixed::FromString(attrs.GetNamedItem(at_y)),
     944           0 :                                 fixed::FromString(attrs.GetNamedItem(at_z)));
     945             : 
     946           0 :                             positionSpline.AddNode(position, CFixedVector3D(), lastPositionTime);
     947           0 :                             lastPositionTime = fixed::Zero();
     948             :                         }
     949           0 :                         else if (elementName == el_rotation)
     950             :                         {
     951             :                             // TODO: Implement rotation slerp/spline as another object
     952             :                         }
     953           0 :                         else if (elementName == el_target)
     954             :                         {
     955           0 :                             CFixedVector3D targetPosition(fixed::FromString(attrs.GetNamedItem(at_x)),
     956           0 :                                 fixed::FromString(attrs.GetNamedItem(at_y)),
     957           0 :                                 fixed::FromString(attrs.GetNamedItem(at_z)));
     958             : 
     959           0 :                             targetSpline.AddNode(targetPosition, CFixedVector3D(), lastTargetTime);
     960           0 :                             lastTargetTime = fixed::Zero();
     961             :                         }
     962             :                         else
     963           0 :                             LOGWARNING("Invalid cinematic element for node child");
     964             :                     }
     965             :                 }
     966             :                 else
     967           0 :                     LOGWARNING("Invalid cinematic element for path child");
     968             :             }
     969             : 
     970             :             // Construct cinema path with data gathered
     971           0 :             CCinemaPath path(pathData, positionSpline, targetSpline);
     972           0 :             if (path.Empty())
     973             :             {
     974           0 :                 LOGWARNING("Path with name '{}' is empty", pathName.ToUTF8());
     975           0 :                 return;
     976             :             }
     977             : 
     978           0 :             if (!cmpCinemaManager)
     979           0 :                 continue;
     980           0 :             if (!cmpCinemaManager->HasPath(pathName))
     981           0 :                 cmpCinemaManager->AddPath(path);
     982             :             else
     983           0 :                 LOGWARNING("Path with name '{}' already exists", pathName.ToUTF8());
     984           0 :         }
     985             :         else
     986           0 :             LOGWARNING("Invalid path child with name '{}'", element.GetText());
     987             :     }
     988             : }
     989             : 
     990           0 : void CXMLReader::ReadTriggers(XMBElement /*parent*/)
     991             : {
     992           0 : }
     993             : 
     994           0 : void CXMLReader::ReadEntities(XMBElement entity, CSimulation2& sim)
     995             : {
     996           0 :     ENSURE(entity.GetNodeName() == el_entity);
     997             : 
     998           0 :     XMBAttributeList attrs = entity.GetAttributes();
     999           0 :     CStr uid = attrs.GetNamedItem(at_uid);
    1000           0 :     ENSURE(!uid.empty());
    1001           0 :     int EntityUid = uid.ToInt();
    1002             : 
    1003           0 :     CStrW TemplateName;
    1004           0 :     int PlayerID = 0;
    1005           0 :     std::vector<entity_id_t> Garrison;
    1006           0 :     std::vector<std::pair<std::string, entity_id_t>> Turrets;
    1007           0 :     CFixedVector3D Position;
    1008           0 :     CFixedVector3D Orientation;
    1009           0 :     long Seed = -1;
    1010             : 
    1011             :     // Obstruction control groups.
    1012           0 :     entity_id_t ControlGroup = INVALID_ENTITY;
    1013           0 :     entity_id_t ControlGroup2 = INVALID_ENTITY;
    1014             : 
    1015           0 :     for (XMBElement setting : entity.GetChildNodes())
    1016             :     {
    1017           0 :         int element_name = setting.GetNodeName();
    1018             : 
    1019             :         // <template>
    1020           0 :         if (element_name == el_template)
    1021             :         {
    1022           0 :             TemplateName = setting.GetText().FromUTF8();
    1023             :         }
    1024             :         // <player>
    1025           0 :         else if (element_name == el_player)
    1026             :         {
    1027           0 :             PlayerID = setting.GetText().ToInt();
    1028             :         }
    1029             :         // <position>
    1030           0 :         else if (element_name == el_position)
    1031             :         {
    1032           0 :             XMBAttributeList positionAttrs = setting.GetAttributes();
    1033           0 :             Position = CFixedVector3D(
    1034           0 :                 fixed::FromString(positionAttrs.GetNamedItem(at_x)),
    1035           0 :                 fixed::FromString(positionAttrs.GetNamedItem(at_y)),
    1036           0 :                 fixed::FromString(positionAttrs.GetNamedItem(at_z)));
    1037             :         }
    1038             :         // <orientation>
    1039           0 :         else if (element_name == el_orientation)
    1040             :         {
    1041           0 :             XMBAttributeList orientationAttrs = setting.GetAttributes();
    1042           0 :             Orientation = CFixedVector3D(
    1043           0 :                 fixed::FromString(orientationAttrs.GetNamedItem(at_x)),
    1044           0 :                 fixed::FromString(orientationAttrs.GetNamedItem(at_y)),
    1045           0 :                 fixed::FromString(orientationAttrs.GetNamedItem(at_z)));
    1046             :             // TODO: what happens if some attributes are missing?
    1047             :         }
    1048             :         // <obstruction>
    1049           0 :         else if (element_name == el_obstruction)
    1050             :         {
    1051           0 :             XMBAttributeList obstructionAttrs = setting.GetAttributes();
    1052           0 :             ControlGroup = obstructionAttrs.GetNamedItem(at_group).ToInt();
    1053           0 :             ControlGroup2 = obstructionAttrs.GetNamedItem(at_group2).ToInt();
    1054             :         }
    1055             :         // <garrison>
    1056           0 :         else if (element_name == el_garrison)
    1057             :         {
    1058           0 :             XMBElementList garrison = setting.GetChildNodes();
    1059           0 :             Garrison.reserve(garrison.size());
    1060           0 :             for (const XMBElement& garr_ent : garrison)
    1061             :             {
    1062           0 :                 XMBAttributeList garrisonAttrs = garr_ent.GetAttributes();
    1063           0 :                 Garrison.push_back(garrisonAttrs.GetNamedItem(at_uid).ToInt());
    1064             :             }
    1065             :         }
    1066             :         // <turrets>
    1067           0 :         else if (element_name == el_turrets)
    1068             :         {
    1069           0 :             XMBElementList turrets = setting.GetChildNodes();
    1070           0 :             Turrets.reserve(turrets.size());
    1071           0 :             for (const XMBElement& turretPoint : turrets)
    1072             :             {
    1073           0 :                 XMBAttributeList turretAttrs = turretPoint.GetAttributes();
    1074           0 :                 Turrets.emplace_back(
    1075           0 :                     turretAttrs.GetNamedItem(at_turret),
    1076           0 :                     turretAttrs.GetNamedItem(at_uid).ToInt()
    1077             :                 );
    1078             :             }
    1079             :         }
    1080             :         // <actor>
    1081           0 :         else if (element_name == el_actor)
    1082             :         {
    1083           0 :             XMBAttributeList attrs = setting.GetAttributes();
    1084           0 :             CStr seedStr = attrs.GetNamedItem(at_seed);
    1085           0 :             if (!seedStr.empty())
    1086             :             {
    1087           0 :                 Seed = seedStr.ToLong();
    1088           0 :                 ENSURE(Seed >= 0);
    1089             :             }
    1090           0 :         }
    1091             :         else
    1092           0 :             debug_warn(L"Invalid map XML data");
    1093             :     }
    1094             : 
    1095           0 :     CmpPtr<ICmpPlayerManager> cmpPlayerManager(sim, SYSTEM_ENTITY);
    1096           0 :     entity_id_t player = cmpPlayerManager->GetPlayerByID(PlayerID);
    1097           0 :     CmpPtr<ICmpPlayer> cmpPlayer(sim, player);
    1098             : 
    1099             :     // Don't add entities for removed players.
    1100           0 :     if (cmpPlayer && cmpPlayer->IsRemoved())
    1101           0 :         return;
    1102             : 
    1103           0 :     entity_id_t ent = sim.AddEntity(TemplateName, EntityUid);
    1104           0 :     if (ent == INVALID_ENTITY || player == INVALID_ENTITY)
    1105             :     {
    1106             :         // Don't add entities with invalid player IDs
    1107           0 :         LOGERROR("Failed to load entity template '{}'", utf8_from_wstring(TemplateName));
    1108           0 :         return;
    1109             :     }
    1110           0 :     CmpPtr<ICmpPosition> cmpPosition(sim, ent);
    1111           0 :     if (cmpPosition)
    1112             :     {
    1113           0 :         cmpPosition->JumpTo(Position.X, Position.Z);
    1114           0 :         cmpPosition->SetYRotation(Orientation.Y);
    1115             :         // TODO: other parts of the position
    1116             :     }
    1117             : 
    1118           0 :     if (!Garrison.empty())
    1119             :     {
    1120           0 :         CmpPtr<ICmpGarrisonHolder> cmpGarrisonHolder(sim, ent);
    1121           0 :         if (cmpGarrisonHolder)
    1122           0 :             cmpGarrisonHolder->SetInitEntities(std::move(Garrison));
    1123             :         else
    1124           0 :             LOGERROR("CXMLMapReader::ReadEntities() entity '{}' of player '{}' has no "
    1125             :                 "GarrisonHolder component and thus cannot garrison units.", ent, PlayerID);
    1126             :     }
    1127             : 
    1128             :     // Needs to be before ownership changes to prevent initialising
    1129             :     // subunits too soon.
    1130           0 :     if (!Turrets.empty())
    1131             :     {
    1132           0 :         CmpPtr<ICmpTurretHolder> cmpTurretHolder(sim, ent);
    1133           0 :         if (cmpTurretHolder)
    1134           0 :             cmpTurretHolder->SetInitEntities(std::move(Turrets));
    1135             :         else
    1136           0 :             LOGERROR("CXMLMapReader::ReadEntities() entity '{}' of player '{}' has no "
    1137             :                 "TurretHolder component and thus cannot use turrets.", ent, PlayerID);
    1138             :     }
    1139             : 
    1140           0 :     CmpPtr<ICmpOwnership> cmpOwnership(sim, ent);
    1141           0 :     if (cmpOwnership)
    1142           0 :         cmpOwnership->SetOwner(PlayerID);
    1143             : 
    1144           0 :     CmpPtr<ICmpObstruction> cmpObstruction(sim, ent);
    1145           0 :     if (cmpObstruction)
    1146             :     {
    1147           0 :         if (ControlGroup != INVALID_ENTITY)
    1148           0 :             cmpObstruction->SetControlGroup(ControlGroup);
    1149           0 :         if (ControlGroup2 != INVALID_ENTITY)
    1150           0 :             cmpObstruction->SetControlGroup2(ControlGroup2);
    1151             : 
    1152           0 :         cmpObstruction->ResolveFoundationCollisions();
    1153             :     }
    1154             : 
    1155           0 :     CmpPtr<ICmpVisual> cmpVisual(sim, ent);
    1156           0 :     if (cmpVisual)
    1157             :     {
    1158           0 :         if (Seed != -1)
    1159           0 :             cmpVisual->SetActorSeed(static_cast<std::uint32_t>(Seed));
    1160             :         // TODO: variation/selection strings
    1161             :     }
    1162             : 
    1163           0 :     if (PlayerID == m_MapReader.m_PlayerID && (TemplateName.ends_with(L"civil_centre") || m_MapReader.m_StartingCameraTarget == INVALID_ENTITY))
    1164             :     {
    1165             :         // Focus on civil centre or first entity owned by player
    1166           0 :         m_MapReader.m_StartingCameraTarget = ent;
    1167             :     }
    1168             : }
    1169             : 
    1170           3 : void CXMLReader::ReadXML()
    1171             : {
    1172          42 :     for (XMBElement node : nodes)
    1173             :     {
    1174          18 :         CStr name = xmb_file.GetElementString(node.GetNodeName());
    1175          18 :         if (name == "Terrain")
    1176             :         {
    1177           3 :             ReadTerrain(node);
    1178             :         }
    1179          15 :         else if (name == "Environment")
    1180             :         {
    1181           3 :             ReadEnvironment(node);
    1182             :         }
    1183          12 :         else if (name == "Camera")
    1184             :         {
    1185           3 :             ReadCamera(node);
    1186             :         }
    1187           9 :         else if (name == "ScriptSettings")
    1188             :         {
    1189             :             // Already loaded - this is to prevent an assertion
    1190             :         }
    1191           6 :         else if (name == "Entities")
    1192             :         {
    1193             :             // Handled by ReadXMLEntities instead
    1194             :         }
    1195           3 :         else if (name == "Paths")
    1196             :         {
    1197           3 :             ReadPaths(node);
    1198             :         }
    1199           0 :         else if (name == "Triggers")
    1200             :         {
    1201          18 :             ReadTriggers(node);
    1202             :         }
    1203           0 :         else if (name == "Script")
    1204             :         {
    1205           0 :             if (m_MapReader.pSimulation2)
    1206           0 :                 m_MapReader.pSimulation2->SetStartupScript(node.GetText());
    1207             :         }
    1208             :         else
    1209             :         {
    1210           0 :             debug_printf("Invalid XML element in map file: %s\n", name.c_str());
    1211          18 :             debug_warn(L"Invalid map XML data");
    1212             :         }
    1213          18 :     }
    1214           3 : }
    1215             : 
    1216             : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    1217             : 
    1218             : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    1219             : 
    1220             : 
    1221             : // load script settings from map
    1222           0 : int CMapReader::LoadScriptSettings()
    1223             : {
    1224           0 :     if (!m_XmlReader)
    1225           0 :         m_XmlReader = std::make_unique<CXMLReader>(m_FilenameXml, *this);
    1226             : 
    1227             :     // parse the script settings
    1228           0 :     if (pSimulation2)
    1229           0 :         pSimulation2->SetMapSettings(m_XmlReader->ReadScriptSettings());
    1230             : 
    1231           0 :     return 0;
    1232             : }
    1233             : 
    1234             : // load player settings script
    1235           0 : int CMapReader::LoadPlayerSettings()
    1236             : {
    1237           0 :     if (pSimulation2)
    1238           0 :         pSimulation2->LoadPlayerSettings(true);
    1239           0 :     return 0;
    1240             : }
    1241             : 
    1242             : // load map settings script
    1243           0 : int CMapReader::LoadMapSettings()
    1244             : {
    1245           0 :     if (pSimulation2)
    1246           0 :         pSimulation2->LoadMapSettings();
    1247           0 :     return 0;
    1248             : }
    1249             : 
    1250           3 : int CMapReader::ReadXML()
    1251             : {
    1252           3 :     if (!m_XmlReader)
    1253           3 :         m_XmlReader = std::make_unique<CXMLReader>(m_FilenameXml, *this);
    1254             : 
    1255           3 :     m_XmlReader->ReadXML();
    1256             : 
    1257           3 :     return 0;
    1258             : }
    1259             : 
    1260             : // progressive
    1261           6 : PS::Loader::Task CMapReader::ReadXMLEntities()
    1262             : {
    1263             :     if (m_SkipEntities)
    1264             :         co_return 0;
    1265             : 
    1266             :     if (!m_XmlReader)
    1267             :         m_XmlReader = std::make_unique<CXMLReader>(m_FilenameXml, *this);
    1268             : 
    1269             :     const std::size_t totalJobs{std::transform_reduce(m_XmlReader->nodes.begin(),
    1270          18 :         m_XmlReader->nodes.end(), static_cast<std::size_t>(0), std::plus<>{}, [](XMBElement node)
    1271             :     {
    1272          18 :         return node.GetChildNodes().size();
    1273             :     })};
    1274             :     ENSURE(pSimulation2 || totalJobs == 0);
    1275             :     std::size_t completedJobs{0};
    1276             :     for (XMBElement node : m_XmlReader->nodes)
    1277             :     {
    1278             :         CStr name = m_XmlReader->xmb_file.GetElementString(node.GetNodeName());
    1279             :         if (name != "Entities")
    1280             :             continue;
    1281             : 
    1282             :         for (XMBElement child : node.GetChildNodes())
    1283             :         {
    1284             :             m_XmlReader->ReadEntities(child, *pSimulation2);
    1285             : 
    1286             :             completedJobs++;
    1287             :             co_yield 100 * completedJobs / totalJobs;
    1288             :         }
    1289             :     }
    1290             : 
    1291             :     m_XmlReader.reset();
    1292             : 
    1293             :     co_return 0;
    1294           3 : }
    1295             : 
    1296             : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    1297             : 
    1298             : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    1299             : 
    1300             : 
    1301           3 : int CMapReader::LoadRMSettings()
    1302             : {
    1303             :     // copy random map settings over to sim
    1304           3 :     ENSURE(pSimulation2);
    1305           3 :     pSimulation2->SetMapSettings(m_ScriptSettings);
    1306             : 
    1307           3 :     return 0;
    1308             : }
    1309             : 
    1310           0 : [[noreturn]] void ThrowMapGenerationError()
    1311             : {
    1312           0 :     throw PSERROR_Game_World_MapLoadFailed{
    1313           0 :         "Error generating random map.\nCheck application log for details."};
    1314             : }
    1315             : 
    1316           0 : PS::Loader::Task CMapReader::RunMapGeneration(const CStrW& scriptFile)
    1317             : {
    1318             :     std::atomic<int> progress{1};
    1319             : 
    1320             :     // The settings are stringified to pass them to the task.
    1321             :     Future<Script::StructuredClone> task = {g_TaskManager,
    1322           0 :         [&progress, scriptFile, settings = Script::StringifyJSON(Script::Request{
    1323           0 :             pSimulation2->GetScriptInterface()}, &m_ScriptSettings)](const StopToken stopToken)
    1324             :         {
    1325           0 :             PROFILE2("Map Generation");
    1326             : 
    1327           0 :             const VfsPath scriptPath{scriptFile.empty() ? L"" :
    1328           0 :                 static_cast<std::wstring>(RANDOM_MAP_PREFIX) + scriptFile};
    1329             : 
    1330           0 :             Script::Context mapgenContext{MAP_GENERATION_CONTEXT_SIZE};
    1331           0 :             Script::Interface mapgenInterface{"Engine", "MapGenerator", mapgenContext,
    1332           0 :                 [](const VfsPath& path){
    1333             :                     // Only allow to load modules inside the maps folder.
    1334           0 :                     return path.string().find(RANDOM_MAP_PREFIX) == 0;
    1335           0 :                 }};
    1336             : 
    1337           0 :             return RunMapGenerationScript(stopToken, progress, mapgenInterface, scriptPath, settings);
    1338           0 :         }};
    1339             : 
    1340             :     while (!task.IsDone())
    1341             :     {
    1342             :         co_yield progress.load();
    1343             :         co_await std::suspend_always{};
    1344             : 
    1345             :         if (IsQuitRequested())
    1346             :         {
    1347             :             LOGWARNING("Quit requested!");
    1348             :             co_return -1;
    1349             :         }
    1350             :     }
    1351             : 
    1352             :     const Script::StructuredClone results{task.Get()};
    1353             :     if (!results)
    1354             :         ThrowMapGenerationError();
    1355             : 
    1356             :     // Parse data into simulation context
    1357             :     Script::Request rq(pSimulation2->GetScriptInterface());
    1358             :     JS::RootedValue data{rq.cx};
    1359             :     Script::ReadStructuredClone(rq, results, &data);
    1360             : 
    1361             :     if (data.isUndefined())
    1362             :         ThrowMapGenerationError();
    1363             : 
    1364             :     m_MapData.init(rq.cx, data);
    1365             : 
    1366             :     co_return 0;
    1367           0 : };
    1368             : 
    1369             : 
    1370           0 : int CMapReader::ParseTerrain()
    1371             : {
    1372           0 :     PROFILE2("ParseTerrain");
    1373           0 :     Script::Request rq(pSimulation2->GetScriptInterface());
    1374             : 
    1375             :     // parse terrain from map data
    1376             :     //  an error here should stop the loading process
    1377           0 :     const auto getTerrainProperty = [&](JS::HandleValue val, const char* prop, auto&& out)
    1378             :     {
    1379           0 :         if (Script::GetProperty(rq, val, prop, std::forward<decltype(out)>(out)))
    1380           0 :             return;
    1381             : 
    1382           0 :         LOGERROR("CMapReader::ParseTerrain() failed to get '{}' property", prop);
    1383           0 :         throw PSERROR_Game_World_MapLoadFailed(
    1384             :             "Error parsing terrain data.\nCheck application log for details");
    1385           0 :     };
    1386             : 
    1387           0 :     std::uint32_t size;
    1388           0 :     getTerrainProperty(m_MapData, "size", size);
    1389             : 
    1390           0 :     m_PatchesPerSide = size / PATCH_SIZE;
    1391             : 
    1392             :     // flat heightmap of std::uint16_t data
    1393           0 :     getTerrainProperty(m_MapData, "height", m_Heightmap);
    1394             : 
    1395             :     // load textures
    1396           0 :     std::vector<std::string> textureNames;
    1397           0 :     getTerrainProperty(m_MapData, "textureNames", textureNames);
    1398             : 
    1399           0 :     for (const std::string& textureName : textureNames)
    1400             :     {
    1401           0 :         if (CTerrainTextureManager::IsInitialised())
    1402             :         {
    1403           0 :             CTerrainTextureEntry* texentry = g_TexMan.FindTexture(textureName);
    1404           0 :             m_TerrainTextures.push_back(texentry);
    1405             :         }
    1406             :     }
    1407             : 
    1408             :     // build tile data
    1409           0 :     m_Tiles.resize(SQR(size));
    1410             : 
    1411           0 :     JS::RootedValue tileData(rq.cx);
    1412           0 :     getTerrainProperty(m_MapData, "tileData", &tileData);
    1413             : 
    1414             :     // parse tile data object into flat arrays
    1415           0 :     std::vector<std::uint16_t> tileIndex;
    1416           0 :     std::vector<std::uint16_t> tilePriority;
    1417           0 :     getTerrainProperty(tileData, "index", tileIndex);
    1418           0 :     getTerrainProperty(tileData, "priority", tilePriority);
    1419             : 
    1420           0 :     ENSURE(SQR(size) == tileIndex.size() && SQR(size) == tilePriority.size());
    1421             : 
    1422             :     // reorder by patches and store
    1423           0 :     for (size_t x = 0; x < size; ++x)
    1424             :     {
    1425           0 :         size_t patchX = x / PATCH_SIZE;
    1426           0 :         size_t offX = x % PATCH_SIZE;
    1427           0 :         for (size_t y = 0; y < size; ++y)
    1428             :         {
    1429           0 :             size_t patchY = y / PATCH_SIZE;
    1430           0 :             size_t offY = y % PATCH_SIZE;
    1431             : 
    1432           0 :             STileDesc tile;
    1433           0 :             tile.m_Tex1Index = tileIndex[y*size + x];
    1434           0 :             tile.m_Tex2Index = 0xFFFF;
    1435           0 :             tile.m_Priority = tilePriority[y*size + x];
    1436             : 
    1437           0 :             m_Tiles[(patchY * m_PatchesPerSide + patchX) * SQR(PATCH_SIZE) + (offY * PATCH_SIZE + offX)] = tile;
    1438             :         }
    1439             :     }
    1440             : 
    1441           0 :     return 0;
    1442           0 : }
    1443             : 
    1444             : struct ParseEntitiesState
    1445             : {
    1446             :     Script::Request rq;
    1447             :     CmpPtr<ICmpPlayerManager> cmpPlayerManager;
    1448             :     std::vector<Entity> entities;
    1449             :     size_t currentEntityIndex{0};
    1450             : 
    1451             :     ParseEntitiesState(CSimulation2& sim)
    1452             :         : rq(sim.GetScriptInterface()), cmpPlayerManager(sim, SYSTEM_ENTITY) {}
    1453             : };
    1454             : 
    1455           0 : PS::Loader::Task CMapReader::ParseEntities()
    1456             : {
    1457             :     PROFILE2("ParseEntities");
    1458             : 
    1459             :     CSimulation2& sim{*pSimulation2};
    1460             :     Script::Request rq{sim.GetScriptInterface()};
    1461             :     CmpPtr<ICmpPlayerManager> cmpPlayerManager{sim, SYSTEM_ENTITY};
    1462             : 
    1463             :     std::vector<Entity> entities;
    1464             :     if (!Script::GetProperty(rq, m_MapData, "entities", entities))
    1465             :         LOGWARNING("CMapReader::ParseEntities() failed to get 'entities' property");
    1466             : 
    1467             :     for (std::size_t index{0}; index != entities.size(); ++index)
    1468             :     {
    1469             :         co_yield Clamp<int>(index * 80 / entities.size(), 20, 100);
    1470             : 
    1471             :         const Entity& currEnt{entities[index]};
    1472             :         // Get current entity struct
    1473             :         entity_id_t player = cmpPlayerManager->GetPlayerByID(currEnt.playerID);
    1474             :         CmpPtr<ICmpPlayer> cmpPlayer(sim, player);
    1475             :         // Don't add entities for removed players.
    1476             :         if (cmpPlayer && cmpPlayer->IsRemoved())
    1477             :             continue;
    1478             : 
    1479             :         entity_id_t ent = sim.AddEntity(currEnt.templateName, currEnt.entityID);
    1480             :         if (ent == INVALID_ENTITY || player == INVALID_ENTITY)
    1481             :         {   // Don't add entities with invalid player IDs
    1482             :             LOGERROR("Failed to load entity template '{}'", utf8_from_wstring(currEnt.templateName));
    1483             :         }
    1484             :         else
    1485             :         {
    1486             :             CmpPtr<ICmpPosition> cmpPosition(sim, ent);
    1487             :             if (cmpPosition)
    1488             :             {
    1489             :                 cmpPosition->JumpTo(currEnt.position.X * (int)TERRAIN_TILE_SIZE, currEnt.position.Z * (int)TERRAIN_TILE_SIZE);
    1490             :                 cmpPosition->SetYRotation(currEnt.rotation.Y);
    1491             :                 // TODO: other parts of the position
    1492             :             }
    1493             : 
    1494             :             CmpPtr<ICmpOwnership> cmpOwnership(sim, ent);
    1495             :             if (cmpOwnership)
    1496             :                 cmpOwnership->SetOwner(currEnt.playerID);
    1497             : 
    1498             :             // Detect and fix collisions between foundation-blocking entities.
    1499             :             // This presently serves to copy wall tower control groups to wall
    1500             :             // segments, allowing players to expand RMS-generated walls.
    1501             :             CmpPtr<ICmpObstruction> cmpObstruction(sim, ent);
    1502             :             if (cmpObstruction)
    1503             :                 cmpObstruction->ResolveFoundationCollisions();
    1504             : 
    1505             :             if (currEnt.playerID == m_PlayerID && (currEnt.templateName.ends_with(L"civil_centre") || m_StartingCameraTarget == INVALID_ENTITY))
    1506             :             {
    1507             :                 // Focus on civil centre or first entity owned by player
    1508             :                 m_StartingCameraTarget = currEnt.entityID;
    1509             :             }
    1510             :         }
    1511             :     }
    1512             : 
    1513             :     co_return 0;
    1514           0 : }
    1515             : 
    1516           0 : int CMapReader::ParseEnvironment()
    1517             : {
    1518             :     // parse environment settings from map data
    1519           0 :     Script::Request rq(pSimulation2->GetScriptInterface());
    1520             : 
    1521           0 :     const auto getEnvironmentProperty = [&](JS::HandleValue val, const char* prop, auto&& out)
    1522             :     {
    1523           0 :         if (!Script::GetProperty(rq, val, prop, std::forward<decltype(out)>(out)))
    1524           0 :             LOGWARNING("CMapReader::ParseEnvironment() failed to get '{}' property", prop);
    1525           0 :     };
    1526             : 
    1527           0 :     JS::RootedValue envObj(rq.cx);
    1528           0 :     getEnvironmentProperty(m_MapData, "Environment", &envObj);
    1529             : 
    1530           0 :     if (envObj.isUndefined())
    1531             :     {
    1532           0 :         LOGWARNING("CMapReader::ParseEnvironment(): Environment settings not found");
    1533           0 :         return 0;
    1534             :     }
    1535             : 
    1536           0 :     if (pPostproc)
    1537           0 :         pPostproc->SetPostEffect(L"default");
    1538             : 
    1539           0 :     std::wstring skySet;
    1540           0 :     getEnvironmentProperty(envObj, "SkySet", skySet);
    1541           0 :     if (pSkyMan)
    1542           0 :         pSkyMan->SetSkySet(skySet);
    1543             : 
    1544           0 :     CColor sunColor;
    1545           0 :     getEnvironmentProperty(envObj, "SunColor", sunColor);
    1546           0 :     m_LightEnv.m_SunColor = RGBColor(sunColor.r, sunColor.g, sunColor.b);
    1547             : 
    1548           0 :     getEnvironmentProperty(envObj, "SunElevation", m_LightEnv.m_Elevation);
    1549           0 :     getEnvironmentProperty(envObj, "SunRotation", m_LightEnv.m_Rotation);
    1550             : 
    1551           0 :     CColor ambientColor;
    1552           0 :     getEnvironmentProperty(envObj, "AmbientColor", ambientColor);
    1553           0 :     m_LightEnv.m_AmbientColor = RGBColor(ambientColor.r, ambientColor.g, ambientColor.b);
    1554             : 
    1555             :     // Water properties
    1556           0 :     JS::RootedValue waterObj(rq.cx);
    1557           0 :     getEnvironmentProperty(envObj, "Water", &waterObj);
    1558             : 
    1559           0 :     JS::RootedValue waterBodyObj(rq.cx);
    1560           0 :     getEnvironmentProperty(waterObj, "WaterBody", &waterBodyObj);
    1561             : 
    1562             :     // Water level - necessary
    1563           0 :     float waterHeight;
    1564           0 :     getEnvironmentProperty(waterBodyObj, "Height", waterHeight);
    1565             : 
    1566           0 :     CmpPtr<ICmpWaterManager> cmpWaterManager(*pSimulation2, SYSTEM_ENTITY);
    1567           0 :     ENSURE(cmpWaterManager);
    1568           0 :     cmpWaterManager->SetWaterLevel(entity_pos_t::FromFloat(waterHeight));
    1569             : 
    1570             :     // If we have graphics, get rest of settings
    1571           0 :     if (pWaterMan)
    1572             :     {
    1573           0 :         getEnvironmentProperty(waterBodyObj, "Type", pWaterMan->m_WaterType);
    1574           0 :         if (pWaterMan->m_WaterType == L"default")
    1575           0 :             pWaterMan->m_WaterType = L"ocean";
    1576           0 :         getEnvironmentProperty(waterBodyObj, "Color", pWaterMan->m_WaterColor);
    1577           0 :         getEnvironmentProperty(waterBodyObj, "Tint", pWaterMan->m_WaterTint);
    1578           0 :         getEnvironmentProperty(waterBodyObj, "Waviness", pWaterMan->m_Waviness);
    1579           0 :         getEnvironmentProperty(waterBodyObj, "Murkiness", pWaterMan->m_Murkiness);
    1580           0 :         getEnvironmentProperty(waterBodyObj, "WindAngle", pWaterMan->m_WindAngle);
    1581             :     }
    1582             : 
    1583           0 :     JS::RootedValue fogObject(rq.cx);
    1584           0 :     getEnvironmentProperty(envObj, "Fog", &fogObject);
    1585             : 
    1586           0 :     getEnvironmentProperty(fogObject, "FogFactor", m_LightEnv.m_FogFactor);
    1587           0 :     getEnvironmentProperty(fogObject, "FogThickness", m_LightEnv.m_FogMax);
    1588             : 
    1589           0 :     CColor fogColor;
    1590           0 :     getEnvironmentProperty(fogObject, "FogColor", fogColor);
    1591           0 :     m_LightEnv.m_FogColor = RGBColor(fogColor.r, fogColor.g, fogColor.b);
    1592             : 
    1593           0 :     JS::RootedValue postprocObject(rq.cx);
    1594           0 :     getEnvironmentProperty(envObj, "Postproc", &postprocObject);
    1595             : 
    1596           0 :     std::wstring postProcEffect;
    1597           0 :     getEnvironmentProperty(postprocObject, "PostprocEffect", postProcEffect);
    1598             : 
    1599           0 :     if (pPostproc)
    1600           0 :         pPostproc->SetPostEffect(postProcEffect);
    1601             : 
    1602           0 :     getEnvironmentProperty(postprocObject, "Brightness", m_LightEnv.m_Brightness);
    1603           0 :     getEnvironmentProperty(postprocObject, "Contrast", m_LightEnv.m_Contrast);
    1604           0 :     getEnvironmentProperty(postprocObject, "Saturation", m_LightEnv.m_Saturation);
    1605           0 :     getEnvironmentProperty(postprocObject, "Bloom", m_LightEnv.m_Bloom);
    1606             : 
    1607           0 :     m_LightEnv.CalculateSunDirection();
    1608           0 :     return 0;
    1609           0 : }
    1610             : 
    1611           0 : int CMapReader::ParseCamera()
    1612             : {
    1613           0 :     Script::Request rq(pSimulation2->GetScriptInterface());
    1614             : 
    1615             :     // parse camera settings from map data
    1616             :     // defaults if we don't find player starting camera
    1617           0 :     float declination = DEGTORAD(30.f), rotation = DEGTORAD(-45.f);
    1618           0 :     CVector3D translation = CVector3D(100, 150, -100);
    1619             : 
    1620           0 :     const auto getCameraProperty = [&](JS::HandleValue val, const char* prop, auto&& out)
    1621             :     {
    1622           0 :         if (!Script::GetProperty(rq, val, prop, std::forward<decltype(out)>(out)))
    1623           0 :             LOGWARNING("CMapReader::ParseCamera() failed to get '{}' property", prop);
    1624           0 :     };
    1625             : 
    1626           0 :     JS::RootedValue cameraObj(rq.cx);
    1627           0 :     getCameraProperty(m_MapData, "Camera", &cameraObj);
    1628             : 
    1629           0 :     if (!cameraObj.isUndefined())
    1630             :     {   // If camera property exists, read values
    1631           0 :         CFixedVector3D pos;
    1632           0 :         getCameraProperty(cameraObj, "Position", pos);
    1633           0 :         translation = pos;
    1634             : 
    1635           0 :         getCameraProperty(cameraObj, "Rotation", rotation);
    1636           0 :         getCameraProperty(cameraObj, "Declination", declination);
    1637             :     }
    1638             : 
    1639           0 :     if (pGameView)
    1640             :     {
    1641           0 :         CCamera camera{pGameView->GetCamera()};
    1642           0 :         camera.m_Orientation.SetXRotation(declination);
    1643           0 :         camera.m_Orientation.RotateY(rotation);
    1644           0 :         camera.m_Orientation.Translate(translation);
    1645           0 :         camera.UpdateFrustum();
    1646           0 :         pGameView->SetCamera(camera);
    1647           0 :     }
    1648             : 
    1649           0 :     return 0;
    1650           0 : }
    1651             : 
    1652          12 : CMapReader::~CMapReader() = default;

Generated by: LCOV version 1.16