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 "ICmpFootprint.h"
21 :
22 : #include "maths/Fixed.h"
23 : #include "maths/FixedVector2D.h"
24 : #include "maths/FixedVector3D.h"
25 : #include "ps/Profile.h"
26 : #include "simulation2/components/ICmpObstruction.h"
27 : #include "simulation2/components/ICmpObstructionManager.h"
28 : #include "simulation2/components/ICmpPathfinder.h"
29 : #include "simulation2/components/ICmpPosition.h"
30 : #include "simulation2/components/ICmpRallyPoint.h"
31 : #include "simulation2/components/ICmpUnitMotion.h"
32 : #include "simulation2/helpers/Geometry.h"
33 : #include "simulation2/helpers/Pathfinding.h"
34 : #include "simulation2/helpers/Position.h"
35 : #include "simulation2/system/Component.h"
36 : #include "simulation2/system/Entity.h"
37 :
38 : #include <algorithm>
39 : #include <string>
40 : #include <utility>
41 : #include <vector>
42 :
43 195 : class CCmpFootprint final : public ICmpFootprint
44 : {
45 : public:
46 : static void ClassInit(CComponentManager&)
47 : {
48 : }
49 :
50 390 : DEFAULT_COMPONENT_ALLOCATOR(Footprint)
51 :
52 : EShape m_Shape;
53 : entity_pos_t m_Size0; // width/radius
54 : entity_pos_t m_Size1; // height/radius
55 : entity_pos_t m_Height;
56 : entity_pos_t m_MaxSpawnDistance;
57 :
58 137 : static std::string GetSchema()
59 : {
60 137 : return
61 : "<a:help>Approximation of the entity's shape, for collision detection and may be used for outline rendering or to determine selectable bounding box. "
62 : "Shapes are flat horizontal squares or circles, extended vertically to a given height.</a:help>"
63 : "<a:example>"
64 : "<Square width='3.0' height='3.0'/>"
65 : "<Height>0.0</Height>"
66 : "<MaxSpawnDistance>8</MaxSpawnDistance>"
67 : "</a:example>"
68 : "<a:example>"
69 : "<Circle radius='0.5'/>"
70 : "<Height>0.0</Height>"
71 : "<MaxSpawnDistance>8</MaxSpawnDistance>"
72 : "</a:example>"
73 : "<choice>"
74 : "<element name='Square' a:help='Set the footprint to a square of the given size'>"
75 : "<attribute name='width' a:help='Size of the footprint along the left/right direction (in meters)'>"
76 : "<data type='decimal'>"
77 : "<param name='minExclusive'>0.0</param>"
78 : "</data>"
79 : "</attribute>"
80 : "<attribute name='depth' a:help='Size of the footprint along the front/back direction (in meters)'>"
81 : "<data type='decimal'>"
82 : "<param name='minExclusive'>0.0</param>"
83 : "</data>"
84 : "</attribute>"
85 : "</element>"
86 : "<element name='Circle' a:help='Set the footprint to a circle of the given size'>"
87 : "<attribute name='radius' a:help='Radius of the footprint (in meters)'>"
88 : "<data type='decimal'>"
89 : "<param name='minExclusive'>0.0</param>"
90 : "</data>"
91 : "</attribute>"
92 : "</element>"
93 : "</choice>"
94 : "<element name='Height' a:help='Vertical extent of the footprint (in meters)'>"
95 : "<ref name='nonNegativeDecimal'/>"
96 : "</element>"
97 : "<optional>"
98 : "<element name='MaxSpawnDistance' a:help='Farthest distance units can spawn away from the edge of this entity'>"
99 : "<ref name='nonNegativeDecimal'/>"
100 : "</element>"
101 137 : "</optional>";
102 : }
103 :
104 195 : void Init(const CParamNode& paramNode) override
105 : {
106 195 : if (paramNode.GetChild("Square").IsOk())
107 : {
108 90 : m_Shape = SQUARE;
109 90 : m_Size0 = paramNode.GetChild("Square").GetChild("@width").ToFixed();
110 90 : m_Size1 = paramNode.GetChild("Square").GetChild("@depth").ToFixed();
111 : }
112 105 : else if (paramNode.GetChild("Circle").IsOk())
113 : {
114 105 : m_Shape = CIRCLE;
115 105 : m_Size0 = m_Size1 = paramNode.GetChild("Circle").GetChild("@radius").ToFixed();
116 : }
117 : else
118 : {
119 : // Error - pick some default
120 0 : m_Shape = CIRCLE;
121 0 : m_Size0 = m_Size1 = entity_pos_t::FromInt(1);
122 : }
123 :
124 195 : m_Height = paramNode.GetChild("Height").ToFixed();
125 :
126 195 : if (paramNode.GetChild("MaxSpawnDistance").IsOk())
127 0 : m_MaxSpawnDistance = paramNode.GetChild("MaxSpawnDistance").ToFixed();
128 : else
129 : // Pick some default
130 195 : m_MaxSpawnDistance = entity_pos_t::FromInt(7);
131 195 : }
132 :
133 195 : void Deinit() override
134 : {
135 195 : }
136 :
137 1032 : void Serialize(ISerializer&) override
138 : {
139 : // No dynamic state to serialize
140 1032 : }
141 :
142 0 : void Deserialize(const CParamNode& paramNode, IDeserializer&) override
143 : {
144 0 : Init(paramNode);
145 0 : }
146 :
147 150 : void GetShape(EShape& shape, entity_pos_t& size0, entity_pos_t& size1, entity_pos_t& height) const override
148 : {
149 150 : shape = m_Shape;
150 150 : size0 = m_Size0;
151 150 : size1 = m_Size1;
152 150 : height = m_Height;
153 150 : }
154 :
155 0 : CFixedVector3D PickSpawnPoint(entity_id_t spawned) const override
156 : {
157 0 : PROFILE3("PickSpawnPoint");
158 :
159 : // Try to find a free space around the building's footprint.
160 : // (Note that we use the footprint, not the obstruction shape - this might be a bit dodgy
161 : // because the footprint might be inside the obstruction, but it hopefully gives us a nicer
162 : // shape.)
163 :
164 0 : const CFixedVector3D error(fixed::FromInt(-1), fixed::FromInt(-1), fixed::FromInt(-1));
165 :
166 0 : CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
167 0 : if (!cmpPosition || !cmpPosition->IsInWorld())
168 0 : return error;
169 :
170 0 : CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
171 0 : if (!cmpObstructionManager)
172 0 : return error;
173 :
174 : // If no spawned obstruction, use a positive radius to avoid division by zero errors.
175 0 : entity_pos_t spawnedRadius = entity_pos_t::FromInt(1);
176 0 : ICmpObstructionManager::tag_t spawnedTag;
177 :
178 0 : CmpPtr<ICmpObstruction> cmpSpawnedObstruction(GetSimContext(), spawned);
179 0 : if (cmpSpawnedObstruction)
180 : {
181 0 : spawnedRadius = cmpSpawnedObstruction->GetSize();
182 : // Force a positive radius to avoid division by zero errors.
183 0 : if (spawnedRadius == entity_pos_t::Zero())
184 0 : spawnedRadius = entity_pos_t::FromInt(1);
185 0 : spawnedTag = cmpSpawnedObstruction->GetObstruction();
186 : }
187 :
188 : // Get passability class from UnitMotion.
189 0 : CmpPtr<ICmpUnitMotion> cmpUnitMotion(GetSimContext(), spawned);
190 0 : if (!cmpUnitMotion)
191 0 : return error;
192 :
193 0 : pass_class_t spawnedPass = cmpUnitMotion->GetPassabilityClass();
194 0 : CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
195 0 : if (!cmpPathfinder)
196 0 : return error;
197 :
198 : // Ignore collisions with the spawned entity and entities that don't block movement.
199 0 : SkipTagRequireFlagsObstructionFilter filter(spawnedTag, ICmpObstructionManager::FLAG_BLOCK_MOVEMENT);
200 :
201 0 : CFixedVector2D initialPos = cmpPosition->GetPosition2D();
202 0 : entity_angle_t initialAngle = cmpPosition->GetRotation().Y;
203 :
204 0 : CFixedVector2D u = CFixedVector2D(fixed::Zero(), fixed::FromInt(1)).Rotate(initialAngle);
205 0 : CFixedVector2D v = u.Perpendicular();
206 :
207 : // Obstructions are squares, so multiply its radius by 2*sqrt(2) ~= 3 to determine the distance between units.
208 0 : entity_pos_t gap = spawnedRadius * 3;
209 0 : int rows = std::max(1, (m_MaxSpawnDistance / gap).ToInt_RoundToInfinity());
210 :
211 : // The first row of units will be half a gap away from the footprint.
212 0 : CFixedVector2D halfSize = m_Shape == CIRCLE ?
213 : CFixedVector2D(m_Size1 + gap / 2, m_Size0 + gap / 2) :
214 0 : CFixedVector2D((m_Size1 + gap) / 2, (m_Size0 + gap) / 2);
215 :
216 : // Figure out how many units can fit on each halfside of the rectangle.
217 : // Since 2*pi/6 ~= 1, this is also how many units can fit on a sixth of the circle.
218 0 : int distX = std::max(1, (halfSize.X / gap).ToInt_RoundToNegInfinity());
219 0 : int distY = std::max(1, (halfSize.Y / gap).ToInt_RoundToNegInfinity());
220 :
221 : // Try more spawning points for large units in case some of them are partially blocked.
222 0 : if (rows == 1)
223 : {
224 0 : distX *= 2;
225 0 : distY *= 2;
226 : }
227 :
228 : // Store the position of the spawning point within each row that's closest to the spawning angle.
229 0 : std::vector<int> offsetPoints(rows, 0);
230 :
231 0 : CmpPtr<ICmpRallyPoint> cmpRallyPoint(GetEntityHandle());
232 0 : if (cmpRallyPoint && cmpRallyPoint->HasPositions())
233 : {
234 0 : CFixedVector2D rallyPointPos = cmpRallyPoint->GetFirstPosition();
235 0 : if (m_Shape == CIRCLE)
236 : {
237 0 : entity_angle_t offsetAngle = atan2_approx(rallyPointPos.X - initialPos.X, rallyPointPos.Y - initialPos.Y) - initialAngle;
238 :
239 : // There are 6*(distX+r) points in row r, so multiply that by angle/2pi to find the offset within the row.
240 0 : for (int r = 0; r < rows; ++r)
241 0 : offsetPoints[r] = (offsetAngle * 3 * (distX + r) / fixed::Pi()).ToInt_RoundToNearest();
242 : }
243 : else
244 : {
245 0 : CFixedVector2D offsetPos = Geometry::NearestPointOnSquare(rallyPointPos - initialPos, u, v, halfSize);
246 :
247 : // Scale and convert the perimeter coordinates of the point to its offset within the row.
248 0 : int x = (offsetPos.Dot(u) * distX / halfSize.X).ToInt_RoundToNearest();
249 0 : int y = (offsetPos.Dot(v) * distY / halfSize.Y).ToInt_RoundToNearest();
250 0 : for (int r = 0; r < rows; ++r)
251 0 : offsetPoints[r] = Geometry::GetPerimeterDistance(
252 : distX + r,
253 : distY + r,
254 0 : x >= distX ? distX + r : x <= -distX ? -distX - r : x,
255 0 : y >= distY ? distY + r : y <= -distY ? -distY - r : y);
256 : }
257 : }
258 :
259 0 : for (int k = 0; k < 2 * (distX + distY + 2 * rows); k = k > 0 ? -k : 1 - k)
260 0 : for (int r = 0; r < rows; ++r)
261 : {
262 0 : CFixedVector2D pos = initialPos;
263 0 : if (m_Shape == CIRCLE)
264 : // Multiply the point by 2pi / 6*(distX+r) to get the angle.
265 0 : pos += u.Rotate(fixed::Pi() * (offsetPoints[r] + k) / (3 * (distX + r))).Multiply(halfSize.X + gap * r );
266 : else
267 : {
268 : // Convert the point to coordinates and scale.
269 0 : std::pair<int, int> p = Geometry::GetPerimeterCoordinates(distX + r, distY + r, offsetPoints[r] + k);
270 0 : pos += u.Multiply((halfSize.X + gap * r) * p.first / (distX + r)) +
271 0 : v.Multiply((halfSize.Y + gap * r) * p.second / (distY + r));
272 : }
273 :
274 0 : if (cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Y, spawnedRadius, spawnedPass) == ICmpObstruction::FOUNDATION_CHECK_SUCCESS)
275 0 : return CFixedVector3D(pos.X, fixed::Zero(), pos.Y);
276 : }
277 :
278 0 : return error;
279 0 : }
280 :
281 0 : CFixedVector3D PickSpawnPointBothPass(entity_id_t spawned) const override
282 : {
283 0 : PROFILE3("PickSpawnPointBothPass");
284 :
285 : // Try to find a free space inside and around this footprint
286 : // at the intersection between the footprint passability and the unit passability.
287 : // (useful for example for destroyed ships where the spawning point should be in the intersection
288 : // of the unit and ship passabilities).
289 : // As the overlap between these passabilities regions may be narrow, we need a small step (1 meter)
290 :
291 0 : const CFixedVector3D error(fixed::FromInt(-1), fixed::FromInt(-1), fixed::FromInt(-1));
292 :
293 0 : CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
294 0 : if (!cmpPosition || !cmpPosition->IsInWorld())
295 0 : return error;
296 :
297 0 : CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
298 0 : if (!cmpObstructionManager)
299 0 : return error;
300 :
301 0 : entity_pos_t spawnedRadius;
302 0 : ICmpObstructionManager::tag_t spawnedTag;
303 :
304 0 : CmpPtr<ICmpObstruction> cmpSpawnedObstruction(GetSimContext(), spawned);
305 0 : if (cmpSpawnedObstruction)
306 : {
307 0 : spawnedRadius = cmpSpawnedObstruction->GetSize();
308 0 : spawnedTag = cmpSpawnedObstruction->GetObstruction();
309 : }
310 : // else use zero radius
311 :
312 : // Get passability class from UnitMotion
313 0 : CmpPtr<ICmpUnitMotion> cmpUnitMotion(GetSimContext(), spawned);
314 0 : if (!cmpUnitMotion)
315 0 : return error;
316 :
317 0 : pass_class_t spawnedPass = cmpUnitMotion->GetPassabilityClass();
318 0 : CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
319 0 : if (!cmpPathfinder)
320 0 : return error;
321 :
322 : // Get the Footprint entity passability
323 0 : CmpPtr<ICmpUnitMotion> cmpEntityMotion(GetEntityHandle());
324 0 : if (!cmpEntityMotion)
325 0 : return error;
326 0 : pass_class_t entityPass = cmpEntityMotion->GetPassabilityClass();
327 :
328 0 : CFixedVector2D initialPos = cmpPosition->GetPosition2D();
329 0 : entity_angle_t initialAngle = cmpPosition->GetRotation().Y;
330 :
331 : // Max spawning distance + 1 (in meters)
332 0 : const std::int32_t maxSpawningDistance = 13;
333 :
334 0 : if (m_Shape == CIRCLE)
335 : {
336 : // Expand outwards from foundation with a fixed step of 1 meter
337 0 : for (std::int32_t dist = 0; dist <= maxSpawningDistance; ++dist)
338 : {
339 : // The spawn point should be far enough from this footprint to fit the unit, plus a little gap
340 0 : entity_pos_t clearance = spawnedRadius + entity_pos_t::FromInt(1+dist);
341 0 : entity_pos_t radius = m_Size0 + clearance;
342 :
343 : // Try equally-spaced points around the circle in alternating directions, starting from the front
344 0 : const std::int32_t numPoints = 31 + 2*dist;
345 0 : for (std::int32_t i = 0; i < (numPoints+1)/2; i = (i > 0 ? -i : 1-i)) // [0, +1, -1, +2, -2, ... (np-1)/2, -(np-1)/2]
346 : {
347 0 : entity_angle_t angle = initialAngle + (entity_angle_t::Pi()*2).Multiply(entity_angle_t::FromInt(i)/(int)numPoints);
348 :
349 0 : fixed s, c;
350 0 : sincos_approx(angle, s, c);
351 :
352 0 : CFixedVector3D pos (initialPos.X + s.Multiply(radius), fixed::Zero(), initialPos.Y + c.Multiply(radius));
353 :
354 0 : SkipTagObstructionFilter filter(spawnedTag); // ignore collisions with the spawned entity
355 0 : if (cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Z, spawnedRadius, spawnedPass) == ICmpObstruction::FOUNDATION_CHECK_SUCCESS &&
356 0 : cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Z, spawnedRadius, entityPass) == ICmpObstruction::FOUNDATION_CHECK_SUCCESS)
357 0 : return pos; // this position is okay, so return it
358 0 : }
359 : }
360 : }
361 : else
362 : {
363 0 : fixed s, c;
364 0 : sincos_approx(initialAngle, s, c);
365 :
366 : // Expand outwards from foundation with a fixed step of 1 meter
367 0 : for (std::int32_t dist = 0; dist <= maxSpawningDistance; ++dist)
368 : {
369 : // The spawn point should be far enough from this footprint to fit the unit, plus a little gap
370 0 : entity_pos_t clearance = spawnedRadius + entity_pos_t::FromInt(1+dist);
371 :
372 0 : for (std::int32_t edge = 0; edge < 4; ++edge)
373 : {
374 : // Compute the direction and length of the current edge
375 0 : CFixedVector2D dir;
376 0 : fixed sx, sy;
377 0 : switch (edge)
378 : {
379 0 : case 0:
380 0 : dir = CFixedVector2D(c, -s);
381 0 : sx = m_Size0;
382 0 : sy = m_Size1;
383 0 : break;
384 0 : case 1:
385 0 : dir = CFixedVector2D(-s, -c);
386 0 : sx = m_Size1;
387 0 : sy = m_Size0;
388 0 : break;
389 0 : case 2:
390 0 : dir = CFixedVector2D(s, c);
391 0 : sx = m_Size1;
392 0 : sy = m_Size0;
393 0 : break;
394 0 : case 3:
395 0 : dir = CFixedVector2D(-c, s);
396 0 : sx = m_Size0;
397 0 : sy = m_Size1;
398 0 : break;
399 : }
400 0 : sx = sx/2 + clearance;
401 0 : sy = sy/2 + clearance;
402 : // Try equally-spaced (1 meter) points along the edge in alternating directions, starting from the middle
403 0 : std::int32_t numPoints = 1 + 2*sx.ToInt_RoundToNearest();
404 0 : CFixedVector2D center = initialPos - dir.Perpendicular().Multiply(sy);
405 0 : for (std::int32_t i = 0; i < (numPoints+1)/2; i = (i > 0 ? -i : 1-i)) // [0, +1, -1, +2, -2, ... (np-1)/2, -(np-1)/2]
406 : {
407 0 : CFixedVector2D pos (center + dir*i);
408 :
409 0 : SkipTagObstructionFilter filter(spawnedTag); // ignore collisions with the spawned entity
410 0 : if (cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Y, spawnedRadius, spawnedPass) == ICmpObstruction::FOUNDATION_CHECK_SUCCESS &&
411 0 : cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Y, spawnedRadius, entityPass) == ICmpObstruction::FOUNDATION_CHECK_SUCCESS)
412 0 : return CFixedVector3D(pos.X, fixed::Zero(), pos.Y); // this position is okay, so return it
413 0 : }
414 : }
415 : }
416 : }
417 :
418 0 : return error;
419 0 : }
420 :
421 0 : void GetGridTiles(
422 : const entity_pos_t& tileSize,
423 : const std::uint16_t tilesW,
424 : const std::uint16_t tilesH,
425 : std::vector<std::pair<std::uint16_t, std::uint16_t>>& tiles) const override
426 : {
427 0 : tiles.clear();
428 :
429 0 : CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
430 0 : if (!cmpPosition || !cmpPosition->IsInWorld())
431 0 : return;
432 :
433 0 : const CFixedVector2D pos{cmpPosition->GetPosition2D()};
434 :
435 0 : const int centerI{Clamp((pos.X / tileSize).ToInt_RoundToNegInfinity(), 0, tilesW - 1)};
436 0 : const int centerJ{Clamp((pos.Y / tileSize).ToInt_RoundToNegInfinity(), 0, tilesH - 1)};
437 :
438 : // The tile containing the entity position is always included.
439 0 : tiles.emplace_back(static_cast<std::uint16_t>(centerI), static_cast<std::uint16_t>(centerJ));
440 :
441 : // Include every tile within halfBound of pos whose center lies inside the footprint.
442 0 : const auto addTilesWithCenterInside = [&](const CFixedVector2D& halfBound, const auto& containsPoint)
443 : {
444 0 : const int minI{std::max(0, ((pos.X - halfBound.X) / tileSize).ToInt_RoundToNegInfinity())};
445 0 : const int maxI{std::min(tilesW - 1, ((pos.X + halfBound.X) / tileSize).ToInt_RoundToNegInfinity())};
446 0 : const int minJ{std::max(0, ((pos.Y - halfBound.Y) / tileSize).ToInt_RoundToNegInfinity())};
447 0 : const int maxJ{std::min(tilesH - 1, ((pos.Y + halfBound.Y) / tileSize).ToInt_RoundToNegInfinity())};
448 :
449 0 : const entity_pos_t halfTile{tileSize / 2};
450 :
451 0 : for (int i = minI; i <= maxI; ++i)
452 0 : for (int j = minJ; j <= maxJ; ++j)
453 : {
454 0 : if (i == centerI && j == centerJ)
455 : continue;
456 :
457 0 : const CFixedVector2D tileCenter{
458 0 : entity_pos_t::FromInt(i).Multiply(tileSize) + halfTile,
459 0 : entity_pos_t::FromInt(j).Multiply(tileSize) + halfTile};
460 :
461 0 : if (containsPoint(tileCenter - pos))
462 0 : tiles.emplace_back(static_cast<std::uint16_t>(i), static_cast<std::uint16_t>(j));
463 : }
464 0 : };
465 :
466 0 : if (m_Shape == CIRCLE)
467 : {
468 0 : const entity_pos_t radius{m_Size0};
469 0 : addTilesWithCenterInside(CFixedVector2D{radius, radius}, [radius](const CFixedVector2D& point) {
470 0 : return point.CompareLength(radius) <= 0;
471 : });
472 0 : return;
473 : }
474 :
475 0 : fixed sinAngle, cosAngle;
476 0 : sincos_approx(cmpPosition->GetRotation().Y, sinAngle, cosAngle);
477 0 : const CFixedVector2D u{cosAngle, -sinAngle};
478 0 : const CFixedVector2D v{sinAngle, cosAngle};
479 0 : const CFixedVector2D halfSize{m_Size0 / 2, m_Size1 / 2};
480 :
481 0 : addTilesWithCenterInside(Geometry::GetHalfBoundingBox(u, v, halfSize), [&](const CFixedVector2D& point) {
482 0 : return Geometry::PointIsInSquare(point, u, v, halfSize);
483 : });
484 : }
485 : };
486 :
487 274 : REGISTER_COMPONENT_TYPE(Footprint)
|