载入中...
搜索中...
未找到
CrowdField.cpp
浏览该文件的文档.
1#include "crowd/CrowdField.h"
2
3#include <algorithm>
4#include <cmath>
5#include <functional>
6#include <limits>
7#include <queue>
8#include <stdexcept>
9#include <utility>
10
11namespace eve::crowd {
12namespace {
13
14constexpr float kSqrt2 = 1.41421356237f;
15
16bool finiteCost(float c) { return c < CrowdField::kUnreachable && c >= 0.f; }
17
18} // namespace
19
20void CrowdField::invalidate() {
21 if (revision_ == std::numeric_limits<std::uint64_t>::max())
22 throw std::overflow_error("Crowd navigation revision exhausted");
23 ++revision_;
24}
25void CrowdField::invalidateInputs() {
26 if (inputRevision_ == std::numeric_limits<std::uint64_t>::max() ||
27 revision_ == std::numeric_limits<std::uint64_t>::max())
28 throw std::overflow_error("Crowd navigation input revision exhausted");
29 ++inputRevision_;
30 invalidate();
31}
32
33void CrowdField::resize(int width, int height, float cellSize, float originX, float originY) {
34 if (!std::isfinite(cellSize) || !std::isfinite(originX) || !std::isfinite(originY))
35 throw std::invalid_argument("Crowd field geometry must be finite");
36 const int nextWidth = std::max(width, 0), nextHeight = std::max(height, 0);
37 const float nextCell = std::max(cellSize, 0.f);
38 const auto count = std::int64_t(nextWidth) * nextHeight;
39 if (count > std::numeric_limits<int>::max()) throw std::length_error("Crowd field dimensions exceed index range");
40 if (nextWidth == width_ && nextHeight == height_ && nextCell == cellSize_ && originX == originX_ &&
41 originY == originY_)
42 return;
43 const bool dimsChanged = nextWidth != width_ || nextHeight != height_;
44 const auto size = static_cast<std::size_t>(count);
45 std::vector<float> costs;
46 if (dimsChanged) costs.assign(size, 1.f);
47 std::vector<float> integration(size, kUnreachable), flowX(size, 0.f), flowY(size, 0.f);
48 // Allocate everything before changing the authoritative geometry or revision.
49 invalidateInputs();
50 navigationCost_.clear();
51 navigationDiagonal_ = true;
52 destinationEntryCost_ = false;
53 if (dimsChanged) {
54 cost_.swap(costs);
55 goals_.clear();
56 }
57 integ_.swap(integration);
58 flowX_.swap(flowX);
59 flowY_.swap(flowY);
60 width_ = nextWidth;
61 height_ = nextHeight;
62 cellSize_ = nextCell;
63 originX_ = originX;
64 originY_ = originY;
65 built_ = false;
66}
67
69 invalidateInputs();
70 navigationCost_.clear();
71 navigationDiagonal_ = true;
72 destinationEntryCost_ = false;
73 width_ = height_ = 0;
74 cellSize_ = 0.f;
75 originX_ = originY_ = 0.f;
76 cost_.clear();
77 integ_.clear();
78 flowX_.clear();
79 flowY_.clear();
80 goals_.clear();
81 built_ = false;
82}
83
84void CrowdField::setBlocked(int cx, int cy, bool blocked) {
85 if (!inBounds(cx, cy)) return;
86 const float value = blocked ? 0.f : 1.f;
87 if (cost_[size_t(index(cx, cy))] == value) return;
88 invalidateInputs();
89 navigationCost_.clear();
90 navigationDiagonal_ = true;
91 destinationEntryCost_ = false;
92 cost_[size_t(index(cx, cy))] = blocked ? 0.f : 1.f;
93}
94
95bool CrowdField::isBlocked(int cx, int cy) const {
96 if (!inBounds(cx, cy)) return true;
97 return cost_[size_t(index(cx, cy))] <= 0.f;
98}
99
100void CrowdField::setCellCost(int cx, int cy, float cost) {
101 if (!inBounds(cx, cy)) return;
102 const float value = cost > 0.f ? cost : 0.f;
103 if (cost_[size_t(index(cx, cy))] == value) return;
104 invalidateInputs();
105 navigationCost_.clear();
106 navigationDiagonal_ = true;
107 destinationEntryCost_ = false;
108 cost_[size_t(index(cx, cy))] = cost > 0.f ? cost : 0.f;
109}
110
111float CrowdField::getCellCost(int cx, int cy) const {
112 if (!inBounds(cx, cy)) return 0.f;
113 return cost_[size_t(index(cx, cy))];
114}
115
117 std::vector<float> costs(size_t(width_ * height_), cost > 0.f ? cost : 1.f);
118 invalidateInputs();
119 navigationCost_.clear();
120 navigationDiagonal_ = true;
121 destinationEntryCost_ = false;
122 cost_.swap(costs);
123}
124
125void CrowdField::setGoal(int gx, int gy) {
126 std::vector<int> replacement;
127 if (inBounds(gx, gy)) replacement = {gx, gy};
128 if (goals_ == replacement) return;
129 invalidate();
130 goals_.swap(replacement);
131}
132
133void CrowdField::addGoal(int gx, int gy) {
134 if (!inBounds(gx, gy)) return;
135 for (std::size_t index = 0; index + 1 < goals_.size(); index += 2)
136 if (goals_[index] == gx && goals_[index + 1] == gy) return;
137 goals_.reserve(goals_.size() + 2);
138 invalidate();
139 goals_.push_back(gx);
140 goals_.push_back(gy);
141}
142
144 if (!goals_.empty()) {
145 invalidate();
146 goals_.clear();
147 }
148}
149
150void CrowdField::worldToCell(float wx, float wy, float &fx, float &fy) const {
151 fx = (wx - originX_) / cellSize_ - 0.5f;
152 fy = (wy - originY_) / cellSize_ - 0.5f;
153}
154
155bool CrowdField::navigationBlocked(int cx, int cy) const {
156 return !inBounds(cx, cy) || navigationCost(index(cx, cy)) <= 0.f;
157}
158float CrowdField::navigationCost(int i) const {
159 return navigationCost_.empty() ? cost_[static_cast<std::size_t>(i)] : navigationCost_[static_cast<std::size_t>(i)];
160}
161
163 CrowdField staged(*this);
164 staged.buildWorking();
165 *this = std::move(staged);
166}
167
168void CrowdField::buildWorking() {
169 beginBuildWorking();
170 while (!isBuilt()) advanceBuildWorking(1000000);
171}
172
173void CrowdField::beginBuildWorking() {
174 const int n = width_ * height_;
175 integ_.assign(size_t(n), kUnreachable);
176 flowX_.assign(size_t(n), 0.f);
177 flowY_.assign(size_t(n), 0.f);
178 built_ = false;
179 flowCursor_ = 0;
180 buildHeap_.clear();
181 if (!valid()) {
182 built_ = true;
183 builtRevision_ = revision_;
184 return;
185 }
186 using HeapNode = std::pair<float, int>;
187 for (size_t i = 0; i + 1 < goals_.size(); i += 2) {
188 const int gx = goals_[i];
189 const int gy = goals_[i + 1];
190 if (!navigationBlocked(gx, gy)) {
191 const int gi = index(gx, gy);
192 if (integ_[size_t(gi)] > 0.f) {
193 integ_[size_t(gi)] = 0.f;
194 buildHeap_.emplace_back(0.f, gi);
195 std::push_heap(buildHeap_.begin(), buildHeap_.end(), std::greater<HeapNode>{});
196 }
197 }
198 }
199}
200
201std::pair<int, int> CrowdField::advanceBuildWorking(int maxWork) {
202 using HeapNode = std::pair<float, int>;
203 int pops = 0, cells = 0;
204 static const int kDx[8] = {1, -1, 0, 0, 1, 1, -1, -1};
205 static const int kDy[8] = {0, 0, 1, -1, 1, -1, 1, -1};
206 static const float kMoveCost[8] = {1.f, 1.f, 1.f, 1.f, kSqrt2, kSqrt2, kSqrt2, kSqrt2};
207
208 while (!buildHeap_.empty() && pops < maxWork) {
209 std::pop_heap(buildHeap_.begin(), buildHeap_.end(), std::greater<HeapNode>{});
210 const HeapNode cur = buildHeap_.back();
211 buildHeap_.pop_back();
212 ++pops;
213 const float dist = cur.first;
214 if (dist > integ_[size_t(cur.second)]) continue;
215 const int cx = cur.second % width_;
216 const int cy = cur.second / width_;
217
218 for (int i = 0; i < 8; ++i) {
219 if (!navigationDiagonal_ && kDx[i] != 0 && kDy[i] != 0) continue;
220 const int nx = cx + kDx[i];
221 const int ny = cy + kDy[i];
222 if (!inBounds(nx, ny) || navigationBlocked(nx, ny)) continue;
223 if (kDx[i] != 0 && kDy[i] != 0) {
224 // 禁止穿过对角两侧都阻挡的"墙角"。
225 if (navigationBlocked(cx + kDx[i], cy) || navigationBlocked(cx, cy + kDy[i])) continue;
226 }
227 const int ni = index(nx, ny);
228 const float tentative = dist + kMoveCost[i] * navigationCost(destinationEntryCost_ ? cur.second : ni);
229 if (tentative >= integ_[size_t(ni)]) continue;
230 integ_[size_t(ni)] = tentative;
231 buildHeap_.emplace_back(tentative, ni);
232 std::push_heap(buildHeap_.begin(), buildHeap_.end(), std::greater<HeapNode>{});
233 }
234 }
235 if (buildHeap_.empty()) {
236 const int count = width_ * height_;
237 while (flowCursor_ < count && pops + cells < maxWork) {
238 rebuildFlowCell(flowCursor_++);
239 ++cells;
240 }
241 if (flowCursor_ == count) {
242 built_ = true;
243 builtRevision_ = revision_;
244 }
245 }
246 return {pops, cells};
247}
248
249void CrowdField::rebuildFlowCell(int i) {
250 const int cx = i % width_, cy = i / width_;
251 const float c = integ_[size_t(i)];
252 if (!finiteCost(c) || c == 0.f) return; // 不可达或目标格无方向
253
254 // 中心差分近似 -∇integ(指向代价下降方向);缺失/不可达的邻格
255 // 用本格值代替,形成单侧差分,保证边缘格方向正确。
256 float gx = 0.f;
257 if (cx > 0 && finiteCost(integ_[size_t(i - 1)]))
258 gx += integ_[size_t(i - 1)];
259 else
260 gx += c;
261 if (cx + 1 < width_ && finiteCost(integ_[size_t(i + 1)]))
262 gx -= integ_[size_t(i + 1)];
263 else
264 gx -= c;
265
266 float gy = 0.f;
267 if (cy > 0 && finiteCost(integ_[size_t(i - width_)]))
268 gy += integ_[size_t(i - width_)];
269 else
270 gy += c;
271 if (cy + 1 < height_ && finiteCost(integ_[size_t(i + width_)]))
272 gy -= integ_[size_t(i + width_)];
273 else
274 gy -= c;
275
276 const float len = std::hypot(gx, gy);
277 if (len > 1e-6f) {
278 flowX_[size_t(i)] = gx / len;
279 flowY_[size_t(i)] = gy / len;
280 }
281}
282
283float CrowdField::costAtCell(int cx, int cy) const {
284 if (!isBuilt() || !inBounds(cx, cy)) return kUnreachable;
285 return integ_[size_t(index(cx, cy))];
286}
287
288bool CrowdField::isReachable(int cx, int cy) const {
289 return finiteCost(costAtCell(cx, cy));
290}
291
292void CrowdField::flowAtCell(int cx, int cy, float &dx, float &dy) const {
293 dx = dy = 0.f;
294 if (!isBuilt() || !inBounds(cx, cy)) return;
295 const int i = index(cx, cy);
296 dx = flowX_[size_t(i)];
297 dy = flowY_[size_t(i)];
298}
299
300float CrowdField::costAtWorld(float wx, float wy) const {
301 if (!valid() || !isBuilt() || !std::isfinite(wx) || !std::isfinite(wy)) return kUnreachable;
302 float fx = 0.f, fy = 0.f;
303 worldToCell(wx, wy, fx, fy);
304 if (fx < -0.5f || fy < -0.5f || fx > float(width_) - 0.5f || fy > float(height_) - 0.5f)
305 return kUnreachable;
306
307 const int x0 = std::clamp(int(std::floor(fx)), 0, width_ - 1);
308 const int y0 = std::clamp(int(std::floor(fy)), 0, height_ - 1);
309 const int x1 = std::min(x0 + 1, width_ - 1);
310 const int y1 = std::min(y0 + 1, height_ - 1);
311 const float tx = std::clamp(fx - float(x0), 0.f, 1.f);
312 const float ty = std::clamp(fy - float(y0), 0.f, 1.f);
313
314 const float c00 = integ_[size_t(index(x0, y0))];
315 const float c10 = integ_[size_t(index(x1, y0))];
316 const float c01 = integ_[size_t(index(x0, y1))];
317 const float c11 = integ_[size_t(index(x1, y1))];
318
319 // 只对有限角落插值;全不可达才返回 kUnreachable,避免把单位"吓停"。
320 float sum = 0.f;
321 float wsum = 0.f;
322 const auto acc = [&](float c, float w) {
323 if (finiteCost(c)) {
324 sum += c * w;
325 wsum += w;
326 }
327 };
328 acc(c00, (1.f - tx) * (1.f - ty));
329 acc(c10, tx * (1.f - ty));
330 acc(c01, (1.f - tx) * ty);
331 acc(c11, tx * ty);
332 return wsum > 0.f ? sum / wsum : kUnreachable;
333}
334
335void CrowdField::flowAtWorld(float wx, float wy, float &dx, float &dy) const {
336 dx = dy = 0.f;
337 if (!valid() || !isBuilt() || !std::isfinite(wx) || !std::isfinite(wy)) return;
338 float fx = 0.f, fy = 0.f;
339 worldToCell(wx, wy, fx, fy);
340 if (fx < -0.5f || fy < -0.5f || fx > float(width_) - 0.5f || fy > float(height_) - 0.5f)
341 return;
342
343 const int x0 = std::clamp(int(std::floor(fx)), 0, width_ - 1);
344 const int y0 = std::clamp(int(std::floor(fy)), 0, height_ - 1);
345 const int x1 = std::min(x0 + 1, width_ - 1);
346 const int y1 = std::min(y0 + 1, height_ - 1);
347 const float tx = std::clamp(fx - float(x0), 0.f, 1.f);
348 const float ty = std::clamp(fy - float(y0), 0.f, 1.f);
349
350 const auto sample = [&](int x, int y, float &sx, float &sy) {
351 const int i = index(x, y);
352 sx = finiteCost(integ_[size_t(i)]) ? flowX_[size_t(i)] : 0.f;
353 sy = finiteCost(integ_[size_t(i)]) ? flowY_[size_t(i)] : 0.f;
354 };
355 float f00x = 0.f, f00y = 0.f, f10x = 0.f, f10y = 0.f;
356 float f01x = 0.f, f01y = 0.f, f11x = 0.f, f11y = 0.f;
357 sample(x0, y0, f00x, f00y);
358 sample(x1, y0, f10x, f10y);
359 sample(x0, y1, f01x, f01y);
360 sample(x1, y1, f11x, f11y);
361
362 dx = (1.f - ty) * ((1.f - tx) * f00x + tx * f10x) + ty * ((1.f - tx) * f01x + tx * f11x);
363 dy = (1.f - ty) * ((1.f - tx) * f00y + tx * f10y) + ty * ((1.f - tx) * f01y + tx * f11y);
364 const float len = std::sqrt(dx * dx + dy * dy);
365 if (len > 1e-6f) {
366 dx /= len;
367 dy /= len;
368 } else {
369 dx = dy = 0.f;
370 }
371}
372
373bool CrowdField::resolvePenetration(float &wx, float &wy, float radius) const {
374 if (!valid() || radius <= 0.f) return false;
375 const float cs = cellSize_;
376 const int cx0 = std::max(0, int(std::floor((wx - radius - originX_) / cs)));
377 const int cx1 = std::min(width_ - 1, int(std::floor((wx + radius - originX_) / cs)));
378 const int cy0 = std::max(0, int(std::floor((wy - radius - originY_) / cs)));
379 const int cy1 = std::min(height_ - 1, int(std::floor((wy + radius - originY_) / cs)));
380 bool pushed = false;
381 for (int cy = cy0; cy <= cy1; ++cy) {
382 for (int cx = cx0; cx <= cx1; ++cx) {
383 if (!isBlocked(cx, cy)) continue;
384 const float loX = originX_ + float(cx) * cs, hiX = loX + cs;
385 const float loY = originY_ + float(cy) * cs, hiY = loY + cs;
386 const float dx = wx - std::clamp(wx, loX, hiX);
387 const float dy = wy - std::clamp(wy, loY, hiY);
388 const float d2 = dx * dx + dy * dy;
389 if (d2 >= radius * radius) continue;
390 if (d2 > 1e-12f) {
391 const float distance = std::sqrt(d2);
392 const float scale = (radius - distance) / distance;
393 wx += dx * scale;
394 wy += dy * scale;
395 } else {
396 // Inside the box: choose the nearest expanded face, including radius.
397 const float left = wx - loX, right = hiX - wx;
398 const float down = wy - loY, up = hiY - wy;
399 const float nearest = std::min({left, right, down, up});
400 if (nearest == left)
401 wx = loX - radius;
402 else if (nearest == right)
403 wx = hiX + radius;
404 else if (nearest == down)
405 wy = loY - radius;
406 else
407 wy = hiY + radius;
408 }
409 pushed = true;
410 }
411 }
412 return pushed;
413}
414
415} // namespace eve::crowd
double y
double x
float w
Definition AnimClip.cpp:738
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
eve::resource::CostSpec cost
glm::vec3 n
Definition Grass.cpp:63
HexVec3 up
HexVec3 left
HexVec3 right
std::int32_t c
std::uint32_t height
std::uint32_t width
std::array< float, 3 > scale
double radius
Definition MeleeHit.cpp:42
float distance
glm::dvec3 dx
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
Object::Ptr value
float dy
Definition Shadow.cpp:151
int count
float size
Definition TreeMesh.cpp:158
uint32_t index
连续流场(flow field)。
Definition CrowdField.h:25
const std::vector< float > & flowX() const
只读访问方向场 X 分量(调试渲染用)。
Definition CrowdField.h:173
void setGoal(int gx, int gy)
设定唯一目标格(等价 clearGoals + addGoal)。
void flowAtCell(int cx, int cy, float &dx, float &dy) const
查询格级方向向量(单位长度;目标格/阻挡/不可达为 0)。
float costAtWorld(float wx, float wy) const
查询世界坐标处的积分代价(双线性插值;场外返回 kUnreachable)。
void setBlocked(int cx, int cy, bool blocked)
设置/清除某格阻挡。
bool isReachable(int cx, int cy) const
某格是否可达(积分代价有限且非负)。
void setCellCost(int cx, int cy, float cost)
设置某格地形代价(进入该格的移动成本)。
const std::vector< float > & integration() const
只读访问积分场(调试渲染用)。
Definition CrowdField.h:171
bool resolvePenetration(float &wx, float &wy, float radius) const
圆 vs 阻挡格碰撞消解:把圆心从覆盖到的阻挡格中推出来。
bool isBuilt() const
Whether directions were built for the current terrain and goals.
Definition CrowdField.h:104
void flowAtWorld(float wx, float wy, float &dx, float &dy) const
查询世界坐标处的跟随方向(双线性插值后归一化)。
void clear()
清空全部数据(回到无效状态)。
bool isBlocked(int cx, int cy) const
查询某格是否阻挡。
void setAllCellCost(float cost)
把全部格子设为同一地形代价(通常 build 前重置用)。
float getCellCost(int cx, int cy) const
查询地形代价(越界/阻挡返回 0)。
const std::vector< float > & flowY() const
只读访问方向场 Y 分量(调试渲染用)。
Definition CrowdField.h:175
static constexpr float kUnreachable
不可达/阻挡的积分代价。
Definition CrowdField.h:28
void resize(int width, int height, float cellSize, float originX, float originY)
配置网格(保留原有 cost/goals,若尺寸变化则重置)。
float costAtCell(int cx, int cy) const
查询格级积分代价(未 build 返回 kUnreachable)。
bool valid() const
是否配置了有效网格。
Definition CrowdField.h:53
void build()
Legacy synchronous build; publish the completed staged Dijkstra result atomically....
void addGoal(int gx, int gy)
Append a unique goal cell; existing goals leave revision unchanged.
void clearGoals()
清空目标列表。