LCOV - code coverage report
Current view: top level - source/graphics - MapGenerator.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 78 161 48.4 %
Date: 2026-12-03 01:19:39 Functions: 6 13 46.2 %

          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 "MapGenerator.h"
      21             : 
      22             : #include "graphics/MapIO.h"
      23             : #include "graphics/Patch.h"
      24             : #include "graphics/Terrain.h"
      25             : #include "lib/code_annotation.h"
      26             : #include "lib/file/vfs/vfs_path.h"
      27             : #include "lib/file/vfs/vfs_util.h"
      28             : #include "lib/path.h"
      29             : #include "lib/posix/posix_types.h"
      30             : #include "lib/status.h"
      31             : #include "lib/utf8.h"
      32             : #include "maths/MathUtil.h"
      33             : #include "ps/CLogger.h"
      34             : #include "ps/CStr.h"
      35             : #include "ps/FileIo.h"
      36             : #include "ps/Filesystem.h"
      37             : #include "ps/Future.h"
      38             : #include "ps/TemplateLoader.h"
      39             : #include "ps/scripting/JSInterface_VFS.h"
      40             : #include "scriptinterface/FunctionWrapper.h"
      41             : #include "scriptinterface/JSON.h"
      42             : #include "scriptinterface/ModuleLoader.h"
      43             : #include "scriptinterface/Object.h"
      44             : #include "scriptinterface/Context.h"
      45             : #include "scriptinterface/Conversions.h"
      46             : #include "scriptinterface/Interface.h"
      47             : #include "scriptinterface/Request.h"
      48             : #include "simulation2/helpers/MapEdgeTiles.h"
      49             : #include "simulation2/system/Component.h"
      50             : 
      51             : #include <boost/random/linear_congruential.hpp>
      52             : #include <cstddef>
      53             : #include <fmt/format.h>
      54             : #include <js/Interrupt.h>
      55             : #include <js/PropertyAndElement.h>
      56             : #include <js/RootingAPI.h>
      57             : #include <js/TypeDecls.h>
      58             : #include <js/Value.h>
      59             : #include <jsapi.h>
      60             : #include <set>
      61             : #include <stdexcept>
      62             : #include <string>
      63             : #include <vector>
      64             : 
      65             : struct JSContext;
      66             : 
      67             : namespace
      68             : {
      69             : constexpr const char* GENERATOR_NAME{"generateMap"};
      70             : 
      71             : bool MapGenerationInterruptCallback(JSContext* cx);
      72             : 
      73             : /**
      74             :  * Provides callback's for the JavaScript.
      75             :  */
      76             : class CMapGenerationCallbacks
      77             : {
      78             : public:
      79             :     // Only the constructor and the destructor are called by C++.
      80             : 
      81           8 :     CMapGenerationCallbacks(const StopToken stopToken, Script::Interface& scriptInterface,
      82           8 :         const std::uint16_t flags) :
      83           8 :         m_StopToken{stopToken},
      84           8 :         m_ScriptInterface{scriptInterface}
      85             :     {
      86           8 :         m_ScriptInterface.SetCallbackData(static_cast<void*>(this));
      87             : 
      88             :         // Enable the script to be aborted
      89           8 :         JS_AddInterruptCallback(m_ScriptInterface.GetGeneralJSContext(),
      90             :             &MapGenerationInterruptCallback);
      91             : 
      92             :         // Set initial seed, callback data.
      93             :         // Expose functions, globals and classes relevant to the map scripts.
      94             : #define REGISTER_MAPGEN_FUNC(func) \
      95             :     Script::Function::Register<&CMapGenerationCallbacks::func, \
      96             :         Script::Interface::ObjectFromCBData<CMapGenerationCallbacks>>(rq, #func, flags);
      97             : 
      98             :         // VFS
      99           8 :         JSI_VFS::RegisterScriptFunctions_ReadOnlySimulationMaps(m_ScriptInterface, flags);
     100             : 
     101             :         // Globalscripts may use VFS script functions
     102           8 :         m_ScriptInterface.LoadGlobalScripts();
     103             : 
     104             :         // File loading
     105           8 :         Script::Request rq(m_ScriptInterface);
     106          36 :         REGISTER_MAPGEN_FUNC(LoadLibrary);
     107           8 :         REGISTER_MAPGEN_FUNC(LoadHeightmapImage);
     108           8 :         REGISTER_MAPGEN_FUNC(LoadMapTerrain);
     109             : 
     110             :         // Template functions
     111           8 :         REGISTER_MAPGEN_FUNC(GetTemplate);
     112           8 :         REGISTER_MAPGEN_FUNC(TemplateExists);
     113           8 :         REGISTER_MAPGEN_FUNC(FindTemplates);
     114           8 :         REGISTER_MAPGEN_FUNC(FindActorTemplates);
     115             : 
     116             :         // Profiling
     117           8 :         REGISTER_MAPGEN_FUNC(GetMicroseconds);
     118             : 
     119             :         // Engine constants
     120             : 
     121             :         // Length of one tile of the terrain grid in metres.
     122             :         // Useful to transform footprint sizes to the tilegrid coordinate system.
     123           8 :         m_ScriptInterface.SetGlobal("TERRAIN_TILE_SIZE", static_cast<int>(TERRAIN_TILE_SIZE));
     124             : 
     125             :         // Number of impassable tiles at the map border
     126           8 :         m_ScriptInterface.SetGlobal("MAP_BORDER_WIDTH", static_cast<int>(MAP_EDGE_TILES));
     127             : 
     128             : #undef REGISTER_MAPGEN_FUNC
     129           8 :     }
     130             : 
     131           8 :     ~CMapGenerationCallbacks()
     132             :     {
     133           8 :         JS_AddInterruptCallback(m_ScriptInterface.GetGeneralJSContext(), nullptr);
     134           8 :         m_ScriptInterface.SetCallbackData(nullptr);
     135           8 :     }
     136             : 
     137             :     StopToken m_StopToken;
     138             : 
     139             : private:
     140             : 
     141             :     // These functions are called by JS.
     142             : 
     143             :     /**
     144             :      * Load all scripts of the given library
     145             :      *
     146             :      * @param libraryName VfsPath specifying name of the library (subfolder of ../maps/random/)
     147             :      * @return true if all scripts ran successfully, false if there's an error
     148             :      */
     149          28 :     bool LoadLibrary(const VfsPath& libraryName)
     150             :     {
     151             :         // Ignore libraries that are already loaded
     152          28 :         if (m_LoadedLibraries.find(libraryName) != m_LoadedLibraries.end())
     153             :             return true;
     154             : 
     155             :         // Mark this as loaded, to prevent it recursively loading itself
     156          28 :         m_LoadedLibraries.insert(libraryName);
     157             : 
     158          84 :         VfsPath path = VfsPath(L"maps/random/") / libraryName / VfsPath();
     159          28 :         VfsPaths pathnames;
     160             : 
     161             :         // Load all scripts in mapgen directory
     162          28 :         Status ret = vfs::GetPathnames(g_VFS, path, L"*.js", pathnames);
     163          28 :         if (ret == INFO::OK)
     164             :         {
     165         280 :             for (const VfsPath& p : pathnames)
     166             :             {
     167         756 :                 LOGMESSAGE("Loading map generator script '{}'", p.string8());
     168             : 
     169         252 :                 if (!m_ScriptInterface.LoadGlobalScriptFile(p))
     170             :                 {
     171           0 :                     LOGERROR("CMapGenerationCallbacks::LoadScripts: Failed to load script '{}'",
     172             :                         p.string8());
     173           0 :                     return false;
     174             :                 }
     175             :             }
     176             :         }
     177             :         else
     178             :         {
     179             :             // Some error reading directory
     180           0 :             wchar_t error[200];
     181           0 :             LOGERROR("CMapGenerationCallbacks::LoadScripts: Error reading scripts in directory "
     182             :                 "'{}': {}", path.string8(),
     183             :                 utf8_from_wstring(StatusDescription(ret, error, ARRAY_SIZE(error))));
     184           0 :             return false;
     185             :         }
     186             : 
     187             :         return true;
     188          56 :     }
     189             : 
     190             :     /**
     191             :      * Load an image file and return it as a height array.
     192             :      */
     193           0 :     JS::Value LoadHeightmapImage(const VfsPath& filename)
     194             :     {
     195           0 :         std::vector<std::uint16_t> heightmap;
     196           0 :         if (LoadHeightmapImageVfs(filename, heightmap) != INFO::OK)
     197             :         {
     198           0 :             LOGERROR("Could not load heightmap file '{}'", filename.string8());
     199           0 :             return JS::UndefinedValue();
     200             :         }
     201             : 
     202           0 :         Script::Request rq(m_ScriptInterface);
     203           0 :         JS::RootedValue returnValue(rq.cx);
     204           0 :         Script::ToJSVal(rq, &returnValue, heightmap);
     205           0 :         return returnValue;
     206           0 :     }
     207             : 
     208             :     /**
     209             :      * Load an Atlas terrain file (PMP) returning textures and heightmap.
     210             :      *
     211             :      * See CMapReader::UnpackTerrain, CMapReader::ParseTerrain for the reordering
     212             :      */
     213           0 :     JS::Value LoadMapTerrain(const VfsPath& filename)
     214             :     {
     215           0 :         Script::Request rq(m_ScriptInterface);
     216             : 
     217           0 :         if (!VfsFileExists(filename))
     218             :         {
     219           0 :             throw std::runtime_error{fmt::format("Terrain file \"{}\" does not exist!",
     220           0 :                 filename.string8().c_str())};
     221             :         }
     222             : 
     223           0 :         CFileUnpacker unpacker;
     224           0 :         unpacker.Read(filename, "PSMP");
     225             : 
     226           0 :         if (unpacker.GetVersion() < CMapIO::FILE_READ_VERSION)
     227             :         {
     228           0 :             throw std::runtime_error{fmt::format(
     229           0 :                 "Could not load terrain file \"{}\" too old version!", filename.string8().c_str())};
     230             :         }
     231             : 
     232             :         // unpack size
     233           0 :         ssize_t patchesPerSide = (ssize_t)unpacker.UnpackSize();
     234           0 :         size_t verticesPerSide = patchesPerSide * PATCH_SIZE + 1;
     235             : 
     236             :         // unpack heightmap
     237           0 :         std::vector<std::uint16_t> heightmap;
     238           0 :         heightmap.resize(SQR(verticesPerSide));
     239           0 :         unpacker.UnpackRaw(&heightmap[0], SQR(verticesPerSide) * sizeof(std::uint16_t));
     240             : 
     241             :         // unpack texture names
     242           0 :         size_t textureCount = unpacker.UnpackSize();
     243           0 :         std::vector<std::string> textureNames;
     244           0 :         textureNames.reserve(textureCount);
     245           0 :         for (size_t i = 0; i < textureCount; ++i)
     246             :         {
     247           0 :             CStr texturename;
     248           0 :             unpacker.UnpackString(texturename);
     249           0 :             textureNames.push_back(texturename);
     250           0 :         }
     251             : 
     252             :         // unpack texture IDs per tile
     253           0 :         ssize_t tilesPerSide = patchesPerSide * PATCH_SIZE;
     254           0 :         std::vector<CMapIO::STileDesc> tiles;
     255           0 :         tiles.resize(size_t(SQR(tilesPerSide)));
     256           0 :         unpacker.UnpackRaw(&tiles[0], sizeof(CMapIO::STileDesc) * tiles.size());
     257             : 
     258             :         // reorder by patches and store and save texture IDs per tile
     259           0 :         std::vector<std::uint16_t> textureIDs;
     260           0 :         for (ssize_t x = 0; x < tilesPerSide; ++x)
     261             :         {
     262           0 :             size_t patchX = x / PATCH_SIZE;
     263           0 :             size_t offX = x % PATCH_SIZE;
     264           0 :             for (ssize_t y = 0; y < tilesPerSide; ++y)
     265             :             {
     266           0 :                 size_t patchY = y / PATCH_SIZE;
     267           0 :                 size_t offY = y % PATCH_SIZE;
     268             :                 // m_Priority and m_Tex2Index unused
     269           0 :                 textureIDs.push_back(tiles[(patchY * patchesPerSide + patchX) * SQR(PATCH_SIZE) +
     270           0 :                     (offY * PATCH_SIZE + offX)].m_Tex1Index);
     271             :             }
     272             :         }
     273             : 
     274           0 :         JS::RootedValue returnValue(rq.cx);
     275             : 
     276           0 :         Script::CreateObject(
     277             :             rq,
     278             :             &returnValue,
     279             :             "height", heightmap,
     280             :             "textureNames", textureNames,
     281             :             "textureIDs", textureIDs);
     282             : 
     283           0 :         return returnValue;
     284           0 :     }
     285             : 
     286             :     /**
     287             :      * Microseconds since the epoch.
     288             :      */
     289           9 :     double GetMicroseconds() const
     290             :     {
     291           9 :         return JS_Now();
     292             :     }
     293             : 
     294             :     /**
     295             :      * Return the template data of the given template name.
     296             :      */
     297           0 :     CParamNode GetTemplate(const std::string& templateName)
     298             :     {
     299           0 :         const CParamNode& templateRoot =
     300           0 :             m_TemplateLoader.GetTemplateFileData(templateName).GetOnlyChild();
     301           0 :         if (!templateRoot.IsOk())
     302           0 :             LOGERROR("Invalid template found for '{}'", templateName);
     303             : 
     304           0 :         return templateRoot;
     305             :     }
     306             : 
     307             :     /**
     308             :      * Check whether the given template exists.
     309             :      */
     310           0 :     bool TemplateExists(const std::string& templateName) const
     311             :     {
     312           0 :         return m_TemplateLoader.TemplateExists(templateName);
     313             :     }
     314             : 
     315             :     /**
     316             :      * Returns all template names of simulation entity templates.
     317             :      */
     318           0 :     std::vector<std::string> FindTemplates(const std::string& path, bool includeSubdirectories)
     319             :     {
     320           0 :         return m_TemplateLoader.FindTemplates(path, includeSubdirectories, SIMULATION_TEMPLATES);
     321             :     }
     322             : 
     323             :     /**
     324             :      * Returns all template names of actors.
     325             :      */
     326           0 :     std::vector<std::string> FindActorTemplates(const std::string& path, bool includeSubdirectories)
     327             :     {
     328           0 :         return m_TemplateLoader.FindTemplates(path, includeSubdirectories, ACTOR_TEMPLATES);
     329             :     }
     330             : 
     331             :     /**
     332             :      * Provides the script context.
     333             :      */
     334             :     Script::Interface& m_ScriptInterface;
     335             : 
     336             :     /**
     337             :      * Currently loaded script librarynames.
     338             :      */
     339             :     std::set<VfsPath> m_LoadedLibraries;
     340             : 
     341             :     /**
     342             :      * Backend to loading template data.
     343             :      */
     344             :     CTemplateLoader m_TemplateLoader;
     345             : };
     346             : 
     347           0 : bool MapGenerationInterruptCallback(JSContext* cx)
     348             : {
     349           0 :     return !Script::Interface::ObjectFromCBData<CMapGenerationCallbacks>(
     350           0 :         Script::Interface::CmptPrivate::GetScriptInterface(cx))->m_StopToken.IsStopRequested();
     351             : }
     352             : } // anonymous namespace
     353             : 
     354           8 : Script::StructuredClone RunMapGenerationScript(const StopToken stopToken, std::atomic<int>& progress,
     355             :     Script::Interface& scriptInterface, const VfsPath& script, const std::string& settings,
     356             :     const std::uint16_t flags)
     357             : {
     358           8 :     Script::Request rq(scriptInterface);
     359             : 
     360             :     // Parse settings
     361           8 :     JS::RootedValue settingsVal(rq.cx);
     362           8 :     if (!Script::ParseJSON(rq, settings, &settingsVal) && settingsVal.isUndefined())
     363             :     {
     364           0 :         LOGERROR("RunMapGenerationScript: Failed to parse settings");
     365           0 :         return nullptr;
     366             :     }
     367             : 
     368             :     // Prevent unintentional modifications to the settings object by random map scripts
     369           8 :     if (!Script::DeepFreezeObject(rq, settingsVal))
     370             :     {
     371           0 :         LOGERROR("RunMapGenerationScript: Failed to deepfreeze settings");
     372           8 :         return nullptr;
     373             :     }
     374             : 
     375             :     // Init RNG seed
     376           8 :     std::uint32_t seed = 0;
     377          16 :     if (!Script::HasProperty(rq, settingsVal, "Seed") ||
     378          16 :         !Script::GetProperty(rq, settingsVal, "Seed", seed))
     379           0 :         LOGWARNING("RunMapGenerationScript: No seed value specified - using 0");
     380             : 
     381           8 :     boost::rand48 mapGenRNG{seed};
     382           8 :     scriptInterface.ReplaceNondeterministicRNG(mapGenRNG);
     383             : 
     384           8 :     CMapGenerationCallbacks callbackData{stopToken, scriptInterface, flags};
     385             : 
     386             :     // Copy settings to global variable
     387           8 :     JS::RootedValue global(rq.cx, rq.globalValue());
     388           8 :     if (!Script::SetProperty(rq, global, "g_MapSettings", settingsVal, flags & JSPROP_READONLY,
     389             :         flags & JSPROP_ENUMERATE))
     390             :     {
     391           0 :         LOGERROR("RunMapGenerationScript: Failed to define g_MapSettings");
     392           8 :         return nullptr;
     393             :     }
     394             : 
     395             :     // Load RMS
     396          24 :     LOGMESSAGE("Loading RMS '{}'", script.string8());
     397           8 :     auto compileResult = scriptInterface.GetModuleLoader().LoadModule(rq, script);
     398           8 :     scriptInterface.GetContext().RunJobs();
     399           8 :     auto& future = *compileResult.begin();
     400           8 :     if (!future.IsDone())
     401           0 :         throw std::runtime_error{fmt::format("Loading module {:?} takes too long.", script.string8())};
     402             : 
     403           8 :     JS::RootedObject nsAsObject{rq.cx, future.Get()};
     404             : 
     405           8 :     {
     406           8 :         bool hasGenerator;
     407           8 :         if (!JS_HasProperty(rq.cx, nsAsObject, GENERATOR_NAME, &hasGenerator))
     408             :         {
     409           0 :             LOGERROR("RunMapGenerationScript: failed to search `{}` in the module-namespace.",
     410             :                 GENERATOR_NAME);
     411           0 :             return nullptr;
     412             :         }
     413             : 
     414           8 :         if (!hasGenerator)
     415             :         {
     416           0 :             throw std::runtime_error{fmt::format(
     417           0 :                 "The map generation script {:?} didn't export a {:?}.", script.string8(),
     418           0 :                 GENERATOR_NAME)};
     419             :         }
     420             :     }
     421             : 
     422           8 :     LOGMESSAGE("Run RMS generator");
     423           8 :     JS::RootedValue ns{rq.cx, JS::ObjectValue(*nsAsObject)};
     424           8 :     JS::RootedValue map{rq.cx, Script::Function::RunGenerator(rq, ns, GENERATOR_NAME, settingsVal,
     425           8 :         [&](const JS::HandleValue value)
     426             :         {
     427             :             // When the task is started, `progress` is only mutated by this thread.
     428           8 :             const int currentProgress{progress.load()};
     429           8 :             int tempProgress;
     430           8 :             if (!Script::FromJSVal(rq, value, tempProgress))
     431           1 :                 throw std::runtime_error{"Failed to convert the yielded value to an "
     432           2 :                     "integer."};
     433           7 :             if (tempProgress < currentProgress)
     434             :             {
     435           0 :                 LOGWARNING("The random map script tried to reduce the loading progress from "
     436             :                     "{} to {}.", currentProgress, tempProgress);
     437           0 :                 return;
     438             :             }
     439           7 :             progress.store(tempProgress);
     440           8 :         })};
     441             : 
     442           8 :     JS::RootedValue exportedMap{rq.cx};
     443           8 :     const bool exportSuccess{Script::Function::Call(rq, map, "MakeExportable", &exportedMap)};
     444          15 :     return Script::WriteStructuredClone(rq, exportSuccess ? exportedMap : map);
     445           8 : }

Generated by: LCOV version 1.16