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 "CCmpUnitMotion.h"
21 :
22 : #include "lib/debug.h"
23 : #include "maths/Fixed.h"
24 : #include "maths/FixedVector2D.h"
25 : #include "maths/FixedVector3D.h"
26 : #include "maths/MathUtil.h"
27 : #include "ps/CLogger.h"
28 : #include "ps/Profiler2.h"
29 : #include "simulation2/MessageTypes.h"
30 : #include "simulation2/components/CCmpUnitMotionManager.h"
31 : #include "simulation2/components/ICmpObstructionManager.h"
32 : #include "simulation2/components/ICmpPathfinder.h"
33 : #include "simulation2/components/ICmpPosition.h"
34 : #include "simulation2/components/ICmpTerrain.h"
35 : #include "simulation2/components/ICmpUnitMotion.h"
36 : #include "simulation2/helpers/Grid.h"
37 : #include "simulation2/helpers/Position.h"
38 : #include "simulation2/serialization/SerializeTemplates.h"
39 : #include "simulation2/system/Component.h"
40 : #include "simulation2/system/Entity.h"
41 : #include "simulation2/system/EntityMap.h"
42 : #include "simulation2/system/Message.h"
43 :
44 : #include <algorithm>
45 : #include <cstdint>
46 : #include <cstdlib>
47 : #include <limits>
48 : #include <string>
49 : #include <type_traits>
50 : #include <unordered_set>
51 : #include <utility>
52 : #include <vector>
53 :
54 : #define DEBUG_STATS 0
55 : #define DEBUG_RENDER 0
56 : #define DEBUG_RENDER_ALL_PUSH 0
57 :
58 : // NB: this TU contains the CCmpUnitMotion/CCmpUnitMotionManager couple.
59 : // In practice, UnitMotionManager functions need access to the full implementation of UnitMotion,
60 : // but UnitMotion needs access to MotionState (defined in UnitMotionManager).
61 : // To avoid inclusion issues, implementation of UnitMotionManager that uses UnitMotion is here.
62 :
63 : namespace {
64 : /**
65 : * Units push within their square and neighboring squares (except diagonals). This is the size of each square (in meters).
66 : * I have tested grid sizes from 10 up to 80 and overall it made little difference to the performance,
67 : * mostly, I suspect, because pushing is generally dwarfed by regular motion costs.
68 : * However, the algorithm remains n^2 in comparisons so it's probably best to err on the side of smaller grids, which will have lower spikes.
69 : * The balancing act is between comparisons, unordered_set insertions and unordered_set iterations.
70 : * For these reasons, a value of 20 which is rather small but not overly so was chosen.
71 : */
72 : constexpr int PUSHING_GRID_SIZE = 20;
73 :
74 : /**
75 : * For pushing, treat the clearances as a circle - they're defined as squares,
76 : * so we'll take the circumscribing square (approximately).
77 : * Clerances are also full-width instead of half, so we want to divide by two. sqrt(2)/2 is about 0.71 < 5/7.
78 : */
79 : constexpr entity_pos_t PUSHING_CORRECTION = entity_pos_t::FromFraction(5, 7);
80 :
81 : /**
82 : * Arbitrary constant used to reduce pushing to levels that won't break physics for our turn length.
83 : */
84 : constexpr int PUSHING_REDUCTION_FACTOR = 2;
85 :
86 : /**
87 : * Maximum distance-related multiplier.
88 : * NB: this value interacts with the "minimal pushing" force,
89 : * as two perfectly overlapping units exert MAX_DISTANCE_FACTOR * Turn length in ms / REDUCTION_FACTOR
90 : * of force on each other each turn. If this is below the minimal pushing force, any 2 units can entirely overlap.
91 : */
92 : constexpr entity_pos_t MAX_DISTANCE_FACTOR = entity_pos_t::FromFraction(5, 2);
93 :
94 : /**
95 : * Maximum pushing multiplier for a single push calculation.
96 : * This exists for numerical stability of the system between a lightweight and a heavy unit.
97 : */
98 : constexpr int MAX_PUSHING_MULTIPLIER = 4;
99 :
100 : /**
101 : * When two units collide, if their movement dot product is below this value, give them a perpendicular nudge instead of trying to push in the regular way.
102 : */
103 : constexpr entity_pos_t PERPENDICULAR_NUDGE_THRESHOLD = entity_pos_t::FromFraction(-1, 10);
104 :
105 : /**
106 : * Pushing is dampened by pushing pressure, but this is capped so that units still get pushed.
107 : */
108 : constexpr int MAX_PUSH_DAMPING_PRESSURE = 160;
109 : static_assert(MAX_PUSH_DAMPING_PRESSURE < CCmpUnitMotionManager::MAX_PRESSURE);
110 :
111 : /**
112 : * When units are obstructed because they're being pushed away from where they want to go,
113 : * raise the pushing pressure to at least this value.
114 : */
115 : constexpr int MIN_PRESSURE_IF_OBSTRUCTED = 80;
116 :
117 : /**
118 : * These two numbers are used to calculate pushing pressure between two units.
119 : */
120 : constexpr entity_pos_t PRESSURE_STATIC_FACTOR = entity_pos_t::FromInt(2);
121 : constexpr int PRESSURE_DISTANCE_FACTOR = 5;
122 : }
123 :
124 : #if DEBUG_RENDER
125 : #include "maths/Frustum.h"
126 :
127 : void RenderDebugOverlay(SceneCollector& collector, const CFrustum& frustum, bool culling);
128 :
129 : struct SDebugData {
130 : std::vector<SOverlaySphere> m_Spheres;
131 : std::vector<SOverlayLine> m_Lines;
132 : std::vector<SOverlayQuad> m_Quads;
133 : } debugDataMotionMgr;
134 : #endif
135 :
136 180 : CCmpUnitMotionManager::MotionState::MotionState(ICmpPosition* cmpPos, CCmpUnitMotion* cmpMotion)
137 180 : : cmpPosition(cmpPos), cmpUnitMotion(cmpMotion)
138 : {
139 180 : static_assert(MAX_PRESSURE <= std::numeric_limits<decltype(pushingPressure)>::max(), "MAX_PRESSURE is higher than the maximum value of the underlying type.");
140 0 : }
141 :
142 137 : void CCmpUnitMotionManager::ClassInit(CComponentManager& componentManager)
143 : {
144 137 : componentManager.SubscribeToMessageType(MT_Deserialized);
145 137 : componentManager.SubscribeToMessageType(MT_TerrainChanged);
146 137 : componentManager.SubscribeToMessageType(MT_TurnStart);
147 137 : componentManager.SubscribeToMessageType(MT_Update_Final);
148 137 : componentManager.SubscribeToMessageType(MT_Update_MotionUnit);
149 137 : componentManager.SubscribeToMessageType(MT_Update_MotionFormation);
150 : #if DEBUG_RENDER
151 : componentManager.SubscribeToMessageType(MT_RenderSubmit);
152 : #endif
153 137 : }
154 :
155 724 : void CCmpUnitMotionManager::HandleMessage(const CMessage& msg, bool /*global*/)
156 : {
157 724 : switch (msg.GetType())
158 : {
159 3 : case MT_TerrainChanged:
160 3 : {
161 3 : CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
162 3 : if (cmpTerrain->GetVerticesPerSide() != m_MovingUnits.width())
163 3 : ResetSubdivisions();
164 : break;
165 : }
166 181 : case MT_TurnStart:
167 181 : {
168 181 : OnTurnStart();
169 181 : break;
170 : }
171 180 : case MT_Update_MotionFormation:
172 180 : {
173 180 : fixed dt = static_cast<const CMessageUpdate_MotionFormation&>(msg).turnLength;
174 180 : m_ComputingMotion = true;
175 360 : MoveFormations(dt);
176 180 : m_ComputingMotion = false;
177 180 : break;
178 : }
179 180 : case MT_Update_MotionUnit:
180 180 : {
181 180 : fixed dt = static_cast<const CMessageUpdate_MotionUnit&>(msg).turnLength;
182 180 : m_ComputingMotion = true;
183 360 : MoveUnits(dt);
184 180 : m_ComputingMotion = false;
185 180 : break;
186 : }
187 0 : case MT_Deserialized:
188 0 : {
189 0 : OnDeserialized();
190 0 : break;
191 : }
192 : #if DEBUG_RENDER
193 : case MT_RenderSubmit:
194 : {
195 : const CMessageRenderSubmit& msgData = static_cast<const CMessageRenderSubmit&> (msg);
196 : RenderDebugOverlay(msgData.collector, msgData.frustum, msgData.culling);
197 : break;
198 : }
199 : #endif
200 : }
201 724 : }
202 7 : void CCmpUnitMotionManager::Init(const CParamNode&)
203 : {
204 : // Load some data - see CCmpPathfinder.xml.
205 : // This assumes the pathfinder component is initialised first and registers the validator.
206 : // TODO: there seems to be no real reason why we could not register a 'system' entity somewhere instead.
207 7 : CParamNode externalParamNode;
208 14 : CParamNode::LoadXML(externalParamNode, L"simulation/data/pathfinder.xml", "pathfinder");
209 7 : CParamNode pushingNode = externalParamNode.GetChild("Pathfinder").GetChild("Pushing");
210 :
211 : // NB: all values are given sane default, but they are not treated as optional in the schema,
212 : // so the XML file is the reference.
213 :
214 7 : {
215 7 : const CParamNode spread = pushingNode.GetChild("MovingSpread");
216 7 : if (spread.IsOk())
217 : {
218 4 : m_MovingPushingSpread = Clamp(spread.ToFixed(), entity_pos_t::Zero(), entity_pos_t::FromInt(1));
219 4 : if (m_MovingPushingSpread != spread.ToFixed())
220 0 : LOGWARNING("Moving pushing spread was clamped to the 0-1 range.");
221 : }
222 : else
223 3 : m_MovingPushingSpread = entity_pos_t::FromInt(5) / 8;
224 7 : }
225 :
226 7 : {
227 7 : const CParamNode spread = pushingNode.GetChild("StaticSpread");
228 7 : if (spread.IsOk())
229 : {
230 4 : m_StaticPushingSpread = Clamp(spread.ToFixed(), entity_pos_t::Zero(), entity_pos_t::FromInt(1));
231 4 : if (m_StaticPushingSpread != spread.ToFixed())
232 0 : LOGWARNING("Static pushing spread was clamped to the 0-1 range.");
233 : }
234 : else
235 3 : m_StaticPushingSpread = entity_pos_t::FromInt(5) / 8;
236 7 : }
237 :
238 7 : const CParamNode radius = pushingNode.GetChild("Radius");
239 7 : if (radius.IsOk())
240 : {
241 4 : m_PushingRadiusMultiplier = radius.ToFixed();
242 4 : if (m_PushingRadiusMultiplier < entity_pos_t::Zero())
243 : {
244 0 : LOGWARNING("Pushing radius multiplier cannot be below 0. De-activating pushing but 'pathfinder.xml' should be updated.");
245 0 : m_PushingRadiusMultiplier = entity_pos_t::Zero();
246 : }
247 : // No upper value, but things won't behave sanely if values are too high.
248 : }
249 : else
250 3 : m_PushingRadiusMultiplier = entity_pos_t::FromInt(8) / 5;
251 :
252 7 : const CParamNode minForce = pushingNode.GetChild("MinimalForce");
253 7 : if (minForce.IsOk())
254 4 : m_MinimalPushing = minForce.ToFixed();
255 : else
256 3 : m_MinimalPushing = entity_pos_t::FromInt(2) / 10;
257 :
258 7 : const CParamNode movingExt = pushingNode.GetChild("MovingExtension");
259 7 : const CParamNode staticExt = pushingNode.GetChild("StaticExtension");
260 7 : if (movingExt.IsOk() && staticExt.IsOk())
261 : {
262 4 : m_MovingPushExtension = movingExt.ToFixed();
263 4 : m_StaticPushExtension = staticExt.ToFixed();
264 : }
265 : else
266 : {
267 3 : m_MovingPushExtension = entity_pos_t::FromInt(5) / 2;
268 3 : m_StaticPushExtension = entity_pos_t::FromInt(2);
269 : }
270 :
271 7 : const CParamNode pressureStrength = pushingNode.GetChild("PressureStrength");
272 7 : if (pressureStrength.IsOk())
273 : {
274 4 : m_PushingPressureStrength = pressureStrength.ToFixed();
275 4 : if (m_PushingPressureStrength < entity_pos_t::Zero())
276 : {
277 0 : LOGWARNING("Pushing pressure strength cannot be below 0. 'pathfinder.xml' should be updated.");
278 0 : m_PushingPressureStrength = entity_pos_t::Zero();
279 : }
280 : // No upper value, but things won't behave sanely if values are too high.
281 : }
282 : else
283 3 : m_PushingPressureStrength = entity_pos_t::FromInt(1);
284 :
285 7 : const CParamNode pushingPressure = pushingNode.GetChild("PressureDecay");
286 7 : if (pushingPressure.IsOk())
287 : {
288 4 : m_PushingPressureDecay = Clamp(pushingPressure.ToFixed(), entity_pos_t::Zero(), entity_pos_t::FromInt(1));
289 4 : if (m_PushingPressureDecay != pushingPressure.ToFixed())
290 0 : LOGWARNING("Pushing pressure decay was clamped to the 0-1 range.");
291 : }
292 : else
293 3 : m_PushingPressureDecay = entity_pos_t::FromInt(6) / 10;
294 :
295 7 : }
296 :
297 : template<>
298 : struct SerializeHelper<CCmpUnitMotionManager::MotionState>
299 : {
300 : template<typename S>
301 1020 : void operator()(S& serialize, const char* /*name*/,
302 : Serialize::qualify<S, CCmpUnitMotionManager::MotionState> value)
303 : {
304 1020 : Serializer(serialize, "pushing pressure", value.pushingPressure);
305 : }
306 : };
307 :
308 : template<>
309 : struct SerializeHelper<EntityMap<CCmpUnitMotionManager::MotionState>>
310 : {
311 36 : void operator()(ISerializer& serialize, const char* /*name*/,
312 : EntityMap<CCmpUnitMotionManager::MotionState>& value)
313 : {
314 : // Serialize manually, we don't have a default-constructor for deserialization.
315 36 : Serializer(serialize, "size", static_cast<std::uint32_t>(value.size()));
316 1092 : for (EntityMap<CCmpUnitMotionManager::MotionState>::iterator it = value.begin(); it != value.end(); ++it)
317 : {
318 1020 : Serializer(serialize, "ent id", it->first);
319 1020 : Serializer(serialize, "state", it->second);
320 : }
321 36 : }
322 :
323 0 : void operator()(IDeserializer& deserialize, const char* /*name*/,
324 : EntityMap<CCmpUnitMotionManager::MotionState>& value)
325 : {
326 0 : std::uint32_t units = 0;
327 0 : Serializer(deserialize, "size", units);
328 0 : for (std::uint32_t i = 0; i < units; ++i)
329 : {
330 0 : entity_id_t ent = INVALID_ENTITY;
331 0 : Serializer(deserialize, "ent id", ent);
332 : // Insert an invalid motion state, will be cleared up in MT_Deserialized.
333 0 : CCmpUnitMotionManager::MotionState state(nullptr, nullptr);
334 0 : Serializer(deserialize, "state", state);
335 0 : value.insert(ent, state);
336 : }
337 0 : }
338 : };
339 :
340 18 : void CCmpUnitMotionManager::Serialize(ISerializer& serialize)
341 : {
342 18 : Serializer(serialize, "m_Units", m_Units);
343 18 : Serializer(serialize, "m_FormationControllers", m_FormationControllers);
344 18 : }
345 :
346 0 : void CCmpUnitMotionManager::Deserialize(const CParamNode& paramNode, IDeserializer& deserialize)
347 : {
348 0 : Init(paramNode);
349 0 : ResetSubdivisions();
350 0 : Serializer(deserialize, "m_Units", m_Units);
351 0 : Serializer(deserialize, "m_FormationControllers", m_FormationControllers);
352 0 : }
353 :
354 : /**
355 : * This deserialization process is rather ugly, but it's required to store some data in the motion states.
356 : * Ideally, the motion state would actually be CCmpUnitMotion themselves, but for data locality
357 : * (because our components are stored randomly on the heap right now) they're not.
358 : * If we ever change the simulation so that components could be registered by their managers and exposed,
359 : * then we could just use CCmpUnitMotion directly and clean this code uglyness.
360 : */
361 0 : void CCmpUnitMotionManager::OnDeserialized()
362 : {
363 : // Fetch the components now that they exist.
364 : // The rest of the data was already deserialized or will be reconstructed.
365 0 : for (EntityMap<MotionState>::iterator it = m_Units.begin(); it != m_Units.end(); ++it)
366 : {
367 0 : it->second.cmpPosition = static_cast<ICmpPosition*>(QueryInterface(GetSimContext(), it->first, IID_Position));
368 : // We can know for a fact that these are CCmpUnitMotion because those are the ones registering with us
369 : // (and to ensure that they pass a CCmpUnitMotion pointer when registering).
370 0 : it->second.cmpUnitMotion = static_cast<CCmpUnitMotion*>(static_cast<ICmpUnitMotion*>(QueryInterface(GetSimContext(), it->first, IID_UnitMotion)));
371 : }
372 0 : for (EntityMap<MotionState>::iterator it = m_FormationControllers.begin(); it != m_FormationControllers.end(); ++it)
373 : {
374 0 : it->second.cmpPosition = static_cast<ICmpPosition*>(QueryInterface(GetSimContext(), it->first, IID_Position));
375 0 : it->second.cmpUnitMotion = static_cast<CCmpUnitMotion*>(static_cast<ICmpUnitMotion*>(QueryInterface(GetSimContext(), it->first, IID_UnitMotion)));
376 : }
377 0 : }
378 :
379 3 : void CCmpUnitMotionManager::ResetSubdivisions()
380 : {
381 3 : CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
382 3 : if (!cmpTerrain)
383 3 : return;
384 :
385 3 : size_t size = cmpTerrain->GetMapSize();
386 3 : std::uint16_t gridSquareSize = static_cast<std::uint16_t>(size / PUSHING_GRID_SIZE + 1);
387 3 : m_MovingUnits.resize(gridSquareSize, gridSquareSize);
388 : }
389 :
390 180 : void CCmpUnitMotionManager::Register(CCmpUnitMotion* component, entity_id_t ent, bool formationController)
391 : {
392 180 : MotionState state(static_cast<ICmpPosition*>(QueryInterface(GetSimContext(), ent, IID_Position)), component);
393 180 : if (!formationController)
394 180 : m_Units.insert(ent, state);
395 : else
396 0 : m_FormationControllers.insert(ent, state);
397 180 : }
398 :
399 30 : void CCmpUnitMotionManager::Unregister(entity_id_t ent)
400 : {
401 30 : EntityMap<MotionState>::iterator it = m_Units.find(ent);
402 30 : if (it != m_Units.end())
403 : {
404 30 : m_Units.erase(it);
405 30 : return;
406 : }
407 0 : it = m_FormationControllers.find(ent);
408 0 : if (it != m_FormationControllers.end())
409 0 : m_FormationControllers.erase(it);
410 : }
411 :
412 181 : void CCmpUnitMotionManager::OnTurnStart()
413 : {
414 362 : for (EntityMap<MotionState>::value_type& data : m_FormationControllers)
415 0 : data.second.cmpUnitMotion->OnTurnStart();
416 :
417 16238 : for (EntityMap<MotionState>::value_type& data : m_Units)
418 7938 : data.second.cmpUnitMotion->OnTurnStart();
419 181 : }
420 :
421 180 : void CCmpUnitMotionManager::MoveUnits(fixed dt)
422 : {
423 180 : Move(m_Units, dt);
424 0 : }
425 :
426 180 : void CCmpUnitMotionManager::MoveFormations(fixed dt)
427 : {
428 180 : Move(m_FormationControllers, dt);
429 0 : }
430 :
431 360 : void CCmpUnitMotionManager::Move(EntityMap<MotionState>& ents, fixed dt)
432 : {
433 : #if DEBUG_RENDER
434 : debugDataMotionMgr.m_Spheres.clear();
435 : debugDataMotionMgr.m_Lines.clear();
436 : debugDataMotionMgr.m_Quads.clear();
437 : #endif
438 : #if DEBUG_STATS
439 : int comparisons = 0;
440 : double start = timer_Time();
441 : #endif
442 :
443 360 : PROFILE2("MotionMgr_Move");
444 360 : std::unordered_set<std::vector<EntityMap<MotionState>::iterator>*> assigned;
445 16956 : for (EntityMap<MotionState>::iterator it = ents.begin(); it != ents.end(); ++it)
446 : {
447 8118 : if (!it->second.cmpPosition->IsInWorld())
448 : {
449 0 : it->second.needUpdate = false;
450 0 : continue;
451 : }
452 : else
453 8118 : it->second.cmpUnitMotion->PreMove(it->second);
454 8118 : it->second.initialPos = it->second.cmpPosition->GetPosition2D();
455 8118 : it->second.initialAngle = it->second.cmpPosition->GetRotation().Y;
456 8118 : it->second.pos = it->second.initialPos;
457 8118 : it->second.speed = it->second.cmpUnitMotion->GetCurrentSpeed();
458 8118 : it->second.angle = it->second.initialAngle;
459 8118 : const int gridX{it->second.pos.X.ToInt_RoundToZero() / PUSHING_GRID_SIZE};
460 8118 : const int gridY{it->second.pos.Y.ToInt_RoundToZero() / PUSHING_GRID_SIZE};
461 8118 : ENSURE(gridX < m_MovingUnits.width() && gridY < m_MovingUnits.height());
462 8118 : std::vector<EntityMap<MotionState>::iterator>& subdiv = m_MovingUnits.get(gridX, gridY);
463 8118 : subdiv.emplace_back(it);
464 8118 : assigned.emplace(&subdiv);
465 : }
466 :
467 6321 : for (std::vector<EntityMap<MotionState>::iterator>* vec : assigned)
468 : {
469 : #if DEBUG_RENDER
470 : {
471 : SOverlayLine gridL;
472 : auto it = (*vec)[0];
473 : gridL.PushCoords(CVector3D(it->second.pos.X.ToInt_RoundToZero() / PUSHING_GRID_SIZE * PUSHING_GRID_SIZE,
474 : it->second.cmpPosition->GetHeightFixed().ToDouble() + 2.f,
475 : it->second.pos.Y.ToInt_RoundToZero() / PUSHING_GRID_SIZE * PUSHING_GRID_SIZE));
476 : gridL.PushCoords(CVector3D(it->second.pos.X.ToInt_RoundToZero() / PUSHING_GRID_SIZE * PUSHING_GRID_SIZE + PUSHING_GRID_SIZE,
477 : it->second.cmpPosition->GetHeightFixed().ToDouble() + 2.f,
478 : it->second.pos.Y.ToInt_RoundToZero() / PUSHING_GRID_SIZE * PUSHING_GRID_SIZE));
479 : gridL.PushCoords(CVector3D(it->second.pos.X.ToInt_RoundToZero() / PUSHING_GRID_SIZE * PUSHING_GRID_SIZE + PUSHING_GRID_SIZE,
480 : it->second.cmpPosition->GetHeightFixed().ToDouble() + 2.f,
481 : it->second.pos.Y.ToInt_RoundToZero() / PUSHING_GRID_SIZE * PUSHING_GRID_SIZE + PUSHING_GRID_SIZE));
482 : gridL.PushCoords(CVector3D(it->second.pos.X.ToInt_RoundToZero() / PUSHING_GRID_SIZE * PUSHING_GRID_SIZE,
483 : it->second.cmpPosition->GetHeightFixed().ToDouble() + 2.f,
484 : it->second.pos.Y.ToInt_RoundToZero() / PUSHING_GRID_SIZE * PUSHING_GRID_SIZE + PUSHING_GRID_SIZE));
485 : gridL.PushCoords(CVector3D(it->second.pos.X.ToInt_RoundToZero() / PUSHING_GRID_SIZE * PUSHING_GRID_SIZE,
486 : it->second.cmpPosition->GetHeightFixed().ToDouble() + 2.f,
487 : it->second.pos.Y.ToInt_RoundToZero() / PUSHING_GRID_SIZE * PUSHING_GRID_SIZE));
488 : gridL.m_Color = CColor(1, 1, 0, 1);
489 : debugDataMotionMgr.m_Lines.push_back(gridL);
490 : }
491 : #endif
492 14079 : for (EntityMap<MotionState>::iterator& it : *vec)
493 : {
494 8118 : if (it->second.needUpdate)
495 7278 : it->second.cmpUnitMotion->Move(it->second, dt);
496 : // Decay pressure after moving so we can get the full 0-MAX_PRESSURE range of values.
497 16236 : it->second.pushingPressure = (m_PushingPressureDecay * it->second.pushingPressure).ToInt_RoundToZero();
498 : }
499 : }
500 :
501 : // Skip pushing entirely if the radius is 0
502 360 : if (&ents == &m_Units && IsPushingActivated())
503 : {
504 180 : PROFILE2("MotionMgr_Pushing");
505 6141 : for (std::vector<EntityMap<MotionState>::iterator>* vec : assigned)
506 : {
507 5961 : ENSURE(!vec->empty());
508 11922 : std::vector< std::vector<EntityMap<MotionState>::iterator>* > consider = { vec };
509 :
510 5961 : int x = (*vec)[0]->second.pos.X.ToInt_RoundToZero() / PUSHING_GRID_SIZE;
511 5961 : int z = (*vec)[0]->second.pos.Y.ToInt_RoundToZero() / PUSHING_GRID_SIZE;
512 5961 : if (x + 1 < m_MovingUnits.width())
513 5961 : consider.push_back(&m_MovingUnits.get(x + 1, z));
514 5961 : if (x > 0)
515 5961 : consider.push_back(&m_MovingUnits.get(x - 1, z));
516 5961 : if (z + 1 < m_MovingUnits.height())
517 5961 : consider.push_back(&m_MovingUnits.get(x, z + 1));
518 5961 : if (z > 0)
519 5961 : consider.push_back(&m_MovingUnits.get(x, z - 1));
520 :
521 14079 : for (EntityMap<MotionState>::iterator& it : *vec)
522 : {
523 8118 : if (it->second.ignore)
524 0 : continue;
525 :
526 : #if DEBUG_RENDER
527 : // Plop a sphere at the unit end-pos.
528 : {
529 : SOverlaySphere sph;
530 : sph.m_Center = CVector3D(it->second.pos.X.ToDouble(), it->second.cmpPosition->GetHeightFixed().ToDouble() + 13.f, it->second.pos.Y.ToDouble());
531 : sph.m_Radius = it->second.cmpUnitMotion->m_Clearance.Multiply(PUSHING_CORRECTION).ToDouble();
532 : // Color the sphere: the redder, the more 'bogged down' it is.
533 : sph.m_Color = CColor(it->second.pushingPressure / static_cast<float>(MAX_PRESSURE), 0, 0, 1);
534 : debugDataMotionMgr.m_Spheres.push_back(sph);
535 : }
536 : /* Show the pushing sphere, kinda unreadable.
537 : {
538 : SOverlaySphere sph;
539 : sph.m_Center = CVector3D(it->second.pos.X.ToDouble(), it->second.cmpPosition->GetHeightFixed().ToDouble() + 13.f, it->second.pos.Y.ToDouble());
540 : sph.m_Radius = (it->second.cmpUnitMotion->m_Clearance.Multiply(PUSHING_CORRECTION).Multiply(m_PushingRadiusMultiplier) + (it->second.isMoving ? m_StaticPushExtension : m_MovingPushExtension)).ToDouble();
541 : // Color the sphere: the redder, the more 'bogged down' it is.
542 : sph.m_Color = CColor(it->second.pushingPressure / static_cast<float>(MAX_PRESSURE), 0, 0, 0.1);
543 : debugDataMotionMgr.m_Spheres.push_back(sph);
544 : }*/
545 : // Show the travel over this turn.
546 : SOverlayLine line;
547 : line.PushCoords(CVector3D(it->second.initialPos.X.ToDouble(),
548 : it->second.cmpPosition->GetHeightFixed().ToDouble() + 13.f,
549 : it->second.initialPos.Y.ToDouble()));
550 : line.PushCoords(CVector3D(it->second.pos.X.ToDouble(),
551 : it->second.cmpPosition->GetHeightFixed().ToDouble() + 13.f,
552 : it->second.pos.Y.ToDouble()));
553 : line.m_Color = CColor(1, 0, 1, 0.5);
554 : debugDataMotionMgr.m_Lines.push_back(line);
555 : #endif
556 48708 : for (std::vector<EntityMap<MotionState>::iterator>* vec2 : consider)
557 72420 : for (EntityMap<MotionState>::iterator& it2 : *vec2)
558 31830 : if (it->first < it2->first && !it2->second.ignore)
559 : {
560 : #if DEBUG_STATS
561 : ++comparisons;
562 : #endif
563 11373 : Push(*it, *it2, dt);
564 : }
565 : }
566 : }
567 180 : }
568 :
569 360 : if (IsPushingActivated())
570 : {
571 360 : PROFILE2("MotionMgr_PushAdjust");
572 360 : CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
573 6321 : for (std::vector<EntityMap<MotionState>::iterator>* vec : assigned)
574 : {
575 14079 : for (EntityMap<MotionState>::iterator& it : *vec)
576 : {
577 :
578 8118 : if (!it->second.needUpdate || it->second.ignore)
579 840 : continue;
580 :
581 : #if DEBUG_RENDER
582 : SOverlayLine line;
583 : line.PushCoords(CVector3D(it->second.pos.X.ToDouble(),
584 : it->second.cmpPosition->GetHeightFixed().ToDouble() + 15.1f ,
585 : it->second.pos.Y.ToDouble()));
586 : line.PushCoords(CVector3D(it->second.pos.X.ToDouble() + it->second.push.X.ToDouble() * 10.f,
587 : it->second.cmpPosition->GetHeightFixed().ToDouble() + 15.1f ,
588 : it->second.pos.Y.ToDouble() + it->second.push.Y.ToDouble() * 10.f));
589 : line.m_Thickness = 0.05f;
590 : #endif
591 :
592 : // Only apply pushing if the effect is significant enough.
593 7278 : if (it->second.push.CompareLength(m_MinimalPushing) <= 0)
594 : {
595 : #if DEBUG_RENDER
596 : line.m_Color = CColor(1, 1, 0, 0.6);
597 : debugDataMotionMgr.m_Lines.push_back(line);
598 : #endif
599 7278 : it->second.push = CFixedVector2D();
600 7278 : continue;
601 : }
602 :
603 : // If there was an attempt at movement, and we're getting pushed significantly and
604 : // away from where we'd like to go (measured by a low dot product)
605 : // then mark the unit as obstructed, but push anyways.
606 : // (this helps units stop earlier in many situations in a realistic-ish manner).
607 0 : if (it->second.pos != it->second.initialPos
608 0 : && (it->second.pos - it->second.initialPos).Dot(it->second.pos + it->second.push - it->second.initialPos) < entity_pos_t::FromInt(1)/2 && it->second.pushingPressure > 30)
609 : {
610 0 : it->second.wasObstructed = true;
611 0 : it->second.pushingPressure = std::max<uint8_t>(MIN_PRESSURE_IF_OBSTRUCTED, it->second.pushingPressure);
612 : // Push anyways.
613 : }
614 : #if DEBUG_RENDER
615 : if (it->second.wasObstructed)
616 : line.m_Color = CColor(1, 0, 0, 1);
617 : else
618 : line.m_Color = CColor(0, 1, 0, 1);
619 : debugDataMotionMgr.m_Lines.push_back(line);
620 : #endif
621 : // Dampen the pushing by the current pushing pressure
622 : // (but prevent full dampening so that clumped units still get unclumped).
623 0 : it->second.push = it->second.push * (MAX_PRESSURE - std::min<uint8_t>(MAX_PUSH_DAMPING_PRESSURE, it->second.pushingPressure)) / MAX_PRESSURE;
624 :
625 : // Prevent pushed units from crossing uncrossable boundaries
626 : // (we can assume that normal movement didn't push units into impassable terrain).
627 0 : if ((it->second.push.X != entity_pos_t::Zero() || it->second.push.Y != entity_pos_t::Zero()) &&
628 0 : !cmpPathfinder->CheckMovement(it->second.cmpUnitMotion->GetObstructionFilter(),
629 0 : it->second.pos.X, it->second.pos.Y,
630 0 : it->second.pos.X + it->second.push.X, it->second.pos.Y + it->second.push.Y,
631 0 : it->second.cmpUnitMotion->m_Clearance,
632 0 : it->second.cmpUnitMotion->m_PassClass))
633 : {
634 : // Mark them as obstructed - this could possibly be optimised
635 : // perhaps it'd make more sense to mark the pushers as blocked.
636 0 : it->second.wasObstructed = true;
637 0 : it->second.wentStraight = false;
638 0 : it->second.push = CFixedVector2D();
639 0 : continue;
640 : }
641 0 : it->second.pos += it->second.push;
642 0 : it->second.push = CFixedVector2D();
643 : }
644 : }
645 360 : }
646 360 : {
647 360 : PROFILE2("MotionMgr_PostMove");
648 16956 : for (EntityMap<MotionState>::value_type& data : ents)
649 : {
650 8118 : if (!data.second.needUpdate)
651 840 : continue;
652 7278 : data.second.cmpUnitMotion->PostMove(data.second, dt);
653 : }
654 0 : }
655 : #if DEBUG_STATS
656 : int size = 0;
657 : for (std::vector<EntityMap<MotionState>::iterator>* vec : assigned)
658 : size += vec->size();
659 : double time = timer_Time() - start;
660 : if (comparisons > 0)
661 : printf(">> %i comparisons over %li grids, %f units per grid in %f secs\n", comparisons, assigned.size(), size / (float)(assigned.size()), time);
662 : #endif
663 6321 : for (std::vector<EntityMap<MotionState>::iterator>* vec : assigned)
664 11922 : vec->clear();
665 360 : }
666 :
667 : // TODO: ought to better simulate in-flight pushing, e.g. if units would cross in-between turns.
668 11373 : void CCmpUnitMotionManager::Push(EntityMap<MotionState>::value_type& a, EntityMap<MotionState>::value_type& b, fixed dt)
669 : {
670 : // The hard problem for pushing is knowing when to actually use the pathfinder to go around unpushable obstacles.
671 : // For simplicitly, the current logic separates moving & stopped entities:
672 : // moving entities will push moving entities, but not stopped ones, and vice-versa.
673 : // this still delivers most of the value of pushing, without a lot of the complexity.
674 11373 : int movingPush = a.second.isMoving + b.second.isMoving;
675 :
676 : // Exception: units in the same control group (i.e. the same formation) never push farther than themselves
677 : // and are also allowed to push idle units (obstructions are ignored within formations,
678 : // so pushing idle units makes one member crossing the formation look better).
679 11373 : bool sameControlGroup = a.second.controlGroup != INVALID_ENTITY && a.second.controlGroup == b.second.controlGroup;
680 11373 : if (sameControlGroup)
681 : movingPush = 0;
682 :
683 11373 : if (movingPush == 1)
684 11295 : return;
685 :
686 9795 : entity_pos_t combinedClearance = (a.second.cmpUnitMotion->m_Clearance + b.second.cmpUnitMotion->m_Clearance).Multiply(PUSHING_CORRECTION);
687 9795 : entity_pos_t maxDist = combinedClearance;
688 9795 : if (!sameControlGroup)
689 9795 : maxDist = combinedClearance.Multiply(m_PushingRadiusMultiplier) + (movingPush ? m_MovingPushExtension : m_StaticPushExtension);
690 9795 : combinedClearance = maxDist.Multiply(movingPush ? m_MovingPushingSpread : m_StaticPushingSpread);
691 :
692 : // Compare the average position of the two units over the turn - this makes overall behaviour better,
693 : // as we really care more about units that end up either crossing paths or staying together.
694 9795 : CFixedVector2D offset = ((a.second.pos + a.second.initialPos) - (b.second.pos + b.second.initialPos)) / 2;
695 :
696 : #if DEBUG_RENDER
697 : SOverlayLine line;
698 : line.PushCoords(CVector3D(a.second.pos.X.ToDouble(),
699 : a.second.cmpPosition->GetHeightFixed().ToDouble() + 8,
700 : a.second.pos.Y.ToDouble()));
701 : line.PushCoords(CVector3D(b.second.pos.X.ToDouble(),
702 : b.second.cmpPosition->GetHeightFixed().ToDouble() + 8,
703 : b.second.pos.Y.ToDouble()));
704 : if (offset.CompareLength(maxDist) > 0)
705 : {
706 : #if DEBUG_RENDER_ALL_PUSH
707 : line.m_Thickness = 0.01f;
708 : line.m_Color = CColor(0, 0, 1, 0.4);
709 : debugDataMotionMgr.m_Lines.push_back(line);
710 : // then will return
711 : #endif
712 : }
713 : #endif
714 21090 : if (offset.CompareLength(maxDist) > 0)
715 : return;
716 :
717 78 : entity_pos_t offsetLength;
718 :
719 : // If the units appear to have crossed paths, give them a strong perpendicular nudge.
720 : // Ideally, this will make them look like they avoided each other.
721 : // Worst case, either the collision detection isn't picked up or they'll end up bogged down.
722 : // NB: the dot product mostly works because we used average positions earlier.
723 : // NB: this kinda works only because our turn lengths are large enough to make this relevant.
724 : // In an ideal world, we'd anticipate here instead.
725 : // Turn it off for formations - our current 'reforming' code is bad and leads to bad behaviour.
726 78 : if (!sameControlGroup && (a.second.pos - b.second.pos).Dot(a.second.initialPos - b.second.initialPos) < PERPENDICULAR_NUDGE_THRESHOLD)
727 : {
728 0 : CFixedVector2D posDelta = (a.second.pos - b.second.pos) - (a.second.initialPos - b.second.initialPos);
729 0 : CFixedVector2D perp = posDelta.Perpendicular();
730 : // Pick the best direction to avoid the target.
731 0 : if (offset.Dot(perp) < (-offset).Dot(perp))
732 0 : offset = -perp;
733 : else
734 : offset = perp;
735 0 : offsetLength = offset.Length();
736 0 : if (offsetLength > entity_pos_t::Epsilon() * 10)
737 : {
738 : // This needs to be a strong effect or it won't really work.
739 0 : offset.X = offset.X / offsetLength * 3;
740 0 : offset.Y = offset.Y / offsetLength * 3;
741 : }
742 : offsetLength = entity_pos_t::Zero();
743 : }
744 : else
745 : {
746 78 : offsetLength = offset.Length();
747 : // If the offset is small enough that precision would be problematic, pick an arbitrary vector instead.
748 78 : if (offsetLength <= entity_pos_t::Epsilon() * 10)
749 : {
750 : // Throw in some 'randomness' so that clumped units unclump more naturaslly.
751 0 : bool dir = a.first % 2;
752 0 : offset.X = entity_pos_t::FromInt(dir ? 1 : 0);
753 0 : offset.Y = entity_pos_t::FromInt(dir ? 0 : 1);
754 0 : offsetLength = entity_pos_t::Epsilon() * 10;
755 : }
756 : else
757 : {
758 78 : offset.X = offset.X / offsetLength;
759 78 : offset.Y = offset.Y / offsetLength;
760 : }
761 : }
762 :
763 : // The pushing distance factor is 1 at the spread-modified combined clearance, >1 up to MAX if the units 'overlap', < 1 otherwise.
764 78 : entity_pos_t distanceFactor = maxDist - combinedClearance;
765 : // Force units that overlap a lot to have the maximum factor.
766 78 : if (distanceFactor <= entity_pos_t::Zero() || offsetLength < combinedClearance / 2)
767 : distanceFactor = MAX_DISTANCE_FACTOR;
768 : else
769 78 : distanceFactor = Clamp((maxDist - offsetLength) / distanceFactor, entity_pos_t::Zero(), MAX_DISTANCE_FACTOR);
770 :
771 : // Mark both as needing an update so they actually get moved.
772 78 : a.second.needUpdate = true;
773 78 : b.second.needUpdate = true;
774 :
775 78 : CFixedVector2D pushingDir = offset.Multiply(distanceFactor);
776 :
777 : // These cannot be zero, checked in the schema.
778 78 : entity_pos_t aWeight = a.second.cmpUnitMotion->GetWeight();
779 78 : entity_pos_t bWeight = b.second.cmpUnitMotion->GetWeight();
780 :
781 : // Final corrections:
782 : // - divide by an arbitrary constant to avoid pushing too much.
783 : // - multiply by the weight ratio (limiting the maximum positive push for numerical accuracy).
784 78 : entity_pos_t timeFactor = dt / PUSHING_REDUCTION_FACTOR;
785 78 : entity_pos_t maxPushing = timeFactor * MAX_PUSHING_MULTIPLIER;
786 78 : a.second.push += pushingDir.Multiply(std::min(bWeight.MulDiv(timeFactor, aWeight), maxPushing));
787 78 : b.second.push -= pushingDir.Multiply(std::min(aWeight.MulDiv(timeFactor, bWeight), maxPushing));
788 :
789 : // Use a constant factor to get a more general slowdown in crowded area.
790 : // The distance factor heavily dampens units that are overlapping.
791 156 : int addedPressure = std::max(0, (PRESSURE_STATIC_FACTOR + (distanceFactor + entity_pos_t::FromInt(-2)/3) * PRESSURE_DISTANCE_FACTOR).Multiply(m_PushingPressureStrength).ToInt_RoundToZero());
792 78 : a.second.pushingPressure = std::min(MAX_PRESSURE, a.second.pushingPressure + addedPressure);
793 156 : b.second.pushingPressure = std::min(MAX_PRESSURE, b.second.pushingPressure + addedPressure);
794 :
795 : #if DEBUG_RENDER
796 : // Make the lines thicker if the force is stronger.
797 : line.m_Thickness = distanceFactor.ToDouble() / 10.0;
798 : line.m_Color = CColor(1, addedPressure / 20.f, 0, 0.8);
799 : debugDataMotionMgr.m_Lines.push_back(line);
800 : #endif
801 : }
802 :
803 : #if DEBUG_RENDER
804 : void RenderDebugOverlay(SceneCollector& collector, const CFrustum& frustum, bool /*culling*/)
805 : {
806 : for (SOverlaySphere& sph: debugDataMotionMgr.m_Spheres)
807 : if (frustum.IsSphereVisible(sph.m_Center, sph.m_Radius))
808 : collector.Submit(&sph);
809 : for (SOverlayLine& l: debugDataMotionMgr.m_Lines)
810 : if (frustum.IsPointVisible(l.m_Coords[0]) || frustum.IsPointVisible(l.m_Coords[1]))
811 : collector.Submit(&l);
812 : for (SOverlayQuad& quad: debugDataMotionMgr.m_Quads)
813 : collector.Submit(&quad);
814 : }
815 : #endif
816 :
817 : #undef DEBUG_STATS
818 : #undef DEBUG_RENDER
819 : #undef DEBUG_RENDER_ALL_PUSH
|