载入中...
搜索中...
未找到
CrowdPreferred.cpp
浏览该文件的文档.
1#include "common/Assert.h"
3namespace eve::crowd {
4namespace {
5enum Action : int32_t { kIdle = 0, kFlow = 1, kSeek = 2, kBoids = 3 };
6}
7void Crowd::Impl::spendPreferredWork(std::int64_t amount) {
8 const auto limit = budgetActive ? activeBudget.maxPreferredVisits : std::numeric_limits<std::int64_t>::max();
9 if (amount > limit - workReport.preferredVisits) throw WorkLimit{"Crowd preferred work budget exhausted"};
11}
13 const size_t n = actions.size();
14 spendPreferredWork(static_cast<std::int64_t>(n) * 2 + 1);
15 preferredCounts.assign(n, 0);
16 preferredStarts.resize(n + 1);
17 const bool forces = sepWeight > 0.f || alignWeight > 0.f || cohesionWeight > 0.f;
18 const float queryR = std::max(sepRadius, perceiveRadius);
19 const auto maxEntries = budgetActive ? activeBudget.maxPreferredNeighbors : std::int64_t(1000000);
20 const auto visit = [&](size_t i, const auto& accept) {
21 if (!forces || interactions[i].holdPosition) return;
22 forEachNeighbor(xs[i], ys[i], queryR, [&](int j) {
23 if (!canAvoid(i, size_t(j))) return;
24 const float dx = xs[size_t(j)] - xs[i], dy = ys[size_t(j)] - ys[i];
25 const float d2 = dx * dx + dy * dy;
26 if (d2 <= 0.f) return;
27 if (!(sepWeight > 0.f && d2 <= sepRadius * sepRadius) &&
28 !((alignWeight > 0.f || cohesionWeight > 0.f) && d2 <= perceiveRadius * perceiveRadius))
29 return;
30 accept(j);
31 });
32 };
33 size_t total = 0;
34 for (size_t i = 0; i < n; ++i) {
35 spendPreferredWork(1);
36 visit(i, [&](int) {
37 spendPreferredWork(1);
38 if (total >= static_cast<std::uint64_t>(maxEntries))
39 throw WorkLimit{"Crowd preferred neighbor capacity exhausted"};
40 ++preferredCounts[i];
41 ++total;
42 });
43 }
44 size_t prefix = 0;
45 for (size_t i = 0; i < n; ++i) {
46 spendPreferredWork(1);
47 preferredStarts[i] = prefix;
48 prefix += preferredCounts[i];
49 }
50 preferredStarts[n] = prefix;
51 spendPreferredWork(static_cast<std::int64_t>(total));
52 preferredNeighbors.resize(total);
53 workReport.preferredNeighborsPeak = std::max(workReport.preferredNeighborsPeak, static_cast<std::int64_t>(total));
54 for (size_t i = 0; i < n; ++i) {
55 spendPreferredWork(1);
56 size_t cursor = preferredStarts[i];
57 visit(i, [&](int j) {
58 spendPreferredWork(1);
59 EV_ASSERT(cursor < preferredStarts[i + 1], "Preferred snapshot changed during fill");
60 preferredNeighbors[cursor++] = j;
61 });
62 EV_ASSERT(cursor == preferredStarts[i + 1], "Preferred count/fill mismatch");
63 }
64}
66 const int n = int(actions.size());
67 preparePreferredNeighbors();
68 spendPreferredWork(n + static_cast<std::int64_t>(preferredNeighbors.size()));
69 spendPreferredWork(std::int64_t(n) * 2);
70 preferredFlows.assign(size_t(n), PreferredFlow{});
71 for (size_t i = 0; i < actions.size(); ++i) {
72 if (actions[i] != kFlow || interactions[i].holdPosition) continue;
73 auto& flow = preferredFlows[i];
74 float fx = 0.f, fy = 0.f;
75 const auto* navigation = navigationField(i);
76 const float cost = navigation ? navigation->costAtWorld(xs[i], ys[i]) : CrowdField::kUnreachable;
77 const bool reachable = navigation && isFlowPointReachable(*navigation, xs[i], ys[i]);
78 if (reachable) navigation->flowAtWorld(xs[i], ys[i], fx, fy);
79 if (reachable && navigation->isBuilt()) {
80 const float cell = navigation->getCellSize();
81 const int cx = int(std::floor((double(xs[i]) - navigation->getOriginX()) / cell));
82 const int cy = int(std::floor((double(ys[i]) - navigation->getOriginY()) / cell));
83 static constexpr int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
84 spendPreferredWork(8);
85 bool edge = false;
86 float best = navigation->costAtCell(cx, cy);
87 int next = -1;
88 for (int side = 0; side < 4; ++side) {
89 const int nx = cx + dx[side], ny = cy + dy[side];
90 if (nx >= 0 && ny >= 0 && nx < navigation->getWidth() && ny < navigation->getHeight() &&
91 !navigation->isReachable(nx, ny))
92 edge = true;
93 const float value = navigation->costAtCell(nx, ny);
94 if (value < best) {
95 best = value;
96 next = side;
97 }
98 }
99 if (edge && next >= 0 && radii[i] < cell * 0.5f) {
100 const float centerX = navigation->getOriginX() + (float(cx) + 0.5f) * cell;
101 const float centerY = navigation->getOriginY() + (float(cy) + 0.5f) * cell;
102 const float inset = std::min(radii[i] + (avoidance.enabled ? avoidance.margin : 0.f), cell * 0.49f);
103 const bool aligned = dx[next] != 0 ? std::fabs(ys[i] - centerY) <= cell * 0.5f - inset
104 : std::fabs(xs[i] - centerX) <= cell * 0.5f - inset;
105 // Align the perpendicular axis before crossing a portal; do not recenter along travel.
106 fx = centerX + (aligned ? float(dx[next]) * cell : 0.f) - xs[i];
107 fy = centerY + (aligned ? float(dy[next]) * cell : 0.f) - ys[i];
108 const float length = std::hypot(fx, fy);
109 if (length > 1e-6f) {
110 fx /= length;
111 fy /= length;
112 }
113 }
114 }
115 // 接近目标时按积分代价线性减速(arrive),避免在目标格附近振荡。
116 float k = 1.f;
117 if (navigation) {
118 const float c = cost;
119 const float cell = std::max(navigation->getCellSize(), 1e-6f);
120 const float arriveCells = arriveRadius / cell;
121 if (c < CrowdField::kUnreachable && arriveCells > 0.f && c < arriveCells) {
122 k = c / arriveCells;
123 flow.arrive = k;
124 }
125 }
126 flow.x = fx * k;
127 flow.y = fy * k;
128 }
129 dispatchWork(size_t(n), [&](std::size_t first, std::size_t last) {
130 for (int i = int(first); i < int(last); ++i) {
131 if (interactions[size_t(i)].holdPosition) {
132 preferredVxs[size_t(i)] = preferredVys[size_t(i)] = 0.f;
133 arriveFactors[size_t(i)] = 1.f;
134 continue;
135 }
136 const float x = xs[size_t(i)];
137 const float y = ys[size_t(i)];
138 const float maxSpeed = maxSpeeds[size_t(i)];
139 const int action = actions[size_t(i)];
140 float arriveK = 1.f; // flow 模式到达减速系数(1=全速,0=停)
141
142 // 基础期望方向。
143 float desX = 0.f, desY = 0.f;
144 if (action == kFlow) {
145 const auto flow = preferredFlows[size_t(i)];
146 desX = flow.x;
147 desY = flow.y;
148 arriveK = flow.arrive;
149 } else if (action == kSeek && hasTargets[size_t(i)]) {
150 const float tx = targetXs[size_t(i)] - x;
151 const float ty = targetYs[size_t(i)] - y;
152 const float d = std::sqrt(tx * tx + ty * ty);
153 if (d > 1e-3f) {
154 desX = tx / d;
155 desY = ty / d;
156 if (d < arriveRadius) {
157 const float k = d / arriveRadius;
158 desX *= k;
159 desY *= k;
160 }
161 }
162 } else if (action == kBoids && hasTargets[size_t(i)] && goalWeight > 0.f) {
163 const float tx = targetXs[size_t(i)] - x;
164 const float ty = targetYs[size_t(i)] - y;
165 const float d = std::sqrt(tx * tx + ty * ty);
166 if (d > 1e-3f) {
167 desX = tx / d * goalWeight;
168 desY = ty / d * goalWeight;
169 }
170 }
171 desX *= maxSpeed;
172 desY *= maxSpeed;
173
174 // Boids 三力。
175 if (sepWeight > 0.f || alignWeight > 0.f || cohesionWeight > 0.f) {
176 float sx = 0.f, sy = 0.f;
177 float axv = 0.f, ayv = 0.f;
178 float cxv = 0.f, cyv = 0.f;
179 int alignN = 0, cohN = 0;
180 for (size_t cursor = preferredStarts[size_t(i)]; cursor < preferredStarts[size_t(i) + 1]; ++cursor) {
181 const int j = preferredNeighbors[cursor];
182 const float dx = xs[size_t(j)] - x;
183 const float dy = ys[size_t(j)] - y;
184 const float d2 = dx * dx + dy * dy;
185 if (d2 <= 0.f) continue;
186 if (sepWeight > 0.f && d2 <= sepRadius * sepRadius) {
187 const float d = std::sqrt(d2);
188 const float fall = 1.f - d / sepRadius;
189 sx += (x - xs[size_t(j)]) / d * fall;
190 sy += (y - ys[size_t(j)]) / d * fall;
191 }
192 if (alignWeight > 0.f && d2 <= perceiveRadius * perceiveRadius) {
193 axv += vxs[size_t(j)];
194 ayv += vys[size_t(j)];
195 ++alignN;
196 }
197 if (cohesionWeight > 0.f && d2 <= perceiveRadius * perceiveRadius) {
198 cxv += xs[size_t(j)];
199 cyv += ys[size_t(j)];
200 ++cohN;
201 }
202 }
203 desX += sx * sepWeight * maxSpeed;
204 desY += sy * sepWeight * maxSpeed;
205 if (alignN > 0) {
206 const float al = std::sqrt(axv * axv + ayv * ayv);
207 if (al > 1e-4f) {
208 desX += axv / al * alignWeight * maxSpeed;
209 desY += ayv / al * alignWeight * maxSpeed;
210 }
211 }
212 if (cohN > 0) {
213 const float cmx = cxv / float(cohN) - x;
214 const float cmy = cyv / float(cohN) - y;
215 const float cl = std::sqrt(cmx * cmx + cmy * cmy);
216 if (cl > 1e-4f) {
217 desX += cmx / cl * cohesionWeight * maxSpeed;
218 desY += cmy / cl * cohesionWeight * maxSpeed;
219 }
220 }
221 }
222
223 // Boids wander。
224 if (action == kBoids && wanderWeight > 0.f) {
225 wanderPhases[size_t(i)] += dt * 2.5f;
226 desX += std::cos(wanderPhases[size_t(i)]) * wanderWeight * maxSpeed;
227 desY += std::sin(wanderPhases[size_t(i)]) * wanderWeight * maxSpeed;
228 }
229
230 // 期望速度限幅。
231 float dl = std::sqrt(desX * desX + desY * desY);
232 if (dl > maxSpeed && dl > 1e-6f) {
233 desX *= maxSpeed / dl;
234 desY *= maxSpeed / dl;
235 }
236
237 preferredVxs[size_t(i)] = desX;
238 preferredVys[size_t(i)] = desY;
239 arriveFactors[size_t(i)] = arriveK;
240 }
241 });
242}
243} // namespace eve::crowd
double y
double x
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
std::size_t cursor
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
eve::resource::CostSpec cost
glm::vec3 n
Definition Grass.cpp:63
std::int32_t c
std::int32_t first
float length
glm::dvec3 dx
double dt
std::string action
Definition PlayHost.cpp:118
std::vector< ActionSpec > actions
Definition PlayHost.cpp:127
Object::Ptr value
float d
float dy
Definition Shadow.cpp:151
Cell cell
std::map< Cell, int > best
int limit
Definition TreeMesh.cpp:166
std::array< float, 4 > radii
static constexpr float kUnreachable
不可达/阻挡的积分代价。
Definition CrowdField.h:28
bool isFlowPointReachable(const CrowdField &field, float x, float y) noexcept
Observe exact containing-cell reachability, independent of interpolation across blocked cells....
std::int64_t maxPreferredVisits
Workspace/count/prefix/fill/force visits.
Definition Crowd.h:84
void spendPreferredWork(std::int64_t amount)
void preparePreferredVelocities(float dt)
std::int64_t preferredVisits
Workspace/preparation/force entry work across substeps.
Definition Crowd.h:96
Non-allocating internal unwind signal, translated at the checked simulation boundary.