Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
Simulation2.h
Go to the documentation of this file.
1/* Copyright (C) 2026 Wildfire Games.
2 * This file is part of 0 A.D.
3 *
4 * 0 A.D. is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * 0 A.D. is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#ifndef INCLUDED_SIMULATION2
19#define INCLUDED_SIMULATION2
20
21#include "lib/code_annotation.h"
23#include "lib/status.h"
24#include "ps/Loader.h"
28
29#include <array>
30#include <js/TypeDecls.h>
31#include <memory>
32#include <ostream>
33#include <span>
34#include <string>
35#include <unordered_map>
36#include <utility>
37#include <vector>
38
39class CFrustum;
40class CMessage;
41class CSimContext;
43class CTerrain;
44class CUnitManager;
45class IComponent;
46class SceneCollector;
47namespace Script { class Context; }
48namespace JS { class Value; }
49namespace Script { class Interface; }
51
52/**
53 * Public API for simulation system.
54 * Most code should interact with the simulation only through this API.
55 */
57{
59
60public:
61 struct LoadScriptError : std::runtime_error
62 {
63 using std::runtime_error::runtime_error;
64 };
65
66 constexpr static auto DEFAULT_SCRIPTS{std::to_array({L"simulation/components/interfaces/",
67 L"simulation/helpers/", L"simulation/components/"})};
68
69 // TODO: CUnitManager should probably be handled automatically by this
70 // module, but for now we'll have it passed in externally instead
71 /**
72 * @param scriptDirectories All scripts in the specified directory
73 * (non-recursively) are loaded, so that they can register new
74 * component types and functions.
75 */
76 CSimulation2(CUnitManager* unitManager, Script::Context& cx, CTerrain* terrain,
77 const std::span<const wchar_t* const> scriptDirectories,
78 const SimulationDebugOptions debugOptions = {});
80
81 /**
82 * Loads the player settings script (called before map is loaded)
83 * @param newPlayers will delete all the existing player entities (if any) and create new ones
84 * (needed for loading maps, but Atlas might want to update existing player data)
85 */
86 void LoadPlayerSettings(bool newPlayers);
87
88 /**
89 * Loads the map settings script (called after map is loaded)
90 */
91 void LoadMapSettings();
92
93 /**
94 * Set a startup script, which will get executed before the first turn.
95 */
96 void SetStartupScript(const std::string& script);
97
98 /**
99 * Get the current startup script.
100 */
101 const std::string& GetStartupScript();
102
103 /**
104 * Set the attributes identifying the scenario/RMS used to initialise this
105 * simulation.
106 */
107 void SetInitAttributes(JS::HandleValue settings);
108
109 /**
110 * Get the data passed to SetInitAttributes.
111 */
112 JS::Value GetInitAttributes();
113 void GetInitAttributes(JS::MutableHandleValue ret);
114
115 /**
116 * Set the initial map settings (as a UTF-8-encoded JSON string),
117 * which will be used to set up the simulation state.
118 * Called from atlas.
119 */
120 void SetMapSettings(const std::string& settings);
121
122 /**
123 * Set the initial map settings, which will be used
124 * to set up the simulation state.
125 * Called from MapReader (for all map-types).
126 */
127 void SetMapSettings(JS::HandleValue settings);
128
129 /**
130 * Get the current map settings as a UTF-8 JSON string.
131 */
132 std::string GetMapSettingsString();
133
134 /**
135 * Get the current map settings.
136 */
137 void GetMapSettings(JS::MutableHandleValue ret);
138
139 /**
140 * RegMemFun incremental loader function.
141 */
143
144 /**
145 * Reload any scripts that were loaded from the given filename.
146 * (This is used to implement hotloading.)
147 */
148 Status ReloadChangedFile(const VfsPath& path);
149
150 /**
151 * Initialise (or re-initialise) the complete simulation state.
152 * Must be called after LoadScripts, and must be called
153 * before any methods that depend on the simulation state.
154 * @param skipScriptedComponents don't load the scripted system components
155 * (this is intended for use by test cases that don't mount all of VFS)
156 * @param skipAI don't initialise the AI system
157 * (this is intended for use by test cases that don't want all entity
158 * templates loaded automatically)
159 */
160 void ResetState(bool skipScriptedComponents = false, bool skipAI = false);
161
162 /**
163 * Replace/destroy some entities (e.g. skirmish replacers)
164 * Called right before InitGame, on CGame instantiation.
165 * (This mustn't be used when e.g. loading saved games, only when starting new ones.)
166 * This calls the PreInitGame function defined in helpers/InitGame.js.
167 */
168 void PreInitGame();
169
170 /**
171 * Initialise a new game, based on some script data. (Called on CGame instantiation)
172 * (This mustn't be used when e.g. loading saved games, only when starting new ones.)
173 * This calls the InitGame function defined in helpers/InitGame.js.
174 */
175 void InitGame();
176
177 void Update(int turnLength);
178 void Update(int turnLength, const std::vector<SimulationCommand>& commands);
179 void Interpolate(float simFrameLength, float frameOffset, float realFrameLength);
180 void RenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling);
181
182 /**
183 * Returns the last frame offset passed to Interpolate(), i.e. the offset corresponding
184 * to the currently-rendered scene.
185 */
186 float GetLastFrameOffset() const;
187
188 /**
189 * Construct a new entity and add it to the world.
190 * @param templateName see ICmpTemplateManager for syntax
191 * @return the new entity ID, or INVALID_ENTITY on error
192 */
193 entity_id_t AddEntity(const std::wstring& templateName);
194 entity_id_t AddEntity(const std::wstring& templateName, entity_id_t preferredId);
195 entity_id_t AddLocalEntity(const std::wstring& templateName);
196
197 /**
198 * Destroys the specified entity, once FlushDestroyedEntities is called.
199 * Has no effect if the entity does not exist, or has already been added to the destruction queue.
200 */
201 void DestroyEntity(entity_id_t ent);
202
203 /**
204 * Does the actual destruction of entities from DestroyEntity.
205 * This is called automatically by Update, but should also be called at other
206 * times when an entity might have been deleted and should be removed from
207 * any further processing (e.g. after editor UI message processing)
208 */
210
211 IComponent* QueryInterface(entity_id_t ent, int iid) const;
212 void PostMessage(entity_id_t ent, const CMessage& msg) const;
213 void BroadcastMessage(const CMessage& msg) const;
214
216 std::vector<std::pair<entity_id_t, IComponent*> >;
217
219 std::unordered_map<entity_id_t, IComponent*>;
220
221 /**
222 * Returns a list of components implementing the given interface, and their
223 * associated entities, sorted by entity ID.
224 */
226
227 /**
228 * Returns a list of components implementing the given interface, and their
229 * associated entities, as an unordered map.
230 */
232
233 const CSimContext& GetSimContext() const;
235
236 bool ComputeStateHash(std::string& outHash, bool quick);
237 bool DumpDebugState(std::ostream& stream);
238 bool SerializeState(std::ostream& stream);
239 bool DeserializeState(std::istream& stream);
240
241 /**
242 * Activate the rejoin-test feature for turn @param turn.
243 */
244 void ActivateRejoinTest(turn_id_t turn);
245
246 std::string GenerateSchema();
247
248 /////////////////////////////////////////////////////////////////////////////
249 // Some functions for Atlas UI to be able to access VFS data
250
251 /**
252 * Get random map script data
253 *
254 * @return vector of strings containing JSON format data
255 */
256 std::vector<std::string> GetRMSData();
257
258 /**
259 * Get victory condition data
260 *
261 * @return vector of strings containing JSON format data
262 */
263 std::vector<std::string> GetVictoryConditiondData();
264
265 /**
266 * Get player default data
267 *
268 * @return string containing JSON format data
269 */
270 std::string GetPlayerDefaults();
271
272 /**
273 * Get map sizes data
274 *
275 * @return string containing JSON format data
276 */
277 std::string GetMapSizes();
278
279 /**
280 * Get AI data
281 *
282 * @return string containing JSON format data
283 */
284 std::string GetAIData();
285
286private:
287 const std::unique_ptr<CSimulation2Impl> m;
288};
289
290#endif // INCLUDED_SIMULATION2
std::int32_t turn_id_t
At 1000 turns/second, a 32-bit counter would overflow in ~49 days.
Definition: SimulationCommand.h:31
Definition: Frustum.h:40
Definition: Message.h:31
Contains pointers to various 'global' objects that are needed by the simulation code,...
Definition: SimContext.h:34
Definition: Simulation2.cpp:76
Public API for simulation system.
Definition: Simulation2.h:57
static constexpr auto DEFAULT_SCRIPTS
Definition: Simulation2.h:66
void PreInitGame()
Replace/destroy some entities (e.g.
Definition: Simulation2.cpp:739
CSimulation2(CUnitManager *unitManager, Script::Context &cx, CTerrain *terrain, const std::span< const wchar_t *const > scriptDirectories, const SimulationDebugOptions debugOptions={})
Definition: Simulation2.cpp:669
const CSimContext & GetSimContext() const
Definition: Simulation2.cpp:729
void FlushDestroyedEntities()
Does the actual destruction of entities from DestroyEntity.
Definition: Simulation2.cpp:699
entity_id_t AddLocalEntity(const std::wstring &templateName)
Definition: Simulation2.cpp:689
float GetLastFrameOffset() const
Returns the last frame offset passed to Interpolate(), i.e.
Definition: Simulation2.cpp:782
void SetInitAttributes(JS::HandleValue settings)
Set the attributes identifying the scenario/RMS used to initialise this simulation.
Definition: Simulation2.cpp:797
std::unordered_map< entity_id_t, IComponent * > InterfaceListUnordered
Definition: Simulation2.h:219
entity_id_t AddEntity(const std::wstring &templateName)
Construct a new entity and add it to the world.
Definition: Simulation2.cpp:679
const std::string & GetStartupScript()
Get the current startup script.
Definition: Simulation2.cpp:792
std::vector< std::string > GetVictoryConditiondData()
Get victory condition data.
Definition: Simulation2.cpp:948
void RenderSubmit(SceneCollector &collector, const CFrustum &frustum, bool culling)
Definition: Simulation2.cpp:774
JS::Value GetInitAttributes()
Get the data passed to SetInitAttributes.
Definition: Simulation2.cpp:802
std::string GetAIData()
Get AI data.
Definition: Simulation2.cpp:983
void InitGame()
Initialise a new game, based on some script data.
Definition: Simulation2.cpp:746
const std::unique_ptr< CSimulation2Impl > m
Definition: Simulation2.h:287
void LoadPlayerSettings(bool newPlayers)
Loads the player settings script (called before map is loaded)
Definition: Simulation2.cpp:835
bool SerializeState(std::ostream &stream)
Definition: Simulation2.cpp:887
std::vector< std::pair< entity_id_t, IComponent * > > InterfaceList
Definition: Simulation2.h:216
InterfaceList GetEntitiesWithInterface(int iid)
Returns a list of components implementing the given interface, and their associated entities,...
Definition: Simulation2.cpp:719
void BroadcastMessage(const CMessage &msg) const
Definition: Simulation2.cpp:714
std::string GenerateSchema()
Definition: Simulation2.cpp:906
void GetMapSettings(JS::MutableHandleValue ret)
Get the current map settings.
Definition: Simulation2.cpp:830
void SetMapSettings(const std::string &settings)
Set the initial map settings (as a UTF-8-encoded JSON string), which will be used to set up the simul...
Definition: Simulation2.cpp:812
Status ReloadChangedFile(const VfsPath &path)
Reload any scripts that were loaded from the given filename.
Definition: Simulation2.cpp:866
void Interpolate(float simFrameLength, float frameOffset, float realFrameLength)
Definition: Simulation2.cpp:769
void PostMessage(entity_id_t ent, const CMessage &msg) const
Definition: Simulation2.cpp:709
void ResetState(bool skipScriptedComponents=false, bool skipAI=false)
Initialise (or re-initialise) the complete simulation state.
Definition: Simulation2.cpp:871
IComponent * QueryInterface(entity_id_t ent, int iid) const
Definition: Simulation2.cpp:704
bool DeserializeState(std::istream &stream)
Definition: Simulation2.cpp:892
std::string GetMapSettingsString()
Get the current map settings as a UTF-8 JSON string.
Definition: Simulation2.cpp:825
std::vector< std::string > GetRMSData()
Get random map script data.
Definition: Simulation2.cpp:943
void ActivateRejoinTest(turn_id_t turn)
Activate the rejoin-test feature for turn.
Definition: Simulation2.cpp:898
void DestroyEntity(entity_id_t ent)
Destroys the specified entity, once FlushDestroyedEntities is called.
Definition: Simulation2.cpp:694
bool ComputeStateHash(std::string &outHash, bool quick)
Definition: Simulation2.cpp:876
NONCOPYABLE(CSimulation2)
bool DumpDebugState(std::ostream &stream)
Definition: Simulation2.cpp:881
PS::Loader::Task ProgressiveLoad()
RegMemFun incremental loader function.
Definition: Simulation2.cpp:861
void SetStartupScript(const std::string &script)
Set a startup script, which will get executed before the first turn.
Definition: Simulation2.cpp:787
void Update(int turnLength)
Definition: Simulation2.cpp:758
Script::Interface & GetScriptInterface() const
Definition: Simulation2.cpp:734
void LoadMapSettings()
Loads the map settings script (called after map is loaded)
Definition: Simulation2.cpp:842
std::string GetMapSizes()
Get map sizes data.
Definition: Simulation2.cpp:978
std::string GetPlayerDefaults()
Get player default data.
Definition: Simulation2.cpp:973
const InterfaceListUnordered & GetEntitiesWithInterfaceUnordered(int iid)
Returns a list of components implementing the given interface, and their associated entities,...
Definition: Simulation2.cpp:724
Definition: Terrain.h:52
Definition: UnitManager.h:39
Definition: IComponent.h:33
Coroutine which performs the actual work.
Definition: Loader.h:126
Definition: path.h:84
This interface accepts renderable objects.
Definition: Scene.h:90
Definition: Context.h:51
Definition: Interface.h:93
Definition: CGUI.h:63
Abstraction around a SpiderMonkey JSContext.
Definition: DapInterface.h:32
std::uint32_t entity_id_t
Entity ID type.
Definition: Entity.h:29
std::int64_t Status
Error handling system.
Definition: status.h:174
Definition: Simulation2.h:62
Simulation command, typically received over the network in multiplayer games.
Definition: SimulationCommand.h:39
Definition: DebugOptions.h:24