载入中...
搜索中...
未找到
Pathfinder.cpp
浏览该文件的文档.
1#include "map/Pathfinder.h"
2#include "common/Exception.h"
3
5
6#include "common/Diagnostic.h"
7
8#include <algorithm>
9#include <cmath>
10#include <cstdint>
11#include <functional>
12#include <limits>
13#include <memory>
14#include <queue>
15#include <tuple>
16#include <unordered_set>
17#include <utility>
18#include <vector>
19
20namespace eve::map {
21namespace {
22
23constexpr float kInf = std::numeric_limits<float>::infinity();
24constexpr float kSqrt2 = 1.41421356237f;
25
26enum class Topology { Ortho4, Ortho8, Hex };
27
28using NeighborFn = std::function<void(int nx, int ny, float moveCost)>;
29
30Topology parseTopology(const std::string &name, Topology fallback) {
31 if (name == "ortho4" || name == "orthogonal4" || name == "4") return Topology::Ortho4;
32 if (name == "ortho8" || name == "orthogonal8" || name == "8") return Topology::Ortho8;
33 if (name == "hex" || name == "hexagonal" || name == "staggered") return Topology::Hex;
34 if (name == "auto") return fallback;
35 return fallback;
36}
37
38const char *topologyName(Topology t) {
39 switch (t) {
40 case Topology::Ortho4:
41 return "ortho4";
42 case Topology::Ortho8:
43 return "ortho8";
44 case Topology::Hex:
45 return "hex";
46 }
47 return "ortho4";
48}
49
50Topology topologyFromOrientation(MapOrientation orientation, bool preferDiagonal) {
51 switch (orientation) {
54 return Topology::Hex;
57 default:
58 return preferDiagonal ? Topology::Ortho8 : Topology::Ortho4;
59 }
60}
61
62void forEachNeighbor(Topology topology, int x, int y, bool staggerAxisY, bool staggerOdd,
63 const NeighborFn &fn) {
64 if (!fn) return;
65 switch (topology) {
66 case Topology::Ortho4: {
67 static const int dx[4] = {1, -1, 0, 0};
68 static const int dy[4] = {0, 0, 1, -1};
69 for (int i = 0; i < 4; ++i) fn(x + dx[i], y + dy[i], 1.f);
70 break;
71 }
72 case Topology::Ortho8: {
73 static const int dx[8] = {1, -1, 0, 0, 1, 1, -1, -1};
74 static const int dy[8] = {0, 0, 1, -1, 1, -1, 1, -1};
75 for (int i = 0; i < 8; ++i) {
76 const float c = (i < 4) ? 1.f : kSqrt2;
77 fn(x + dx[i], y + dy[i], c);
78 }
79 break;
80 }
81 case Topology::Hex: {
82 if (staggerAxisY) {
83 const bool rowOdd = ((y & 1) != 0);
84 const bool shifted = staggerOdd ? rowOdd : !rowOdd;
85 if (shifted) {
86 fn(x + 1, y, 1.f);
87 fn(x - 1, y, 1.f);
88 fn(x, y - 1, 1.f);
89 fn(x + 1, y - 1, 1.f);
90 fn(x, y + 1, 1.f);
91 fn(x + 1, y + 1, 1.f);
92 } else {
93 fn(x + 1, y, 1.f);
94 fn(x - 1, y, 1.f);
95 fn(x - 1, y - 1, 1.f);
96 fn(x, y - 1, 1.f);
97 fn(x - 1, y + 1, 1.f);
98 fn(x, y + 1, 1.f);
99 }
100 } else {
101 const bool colOdd = ((x & 1) != 0);
102 const bool shifted = staggerOdd ? colOdd : !colOdd;
103 if (shifted) {
104 fn(x, y + 1, 1.f);
105 fn(x, y - 1, 1.f);
106 fn(x - 1, y, 1.f);
107 fn(x - 1, y + 1, 1.f);
108 fn(x + 1, y, 1.f);
109 fn(x + 1, y + 1, 1.f);
110 } else {
111 fn(x, y + 1, 1.f);
112 fn(x, y - 1, 1.f);
113 fn(x - 1, y - 1, 1.f);
114 fn(x - 1, y, 1.f);
115 fn(x + 1, y - 1, 1.f);
116 fn(x + 1, y, 1.f);
117 }
118 }
119 break;
120 }
121 }
122}
123
124float heuristic(Topology topology, int x0, int y0, int x1, int y1) {
125 const int dx = std::abs(x1 - x0);
126 const int dy = std::abs(y1 - y0);
127 switch (topology) {
128 case Topology::Ortho4:
129 return float(dx + dy);
130 case Topology::Ortho8:
131 return float(std::max(dx, dy)) + (kSqrt2 - 1.f) * float(std::min(dx, dy));
132 case Topology::Hex: {
133 auto toCube = [](int x, int y) {
134 const int q = x - (y - (y & 1)) / 2;
135 const int r = y;
136 const int s = -q - r;
137 return std::tuple<int, int, int>{q, r, s};
138 };
139 auto [q0, r0, s0] = toCube(x0, y0);
140 auto [q1, r1, s1] = toCube(x1, y1);
141 return float(std::max({std::abs(q0 - q1), std::abs(r0 - r1), std::abs(s0 - s1)}));
142 }
143 }
144 return float(dx + dy);
145}
146
148struct Grid {
149 int width = 0;
150 int height = 0;
151 TileLayer *layer = nullptr;
152 uint64_t layerRevision = 0;
153 Topology topology = Topology::Ortho4;
154 bool topologyManual = false;
155 bool diagonal = false;
156 bool blockEmpty = true;
157 bool staggerAxisY = true;
158 bool staggerOdd = true;
159 bool dirty = true;
160 std::vector<float> cost; // ≤0 => blocked
161 std::vector<uint8_t> enterMask;
162 std::vector<uint8_t> exitMask;
163 std::unordered_set<uint32_t> blockedGids;
164
165 int index(int x, int y) const { return y * width + x; }
166 bool inBounds(int x, int y) const { return x >= 0 && y >= 0 && x < width && y < height; }
167
168 void resize(int w, int h) {
169 width = w > 0 ? w : 0;
170 height = h > 0 ? h : 0;
171 cost.assign(size_t(width * height), 1.f);
172 enterMask.assign(size_t(width * height), 0xff);
173 exitMask.assign(size_t(width * height), 0xff);
174 dirty = true;
175 }
176
177 void applyAutoTopologyFromLayer() {
178 if (!layer) return;
179 topology = topologyFromOrientation(layer->config()->orientation, diagonal);
180 }
181
182 void bindLayer(TileLayer *l) {
183 layer = l;
184 if (!layer) return;
185 auto cfg = layer->config();
186 resize(cfg->mapW, cfg->mapH);
187 staggerAxisY = cfg->staggerAxis == StaggerAxis::Y;
188 staggerOdd = cfg->staggerIndex == StaggerIndex::Odd;
189 if (!topologyManual) applyAutoTopologyFromLayer();
190 syncFromLayer();
191 }
192
193 void clearLayer() { layer = nullptr; }
194
195 void syncFromLayer() {
196 if (!layer) return;
197 auto cfg = layer->config();
198 auto tiles = layer->tiles();
199 if (cfg->mapW != width || cfg->mapH != height) resize(cfg->mapW, cfg->mapH);
200 staggerAxisY = cfg->staggerAxis == StaggerAxis::Y;
201 staggerOdd = cfg->staggerIndex == StaggerIndex::Odd;
202 if (!topologyManual) applyAutoTopologyFromLayer();
203
204 const auto tileset = layer->tileset();
205 const int n = width * height;
206 for (int i = 0; i < n; ++i) {
207 const uint32_t gid = (i < int(tiles->gids.size())) ? tileGid(tiles->gids[size_t(i)]) : 0u;
208 bool blocked = false;
209 float movementCost = 1.f;
210 uint8_t cellEnterMask = 0xff;
211 uint8_t cellExitMask = 0xff;
212 if (blockEmpty && gid == 0u) blocked = true;
213 if (blockedGids.count(gid)) blocked = true;
214 if (gid != 0u) {
215 const auto visual = std::find_if(
216 tileset->visuals.begin(), tileset->visuals.end(),
217 [gid](const TileLayer::Tileset::Visual &candidate) { return candidate.gid == int(gid); });
218 if (visual != tileset->visuals.end()) {
219 blocked = blocked || !visual->walkable;
220 movementCost = std::max(0.001f, visual->cost);
221 cellEnterMask = visual->enterMask;
222 cellExitMask = visual->exitMask;
223 }
224 }
225 cost[size_t(i)] = blocked ? 0.f : movementCost;
226 enterMask[size_t(i)] = cellEnterMask;
227 exitMask[size_t(i)] = cellExitMask;
228 }
229 layerRevision = tiles->revision;
230 dirty = true;
231 }
232
233 void setTopology(const std::string &name) {
234 if (name == "auto") {
235 topologyManual = false;
236 if (layer) applyAutoTopologyFromLayer();
237 else topology = diagonal ? Topology::Ortho8 : Topology::Ortho4;
238 } else {
239 topologyManual = true;
240 topology = parseTopology(name, topology);
241 }
242 dirty = true;
243 }
244
245 void setDiagonal(bool enable) {
246 diagonal = enable;
247 if (!topologyManual && layer) applyAutoTopologyFromLayer();
248 else if (!topologyManual) topology = diagonal ? Topology::Ortho8 : Topology::Ortho4;
249 dirty = true;
250 }
251
252 void blockGid(int gid) {
253 if (gid < 0) return;
254 blockedGids.insert(uint32_t(gid));
255 dirty = true;
256 if (layer) syncFromLayer();
257 }
258
259 void unblockGid(int gid) {
260 if (gid < 0) return;
261 blockedGids.erase(uint32_t(gid));
262 dirty = true;
263 if (layer) syncFromLayer();
264 }
265
266 void clearBlockedGids() {
267 blockedGids.clear();
268 dirty = true;
269 if (layer) syncFromLayer();
270 }
271
272 void setBlockEmpty(bool enable) {
273 blockEmpty = enable;
274 dirty = true;
275 if (layer) syncFromLayer();
276 }
277
278 bool isWalkable(int x, int y) const {
279 if (!inBounds(x, y)) return false;
280 return cost[size_t(index(x, y))] > 0.f;
281 }
282
283 void setBlocked(int x, int y, bool blocked) {
284 if (!inBounds(x, y)) return;
285 cost[size_t(index(x, y))] = blocked ? 0.f : 1.f;
286 dirty = true;
287 }
288
289 void setCellCost(int x, int y, float c) {
290 if (!inBounds(x, y)) return;
291 cost[size_t(index(x, y))] = c;
292 dirty = true;
293 }
294
295 float getCellCost(int x, int y) const {
296 if (!inBounds(x, y)) return 0.f;
297 return cost[size_t(index(x, y))];
298 }
299
300 bool canTraverseCardinal(int x, int y, int nx, int ny) const {
301 if (!isWalkable(x, y) || !isWalkable(nx, ny)) return false;
302 uint8_t direction = 0;
303 uint8_t opposite = 0;
304 if (nx == x && ny == y - 1) {
305 direction = 1;
306 opposite = 4;
307 } else if (nx == x + 1 && ny == y) {
308 direction = 2;
309 opposite = 8;
310 } else if (nx == x && ny == y + 1) {
311 direction = 4;
312 opposite = 1;
313 } else if (nx == x - 1 && ny == y) {
314 direction = 8;
315 opposite = 2;
316 } else {
317 return true;
318 }
319 return (exitMask[size_t(index(x, y))] & direction) != 0 && (enterMask[size_t(index(nx, ny))] & opposite) != 0;
320 }
321
322 void forEachWalkableNeighbor(int x, int y, const NeighborFn &fn) const {
323 if (!fn || !inBounds(x, y)) return;
324 forEachNeighbor(topology, x, y, staggerAxisY, staggerOdd, [&](int nx, int ny, float moveCost) {
325 if (!isWalkable(nx, ny)) return;
326 if (!canTraverseCardinal(x, y, nx, ny)) return;
327 if (topology == Topology::Ortho8) {
328 const int dx = nx - x;
329 const int dy = ny - y;
330 if (dx != 0 && dy != 0) {
331 if (!canTraverseCardinal(x, y, x + dx, y) || !canTraverseCardinal(x, y, x, y + dy)) return;
332 }
333 }
334 fn(nx, ny, moveCost * getCellCost(nx, ny));
335 });
336 }
337};
338
339struct HeapNode {
340 float f = 0.f;
341 int idx = 0;
342 bool operator>(const HeapNode &o) const { return f > o.f; }
343};
344
345} // namespace
346
348 bool staggerAxisY = true, staggerOdd = true;
349 int width = 0, height = 0;
350 std::uint64_t revision = 1;
352 std::vector<float> costs;
353 std::vector<std::uint8_t> enterMasks, exitMasks;
354};
355int NavigationGridSnapshot::width() const noexcept { return data_ ? data_->width : 0; }
356int NavigationGridSnapshot::height() const noexcept { return data_ ? data_->height : 0; }
357std::uint64_t NavigationGridSnapshot::revision() const noexcept { return data_ ? data_->revision : 0; }
359 return data_ ? data_->topology : NavigationTopology::Ortho4;
360}
361bool NavigationGridSnapshot::isStaggerAxisY() const noexcept { return !data_ || data_->staggerAxisY; }
362bool NavigationGridSnapshot::isStaggerOdd() const noexcept { return !data_ || data_->staggerOdd; }
363std::span<const float> NavigationGridSnapshot::costs() const noexcept {
364 return data_ ? std::span<const float>(data_->costs) : std::span<const float>{};
365}
366std::span<const std::uint8_t> NavigationGridSnapshot::enterMasks() const noexcept {
367 return data_ ? std::span<const std::uint8_t>(data_->enterMasks) : std::span<const std::uint8_t>{};
368}
369std::span<const std::uint8_t> NavigationGridSnapshot::exitMasks() const noexcept {
370 return data_ ? std::span<const std::uint8_t>(data_->exitMasks) : std::span<const std::uint8_t>{};
371}
372
382
383Pathfinder::Pathfinder() : impl_(std::make_unique<Impl>()) {}
384
386
388
389Pathfinder::~Pathfinder() = default;
390Pathfinder::Pathfinder(Pathfinder &&) noexcept = default;
391Pathfinder &Pathfinder::operator=(Pathfinder &&) noexcept = default;
392
393NavigationChangeStamp Pathfinder::getNavigationChangeStamp() const noexcept {
394 auto *layer = impl_->grid.layer;
395 return {impl_->changes, layer ? layer->tiles()->revision : 0};
396}
397
400 impl_->grid.bindLayer(layer);
401}
402
405 impl_->grid.clearLayer();
406 impl_->grid.resize(width, height);
407}
408
409void Pathfinder::setTopology(const std::string &name) {
411 impl_->grid.setTopology(name);
412}
413
414std::string Pathfinder::getTopology() const { return topologyName(impl_->grid.topology); }
415
416void Pathfinder::setDiagonal(bool enable) {
418 impl_->grid.setDiagonal(enable);
419}
420
421bool Pathfinder::getDiagonal() const { return impl_->grid.diagonal; }
422
423void Pathfinder::blockGid(int gid) {
425 impl_->grid.blockGid(gid);
426}
427
430 impl_->grid.unblockGid(gid);
431}
432
435 impl_->grid.clearBlockedGids();
436}
437
438void Pathfinder::setBlockEmpty(bool enable) {
440 impl_->grid.setBlockEmpty(enable);
441}
442
443bool Pathfinder::getBlockEmpty() const { return impl_->grid.blockEmpty; }
444
445void Pathfinder::setBlocked(int x, int y, bool blocked) {
447 impl_->grid.setBlocked(x, y, blocked);
448}
449
450bool Pathfinder::isWalkable(int x, int y) const { return impl_->grid.isWalkable(x, y); }
451
452void Pathfinder::setCellCost(int x, int y, float cost) {
454 impl_->grid.setCellCost(x, y, cost);
455}
456
457float Pathfinder::getCellCost(int x, int y) const { return impl_->grid.getCellCost(x, y); }
458
461 impl_->grid.syncFromLayer();
462}
463
465 if (impl_->changes == std::numeric_limits<std::uint64_t>::max())
466 throw eve::Exception("Navigation input revision exhausted");
467 ++impl_->changes;
468 impl_->hasCachedField = false;
469 impl_->cachedField.clear();
470}
471
472namespace {
473
474bool ensureSynced(Grid &grid) {
475 if (grid.layer && (grid.dirty || grid.layerRevision != grid.layer->tiles()->revision))
476 grid.syncFromLayer();
477 return grid.width > 0 && grid.height > 0;
478}
479
480FlowField *buildFlowFieldUncached(Grid &grid, int gx, int gy) {
481 auto *field = new FlowField();
482 if (!ensureSynced(grid) || !grid.isWalkable(gx, gy)) {
483 field->resize(grid.width, grid.height);
484 field->setGoal(gx, gy);
485 return field;
486 }
487
488 const int w = grid.width;
489 const int h = grid.height;
490 field->resize(w, h);
491 field->setGoal(gx, gy);
492
493 const auto idx = [w](int x, int y) { return y * w + x; };
494 std::vector<float> dist(size_t(w * h), kInf);
495 std::priority_queue<HeapNode, std::vector<HeapNode>, std::greater<HeapNode>> open;
496
497 dist[size_t(idx(gx, gy))] = 0.f;
498 field->setCost(gx, gy, 0.f);
499 field->setNext(gx, gy, gx, gy);
500 open.push(HeapNode{0.f, idx(gx, gy)});
501
502 while (!open.empty()) {
503 const HeapNode cur = open.top();
504 open.pop();
505 if (cur.f > dist[size_t(cur.idx)]) continue;
506 const int cx = cur.idx % w;
507 const int cy = cur.idx / w;
508 const float enterCur = grid.getCellCost(cx, cy);
509 forEachNeighbor(grid.topology, cx, cy, grid.staggerAxisY, grid.staggerOdd,
510 [&](int nx, int ny, float moveCost) {
511 if (!grid.isWalkable(nx, ny)) return;
512 if (grid.topology == Topology::Ortho8) {
513 const int dx = nx - cx;
514 const int dy = ny - cy;
515 if (dx != 0 && dy != 0) {
516 if (!grid.isWalkable(cx + dx, cy) || !grid.isWalkable(cx, cy + dy))
517 return;
518 }
519 }
520 const int ni = idx(nx, ny);
521 const float tentative = dist[size_t(cur.idx)] + moveCost * enterCur;
522 if (tentative + 1e-6f >= dist[size_t(ni)]) return;
523 dist[size_t(ni)] = tentative;
524 field->setCost(nx, ny, tentative);
525 field->setNext(nx, ny, cx, cy);
526 open.push(HeapNode{tentative, ni});
527 });
528 }
529 return field;
530}
531
532} // namespace
533
534Result<NavigationGridSnapshot> Pathfinder::captureNavigationGrid() try {
535 if (!impl_)
537 Diagnostic::error(DiagnosticCode::Conflict, "Moved-from Pathfinder", "navigationGrid"));
538 Grid staged = impl_->grid;
539 if (!ensureSynced(staged) || std::int64_t(staged.width) * staged.height > 4 * 1024 * 1024)
541 DiagnosticCode::InvalidArgument, "Unconfigured or oversized navigation grid", "navigationGrid"));
542 const auto count = static_cast<std::size_t>(std::int64_t(staged.width) * staged.height);
543 if (staged.cost.size() != count || staged.enterMask.size() != count || staged.exitMask.size() != count)
545 DiagnosticCode::PreconditionViolation, "Inconsistent navigation grid buffers", "navigationGrid"));
546 for (const float cost : staged.cost)
547 if (!std::isfinite(cost))
549 Diagnostic::error(DiagnosticCode::InvalidArgument, "Nonfinite map navigation cost", "navigationGrid"));
550 const auto topology = static_cast<NavigationTopology>(staged.topology);
551 const bool axisY = topology != NavigationTopology::Hex || staged.staggerAxisY;
552 const bool odd = topology != NavigationTopology::Hex || staged.staggerOdd;
553 const auto &previous = impl_->lastCapture.data_;
554 if (previous && previous->width == staged.width && previous->height == staged.height &&
555 previous->topology == topology && previous->staggerAxisY == axisY && previous->staggerOdd == odd &&
556 previous->costs == staged.cost && previous->enterMasks == staged.enterMask &&
557 previous->exitMasks == staged.exitMask)
559 if (previous && previous->revision == std::numeric_limits<std::uint64_t>::max())
561 Diagnostic::error(DiagnosticCode::Conflict, "Navigation capture revision exhausted", "navigationGrid"));
562 auto data = std::make_shared<NavigationGridSnapshot::Data>();
563 data->width = staged.width;
564 data->height = staged.height;
565 data->topology = topology;
566 data->revision = previous ? previous->revision + 1 : 1;
567 data->staggerAxisY = axisY;
568 data->staggerOdd = odd;
569 data->costs = std::move(staged.cost);
570 data->enterMasks = std::move(staged.enterMask);
571 data->exitMasks = std::move(staged.exitMask);
573 result.data_ = std::move(data);
574 impl_->lastCapture = result;
576} catch (const std::exception &error) {
578 Diagnostic::error(DiagnosticCode::Failed, error.what(), "navigationGrid"));
579}
580
581
582Path *Pathfinder::findPath(int sx, int sy, int gx, int gy) {
583 return findPath(sx, sy, gx, gy, {});
584}
585
586namespace {
587
588struct CellHash {
589 std::size_t operator()(const std::pair<int, int> &cell) const noexcept {
590 return (static_cast<std::size_t>(static_cast<std::uint32_t>(cell.first)) << 32) ^
591 static_cast<std::uint32_t>(cell.second);
592 }
593};
594
595Result<bool> keepsPathOpenWithBlocks(Pathfinder &finder, Grid &grid, int sx, int sy, int gx, int gy,
596 const std::unordered_set<std::pair<int, int>, CellHash> &blocks) {
597 if (!ensureSynced(grid) || grid.width <= 0 || grid.height <= 0) {
599 "pathfinder grid is empty", "pathfinder.grid", {}, "map"));
600 }
601 for (const auto &cell : blocks) {
602 if (cell.first < 0 || cell.second < 0 || cell.first >= grid.width || cell.second >= grid.height) {
604 "temporary block cell is out of bounds",
605 "pathfinder.block", {}, "map"));
606 }
607 if ((cell.first == sx && cell.second == sy) || (cell.first == gx && cell.second == gy))
608 return Result<bool>::success(false);
609 }
610 if (!grid.isWalkable(sx, sy) || !grid.isWalkable(gx, gy)) return Result<bool>::success(false);
611 std::unique_ptr<Path> path(finder.findPath(sx, sy, gx, gy, [&blocks](int x, int y) {
612 return blocks.count({x, y}) ? kInf : 0.f;
613 }));
614 return Result<bool>::success(path && path->getLength() > 0);
615}
616
617} // namespace
618
619Result<bool> Pathfinder::keepsPathOpen(int sx, int sy, int gx, int gy, int blockX, int blockY) {
620 std::unordered_set<std::pair<int, int>, CellHash> blocks;
621 blocks.emplace(blockX, blockY);
622 return keepsPathOpenWithBlocks(*this, impl_->grid, sx, sy, gx, gy, blocks);
623}
624
625Result<bool> Pathfinder::keepsPathOpenFootprint(int sx, int sy, int gx, int gy, int originX, int originY,
626 int footprintW, int footprintH) {
627 if (footprintW <= 0 || footprintH <= 0) {
629 "footprint size must be positive",
630 "pathfinder.footprint", {}, "map"));
631 }
632 std::unordered_set<std::pair<int, int>, CellHash> blocks;
633 blocks.reserve(static_cast<std::size_t>(footprintW) * static_cast<std::size_t>(footprintH));
634 for (int y = 0; y < footprintH; ++y)
635 for (int x = 0; x < footprintW; ++x) blocks.emplace(originX + x, originY + y);
636 return keepsPathOpenWithBlocks(*this, impl_->grid, sx, sy, gx, gy, blocks);
637}
638
639Path *Pathfinder::findPath(int sx, int sy, int gx, int gy,
640 const std::function<float(int, int)> &entryPenalty) {
641 auto *path = new Path();
642 Grid &grid = impl_->grid;
643 if (!ensureSynced(grid)) return path;
644 if (!grid.isWalkable(sx, sy) || !grid.isWalkable(gx, gy)) return path;
645 if (sx == gx && sy == gy) {
646 path->add(sx, sy);
647 path->setTotalCost(0.f);
648 return path;
649 }
650
651 const int w = grid.width;
652 const int n = w * grid.height;
653 const auto idx = [w](int x, int y) { return y * w + x; };
654
655 std::vector<float> gScore(size_t(n), kInf);
656 std::vector<int> parent(size_t(n), -1);
657 std::vector<uint8_t> closed(size_t(n), 0);
658
659 std::priority_queue<HeapNode, std::vector<HeapNode>, std::greater<HeapNode>> open;
660 const int start = idx(sx, sy);
661 const int goal = idx(gx, gy);
662 gScore[size_t(start)] = 0.f;
663 open.push(HeapNode{heuristic(grid.topology, sx, sy, gx, gy), start});
664
665 bool found = false;
666 while (!open.empty()) {
667 const HeapNode cur = open.top();
668 open.pop();
669 if (closed[size_t(cur.idx)]) continue;
670 closed[size_t(cur.idx)] = 1;
671 if (cur.idx == goal) {
672 found = true;
673 break;
674 }
675 const int cx = cur.idx % w;
676 const int cy = cur.idx / w;
677 grid.forEachWalkableNeighbor(cx, cy, [&](int nx, int ny, float edgeCost) {
678 const int ni = idx(nx, ny);
679 if (closed[size_t(ni)]) return;
680 float penalty = entryPenalty ? entryPenalty(nx, ny) : 0.0f;
681 if (!std::isfinite(penalty)) return;
682 penalty = std::max(0.0f, penalty);
683 const float tentative = gScore[size_t(cur.idx)] + edgeCost + penalty;
684 if (tentative >= gScore[size_t(ni)]) return;
685 gScore[size_t(ni)] = tentative;
686 parent[size_t(ni)] = cur.idx;
687 open.push(HeapNode{tentative + heuristic(grid.topology, nx, ny, gx, gy), ni});
688 });
689 }
690
691 if (!found) return path;
692
693 int cur = goal;
694 while (cur != -1) {
695 path->add(cur % w, cur / w);
696 if (cur == start) break;
697 cur = parent[size_t(cur)];
698 }
699 path->reverse();
700 path->setTotalCost(gScore[size_t(goal)]);
701 return path;
702}
703
704FlowField *Pathfinder::buildFlowField(int gx, int gy) {
705 Grid &grid = impl_->grid;
706 if (!ensureSynced(grid)) {
707 auto *empty = new FlowField();
708 empty->resize(0, 0);
709 empty->setGoal(gx, gy);
710 return empty;
711 }
712
713 if (impl_->hasCachedField && !grid.dirty && impl_->cachedGoalX == gx && impl_->cachedGoalY == gy &&
714 impl_->cachedField.getWidth() == grid.width &&
715 impl_->cachedField.getHeight() == grid.height) {
716 auto *copy = new FlowField();
717 *copy = impl_->cachedField;
718 return copy;
719 }
720
721 FlowField *field = buildFlowFieldUncached(grid, gx, gy);
722 impl_->cachedField = *field;
723 impl_->cachedGoalX = gx;
724 impl_->cachedGoalY = gy;
725 impl_->hasCachedField = true;
726 grid.dirty = false;
727 return field;
728}
729
730Path *Pathfinder::followFlow(FlowField *field, int sx, int sy) {
731 auto *path = new Path();
732 Grid &grid = impl_->grid;
733 if (!field || !ensureSynced(grid)) return path;
734 if (!field->isReachable(sx, sy)) return path;
735
736 const int gx = field->getGoalX();
737 const int gy = field->getGoalY();
738 const int maxSteps = grid.width * grid.height + 2;
739 int x = sx;
740 int y = sy;
741 path->add(x, y);
742 float total = 0.f;
743 for (int step = 0; step < maxSteps; ++step) {
744 if (x == gx && y == gy) break;
745 const int nx = field->nextX(x, y);
746 const int ny = field->nextY(x, y);
747 if (nx == x && ny == y) break;
748 const float c0 = field->costAt(x, y);
749 const float c1 = field->costAt(nx, ny);
750 if (c0 < kInf && c1 < kInf && c0 >= c1) total += (c0 - c1);
751 x = nx;
752 y = ny;
753 path->add(x, y);
754 }
755 path->setTotalCost(total);
756 if (path->getLength() > 0) {
757 const int lx = path->getX(path->getLength() - 1);
758 const int ly = path->getY(path->getLength() - 1);
759 if (lx != gx || ly != gy) path->clear();
760 }
761 return path;
762}
763
764Path *Pathfinder::findGroupPath(int sx, int sy, int gx, int gy) {
765 Grid &grid = impl_->grid;
766 if (!ensureSynced(grid)) return new Path();
767 if (!impl_->hasCachedField || grid.dirty || impl_->cachedGoalX != gx || impl_->cachedGoalY != gy ||
768 impl_->cachedField.getWidth() != grid.width ||
769 impl_->cachedField.getHeight() != grid.height) {
770 FlowField *tmp = buildFlowFieldUncached(grid, gx, gy);
771 impl_->cachedField = *tmp;
772 delete tmp;
773 impl_->cachedGoalX = gx;
774 impl_->cachedGoalY = gy;
775 impl_->hasCachedField = true;
776 grid.dirty = false;
777 }
778 return followFlow(&impl_->cachedField, sx, sy);
779}
780
781// --- Path / FlowField (same TU; keep export surface small on Windows) ---
782
783void Path::clear() {
784 cells_.clear();
785 totalCost_ = 0.f;
786}
787
788void Path::add(int x, int y) { cells_.push_back(Cell{x, y}); }
789
790void Path::reverse() {
791 for (size_t i = 0, j = cells_.size(); i + 1 < j; ++i, --j) std::swap(cells_[i], cells_[j - 1]);
792}
793
794int Path::getLength() const { return int(cells_.size()); }
795
796int Path::getX(int index) const {
797 if (index < 0 || index >= int(cells_.size())) return 0;
798 return cells_[size_t(index)].x;
799}
800
801int Path::getY(int index) const {
802 if (index < 0 || index >= int(cells_.size())) return 0;
803 return cells_[size_t(index)].y;
804}
805
806float Path::getTotalCost() const { return totalCost_; }
807
808void Path::setTotalCost(float cost) { totalCost_ = cost; }
809
810void FlowField::clear() {
811 width_ = height_ = 0;
812 goalX_ = goalY_ = 0;
813 cost_.clear();
814 nextX_.clear();
815 nextY_.clear();
816}
817
818void FlowField::resize(int width, int height) {
819 width_ = width > 0 ? width : 0;
820 height_ = height > 0 ? height : 0;
821 const int n = width_ * height_;
822 cost_.assign(size_t(n), kUnreachable);
823 nextX_.assign(size_t(n), 0);
824 nextY_.assign(size_t(n), 0);
825 for (int y = 0; y < height_; ++y) {
826 for (int x = 0; x < width_; ++x) {
827 const int i = index(x, y);
828 nextX_[size_t(i)] = x;
829 nextY_[size_t(i)] = y;
830 }
831 }
832}
833
834void FlowField::setGoal(int x, int y) {
835 goalX_ = x;
836 goalY_ = y;
837}
838
839bool FlowField::inBounds(int x, int y) const {
840 return x >= 0 && y >= 0 && x < width_ && y < height_;
841}
842
843float FlowField::costAt(int x, int y) const {
844 if (!inBounds(x, y)) return kUnreachable;
845 return cost_[size_t(index(x, y))];
846}
847
848void FlowField::setCost(int x, int y, float cost) {
849 if (!inBounds(x, y)) return;
850 cost_[size_t(index(x, y))] = cost;
851}
852
853int FlowField::nextX(int x, int y) const {
854 if (!inBounds(x, y)) return x;
855 return nextX_[size_t(index(x, y))];
856}
857
858int FlowField::nextY(int x, int y) const {
859 if (!inBounds(x, y)) return y;
860 return nextY_[size_t(index(x, y))];
861}
862
863void FlowField::setNext(int x, int y, int nx, int ny) {
864 if (!inBounds(x, y)) return;
865 const int i = index(x, y);
866 nextX_[size_t(i)] = nx;
867 nextY_[size_t(i)] = ny;
868}
869
870bool FlowField::isReachable(int x, int y) const {
871 const float c = costAt(x, y);
872 return c < kUnreachable && c >= 0.f;
873}
874
875} // namespace eve::map
double y
double x
Duration start
float w
Definition AnimClip.cpp:738
const std::string & s
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
Stable, structured diagnostics shared by engine modules.
eve::resource::CostSpec cost
std::string name
Definition ECS.cpp:154
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
double r
std::int32_t c
int h
std::uint32_t height
std::uint32_t width
const ColourScope * parent
Poco::JSON::Object::Ptr result
glm::dvec3 dx
std::shared_ptr< const OceanSprayFrame > previous
std::string error
Definition Package.cpp:174
Topology topology
bool staggerOdd
std::unordered_set< uint32_t > blockedGids
std::vector< uint8_t > exitMask
bool topologyManual
bool diagonal
bool staggerAxisY
uint64_t layerRevision
bool blockEmpty
TileLayer * layer
bool dirty
std::vector< uint8_t > enterMask
int idx
float f
std::string path
Definition PlayHost.cpp:111
float t
RoadLaneDirection direction
float axisY
Definition RockMesh.cpp:22
std::vector< WfcTile > tiles
bool found
float dy
Definition Shadow.cpp:151
int count
Cell cell
float step
Definition TreeMesh.cpp:451
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
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
Integration + direction field for group pathfinding to a single goal. nextX/nextY point to the neighb...
Definition FlowField.h:15
Immutable owning capture; independent of Pathfinder and TileLayer lifetimes.
Definition Pathfinder.h:27
bool isStaggerAxisY() const noexcept
Read hex stagger axis (normalized to Y for orthogonal captures).
NavigationTopology topology() const noexcept
Read captured adjacency.
int height() const noexcept
Read row count.
std::span< const float > costs() const noexcept
Borrow costs while at least one snapshot retains this capture; reassignment releases it.
int width() const noexcept
Read column count.
std::span< const std::uint8_t > enterMasks() const noexcept
Borrow directional enter masks with the same snapshot lifetime.
bool isStaggerOdd() const noexcept
Read hex stagger parity (normalized to odd for orthogonal captures).
std::uint64_t revision() const noexcept
Read content revision, advanced only on changed captured content.
std::span< const std::uint8_t > exitMasks() const noexcept
Borrow directional exit masks with the same snapshot lifetime.
Ordered tile-index waypoints from start to goal (inclusive).
Definition Path.h:10
Pathfinding facade. Single-agent: A*. Group (same goal): Flow Field + follow. Grid/topology internals...
Definition Pathfinder.h:62
std::string getTopology() const
Returns the topology.
void invalidateCache()
Invalidate cached flow field (also called when grid dirties).
void setBlockEmpty(bool enable)
Sets the block empty.
void syncFromLayer()
Synchronizes from layer.
float getCellCost(int x, int y) const
Returns the cell cost.
void bindLayer(TileLayer *layer)
Binds layer.
void setCellCost(int x, int y, float cost)
Sets the cell cost.
void setTopology(const std::string &name)
Sets the topology.
bool getBlockEmpty() const
Returns the block empty.
bool isWalkable(int x, int y) const
True when walkable.
bool getDiagonal() const
Returns the diagonal.
Pathfinder()
Pathfinder.
void blockGid(int gid)
Block gid.
void setBlocked(int x, int y, bool blocked)
Sets the blocked.
~Pathfinder()
Pathfinder.
void setSize(int width, int height)
Sets the size.
void clearBlockedGids()
Clears blocked gids.
void unblockGid(int gid)
Unblock gid.
void setDiagonal(bool enable)
Sets the diagonal.
ECS tile layer entity. Script mutates tile GIDs / tileset / draw; TileRenderSystem batch-draws atlas ...
Definition TileLayer.h:33
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
void bindLayer(Shader *shader, bool alwaysDark)
Binds layer.
Definition Grass.cpp:291
std::int32_t moveCost(const HexMap &map, HexCoordinates from, HexCoordinates to, HexDirection direction, const HexOccupancyQuery &occupied)
Cost of moving between two adjacent cells.
constexpr HexDirection opposite(HexDirection d) noexcept
The direction opposite to d.
Definition HexMetrics.h:65
放置世界:格子占用(多通道)+ 地形语义 + 已放置建筑实例。 行为由 PlacementSystem 提供;本类暴露便于脚本绑定的薄封装方法。 坐标换算统一走 eve::grid(支持 rectang...
MapOrientation
Tile map layout: orthogonal, isometric, staggered, or hexagonal.
uint32_t tileGid(uint32_t raw)
Strip Tiled flip / rotate flags; keep low 28 bits.
Definition TileLayer.h:392
NavigationTopology
Logical adjacency of a captured map navigation grid.
Definition Pathfinder.h:18
WidgetDesc grid(int columns, std::vector< WidgetDesc > children, std::string id)
Fixed-column grid; children are placed in source order.
Definition Widget.cpp:878
SettlementPipeline::Stage fn
Cheap invalidation hint, distinct from immutable capture content revisions. Includes bound-layer tile...
Definition Pathfinder.h:22
std::vector< std::uint8_t > enterMasks
std::vector< std::uint8_t > exitMasks
One waypoint.
Definition Path.h:34
NavigationGridSnapshot lastCapture