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 : #ifndef INCLUDED_COMPONENTMANAGER
19 : #define INCLUDED_COMPONENTMANAGER
20 :
21 : #include "lib/code_annotation.h"
22 : #include "lib/debug.h"
23 : #include "scriptinterface/Interface.h"
24 : #include "simulation2/system/Component.h"
25 : #include "simulation2/system/DynamicSubscription.h"
26 : #include "simulation2/system/Entity.h"
27 :
28 : #include <boost/random/linear_congruential.hpp>
29 : #include <iosfwd>
30 : #include <js/RootingAPI.h>
31 : #include <js/TypeDecls.h>
32 : #include <js/Value.h>
33 : #include <map>
34 : #include <memory>
35 : #include <set>
36 : #include <string>
37 : #include <unordered_map>
38 : #include <utility>
39 : #include <vector>
40 :
41 : class CMessage;
42 : class JSTracer;
43 : namespace Script { class Context; }
44 :
45 : class CComponentManager
46 : {
47 : NONCOPYABLE(CComponentManager);
48 : public:
49 : // We can't use EInterfaceId/etc directly, since scripts dynamically generate new IDs
50 : // and casting arbitrary ints to enums is undefined behaviour, so use 'int' typedefs
51 : typedef int InterfaceId;
52 : typedef int ComponentTypeId;
53 : typedef int MessageTypeId;
54 :
55 : private:
56 : using AllocFunc = IComponent::AllocFunc;
57 : using DeallocFunc = IComponent::DeallocFunc;
58 : using ClassInitFunc = IComponent::ClassInitFunc;
59 :
60 : // ComponentTypes come in three types:
61 : // Native: normal C++ component
62 : // ScriptWrapper: C++ component that wraps a JS component implementation
63 : // Script: a ScriptWrapper linked to a specific JS component implementation
64 : enum EComponentTypeType
65 : {
66 : CT_Native,
67 : CT_ScriptWrapper,
68 : CT_Script
69 : };
70 :
71 : // Representation of a component type, to be used when instantiating components
72 395 : struct ComponentType
73 : {
74 : EComponentTypeType type;
75 : InterfaceId iid;
76 : AllocFunc alloc;
77 : DeallocFunc dealloc;
78 : std::string name;
79 : std::string schema; // RelaxNG fragment
80 : std::unique_ptr<JS::PersistentRootedValue> ctor; // only valid if type == CT_Script
81 : ClassInitFunc classInit;
82 : };
83 :
84 : public:
85 : CComponentManager(CSimContext&, Script::Context& cx, bool skipScriptFunctions = false);
86 : ~CComponentManager();
87 :
88 : void LoadComponentTypes();
89 :
90 : /**
91 : * Load a script and execute it in a new function scope.
92 : * @param filename VFS path to load
93 : * @param hotload set to true if this script has been loaded before, and redefinitions of
94 : * existing components should not be considered errors
95 : */
96 : bool LoadScript(const VfsPath& filename, bool hotload = false);
97 :
98 : void RegisterMessageType(MessageTypeId mtid, const char* name);
99 :
100 : void RegisterComponentType(InterfaceId, ComponentTypeId, AllocFunc, DeallocFunc, const char*, const std::string& schema);
101 : void RegisterComponentTypeScriptWrapper(InterfaceId, ComponentTypeId, AllocFunc, DeallocFunc,
102 : const char*, const std::string& schema, ClassInitFunc classInit);
103 :
104 : void MarkScriptedComponentForSystemEntity(CComponentManager::ComponentTypeId cid);
105 :
106 : /**
107 : * Subscribe the current component type to the given message type.
108 : * Each component's HandleMessage will be called on any BroadcastMessage of this message type,
109 : * or on any PostMessage of this type targeted at the component's entity.
110 : * Must only be called by a component type's ClassInit.
111 : */
112 : void SubscribeToMessageType(MessageTypeId mtid);
113 :
114 : /**
115 : * Subscribe the current component type to all messages of the given message type.
116 : * Each component's HandleMessage will be called on any BroadcastMessage or PostMessage of this message type,
117 : * regardless of the entity.
118 : * Must only be called by a component type's ClassInit.
119 : */
120 : void SubscribeGloballyToMessageType(MessageTypeId mtid);
121 :
122 : /**
123 : * Check if the current component type is subscribed to messages of the given type.
124 : */
125 : bool IsLocallySubscribed(MessageTypeId mtid);
126 :
127 : /**
128 : * Check if the current component type is globally subscribed to messages of the given type.
129 : */
130 : bool IsGloballySubscribed(MessageTypeId mtid);
131 :
132 : /**
133 : * Subscribe the given component instance to all messages of the given message type.
134 : * The component's HandleMessage will be called on any BroadcastMessage or PostMessage of
135 : * this message type, regardless of the entity.
136 : *
137 : * This can be called at any time (including inside the HandleMessage callback for this message type).
138 : *
139 : * The component type must not have statically subscribed to this message type in its ClassInit.
140 : *
141 : * The subscription status is not saved or network-synchronised. Components must remember to
142 : * resubscribe in their Deserialize methods if they still want the message.
143 : *
144 : * This is primarily intended for Interpolate and RenderSubmit messages, to avoid the cost of
145 : * sending the message to components that do not currently need to do any rendering.
146 : */
147 : void DynamicSubscriptionNonsync(MessageTypeId mtid, IComponent* component, bool enabled);
148 :
149 : /**
150 : * @param cname Requested component type name (not including any "CID" or "CCmp" prefix)
151 : * @return The component type id, or CID__Invalid if not found
152 : */
153 : ComponentTypeId LookupCID(const std::string& cname) const;
154 :
155 : /**
156 : * @return The name of the given component type, or "" if not found
157 : */
158 : std::string LookupComponentTypeName(ComponentTypeId cid) const;
159 :
160 : /**
161 : * Set up an empty SYSTEM_ENTITY. Must be called after ResetState() and before GetSystemEntity().
162 : */
163 : void InitSystemEntity();
164 :
165 : /**
166 : * Returns a CEntityHandle with id SYSTEM_ENTITY.
167 : */
168 32 : CEntityHandle GetSystemEntity() { ASSERT(m_SystemEntity.GetId() == SYSTEM_ENTITY); return m_SystemEntity; }
169 :
170 : /**
171 : * Returns a CEntityHandle with id @p ent.
172 : * If @p allowCreate is true and there is no existing CEntityHandle, a new handle will be allocated.
173 : */
174 : CEntityHandle LookupEntityHandle(entity_id_t ent, bool allowCreate = false);
175 :
176 : /**
177 : * Returns true if the entity with id @p ent exists.
178 : */
179 : bool EntityExists(entity_id_t ent) const;
180 :
181 : /**
182 : * Returns a new entity ID that has never been used before.
183 : * This affects the simulation state so it must only be called in network-synchronised ways.
184 : */
185 : entity_id_t AllocateNewEntity();
186 :
187 : /**
188 : * Returns a new local entity ID that has never been used before.
189 : * This entity will not be synchronised over the network, stored in saved games, etc.
190 : */
191 : entity_id_t AllocateNewLocalEntity();
192 :
193 : /**
194 : * Returns a new entity ID that has never been used before.
195 : * If possible, returns preferredId, and ensures this ID won't be allocated again.
196 : * This affects the simulation state so it must only be called in network-synchronised ways.
197 : */
198 : entity_id_t AllocateNewEntity(entity_id_t preferredId);
199 :
200 : /**
201 : * Constructs a component of type 'cid', initialised with data 'paramNode',
202 : * and attaches it to entity 'ent'.
203 : *
204 : * @return true on success; false on failure, and logs an error message
205 : */
206 : bool AddComponent(CEntityHandle ent, ComponentTypeId cid, const CParamNode& paramNode);
207 :
208 : /**
209 : * Add all system components to the system entity (skip the scripted components or the AI components on demand)
210 : */
211 : void AddSystemComponents(bool skipScriptedComponents, bool skipAI);
212 :
213 : /**
214 : * Adds an externally-created component, so that it is returned by QueryInterface
215 : * but does not get destroyed and does not receive messages from the component manager.
216 : * (This is intended for unit tests that need to add mock objects the tested components
217 : * expect to exist.)
218 : */
219 : void AddMockComponent(CEntityHandle ent, InterfaceId iid, IComponent& component);
220 :
221 : /**
222 : * Allocates a component object of type 'cid', and attaches it to entity 'ent'.
223 : * (The component's Init is not called here - either Init or Deserialize must be called
224 : * before using the returned object.)
225 : */
226 : IComponent* ConstructComponent(CEntityHandle ent, ComponentTypeId cid);
227 :
228 : /**
229 : * Constructs an entity based on the given template, and adds it the world with
230 : * entity ID @p ent. There should not be any existing components with that entity ID.
231 : * @return ent, or INVALID_ENTITY on error
232 : */
233 : entity_id_t AddEntity(const std::wstring& templateName, entity_id_t ent);
234 :
235 : /**
236 : * Destroys all the components belonging to the specified entity when FlushDestroyedComponents is called.
237 : * Has no effect if the entity does not exist, or has already been added to the destruction queue.
238 : */
239 : void DestroyComponentsSoon(entity_id_t ent);
240 :
241 : /**
242 : * Does the actual destruction of components from DestroyComponentsSoon.
243 : * This must not be called if the component manager is on the call stack (since it
244 : * will break internal iterators).
245 : */
246 : void FlushDestroyedComponents();
247 :
248 : /**
249 : * Called during GC tracing of our components.
250 : */
251 : static void Trace(JSTracer* trc, void* data);
252 : /**
253 : * Call this from components when they need to save their JS instance.
254 : * Not done by the component manager because C++ components do it lazily.
255 : */
256 : void RegisterTrace(entity_id_t ent, const JS::Heap<JS::Value>& instance);
257 :
258 : IComponent* QueryInterface(entity_id_t ent, InterfaceId iid) const;
259 :
260 : using InterfacePair = std::pair<entity_id_t, IComponent*>;
261 : using InterfaceList = std::vector<InterfacePair>;
262 : using InterfaceListUnordered = std::unordered_map<entity_id_t, IComponent*>;
263 :
264 : InterfaceList GetEntitiesWithInterface(InterfaceId iid) const;
265 : const InterfaceListUnordered& GetEntitiesWithInterfaceUnordered(InterfaceId iid) const;
266 :
267 : /**
268 : * Send a message, targeted at a particular entity. The message will be received by any
269 : * components of that entity which subscribed to the message type, and by any other components
270 : * that subscribed globally to the message type.
271 : */
272 : void PostMessage(entity_id_t ent, const CMessage& msg);
273 :
274 : /**
275 : * Send a message, not targeted at any particular entity. The message will be received by any
276 : * components that subscribed (either globally or not) to the message type.
277 : */
278 : void BroadcastMessage(const CMessage& msg);
279 :
280 : /**
281 : * Resets the dynamic simulation state (deletes all entities, resets entity ID counters;
282 : * doesn't unload/reload component scripts).
283 : */
284 : void ResetState();
285 :
286 : /**
287 : * Initializes the random number generator with a seed determined by the host.
288 : */
289 : void SetRNGSeed(std::uint32_t seed);
290 :
291 : // Various state serialization functions:
292 : bool ComputeStateHash(std::string& outHash, bool quick) const;
293 : bool DumpDebugState(std::ostream& stream, bool includeDebugInfo) const;
294 : // FlushDestroyedComponents must be called before SerializeState (since the destruction queue
295 : // won't get serialized)
296 : bool SerializeState(std::ostream& stream) const;
297 : bool DeserializeState(std::istream& stream);
298 :
299 : std::string GenerateSchema() const;
300 :
301 3714 : Script::Interface& GetScriptInterface() { return m_ScriptInterface; }
302 :
303 : private:
304 : // Implementations of functions exposed to scripts
305 : void Script_RegisterComponentType_Common(int iid, const std::string& cname, JS::HandleValue ctor, bool reRegister, bool systemComponent);
306 : void Script_RegisterComponentType(int iid, const std::string& cname, JS::HandleValue ctor);
307 : void Script_RegisterSystemComponentType(int iid, const std::string& cname, JS::HandleValue ctor);
308 : void Script_ReRegisterComponentType(int iid, const std::string& cname, JS::HandleValue ctor);
309 : void Script_RegisterInterface(const std::string& name);
310 : void Script_RegisterMessageType(const std::string& name);
311 : void Script_RegisterGlobal(const std::string& name, JS::HandleValue value);
312 : std::vector<int> Script_GetEntitiesWithInterface(int iid);
313 : std::vector<IComponent*> Script_GetComponentsWithInterface(int iid);
314 : void Script_PostMessage(int ent, int mtid, JS::HandleValue data);
315 : void Script_BroadcastMessage(int mtid, JS::HandleValue data);
316 : int Script_AddEntity(const std::wstring& templateName);
317 : int Script_AddLocalEntity(const std::wstring& templateName);
318 : const CParamNode& Script_GetTemplate(const std::string& templateName);
319 :
320 : CMessage* ConstructMessage(int mtid, JS::HandleValue data);
321 : void SendGlobalMessage(entity_id_t ent, const CMessage& msg);
322 :
323 : void FlattenDynamicSubscriptions();
324 : void RemoveComponentDynamicSubscriptions(IComponent* component);
325 :
326 : ComponentTypeId GetScriptWrapper(InterfaceId iid);
327 :
328 : CEntityHandle AllocateEntityHandle(entity_id_t ent);
329 :
330 : Script::Interface m_ScriptInterface;
331 : CSimContext& m_SimContext;
332 :
333 : CEntityHandle m_SystemEntity;
334 :
335 : ComponentTypeId m_CurrentComponent; // used when loading component types
336 : bool m_CurrentlyHotloading;
337 :
338 : // TODO: some of these should be vectors
339 : std::map<ComponentTypeId, ComponentType> m_ComponentTypesById;
340 : std::vector<CComponentManager::ComponentTypeId> m_ScriptedSystemComponents;
341 : std::vector<std::unordered_map<entity_id_t, IComponent*> > m_ComponentsByInterface; // indexed by InterfaceId
342 : std::map<ComponentTypeId, std::map<entity_id_t, IComponent*> > m_ComponentsByTypeId;
343 : std::map<MessageTypeId, std::vector<ComponentTypeId> > m_LocalMessageSubscriptions;
344 : std::map<MessageTypeId, std::vector<ComponentTypeId> > m_GlobalMessageSubscriptions;
345 : std::map<std::string, ComponentTypeId> m_ComponentTypeIdsByName;
346 : std::map<std::string, MessageTypeId> m_MessageTypeIdsByName;
347 : std::map<MessageTypeId, std::string> m_MessageTypeNamesById;
348 : std::map<std::string, InterfaceId> m_InterfaceIdsByName;
349 :
350 : std::map<MessageTypeId, CDynamicSubscription> m_DynamicMessageSubscriptionsNonsync;
351 : std::map<IComponent*, std::set<MessageTypeId> > m_DynamicMessageSubscriptionsNonsyncByComponent;
352 :
353 : std::unordered_map<entity_id_t, SEntityComponentCache*> m_ComponentCaches;
354 : std::unordered_map<entity_id_t, std::vector<JS::Heap<JS::Value>*>> m_TraceCache;
355 :
356 : // TODO: maintaining both ComponentsBy* is nasty; can we get rid of one,
357 : // while keeping QueryInterface and PostMessage sufficiently efficient?
358 :
359 : std::vector<entity_id_t> m_DestructionQueue;
360 :
361 : ComponentTypeId m_NextScriptComponentTypeId;
362 : entity_id_t m_NextEntityId;
363 : entity_id_t m_NextLocalEntityId;
364 :
365 : boost::rand48 m_RNG;
366 :
367 : friend class TestComponentManager;
368 : };
369 :
370 : #endif // INCLUDED_COMPONENTMANAGER
|