载入中...
搜索中...
未找到
RTSTraffic.cpp
浏览该文件的文档.
1#include "common/Profile.h"
2#include "map/Pathfinder.h"
3#include "rts/RTS.h"
5
6#include <algorithm>
7#include <array>
8#include <limits>
9#include <map>
10#include <set>
11
12namespace eve::rts {
13namespace {
14using Cell = std::pair<int, int>;
15constexpr std::array<Cell, 4> directions{{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}};
16
17std::optional<Cell> cellAt(WorldPosition point, const NavigationGrid& grid) {
18 const double x = (static_cast<double>(point.x) - grid.originX) / grid.cellSize;
19 const double y = (static_cast<double>(point.y) - grid.originY) / grid.cellSize;
20 constexpr double limit = static_cast<double>(std::numeric_limits<int>::max()) - 4096.0;
21 if (!std::isfinite(x) || !std::isfinite(y) || std::abs(x) > limit || std::abs(y) > limit) return std::nullopt;
22 return Cell{static_cast<int>(std::lround(x)), static_cast<int>(std::lround(y))};
23}
24
25bool isNarrow(const map::Pathfinder& pathfinder, Cell cell) {
26 if (!pathfinder.isWalkable(cell.first, cell.second)) return false;
27 int exits = 0;
28 for (const auto& [dx, dy] : directions)
29 if (pathfinder.isWalkable(cell.first + dx, cell.second + dy)) ++exits;
30 return exits <= 2;
31}
32
33struct Corridor {
34 std::set<Cell> cells;
35 std::set<Cell> exits;
36};
37
38Result<Corridor> discoverCorridor(const map::Pathfinder& pathfinder, Cell seed) {
40 result.cells.insert(seed);
41 std::vector<Cell> pending{seed};
42 for (std::size_t i = 0; i < pending.size(); ++i) {
43 const auto cell = pending[i];
44 int narrowNeighbors = 0;
45 for (const auto& [dx, dy] : directions) {
46 const Cell next{cell.first + dx, cell.second + dy};
47 if (!pathfinder.isWalkable(next.first, next.second)) continue;
48 if (!isNarrow(pathfinder, next)) {
49 result.exits.insert(next);
50 continue;
51 }
52 ++narrowNeighbors;
53 if (result.cells.contains(next)) continue;
54 if (result.cells.size() >= 1024)
57 "RTS corridor exceeds the 1024-cell reservation budget", "traffic.corridor"));
58 result.cells.insert(next);
59 pending.push_back(next);
60 }
61 if (narrowNeighbors <= 1) result.exits.insert(cell);
62 }
63 return Result<Corridor>::success(std::move(result));
64}
65
66std::optional<WorldPosition> evacuationStep(const map::Pathfinder& pathfinder, const NavigationGrid& grid,
67 const Corridor& corridor, Cell exit, Cell current, WorldPosition position,
68 float radius, std::set<Cell>& parking) {
69 if (corridor.cells.contains(exit)) return std::nullopt;
70 const auto world = [&](Cell cell) {
71 return WorldPosition{grid.originX + static_cast<float>(cell.first) * grid.cellSize,
72 grid.originY + static_cast<float>(cell.second) * grid.cellSize};
73 };
74 std::optional<Cell> bay;
75 for (const auto& [dx, dy] : directions) {
76 if (!corridor.cells.contains({exit.first - dx, exit.second - dy})) continue;
77 for (int forward = 0; forward < 3 && !bay; ++forward) {
78 for (int side = 1; side <= 3 && !bay; ++side) {
79 for (int sign : {-1, 1}) {
80 const Cell candidate{exit.first + dx * forward - dy * side * sign,
81 exit.second + dy * forward + dx * side * sign};
82 if (!parking.contains(candidate) && !corridor.cells.contains(candidate) &&
83 systems_internal::isFormationSegmentClear(pathfinder, grid, world(exit), world(candidate),
84 radius)) {
85 bay = candidate;
86 break;
87 }
88 }
89 }
90 }
91 }
92 if (!bay) return std::nullopt;
93 parking.insert(*bay);
94 WorldPosition target = world(*bay);
95 if (corridor.cells.contains(current)) {
96 std::map<Cell, Cell> towardExit;
97 towardExit.emplace(exit, exit);
98 std::vector<Cell> pending{exit};
99 for (std::size_t i = 0; i < pending.size() && !towardExit.contains(current); ++i) {
100 for (const auto& [dx, dy] : directions) {
101 const Cell next{pending[i].first + dx, pending[i].second + dy};
102 if (corridor.cells.contains(next) && towardExit.emplace(next, pending[i]).second)
103 pending.push_back(next);
104 }
105 }
106 const auto next = towardExit.find(current);
107 if (next == towardExit.end()) return std::nullopt;
108 target = world(next->second);
109 }
111 target = world(current);
112 if (!systems_internal::isFormationSegmentClear(pathfinder, grid, position, target, radius)) return std::nullopt;
113 }
114 if (std::hypot(static_cast<double>(target.x) - position.x, static_cast<double>(target.y) - position.y) < 1e-4)
115 return std::nullopt;
116 return target;
117}
118} // namespace
119
121 EV_PROFILE_MODULE("rts", "TrafficReservationSystem::step");
122 if (!std::isfinite(grid.cellSize) || grid.cellSize <= 0.f || !std::isfinite(grid.originX) ||
123 !std::isfinite(grid.originY))
126 "RTS traffic grid requires finite origin and positive cell size", "traffic.grid"));
127 struct Candidate {
128 Unit::Navigation* navigation;
130 int priority;
131 Cell current;
132 Cell exit;
133 Cell next;
134 bool occupant;
136 float radius;
137 };
138 std::map<Cell, Corridor> corridors;
139 std::map<Cell, Cell> owners;
140 std::map<Cell, std::vector<Candidate>> contenders;
141 std::vector<Unit::Navigation*> recovering;
142 std::size_t processed = 0;
143 auto view =
144 ecs::View<Unit, Unit::Identity, Unit::Motion, Unit::Navigation, Unit::Orders, Unit::Containment, Unit::Crowd>();
145 for (auto it = view.begin(); it != view.end(); ++it) {
146 auto [identity, motion, navigation, orders, containment, crowd] = *it;
147 if (!identity)
149 DiagnosticCode::InvariantViolation, "RTS traffic candidate has no identity", "unit.identity"));
150 navigation->trafficWaiting = false;
151 if (navigation->trafficRecoveryTarget) recovering.push_back(navigation);
152 navigation->trafficRecoveryTarget.reset();
153 if (containment->container.isBound()) continue;
154 auto currentOrder = systems_internal::readCurrent(orders->values);
155 if (!currentOrder) return Result<std::size_t>::failure(currentOrder.status());
156 const auto& order = currentOrder.value();
157 if (!order || !systems_internal::isMovementOrder(order->kind) || navigation->unreachable) continue;
158 const bool hasPath = navigation->plannedOrderId == order->id;
159 const auto current = cellAt({motion->x, motion->y}, grid);
160 const auto goal = cellAt(hasPath ? navigation->plannedGoal : order->target, grid);
161 if (!current || !goal)
163 "RTS traffic coordinates exceed the grid index range",
164 "traffic.position"));
165 ++processed;
166 std::optional<Cell> seed;
167 if (isNarrow(pathfinder, *current)) seed = current;
168 const std::size_t begin = hasPath ? navigation->waypointIndex : navigation->waypoints.size();
169 for (std::size_t index = begin; !seed && index < navigation->waypoints.size() && index - begin < 3; ++index) {
170 const auto cell = cellAt(navigation->waypoints[index], grid);
171 if (cell && isNarrow(pathfinder, *cell)) seed = cell;
172 }
173 if (!seed && navigation->waypoints.empty()) {
174 const int gx = goal->first - current->first, gy = goal->second - current->second;
175 const bool horizontal = std::abs(gx) >= std::abs(gy);
176 const int sign = (horizontal ? gx : gy) >= 0 ? 1 : -1;
177 for (int forward = 1; forward <= 3 && !seed; ++forward) {
178 for (int side = -1; side <= 1 && !seed; ++side) {
179 const Cell candidate{current->first + (horizontal ? forward * sign : side),
180 current->second + (horizontal ? side : forward * sign)};
181 const WorldPosition point{grid.originX + float(candidate.first) * grid.cellSize,
182 grid.originY + float(candidate.second) * grid.cellSize};
183 // Pre-reserve a through portal, not an open-map corner or a corridor endpoint.
184 const int ax = horizontal ? 1 : 0, ay = horizontal ? 0 : 1;
185 const bool through = pathfinder.isWalkable(candidate.first - ax, candidate.second - ay) &&
186 pathfinder.isWalkable(candidate.first + ax, candidate.second + ay) &&
187 !pathfinder.isWalkable(candidate.first - ay, candidate.second - ax) &&
188 !pathfinder.isWalkable(candidate.first + ay, candidate.second + ax);
189 if (through && isNarrow(pathfinder, candidate) &&
190 systems_internal::isFormationSegmentClear(pathfinder, grid, {motion->x, motion->y}, point,
191 crowd->radius))
192 seed = candidate;
193 }
194 }
195 }
196 if (!seed) continue;
197 auto owner = owners.find(*seed);
198 if (owner == owners.end()) {
199 auto discovered = discoverCorridor(pathfinder, *seed);
200 if (!discovered) return Result<std::size_t>::failure(discovered.status());
201 auto corridor = std::move(discovered).takeValue();
202 const Cell key = *corridor.cells.begin();
203 for (auto cell : corridor.cells) owners.emplace(cell, key);
204 corridors.emplace(key, std::move(corridor));
205 owner = owners.find(*seed);
206 }
207 const Cell key = owner->second;
208 const auto& corridor = corridors.at(key);
209 Cell exit = *goal;
210 if (!corridor.exits.empty()) {
211 exit = *std::min_element(corridor.exits.begin(), corridor.exits.end(), [&](Cell left, Cell right) {
212 const auto distance = [&](Cell cell) {
213 return std::hypot(static_cast<double>(cell.first) - goal->first,
214 static_cast<double>(cell.second) - goal->second);
215 };
216 const double a = distance(left), b = distance(right);
217 return a != b ? a < b : left < right;
218 });
219 }
220 Cell next = navigation->waypoints.empty() ? (corridor.cells.contains(*current) ? exit : *seed) : *goal;
221 if (begin < navigation->waypoints.size()) {
222 const auto point = cellAt(navigation->waypoints[begin], grid);
223 if (point) next = *point;
224 }
225 contenders[key].push_back({navigation,
226 identity->subject,
227 navigation->movementPriority,
228 *current,
229 exit,
230 next,
231 corridor.cells.contains(*current),
232 {motion->x, motion->y},
233 crowd->radius});
234 }
235 for (auto& [key, values] : contenders) {
236 std::sort(values.begin(), values.end(), [](const Candidate& left, const Candidate& right) {
237 if (left.occupant != right.occupant) return left.occupant;
238 if (left.priority != right.priority) return left.priority > right.priority;
239 return left.subject.format() < right.subject.format();
240 });
241 const Cell direction = values.front().exit;
242 std::set<Cell> reserved;
243 std::set<Cell> parking;
244 for (auto& value : values) {
245 const bool sameDirection = value.exit == direction;
246 const bool narrowNext = isNarrow(pathfinder, value.next);
247 value.navigation->trafficWaiting = !sameDirection || (narrowNext && !reserved.insert(value.next).second);
248 if (sameDirection && !value.navigation->trafficWaiting && value.navigation->waypoints.empty())
249 value.navigation->trafficRecoveryTarget =
250 WorldPosition{grid.originX + float(value.next.first) * grid.cellSize,
251 grid.originY + float(value.next.second) * grid.cellSize};
252 if (!sameDirection)
253 value.navigation->trafficRecoveryTarget =
254 evacuationStep(pathfinder, grid, corridors.at(key), direction, value.current, value.position,
255 value.radius, parking);
256 }
257 }
258 for (auto* navigation : recovering) {
259 if (navigation->trafficRecoveryTarget) continue;
260 navigation->plannedOrderId.clear();
261 navigation->trafficWaiting = true;
262 }
263 return Result<std::size_t>::success(processed,
265}
266void RTS::setNavigationProvider(map::Pathfinder* pathfinder, NavigationGrid grid,
267 NavigationEvent unreachable) noexcept {
268 invalidateCrowdSurfaceSource();
269 auto* currentTable = ecs::current();
270 for (const auto& handle : units_) {
271 if (handle.table != currentTable) continue;
272 auto* unit = dynamic_cast<Unit*>(ecs::try_get(handle));
273 if (!unit || !unit->navigation()->trafficRecoveryTarget) continue;
274 unit->navigation()->trafficRecoveryTarget.reset();
275 unit->navigation()->trafficWaiting = false;
276 unit->navigation()->plannedOrderId.clear();
277 }
278 pathfinder_ = pathfinder;
279 navigationGrid_ = grid;
280 navigationEvent_ = std::move(unreachable);
281}
282
283} // namespace eve::rts
double y
double x
LogicalId target
int subject
Definition AnimSmr.cpp:163
std::vector< QuestEvent > pending
int priority
SQObjectPtr key
Definition ECS.cpp:155
HexVec3 left
HexVec3 right
std::int32_t second
std::int32_t first
std::array< float, 3 > position
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
std::vector< std::int32_t > order
std::shared_ptr< OceanGpuSpectrum > owner
glm::dvec3 dx
OceanSprayView view
size_t directions
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
PrimitiveHandle handle
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
std::set< std::string > values
Object::Ptr value
std::set< Cell > exits
RTS module owner and phase-one composition profile entry point.
RoadLaneDirection direction
size_t begin
double current
float dy
Definition Shadow.cpp:151
Cell cell
TacticalUnit * unit
int limit
Definition TreeMesh.cpp:166
uint32_t seed
Definition TreeMesh.cpp:276
uint32_t index
V forward
glm::vec3 point
uint64_t identity
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
Strong, domain-neutral reference to a runtime subject.
Definition SubjectRef.h:26
Pathfinding facade. Single-agent: A*. Group (same goal): Flow Field + follow. Grid/topology internals...
Definition Pathfinder.h:62
bool isWalkable(int x, int y) const
True when walkable.
static Result< std::size_t > step(const map::Pathfinder &pathfinder, const NavigationGrid &grid)
Reserve corridor direction, then next narrow cells, by occupancy, priority and stable identity.
RTS unit domain root.
Definition RTSTypes.h:501
@ Cell
A cell was removed; the out-parameter holds it.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
constexpr uint32_t Corridor
Definition Semantic.h:15
Result< std::optional< OrderRecord > > readCurrent(OrderComponent &orders)
EVENGINE_API_DOMAINS bool isFormationSegmentClear(const map::Pathfinder &pathfinder, const NavigationGrid &grid, WorldPosition from, WorldPosition to, float radius)
std::function< void(Unit &, const OrderRecord &)> NavigationEvent
Notification emitted once when a newly planned order has no canonical map route.
Definition RTSSystems.h:282
WidgetDesc grid(int columns, std::vector< WidgetDesc > children, std::string id)
Fixed-column grid; children are placed in source order.
Definition Widget.cpp:878
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
World/grid conversion used when an RTS composition consumes a canonical map Pathfinder.
Definition RTSSystems.h:265
RTS projection of a canonical map path; the map provider remains the grid authority.
Definition RTSTypes.h:578
Two-dimensional deterministic RTS world position.
Definition RTSTypes.h:53