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 "ICmpTerritoryManager.h"
21 :
22 : #include "graphics/Color.h"
23 : #include "graphics/Overlay.h"
24 : #include "graphics/SColor.h"
25 : #include "graphics/TerritoryBoundary.h"
26 : #include "graphics/Texture.h"
27 : #include "graphics/TextureManager.h"
28 : #include "lib/code_annotation.h"
29 : #include "lib/code_generation.h"
30 : #include "lib/debug.h"
31 : #include "lib/path.h"
32 : #include "maths/Fixed.h"
33 : #include "maths/FixedVector2D.h"
34 : #include "maths/MathUtil.h"
35 : #include "maths/Vector2D.h"
36 : #include "ps/Filesystem.h"
37 : #include "ps/Profile.h"
38 : #include "ps/XML/Xeromyces.h"
39 : #include "renderer/Renderer.h"
40 : #include "renderer/Scene.h"
41 : #include "renderer/TerrainOverlay.h"
42 : #include "renderer/backend/Sampler.h"
43 : #include "simulation2/MessageTypes.h"
44 : #include "simulation2/components/ICmpFootprint.h"
45 : #include "simulation2/components/ICmpObstructionManager.h"
46 : #include "simulation2/components/ICmpOwnership.h"
47 : #include "simulation2/components/ICmpPathfinder.h"
48 : #include "simulation2/components/ICmpPlayer.h"
49 : #include "simulation2/components/ICmpPlayerManager.h"
50 : #include "simulation2/components/ICmpPosition.h"
51 : #include "simulation2/components/ICmpTerritoryDecayManager.h"
52 : #include "simulation2/components/ICmpTerritoryInfluence.h"
53 : #include "simulation2/helpers/Grid.h"
54 : #include "simulation2/helpers/Pathfinding.h"
55 : #include "simulation2/helpers/Player.h"
56 : #include "simulation2/helpers/Position.h"
57 : #include "simulation2/helpers/Render.h"
58 : #include "simulation2/system/Component.h"
59 : #include "simulation2/system/Entity.h"
60 : #include "simulation2/system/Message.h"
61 :
62 : #include <array>
63 : #include <cmath>
64 : #include <cstddef>
65 : #include <limits>
66 : #include <map>
67 : #include <numbers>
68 : #include <queue>
69 : #include <string>
70 : #include <type_traits>
71 : #include <utility>
72 : #include <vector>
73 :
74 : class CCmpTerritoryManager;
75 : class CFrustum;
76 :
77 : namespace
78 : {
79 : constexpr bool DISABLE_TERRITORY_OVERLAY{true};
80 :
81 : void BuildTextureRGBA(Grid<std::uint8_t>*& territories, std::uint8_t* data, const int w, const int h)
82 : {
83 : TerrainTextureOverlay::OverwriteEachTile(data, w, h, [&](const int i, const int j)
84 : {
85 : const std::uint8_t id{static_cast<std::uint8_t>(territories->get(j, i) &
86 : ICmpTerritoryManager::TERRITORY_PLAYER_MASK)};
87 : return TerrainTextureOverlay::GetColor(id, 64);
88 : });
89 : }
90 : }
91 :
92 8 : class CCmpTerritoryManager : public ICmpTerritoryManager
93 : {
94 : public:
95 137 : static void ClassInit(CComponentManager& componentManager)
96 : {
97 137 : componentManager.SubscribeGloballyToMessageType(MT_OwnershipChanged);
98 137 : componentManager.SubscribeGloballyToMessageType(MT_PlayerColorChanged);
99 137 : componentManager.SubscribeGloballyToMessageType(MT_PositionChanged);
100 137 : componentManager.SubscribeGloballyToMessageType(MT_ValueModification);
101 137 : componentManager.SubscribeToMessageType(MT_ObstructionMapShapeChanged);
102 137 : componentManager.SubscribeToMessageType(MT_TerrainChanged);
103 137 : componentManager.SubscribeToMessageType(MT_WaterChanged);
104 137 : componentManager.SubscribeToMessageType(MT_Update);
105 137 : componentManager.SubscribeToMessageType(MT_Interpolate);
106 137 : componentManager.SubscribeToMessageType(MT_RenderSubmit);
107 137 : }
108 :
109 16 : DEFAULT_COMPONENT_ALLOCATOR(TerritoryManager)
110 :
111 137 : static std::string GetSchema()
112 : {
113 274 : return "<a:component type='system'/><empty/>";
114 : }
115 :
116 : std::uint8_t m_ImpassableCost;
117 : float m_BorderThickness;
118 : float m_BorderSeparation;
119 :
120 : // Player ID in bits 0-4 (TERRITORY_PLAYER_MASK)
121 : // connected flag in bit 5 (TERRITORY_CONNECTED_MASK)
122 : // blinking flag in bit 6 (TERRITORY_BLINKING_MASK)
123 : // processed flag in bit 7 (TERRITORY_PROCESSED_MASK)
124 : Grid<std::uint8_t>* m_Territories;
125 :
126 : std::vector<std::uint16_t> m_TerritoryCellCounts;
127 : std::uint16_t m_TerritoryTotalPassableCellCount;
128 :
129 : // Saves the cost per tile (to stop territory on impassable tiles)
130 : Grid<std::uint8_t>* m_CostGrid;
131 :
132 : // Set to true when territories change; will send a TerritoriesChanged message
133 : // during the Update phase
134 : bool m_TriggerEvent;
135 :
136 0 : struct SBoundaryLine
137 : {
138 : bool blinking;
139 : player_id_t owner;
140 : CColor color;
141 : SOverlayTexturedLine overlay;
142 : };
143 :
144 : std::vector<SBoundaryLine> m_BoundaryLines;
145 : bool m_BoundaryLinesDirty;
146 :
147 : double m_AnimTime; // time since start of rendering, in seconds
148 :
149 : TerrainTextureOverlay* m_DebugOverlay;
150 :
151 : bool m_EnableLineDebugOverlays; ///< Enable node debugging overlays for boundary lines?
152 : std::vector<SOverlayLine> m_DebugBoundaryLineNodes;
153 :
154 8 : void Init(const CParamNode&) override
155 : {
156 8 : m_Territories = NULL;
157 8 : m_CostGrid = NULL;
158 8 : m_DebugOverlay = DISABLE_TERRITORY_OVERLAY? nullptr :
159 : new TerrainTextureOverlay{static_cast<float>(Pathfinding::NAVCELLS_PER_TERRAIN_TILE) /
160 : ICmpTerritoryManager::NAVCELLS_PER_TERRITORY_TILE,
161 : std::bind_front(BuildTextureRGBA, std::ref(m_Territories))};
162 8 : m_BoundaryLinesDirty = true;
163 8 : m_TriggerEvent = true;
164 8 : m_EnableLineDebugOverlays = false;
165 8 : m_DirtyID = 1;
166 8 : m_DirtyBlinkingID = 1;
167 8 : m_ColorChanged = false;
168 :
169 8 : m_AnimTime = 0.0;
170 :
171 8 : m_TerritoryTotalPassableCellCount = 0;
172 :
173 : // Register Relax NG validator
174 8 : g_Xeromyces.AddValidator(g_VFS, "territorymanager", "simulation/data/territorymanager.rng");
175 :
176 8 : CParamNode externalParamNode;
177 16 : CParamNode::LoadXML(externalParamNode, L"simulation/data/territorymanager.xml", "territorymanager");
178 :
179 8 : int impassableCost = externalParamNode.GetChild("TerritoryManager").GetChild("ImpassableCost").ToInt();
180 8 : ENSURE(0 <= impassableCost && impassableCost <= 255);
181 8 : m_ImpassableCost = static_cast<std::uint8_t>(impassableCost);
182 :
183 8 : const std::string& visibilityStatus = externalParamNode.GetChild("TerritoryManager").GetChild("VisibilityStatus").ToString();
184 8 : m_Enabled = visibilityStatus != "off";
185 8 : m_Visible = m_Enabled && visibilityStatus == "visible";
186 :
187 8 : m_BorderThickness = externalParamNode.GetChild("TerritoryManager").GetChild("BorderThickness").ToFixed().ToFloat();
188 8 : m_BorderSeparation = externalParamNode.GetChild("TerritoryManager").GetChild("BorderSeparation").ToFixed().ToFloat();
189 8 : }
190 :
191 8 : void Deinit() override
192 : {
193 12 : SAFE_DELETE(m_Territories);
194 12 : SAFE_DELETE(m_CostGrid);
195 8 : SAFE_DELETE(m_DebugOverlay);
196 8 : }
197 :
198 18 : void Serialize(ISerializer& serialize) override
199 : {
200 : // Territory state can be recomputed as required, so we don't need to serialize any of it.
201 18 : serialize.Bool("trigger event", m_TriggerEvent);
202 18 : }
203 :
204 0 : void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override
205 : {
206 0 : Init(paramNode);
207 0 : deserialize.Bool("trigger event", m_TriggerEvent);
208 0 : }
209 :
210 8791 : void HandleMessage(const CMessage& msg, bool /*global*/) override
211 : {
212 8791 : switch (msg.GetType())
213 : {
214 225 : case MT_OwnershipChanged:
215 225 : {
216 225 : const CMessageOwnershipChanged& msgData = static_cast<const CMessageOwnershipChanged&> (msg);
217 225 : MakeDirtyIfRelevantEntity(msgData.entity);
218 225 : break;
219 : }
220 0 : case MT_PlayerColorChanged:
221 0 : {
222 0 : MakeDirty();
223 0 : break;
224 : }
225 7941 : case MT_PositionChanged:
226 7941 : {
227 7941 : const CMessagePositionChanged& msgData = static_cast<const CMessagePositionChanged&> (msg);
228 7941 : MakeDirtyIfRelevantEntity(msgData.entity);
229 7941 : break;
230 : }
231 432 : case MT_ValueModification:
232 432 : {
233 432 : const CMessageValueModification& msgData = static_cast<const CMessageValueModification&> (msg);
234 432 : if (msgData.component == L"TerritoryInfluence")
235 0 : MakeDirty();
236 : break;
237 : }
238 10 : case MT_ObstructionMapShapeChanged:
239 10 : case MT_TerrainChanged:
240 10 : case MT_WaterChanged:
241 10 : {
242 : // also recalculate the cost grid to support atlas changes
243 11 : SAFE_DELETE(m_CostGrid);
244 10 : MakeDirty();
245 10 : break;
246 : }
247 180 : case MT_Update:
248 180 : {
249 180 : if (m_TriggerEvent)
250 : {
251 3 : m_TriggerEvent = false;
252 6 : GetSimContext().GetComponentManager().BroadcastMessage(CMessageTerritoriesChanged());
253 : }
254 : break;
255 : }
256 3 : case MT_Interpolate:
257 3 : {
258 3 : const CMessageInterpolate& msgData = static_cast<const CMessageInterpolate&> (msg);
259 3 : Interpolate(msgData.deltaSimTime, msgData.offset);
260 3 : break;
261 : }
262 0 : case MT_RenderSubmit:
263 0 : {
264 0 : const CMessageRenderSubmit& msgData = static_cast<const CMessageRenderSubmit&> (msg);
265 0 : RenderSubmit(msgData.collector, msgData.frustum, msgData.culling);
266 0 : break;
267 : }
268 : }
269 8791 : }
270 :
271 : // Check whether the entity is either a settlement or territory influence;
272 : // ignore any others
273 8166 : void MakeDirtyIfRelevantEntity(entity_id_t ent)
274 : {
275 8166 : CmpPtr<ICmpTerritoryInfluence> cmpTerritoryInfluence(GetSimContext(), ent);
276 8166 : if (cmpTerritoryInfluence)
277 0 : MakeDirty();
278 8166 : }
279 :
280 6 : const Grid<std::uint8_t>& GetTerritoryGrid() override
281 : {
282 6 : CalculateTerritories();
283 6 : ENSURE(m_Territories);
284 6 : return *m_Territories;
285 : }
286 :
287 : player_id_t GetOwner(entity_pos_t x, entity_pos_t z) override;
288 : std::vector<std::uint32_t> GetNeighbours(entity_pos_t x, entity_pos_t z, bool filterConnected) override;
289 : bool IsConnected(entity_pos_t x, entity_pos_t z) override;
290 :
291 : void SetTerritoryBlinking(entity_pos_t x, entity_pos_t z, bool enable) override;
292 : bool IsTerritoryBlinking(entity_pos_t x, entity_pos_t z) override;
293 :
294 : // To support lazy updates of territory render data,
295 : // we maintain a DirtyID here and increment it whenever territories change;
296 : // if a caller has a lower DirtyID then it needs to be updated.
297 : // We also do the same thing for blinking updates using DirtyBlinkingID.
298 :
299 : size_t m_DirtyID;
300 : size_t m_DirtyBlinkingID;
301 :
302 : bool m_ColorChanged;
303 :
304 10 : void MakeDirty()
305 : {
306 11 : SAFE_DELETE(m_Territories);
307 10 : ++m_DirtyID;
308 10 : m_BoundaryLinesDirty = true;
309 10 : m_TriggerEvent = true;
310 10 : }
311 :
312 0 : bool NeedUpdateTexture(size_t* dirtyID) override
313 : {
314 0 : if (*dirtyID == m_DirtyID && !m_ColorChanged)
315 : return false;
316 :
317 0 : *dirtyID = m_DirtyID;
318 0 : m_ColorChanged = false;
319 0 : return true;
320 : }
321 :
322 3 : bool NeedUpdateAI(size_t* dirtyID, size_t* dirtyBlinkingID) const override
323 : {
324 3 : if (*dirtyID == m_DirtyID && *dirtyBlinkingID == m_DirtyBlinkingID)
325 : return false;
326 :
327 3 : *dirtyID = m_DirtyID;
328 3 : *dirtyBlinkingID = m_DirtyBlinkingID;
329 3 : return true;
330 : }
331 :
332 : void CalculateCostGrid();
333 :
334 : void CalculateTerritories();
335 :
336 : std::uint8_t GetTerritoryPercentage(player_id_t player) override;
337 :
338 : std::vector<STerritoryBoundary> ComputeBoundaries();
339 :
340 : void UpdateBoundaryLines();
341 :
342 : void Interpolate(float frameTime, float frameOffset);
343 :
344 : void RenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling);
345 :
346 0 : void SetVisibility(bool visible) override
347 : {
348 0 : if (!m_Enabled)
349 : return;
350 :
351 0 : m_Visible = visible;
352 : }
353 :
354 0 : bool IsVisible() const override
355 : {
356 0 : return m_Enabled && m_Visible;
357 : }
358 :
359 : void UpdateColors() override;
360 :
361 : private:
362 : bool m_Visible;
363 : bool m_Enabled;
364 :
365 : /**
366 : * Mark the territory tiles covered by an entity's footprint with infinite weight.
367 : * This ensures that buildings always own the territory directly beneath them.
368 : * Tiles already claimed by another footprint are left untouched, so when called
369 : * in ascending entity ID order, the oldest building keeps contested tiles.
370 : */
371 : void MarkFootprintTiles(
372 : entity_id_t ent,
373 : player_id_t owner,
374 : Grid<std::uint32_t>& bestWeightGrid,
375 : const std::uint16_t tilesW,
376 : const std::uint16_t tilesH,
377 : std::vector<std::pair<std::uint16_t, std::uint16_t>>& tiles);
378 : };
379 :
380 274 : REGISTER_COMPONENT_TYPE(TerritoryManager)
381 :
382 : // Tile data type, for easier accessing of coordinates
383 : struct Tile
384 : {
385 420 : Tile(std::uint16_t i, std::uint16_t j) : x(i), z(j) { }
386 : std::uint16_t x, z;
387 : };
388 :
389 : /**
390 : * Queue based eight directional floodfill algorithm.
391 : *
392 : * @param origin Where to start the floodfill. In the first iteration it is
393 : * passed as the second argument to the @see decider and the floodfill only
394 : * continues when the invocation returns @c true.
395 : * @param gridSize Tiles outside the boundary are never exteded. The
396 : * @see decider isn't called with thous tiles.
397 : * @param decider It is called with a tile wich was already added as the first
398 : * argument and a neighbour as the second argument. The invocation shall
399 : * return whether to extend the wavefront to the neighbour (if allways
400 : * @c true is returned, an infinite loop will occur). In the first iteration
401 : * the @see decider is invoked with a null pointer as the first argument and
402 : * @see origin as the second argument.
403 : */
404 : template<typename Decider>
405 4 : void Floodfill(const Tile& origin, const Tile& gridSize, Decider decider)
406 : {
407 : static_assert(std::is_invocable_r_v<bool, Decider, const Tile*, const Tile&>);
408 :
409 4 : constexpr std::array<std::array<int, 2>, 8> neighbours{{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1},
410 : {-1, -1}, {1, -1}, {-1, 1}}};
411 4 : std::queue<Tile> openTiles;
412 :
413 56 : const auto emplaceIfRequested = [decider = std::move(decider), &openTiles](
414 : const Tile* currentTile, const Tile& neighbourTile)
415 : {
416 298 : if (decider(currentTile, neighbourTile))
417 298 : openTiles.emplace(neighbourTile);
418 : };
419 :
420 4 : emplaceIfRequested(nullptr, origin);
421 56 : while (!openTiles.empty())
422 : {
423 52 : const Tile currentTile{openTiles.front()};
424 468 : openTiles.pop();
425 468 : for (const std::array<int, 2>& neighbour : neighbours)
426 : {
427 416 : const Tile neighbourTile{
428 416 : static_cast<std::uint16_t>(currentTile.x + std::get<0>(neighbour)),
429 416 : static_cast<std::uint16_t>(currentTile.z + std::get<1>(neighbour))};
430 :
431 : // Check the bounds, underflow will cause the values to be big again.
432 416 : if (neighbourTile.x < gridSize.x && neighbourTile.z < gridSize.z)
433 294 : emplaceIfRequested(¤tTile, neighbourTile);
434 : }
435 : }
436 4 : }
437 :
438 : /**
439 : * Compute the tile indexes on the grid nearest to a given point
440 : */
441 4 : static void NearestTerritoryTile(entity_pos_t x, entity_pos_t z, std::uint16_t& i, std::uint16_t& j,
442 : std::uint16_t w, std::uint16_t h)
443 : {
444 4 : entity_pos_t scale = Pathfinding::NAVCELL_SIZE * ICmpTerritoryManager::NAVCELLS_PER_TERRITORY_TILE;
445 4 : i = Clamp((x / scale).ToInt_RoundToNegInfinity(), 0, w - 1);
446 4 : j = Clamp((z / scale).ToInt_RoundToNegInfinity(), 0, h - 1);
447 : }
448 :
449 5 : void CCmpTerritoryManager::CalculateCostGrid()
450 : {
451 5 : if (m_CostGrid)
452 : return;
453 :
454 5 : CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
455 5 : if (!cmpPathfinder)
456 : return;
457 :
458 5 : pass_class_t passClassTerritory = cmpPathfinder->GetPassabilityClass("default-terrain-only");
459 5 : pass_class_t passClassUnrestricted = cmpPathfinder->GetPassabilityClass("unrestricted");
460 :
461 5 : const Grid<NavcellData>& passGrid = cmpPathfinder->GetPassabilityGrid();
462 :
463 5 : int tilesW = passGrid.m_W / NAVCELLS_PER_TERRITORY_TILE;
464 5 : int tilesH = passGrid.m_H / NAVCELLS_PER_TERRITORY_TILE;
465 :
466 5 : m_CostGrid = new Grid<std::uint8_t>(tilesW, tilesH);
467 5 : m_TerritoryTotalPassableCellCount = 0;
468 :
469 303 : for (int i = 0; i < tilesW; ++i)
470 : {
471 27996 : for (int j = 0; j < tilesH; ++j)
472 : {
473 : NavcellData c = 0;
474 249282 : for (std::uint16_t di = 0; di < NAVCELLS_PER_TERRITORY_TILE; ++di)
475 1994256 : for (std::uint16_t dj = 0; dj < NAVCELLS_PER_TERRITORY_TILE; ++dj)
476 1772672 : c |= passGrid.get(
477 1772672 : i * NAVCELLS_PER_TERRITORY_TILE + di,
478 1772672 : j * NAVCELLS_PER_TERRITORY_TILE + dj);
479 27698 : if (!IS_PASSABLE(c, passClassTerritory))
480 27698 : m_CostGrid->set(i, j, m_ImpassableCost);
481 25442 : else if (!IS_PASSABLE(c, passClassUnrestricted))
482 0 : m_CostGrid->set(i, j, 255); // off the world; use maximum cost
483 : else
484 : {
485 25442 : m_CostGrid->set(i, j, 1);
486 25442 : ++m_TerritoryTotalPassableCellCount;
487 : }
488 : }
489 : }
490 : }
491 :
492 2 : void CCmpTerritoryManager::MarkFootprintTiles(
493 : entity_id_t ent,
494 : player_id_t owner,
495 : Grid<std::uint32_t>& bestWeightGrid,
496 : const std::uint16_t tilesW,
497 : const std::uint16_t tilesH,
498 : std::vector<std::pair<std::uint16_t, std::uint16_t>>& tiles)
499 : {
500 : // Get the footprint component
501 2 : CmpPtr<ICmpFootprint> cmpFootprint{GetSimContext(), ent};
502 2 : if (!cmpFootprint)
503 2 : return;
504 :
505 : // Calculate tile size
506 0 : const entity_pos_t tileSize{Pathfinding::NAVCELL_SIZE * NAVCELLS_PER_TERRITORY_TILE};
507 :
508 : // Get the tiles covered by this footprint
509 0 : cmpFootprint->GetGridTiles(tileSize, tilesW, tilesH, tiles);
510 :
511 0 : const std::uint32_t infiniteWeight = std::numeric_limits<std::uint32_t>::max();
512 :
513 : // Apply infinite weight to all footprint tiles not yet claimed by another footprint
514 0 : for (const auto& tile : tiles)
515 : {
516 0 : if (bestWeightGrid.get(tile.first, tile.second) == infiniteWeight)
517 0 : continue;
518 :
519 0 : m_Territories->set(tile.first, tile.second, owner);
520 0 : bestWeightGrid.set(tile.first, tile.second, infiniteWeight);
521 : }
522 : }
523 :
524 44 : void CCmpTerritoryManager::CalculateTerritories()
525 : {
526 44 : if (m_Territories)
527 39 : return;
528 :
529 5 : PROFILE("CalculateTerritories");
530 :
531 : // If the pathfinder hasn't been loaded (e.g. this is called during map initialisation),
532 : // abort the computation (and assume callers can cope with m_Territories == NULL)
533 5 : CalculateCostGrid();
534 5 : if (!m_CostGrid)
535 0 : return;
536 :
537 5 : const std::uint16_t tilesW = m_CostGrid->m_W;
538 5 : const std::uint16_t tilesH = m_CostGrid->m_H;
539 :
540 5 : m_Territories = new Grid<std::uint8_t>(tilesW, tilesH);
541 :
542 : // Reset territory counts for all players
543 5 : CmpPtr<ICmpPlayerManager> cmpPlayerManager(GetSystemEntity());
544 5 : if (cmpPlayerManager && (size_t)cmpPlayerManager->GetNumPlayers() != m_TerritoryCellCounts.size())
545 4 : m_TerritoryCellCounts.resize(cmpPlayerManager->GetNumPlayers());
546 18 : for (std::uint16_t& count : m_TerritoryCellCounts)
547 13 : count = 0;
548 :
549 : // Find all territory influence entities (sorted by entity ID)
550 5 : CComponentManager::InterfaceList influences = GetSimContext().GetComponentManager().GetEntitiesWithInterface(IID_TerritoryInfluence);
551 :
552 : // Store the overall best weight for comparison
553 5 : Grid<std::uint32_t> bestWeightGrid(tilesW, tilesH);
554 :
555 : // Reusable buffer for footprint tiles - avoids per-entity allocations
556 5 : std::vector<std::pair<std::uint16_t, std::uint16_t>> footprintTiles;
557 :
558 : // Split influence entities into per-player lists, ignoring any with invalid properties,
559 : // and mark their footprint tiles in entity ID order so the oldest building wins overlaps.
560 5 : std::map<player_id_t, std::vector<entity_id_t> > influenceEntities;
561 7 : for (const CComponentManager::InterfacePair& pair : influences)
562 : {
563 2 : entity_id_t ent = pair.first;
564 :
565 2 : CmpPtr<ICmpOwnership> cmpOwnership(GetSimContext(), ent);
566 2 : if (!cmpOwnership)
567 0 : continue;
568 :
569 : // Ignore Gaia and unassigned or players we can't represent
570 2 : player_id_t owner = cmpOwnership->GetOwner();
571 2 : if (owner <= 0 || owner > TERRITORY_PLAYER_MASK)
572 0 : continue;
573 :
574 : // Ignore entities that project no territory, they shouldn't claim their footprint either
575 2 : const ICmpTerritoryInfluence* const cmpTerritoryInfluence{static_cast<const ICmpTerritoryInfluence*>(pair.second)};
576 2 : if (cmpTerritoryInfluence->GetWeight() == 0 || cmpTerritoryInfluence->GetRadius() == 0)
577 0 : continue;
578 :
579 2 : influenceEntities[owner].push_back(ent);
580 :
581 : // Mark the entity's footprint tiles with infinite weight
582 2 : MarkFootprintTiles(ent, owner, bestWeightGrid, tilesW, tilesH, footprintTiles);
583 : }
584 :
585 : // store the root influences to mark territory as connected
586 5 : std::vector<entity_id_t> rootInfluenceEntities;
587 :
588 7 : for (const std::pair<const player_id_t, std::vector<entity_id_t>>& pair : influenceEntities)
589 : {
590 : // entityGrid stores the weight for a single entity, and is reset per entity
591 2 : Grid<std::uint32_t> entityGrid(tilesW, tilesH);
592 : // playerGrid stores the combined weight of all entities for this player
593 2 : Grid<std::uint32_t> playerGrid(tilesW, tilesH);
594 :
595 2 : std::uint8_t owner = static_cast<std::uint8_t>(pair.first);
596 2 : const std::vector<entity_id_t>& ents = pair.second;
597 : // With 2^16 entities, we're safe against overflows as the weight is also limited to 2^16
598 2 : ENSURE(ents.size() < 1 << 16);
599 : // Compute the influence map of the current entity, then add it to the player grid
600 4 : for (entity_id_t ent : ents)
601 : {
602 2 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), ent);
603 2 : if (!cmpPosition || !cmpPosition->IsInWorld())
604 0 : continue;
605 :
606 2 : CmpPtr<ICmpTerritoryInfluence> cmpTerritoryInfluence(GetSimContext(), ent);
607 2 : const std::uint32_t originWeight = cmpTerritoryInfluence->GetWeight();
608 : // Non-zero, entities with zero weight or radius were filtered out above
609 2 : const std::uint32_t radius = cmpTerritoryInfluence->GetRadius();
610 2 : const std::uint32_t relativeFalloff = originWeight *
611 2 : (Pathfinding::NAVCELL_SIZE * NAVCELLS_PER_TERRITORY_TILE)
612 2 : .ToInt_RoundToNegInfinity() / radius;
613 :
614 2 : CFixedVector2D pos = cmpPosition->GetPosition2D();
615 2 : std::uint16_t i, j;
616 2 : NearestTerritoryTile(pos.X, pos.Y, i, j, tilesW, tilesH);
617 :
618 2 : if (cmpTerritoryInfluence->IsRoot())
619 2 : rootInfluenceEntities.push_back(ent);
620 :
621 : // Expand influences outwards
622 2 : Floodfill({i, j}, {tilesW, tilesH}, [&](const Tile* current, const Tile& neighbour)
623 : {
624 149 : const bool diagonalProgression{current && neighbour.x != current->x &&
625 106 : neighbour.z != current->z};
626 :
627 149 : const std::uint32_t falloffPerTile{relativeFalloff *
628 149 : m_CostGrid->get(neighbour.x, neighbour.z)};
629 : // diagonal neighbour -> multiply with approx sqrt(2)
630 149 : const std::uint32_t falloff{diagonalProgression ? (falloffPerTile * 362) / 256 :
631 : falloffPerTile};
632 :
633 : // Don't expand if new cost is not better than previous value for that tile
634 : // (arranged to avoid underflow if entityGrid.get(x, z) < falloff)
635 149 : if (current &&
636 147 : entityGrid.get(current->x, current->z) <=
637 147 : entityGrid.get(neighbour.x, neighbour.z) + falloff)
638 : {
639 : return false;
640 : }
641 :
642 : // weight of this tile = weight of predecessor - falloff from predecessor
643 26 : const std::uint32_t weight{current ?
644 24 : entityGrid.get(current->x, current->z) - falloff : originWeight};
645 2 : const std::uint32_t totalWeight{weight + (current ?
646 50 : playerGrid.get(neighbour.x, neighbour.z) -
647 24 : entityGrid.get(neighbour.x, neighbour.z) : 0)};
648 :
649 26 : playerGrid.set(neighbour.x, neighbour.z, totalWeight);
650 26 : entityGrid.set(neighbour.x, neighbour.z, weight);
651 : // if this weight is better than the best thus far, set the owner
652 26 : if (totalWeight > bestWeightGrid.get(neighbour.x, neighbour.z))
653 : {
654 26 : bestWeightGrid.set(neighbour.x, neighbour.z, totalWeight);
655 26 : m_Territories->set(neighbour.x, neighbour.z, owner);
656 : }
657 : return true;
658 : });
659 2 : entityGrid.reset();
660 : }
661 4 : }
662 :
663 : // Detect territories connected to a 'root' influence (typically a civ center)
664 : // belonging to their player, and mark them with the connected flag
665 7 : for (entity_id_t ent : rootInfluenceEntities)
666 : {
667 : // (These components must be valid else the entities wouldn't be added to this list)
668 2 : CmpPtr<ICmpOwnership> cmpOwnership(GetSimContext(), ent);
669 2 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), ent);
670 :
671 2 : CFixedVector2D pos = cmpPosition->GetPosition2D();
672 2 : std::uint16_t i, j;
673 2 : NearestTerritoryTile(pos.X, pos.Y, i, j, tilesW, tilesH);
674 :
675 2 : std::uint8_t owner = static_cast<std::uint8_t>(cmpOwnership->GetOwner());
676 :
677 2 : Floodfill({i, j}, {tilesW, tilesH}, [&](const Tile*, const Tile& neighbour)
678 : {
679 : // Don't expand non-owner tiles, or tiles that already have a connected mask
680 149 : if (m_Territories->get(neighbour.x, neighbour.z) != owner)
681 : return false;
682 26 : m_Territories->set(neighbour.x, neighbour.z, owner | TERRITORY_CONNECTED_MASK);
683 26 : if (m_CostGrid->get(neighbour.x, neighbour.z) < m_ImpassableCost)
684 26 : ++m_TerritoryCellCounts[owner];
685 : return true;
686 : });
687 : }
688 :
689 : // Then recomputes the blinking tiles
690 5 : CmpPtr<ICmpTerritoryDecayManager> cmpTerritoryDecayManager(GetSystemEntity());
691 5 : if (cmpTerritoryDecayManager)
692 : {
693 3 : size_t dirtyBlinkingID = m_DirtyBlinkingID;
694 3 : cmpTerritoryDecayManager->SetBlinkingEntities();
695 3 : m_DirtyBlinkingID = dirtyBlinkingID;
696 : }
697 12 : }
698 :
699 0 : std::vector<STerritoryBoundary> CCmpTerritoryManager::ComputeBoundaries()
700 : {
701 0 : PROFILE("ComputeBoundaries");
702 :
703 0 : CalculateTerritories();
704 0 : ENSURE(m_Territories);
705 :
706 0 : return CTerritoryBoundaryCalculator::ComputeBoundaries(m_Territories);
707 0 : }
708 :
709 42 : std::uint8_t CCmpTerritoryManager::GetTerritoryPercentage(player_id_t player)
710 : {
711 42 : if (player <= 0 || (m_Territories && static_cast<size_t>(player) >= m_TerritoryCellCounts.size()))
712 : return 0;
713 :
714 38 : CalculateTerritories();
715 :
716 : // Territories may have been recalculated, check whether player is still there.
717 38 : if (m_TerritoryTotalPassableCellCount == 0 || static_cast<size_t>(player) >= m_TerritoryCellCounts.size())
718 : return 0;
719 :
720 38 : std::uint8_t percentage = (m_TerritoryCellCounts[player] * 100) / m_TerritoryTotalPassableCellCount;
721 38 : ENSURE(percentage <= 100);
722 : return percentage;
723 : }
724 :
725 3 : void CCmpTerritoryManager::UpdateBoundaryLines()
726 : {
727 3 : PROFILE("update boundary lines");
728 :
729 3 : m_BoundaryLines.clear();
730 3 : m_DebugBoundaryLineNodes.clear();
731 :
732 3 : if (!CRenderer::IsInitialised())
733 : return;
734 :
735 0 : std::vector<STerritoryBoundary> boundaries = ComputeBoundaries();
736 :
737 0 : CTextureProperties texturePropsBase("art/textures/misc/territory_border.png");
738 0 : texturePropsBase.SetAddressMode(
739 : Renderer::Backend::Sampler::AddressMode::CLAMP_TO_BORDER,
740 : Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
741 0 : texturePropsBase.SetAnisotropicFilter(true);
742 0 : CTexturePtr textureBase = g_Renderer.GetTextureManager().CreateTexture(texturePropsBase);
743 :
744 0 : CTextureProperties texturePropsMask("art/textures/misc/territory_border_mask.png");
745 0 : texturePropsMask.SetAddressMode(
746 : Renderer::Backend::Sampler::AddressMode::CLAMP_TO_BORDER,
747 : Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
748 0 : texturePropsMask.SetAnisotropicFilter(true);
749 0 : CTexturePtr textureMask = g_Renderer.GetTextureManager().CreateTexture(texturePropsMask);
750 :
751 0 : CmpPtr<ICmpPlayerManager> cmpPlayerManager(GetSystemEntity());
752 0 : if (!cmpPlayerManager)
753 0 : return;
754 :
755 0 : for (size_t i = 0; i < boundaries.size(); ++i)
756 : {
757 0 : if (boundaries[i].points.empty())
758 0 : continue;
759 :
760 0 : CColor color(1, 0, 1, 1);
761 0 : CmpPtr<ICmpPlayer> cmpPlayer(GetSimContext(), cmpPlayerManager->GetPlayerByID(boundaries[i].owner));
762 0 : if (cmpPlayer)
763 0 : color = cmpPlayer->GetDisplayedColor();
764 :
765 0 : m_BoundaryLines.push_back(SBoundaryLine());
766 0 : m_BoundaryLines.back().blinking = boundaries[i].blinking;
767 0 : m_BoundaryLines.back().owner = boundaries[i].owner;
768 0 : m_BoundaryLines.back().color = color;
769 0 : m_BoundaryLines.back().overlay.m_SimContext = &GetSimContext();
770 0 : m_BoundaryLines.back().overlay.m_TextureBase = textureBase;
771 0 : m_BoundaryLines.back().overlay.m_TextureMask = textureMask;
772 0 : m_BoundaryLines.back().overlay.m_Color = color;
773 0 : m_BoundaryLines.back().overlay.m_Thickness = m_BorderThickness;
774 0 : m_BoundaryLines.back().overlay.m_Closed = true;
775 :
776 0 : SimRender::SmoothPointsAverage(boundaries[i].points, m_BoundaryLines.back().overlay.m_Closed);
777 0 : SimRender::InterpolatePointsRNS(boundaries[i].points, m_BoundaryLines.back().overlay.m_Closed, m_BorderSeparation);
778 :
779 0 : std::vector<CVector2D>& points = m_BoundaryLines.back().overlay.m_Coords;
780 0 : for (size_t j = 0; j < boundaries[i].points.size(); ++j)
781 : {
782 0 : points.push_back(boundaries[i].points[j]);
783 :
784 0 : if (m_EnableLineDebugOverlays)
785 : {
786 0 : const size_t numHighlightNodes = 7; // highlight the X last nodes on either end to see where they meet (if closed)
787 0 : SOverlayLine overlayNode;
788 0 : if (j > boundaries[i].points.size() - 1 - numHighlightNodes)
789 0 : overlayNode.m_Color = CColor(1.f, 0.f, 0.f, 1.f);
790 0 : else if (j < numHighlightNodes)
791 0 : overlayNode.m_Color = CColor(0.f, 1.f, 0.f, 1.f);
792 : else
793 0 : overlayNode.m_Color = CColor(1.0f, 1.0f, 1.0f, 1.0f);
794 :
795 0 : overlayNode.m_Thickness = 0.1f;
796 0 : SimRender::ConstructCircleOnGround(GetSimContext(), boundaries[i].points[j].X, boundaries[i].points[j].Y, 0.1f, overlayNode, true);
797 0 : m_DebugBoundaryLineNodes.push_back(overlayNode);
798 0 : }
799 : }
800 :
801 : }
802 3 : }
803 :
804 3 : void CCmpTerritoryManager::Interpolate(float frameTime, float /*frameOffset*/)
805 : {
806 3 : m_AnimTime += frameTime;
807 :
808 3 : if (m_BoundaryLinesDirty)
809 : {
810 3 : UpdateBoundaryLines();
811 3 : m_BoundaryLinesDirty = false;
812 : }
813 :
814 3 : for (size_t i = 0; i < m_BoundaryLines.size(); ++i)
815 : {
816 0 : if (m_BoundaryLines[i].blinking)
817 : {
818 0 : CColor c = m_BoundaryLines[i].color;
819 0 : c.a *= 0.2f + 0.8f * fabsf(static_cast<float>(cos(m_AnimTime * std::numbers::pi))); // TODO: should let artists tweak this
820 0 : m_BoundaryLines[i].overlay.m_Color = c;
821 : }
822 : }
823 3 : }
824 :
825 0 : void CCmpTerritoryManager::RenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling)
826 : {
827 0 : if (!IsVisible())
828 : return;
829 :
830 0 : for (size_t i = 0; i < m_BoundaryLines.size(); ++i)
831 : {
832 0 : if (culling && !m_BoundaryLines[i].overlay.IsVisibleInFrustum(frustum))
833 0 : continue;
834 0 : collector.Submit(&m_BoundaryLines[i].overlay);
835 : }
836 :
837 0 : for (size_t i = 0; i < m_DebugBoundaryLineNodes.size(); ++i)
838 0 : collector.Submit(&m_DebugBoundaryLineNodes[i]);
839 :
840 : }
841 :
842 0 : player_id_t CCmpTerritoryManager::GetOwner(entity_pos_t x, entity_pos_t z)
843 : {
844 0 : std::uint16_t i, j;
845 0 : if (!m_Territories)
846 : {
847 0 : CalculateTerritories();
848 0 : if (!m_Territories)
849 : return 0;
850 : }
851 :
852 0 : NearestTerritoryTile(x, z, i, j, m_Territories->m_W, m_Territories->m_H);
853 0 : return m_Territories->get(i, j) & TERRITORY_PLAYER_MASK;
854 : }
855 :
856 0 : std::vector<std::uint32_t> CCmpTerritoryManager::GetNeighbours(entity_pos_t x, entity_pos_t z, bool filterConnected)
857 : {
858 0 : CmpPtr<ICmpPlayerManager> cmpPlayerManager(GetSystemEntity());
859 0 : if (!cmpPlayerManager)
860 0 : return std::vector<std::uint32_t>();
861 :
862 0 : std::vector<std::uint32_t> ret(cmpPlayerManager->GetNumPlayers(), 0);
863 0 : CalculateTerritories();
864 0 : if (!m_Territories)
865 0 : return ret;
866 :
867 0 : std::uint16_t i, j;
868 0 : NearestTerritoryTile(x, z, i, j, m_Territories->m_W, m_Territories->m_H);
869 :
870 : // calculate the neighbours
871 0 : player_id_t thisOwner = m_Territories->get(i, j) & TERRITORY_PLAYER_MASK;
872 :
873 0 : std::uint16_t tilesW = m_Territories->m_W;
874 0 : std::uint16_t tilesH = m_Territories->m_H;
875 :
876 : // use a flood-fill algorithm that fills up to the borders and remembers the owners
877 0 : Grid<bool> markerGrid(tilesW, tilesH);
878 :
879 0 : Floodfill({i, j}, {tilesW, tilesH}, [&](const Tile*, const Tile& neighbour)
880 : {
881 0 : if (markerGrid.get(neighbour.x, neighbour.z))
882 : return false;
883 : // mark the tile as visited in any case
884 0 : markerGrid.set(neighbour.x, neighbour.z, true);
885 0 : int owner = m_Territories->get(neighbour.x, neighbour.z) & TERRITORY_PLAYER_MASK;
886 0 : if (owner != thisOwner)
887 : {
888 0 : if (owner == 0 || !filterConnected || (m_Territories->get(neighbour.x, neighbour.z) & TERRITORY_CONNECTED_MASK) != 0)
889 0 : ret[owner]++; // add player to the neighbour list when requested
890 0 : return false; // don't expand non-owner tiles further
891 : }
892 : return true;
893 : });
894 :
895 0 : return ret;
896 0 : }
897 :
898 0 : bool CCmpTerritoryManager::IsConnected(entity_pos_t x, entity_pos_t z)
899 : {
900 0 : std::uint16_t i, j;
901 0 : CalculateTerritories();
902 0 : if (!m_Territories)
903 : return false;
904 :
905 0 : NearestTerritoryTile(x, z, i, j, m_Territories->m_W, m_Territories->m_H);
906 0 : return (m_Territories->get(i, j) & TERRITORY_CONNECTED_MASK) != 0;
907 : }
908 :
909 0 : void CCmpTerritoryManager::SetTerritoryBlinking(entity_pos_t x, entity_pos_t z, bool enable)
910 : {
911 0 : CalculateTerritories();
912 0 : if (!m_Territories)
913 0 : return;
914 :
915 0 : std::uint16_t i, j;
916 0 : NearestTerritoryTile(x, z, i, j, m_Territories->m_W, m_Territories->m_H);
917 :
918 0 : std::uint16_t tilesW = m_Territories->m_W;
919 0 : std::uint16_t tilesH = m_Territories->m_H;
920 :
921 0 : player_id_t thisOwner = m_Territories->get(i, j) & TERRITORY_PLAYER_MASK;
922 :
923 0 : Floodfill({i, j}, {tilesW, tilesH}, [&](const Tile*, const Tile& neighbour)
924 : {
925 0 : const std::uint8_t bitmask{m_Territories->get(neighbour.x, neighbour.z)};
926 0 : if ((bitmask & TERRITORY_PLAYER_MASK) != thisOwner)
927 : return false;
928 0 : const bool blinking{(bitmask & TERRITORY_BLINKING_MASK) != 0};
929 0 : if (enable != blinking)
930 : {
931 0 : m_Territories->set(neighbour.x, neighbour.z, enable ?
932 : bitmask | TERRITORY_BLINKING_MASK : bitmask & ~TERRITORY_BLINKING_MASK);
933 0 : return true;
934 : }
935 : return false;
936 : });
937 0 : ++m_DirtyBlinkingID;
938 0 : m_BoundaryLinesDirty = true;
939 : }
940 :
941 0 : bool CCmpTerritoryManager::IsTerritoryBlinking(entity_pos_t x, entity_pos_t z)
942 : {
943 0 : CalculateTerritories();
944 0 : if (!m_Territories)
945 : return false;
946 :
947 0 : std::uint16_t i, j;
948 0 : NearestTerritoryTile(x, z, i, j, m_Territories->m_W, m_Territories->m_H);
949 0 : return (m_Territories->get(i, j) & TERRITORY_BLINKING_MASK) != 0;
950 : }
951 :
952 0 : void CCmpTerritoryManager::UpdateColors()
953 : {
954 0 : m_ColorChanged = true;
955 :
956 0 : CmpPtr<ICmpPlayerManager> cmpPlayerManager(GetSystemEntity());
957 0 : if (!cmpPlayerManager)
958 0 : return;
959 :
960 0 : for (SBoundaryLine& boundaryLine : m_BoundaryLines)
961 : {
962 0 : CmpPtr<ICmpPlayer> cmpPlayer(GetSimContext(), cmpPlayerManager->GetPlayerByID(boundaryLine.owner));
963 0 : if (!cmpPlayer)
964 0 : continue;
965 :
966 0 : boundaryLine.color = cmpPlayer->GetDisplayedColor();
967 0 : boundaryLine.overlay.m_Color = boundaryLine.color;
968 : }
969 : }
|