1 /* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
2 
3 #ifndef UNITHANDLER_H
4 #define UNITHANDLER_H
5 
6 #include <vector>
7 
8 #include "UnitDef.h"
9 #include "UnitSet.h"
10 #include "Sim/Misc/SimObjectIDPool.h"
11 #include "System/creg/STL_Map.h"
12 #include "System/creg/STL_List.h"
13 
14 class CUnit;
15 class CBuilderCAI;
16 
17 class CUnitHandler
18 {
19 	CR_DECLARE_STRUCT(CUnitHandler)
20 
21 public:
22 	CUnitHandler();
23 	~CUnitHandler();
24 
25 	void Update();
26 	void DeleteUnit(CUnit* unit);
27 	void DeleteUnitNow(CUnit* unit);
28 	bool AddUnit(CUnit* unit);
29 	void PostLoad();
30 
CanAddUnit(int id)31 	bool CanAddUnit(int id) const {
32 		// do we want to be assigned a random ID and are any left in pool?
33 		if (id < 0)
34 			return (!idPool.IsEmpty());
35 		// is this ID not already in use?
36 		if (id < MaxUnits())
37 			return (units[id] == NULL);
38 		// AddUnit will not make new room for us
39 		return false;
40 	}
41 
MaxUnits()42 	unsigned int MaxUnits() const { return maxUnits; }
MaxUnitRadius()43 	float MaxUnitRadius() const { return maxUnitRadius; }
44 
45 	/// Returns true if a unit of type unitID can be built, false otherwise
46 	bool CanBuildUnit(const UnitDef* unitdef, int team) const;
47 
48 	void AddBuilderCAI(CBuilderCAI*);
49 	void RemoveBuilderCAI(CBuilderCAI*);
50 
51 	// note: negative ID's are implicitly converted
GetUnitUnsafe(unsigned int unitID)52 	CUnit* GetUnitUnsafe(unsigned int unitID) const { return units[unitID]; }
GetUnit(unsigned int unitID)53 	CUnit* GetUnit(unsigned int unitID) const { return (unitID < MaxUnits()? units[unitID]: NULL); }
54 
55 	std::vector<CUnit*> units;                        ///< used to get units from IDs (0 if not created)
56 	std::vector< std::vector<CUnitSet> > unitsByDefs; ///< units sorted by team and unitDef
57 	std::list<CUnit*> activeUnits;                    ///< used to get all active units
58 
59 	std::map<unsigned int, CBuilderCAI*> builderCAIs;
60 
61 private:
62 	void InsertActiveUnit(CUnit* unit);
63 
64 private:
65 	SimObjectIDPool idPool;
66 
67 	std::vector<CUnit*> unitsToBeRemoved;              ///< units that will be removed at start of next update
68 	std::list<CUnit*>::iterator activeSlowUpdateUnit;  ///< first unit of batch that will be SlowUpdate'd this frame
69 
70 	///< global unit-limit (derived from the per-team limit)
71 	///< units.size() is equal to this and constant at runtime
72 	unsigned int maxUnits;
73 
74 	///< largest radius of any unit added so far (some
75 	///< spatial query filters in GameHelper use this)
76 	float maxUnitRadius;
77 };
78 
79 extern CUnitHandler* unitHandler;
80 
81 #endif /* UNITHANDLER_H */
82