载入中...
搜索中...
未找到
RTSCrowdFlowNavigation.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <array>
3#include <cmath>
4#include <limits>
6namespace eve::rts {
7namespace {
8template <class T>
9Result<T> failure(DiagnosticCode code, const char* text) {
10 return Result<T>::failure(Diagnostic::error(code, text, "crowdFlowNavigation"));
11}
12} // namespace
14 if (enabled_ && settings.maxWorkPerTick == settings_.maxWorkPerTick &&
15 settings.maxStartsPerTick == settings_.maxStartsPerTick)
17 settings_ = settings;
18 enabled_ = true;
20}
22 enabled_ = false;
23 jobs_.clear();
24 groups_.clear();
25 notices_.clear();
26 workAfter_ = roundThrough_ = 0;
27}
29 if (!enabled_) return failure<InputChange>(DiagnosticCode::PreconditionViolation, "Shared-flow policy is disabled");
30 notices_.clear();
31 const auto source = crowd.getFieldStatus();
32 if (source.surface.surface.isZero())
33 return failure<InputChange>(DiagnosticCode::PreconditionViolation,
34 "Shared-flow mode requires an imported movement projection");
35 const bool ownerChanged = owner_ != source.owner;
36 const bool changed = ownerChanged || input_ != source.inputRevision;
37 if (changed) {
38 jobs_.clear();
39 workAfter_ = 0;
40 roundThrough_ = 0;
41 frame_.reset();
42 if (ownerChanged) pumped_.reset();
43 owner_ = source.owner;
44 input_ = source.inputRevision;
45 }
46 if (!frame_ || *frame_ != step.tick) {
47 if (frame_)
48 jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [&](const Job& job) { return job.used != *frame_; }),
49 jobs_.end());
50 frame_ = step.tick;
51 }
53}
54Result<crowd::FlowGoal> CrowdFlowNavigation::goalCell(crowd::Crowd& crowd, WorldPosition target) const {
55 if (!std::isfinite(target.x) || !std::isfinite(target.y))
56 return failure<crowd::FlowGoal>(DiagnosticCode::InvalidArgument, "Nonfinite shared goal");
57 const double x = std::floor((double(target.x) - crowd.getFieldOriginX()) / crowd.getCellSize());
58 const double y = std::floor((double(target.y) - crowd.getFieldOriginY()) / crowd.getCellSize());
59 if (x < 0 || y < 0 || x >= crowd.getFieldWidth() || y >= crowd.getFieldHeight())
60 return failure<crowd::FlowGoal>(DiagnosticCode::InvalidArgument, "Shared goal outside navigation surface");
61 return Result<crowd::FlowGoal>::success({static_cast<int>(x), static_cast<int>(y)});
62}
63Result<std::vector<crowd::FlowGoal>> CrowdFlowNavigation::goalSet(crowd::Crowd& crowd,
64 std::span<const WorldPosition> targets) const {
65 if (targets.empty() || targets.size() > 1024)
66 return failure<std::vector<crowd::FlowGoal>>(DiagnosticCode::InvalidArgument,
67 "Expected 1..1024 shared targets");
68 std::vector<crowd::FlowGoal> goals;
69 goals.reserve(targets.size());
70 for (const auto target : targets) {
71 auto cell = goalCell(crowd, target);
72 if (!cell) return Result<std::vector<crowd::FlowGoal>>::failure(cell.status());
73 goals.push_back(cell.value());
74 }
75 std::sort(goals.begin(), goals.end());
76 goals.erase(std::unique(goals.begin(), goals.end()), goals.end());
77 return Result<std::vector<crowd::FlowGoal>>::success(std::move(goals));
78}
80 return request(crowd, std::span<const WorldPosition>(&target, 1), tick);
81}
82Result<void> CrowdFlowNavigation::request(crowd::Crowd& crowd, std::span<const WorldPosition> targets,
83 SimulationTick tick) try {
84 auto goal = goalSet(crowd, targets);
85 if (!goal) return Result<void>::failure(goal.status());
86 return requestGoals(goal.value(), tick);
87} catch (const std::exception& error) {
88 return failure<void>(DiagnosticCode::Failed, error.what());
89}
90Result<void> CrowdFlowNavigation::requestGoals(std::span<const crowd::FlowGoal> goals, SimulationTick tick) try {
91 auto found = std::lower_bound(jobs_.begin(), jobs_.end(), goals, [](const Job& job, const auto& key) {
92 return std::lexicographical_compare(job.goals.begin(), job.goals.end(), key.begin(), key.end());
93 });
94 if (found != jobs_.end() && std::equal(found->goals.begin(), found->goals.end(), goals.begin(), goals.end())) {
95 found->used = tick;
97 }
98 if (jobs_.size() == 10000)
99 return failure<void>(DiagnosticCode::PreconditionViolation,
100 "Shared-goal queue exceeds 10000 distinct goal sets");
101 if (nextSequence_ == std::numeric_limits<std::uint64_t>::max())
102 return failure<void>(DiagnosticCode::PreconditionViolation, "Shared-goal admission sequence exhausted");
103 Job job;
104 job.sequence = nextSequence_;
105 job.goals.assign(goals.begin(), goals.end());
106 job.used = tick;
107 jobs_.insert(found, std::move(job));
108 ++nextSequence_;
109 return Result<void>::success();
110} catch (const std::exception& error) {
111 return failure<void>(DiagnosticCode::Failed, error.what());
112}
114 if (step.delta.isZero() || (pumped_ && *pumped_ == step.tick))
116 // One attempt owns this tick's quota, even if a later stage fails. Input replacement
117 // may retire the partial plans, but does not refund work in the same owner timeline.
118 pumped_ = step.tick;
119 stats_.lastWork = stats_.lastStarts = 0;
120 stats_.cachePressure = false;
121 // Canonical key order serves lookup only. Admission order serves quotas, so new low keys
122 // cannot displace older work. These pointers are borrowed only while jobs_ is unchanged.
123 std::vector<Job*> ordered(jobs_.size(), nullptr);
124 std::size_t count = 0, activeBuilders = 0;
125 for (const auto& job : jobs_) {
126 const auto state = job.plan.state();
129 ++activeBuilders;
130 }
131 for (auto& job : jobs_)
132 if (job.used == step.tick) ordered[count++] = &job;
133 std::sort(ordered.begin(), ordered.begin() + count,
134 [](const Job* left, const Job* right) { return left->sequence < right->sequence; });
135 for (std::size_t index = 0; index < count; ++index) {
136 auto& job = *ordered[index];
137 if (job.used != step.tick || job.lease.generation() != 0) continue;
138 if (job.plan.state() == crowd::Crowd::FlowBuildState::Cancelled) {
139 auto cached = crowd.acquireFlowField(job.goals);
140 if (cached) {
141 job.lease = std::move(cached).takeValue();
142 ++stats_.cacheHits;
143 continue;
144 }
145 if (cached.code() != StatusCode::NotFound) return Result<void>::failure(cached.status());
146 cached.ignore("Ready cache miss; explicit bounded preparation follows");
147 if (stats_.lastStarts == settings_.maxStartsPerTick || activeBuilders == 64) continue;
148 ++stats_.lastStarts;
149 auto prepared = crowd.prepareFlowBuild(job.goals);
150 if (!prepared) return Result<void>::failure(prepared.status());
151 job.plan = std::move(prepared).takeValue();
152 ++stats_.prepared;
153 ++activeBuilders;
154 }
155 }
156 int remaining = settings_.maxWorkPerTick;
157 while (remaining > 0 && count != 0) {
158 Job* selected = nullptr;
159 for (std::size_t index = 0; index < count; ++index) {
160 auto* job = ordered[index];
161 if (job->sequence > workAfter_ && job->sequence <= roundThrough_ &&
162 job->plan.state() == crowd::Crowd::FlowBuildState::Pending) {
163 selected = job;
164 break;
165 }
166 }
167 if (!selected) {
168 // Freeze admission at each round boundary: newcomers wait until older
169 // pending requests have each had their quantum, even across ticks.
170 roundThrough_ = ordered[count - 1]->sequence;
171 workAfter_ = 0;
172 for (std::size_t index = 0; index < count; ++index)
175 break;
176 }
177 }
178 if (!selected) break;
179 const int reserved = std::min(remaining, 256);
180 stats_.lastWork += reserved;
181 auto progress = crowd.advanceFlowBuild(selected->plan, reserved);
182 if (!progress) {
183 // A failed builder may contain partial internal work; it must never become a ready field.
184 auto cancelled = selected->plan.cancel();
185 if (!cancelled) return Result<void>::failure(cancelled.status());
186 return Result<void>::failure(progress.status());
187 }
188 const int work = progress.value().heapPops + progress.value().directionCells;
189 workAfter_ = selected->sequence;
190 remaining -= work;
191 stats_.lastWork += work - reserved;
192 if (work == 0 && selected->plan.state() == crowd::Crowd::FlowBuildState::Pending) break;
193 }
194 for (auto& job : jobs_) {
195 if (job.used != step.tick || job.lease.generation() != 0) continue;
196 if (job.plan.state() != crowd::Crowd::FlowBuildState::Ready &&
198 continue;
199 auto acquired = crowd.acquireFlowField(std::move(job.plan));
200 if (acquired) {
201 job.lease = std::move(acquired).takeValue();
202 continue;
203 }
204 if (acquired.code() != StatusCode::Rejected) return Result<void>::failure(acquired.status());
205 acquired.ignore("Cache pressure retains completed work for the next quota phase");
206 stats_.cachePressure = true;
207 }
208 return Result<void>::success();
209} catch (const std::exception& error) {
210 return failure<void>(DiagnosticCode::Failed, error.what());
211}
214 crowd::MovementBinding movement,
215 crowd::AgentUpdate& update) {
216 return steer(crowd, position, std::span<const WorldPosition>(&target, 1), target, radius, movement, update);
217}
219 std::span<const WorldPosition> targets,
221 crowd::MovementBinding movement,
222 crowd::AgentUpdate& update) {
223 auto goal = goalSet(crowd, targets);
224 if (!goal) return Result<DriveState>::failure(goal.status());
225 return steerGoals(crowd, position, goal.value(), target, radius, movement, update);
226}
227Result<CrowdFlowNavigation::DriveState> CrowdFlowNavigation::steerGoals(crowd::Crowd& crowd, WorldPosition position,
228 std::span<const crowd::FlowGoal> goals,
230 crowd::MovementBinding movement,
231 crowd::AgentUpdate& update) {
232 auto destinationCell = goalCell(crowd, target);
233 if (!destinationCell) return Result<DriveState>::failure(destinationCell.status());
234 if (!std::binary_search(goals.begin(), goals.end(), destinationCell.value()))
236 DiagnosticCode::InvalidArgument, "Exact destination must belong to the shared goal set", "target"));
237 auto found = std::lower_bound(jobs_.begin(), jobs_.end(), goals, [](const Job& job, const auto& key) {
238 return std::lexicographical_compare(job.goals.begin(), job.goals.end(), key.begin(), key.end());
239 });
240 update.flow = crowd::FlowLease{};
241 update.intent = {crowd::AgentAction::Idle, false, 0.f, 0.f};
242 if (found == jobs_.end() || !std::equal(found->goals.begin(), found->goals.end(), goals.begin(), goals.end()) ||
243 found->lease.generation() == 0) {
244 update.maxSpeed = 0.f;
246 }
247 update.flow = found->lease;
248 const auto source = crowd.getFieldStatus().surface;
249 if (radius > source.clearanceRadius ||
250 (!movement.movement.isZero() &&
251 (movement.movement != source.movement || movement.revision != source.movementRevision))) {
252 update.maxSpeed = 0.f;
254 }
255 auto sampled = crowd.sampleFlowField(found->lease, position.x, position.y);
256 if (!sampled) return Result<DriveState>::failure(sampled.status());
257 auto destination = crowd.sampleFlowField(found->lease, target.x, target.y);
258 if (!destination) return Result<DriveState>::failure(destination.status());
259 if (sampled.value().state == crowd::FlowSampleState::Unreachable ||
260 destination.value().state == crowd::FlowSampleState::Unreachable) {
261 update.maxSpeed = 0.f;
263 }
264 auto cell = goalCell(crowd, position);
265 if (!cell) return Result<DriveState>::failure(cell.status());
266 update.intent = cell.value() == destinationCell.value()
267 ? crowd::SteeringIntent{crowd::AgentAction::Seek, true, target.x, target.y}
268 : crowd::SteeringIntent{crowd::AgentAction::Flow, false, 0.f, 0.f};
270}
272 auto result = stats_;
273 for (const auto& job : jobs_) {
274 if (job.lease.generation() == 0)
276 else
277 ++result.readyGoals;
278 }
279 return result;
280}
282 if (settings.maxWorkPerTick < 1 || settings.maxWorkPerTick > 1000000 || settings.maxStartsPerTick < 1 ||
283 settings.maxStartsPerTick > 16)
284 return failure<void>(DiagnosticCode::InvalidArgument, "Invalid shared-flow quotas");
285 if (crowdFlowNavigation_) return crowdFlowNavigation_->configure(settings);
286 crowdFlowNavigation_ = std::make_unique<CrowdFlowNavigation>(settings);
287 return Result<void>::success();
288} catch (const std::exception& error) {
289 return failure<void>(DiagnosticCode::Failed, error.what());
290}
292 if (crowdFlowNavigation_) crowdFlowNavigation_->disable();
293 clearCrowdFlowBindings_ = true;
294}
295Result<std::size_t> RTS::advanceCrowdMotion(const SimulationStep& step) try {
296 if (clearCrowdFlowBindings_) {
298 auto view = ecs::View<Unit, Unit::Identity, Unit::Crowd>();
299 for (auto it = view.begin(); it != view.end(); ++it) {
300 auto [identity, settings] = *it;
301 if (!identity || !ecs::try_get(identity->self)) continue;
302 const crowd::AgentRef ref{settings->runtimeAgent, settings->runtimeOwner};
303 if (!crowd_->isAgentAlive(ref)) continue;
304 crowd::AgentUpdate update;
305 update.reference = ref;
306 update.flow = crowd::FlowLease{};
307 updates.agents.push_back(std::move(update));
308 }
309 auto cleared = crowd_->updateAgents(updates);
310 if (!cleared) return Result<std::size_t>::failure(cleared.status());
311 clearCrowdFlowBindings_ = false;
312 }
313 const bool shared = crowdFlowNavigation_ && crowdFlowNavigation_->enabled();
314 auto moved = shared ? CrowdMotionSystem::stepSharedFlow(step, *crowd_, *crowdFlowNavigation_)
315 : CrowdMotionSystem::step(step, *crowd_);
316 if (!moved) return moved;
317 if (shared) {
318 auto notices = crowdFlowNavigation_->takeNotices();
319 const auto callback = navigationEvent_;
320 for (const auto& notice : notices) {
321 auto* unit = dynamic_cast<Unit*>(ecs::try_get(notice.unit));
322 if (unit && unit->navigation()->unreachable && unit->navigation()->plannedOrderId == notice.order.id) {
323 unit->navigation()->unreachableReported = true;
324 if (callback) callback(*unit, notice.order);
325 }
326 }
327 }
328 return moved;
329} catch (const std::exception& error) {
330 return failure<std::size_t>(DiagnosticCode::Failed, error.what());
331}
333 return crowdFlowNavigation_ && crowdFlowNavigation_->enabled() ? crowdFlowNavigation_->observation()
335}
336} // namespace eve::rts
double y
double x
LogicalId target
std::string selected
bool changed
SQObjectPtr key
Definition ECS.cpp:155
std::vector< FieldTarget > targets
DiagnosticCode code
const GltfImportRequest & request
HexVec3 left
HexVec3 right
bool ordered
std::array< float, 3 > position
std::shared_ptr< std::atomic< bool > > cancelled
Poco::JSON::Object::Ptr result
double radius
Definition MeleeHit.cpp:42
OceanWakeSettings settings
OceanSprayView view
std::string error
Definition Package.cpp:174
bool found
std::string text
std::string_view source
int count
Cell cell
TacticalUnit * unit
SimulationTick tick
float step
Definition TreeMesh.cpp:451
uint32_t index
ViewPreparation callback
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
群体行为模块:连续流场寻路 + 海量单位移动/转向/行动 + Boids 鸟群。
Definition Crowd.h:266
FieldObservation getFieldStatus() const noexcept
Observe current field readiness and owner-local revision without rebuilding.
Definition Crowd.cpp:62
Result< FlowBuildPlan > prepareFlowBuild(int gx, int gy) const
Prepare owned navigation workstate for one goal without changing the live field.
int getFieldWidth() const
网格信息访问器(调试渲染用)。
Definition Crowd.cpp:95
float getCellSize() const
Returns the cell size.
Definition Crowd.cpp:97
float getFieldOriginY() const
Returns the field origin y.
Definition Crowd.cpp:99
Result< AgentBatchReceipt > updateAgents(const AgentUpdateBatch &batch)
Compatibility-only one-call facade over canonical prepareAgentUpdates/commitAgentUpdates....
Result< FlowLease > acquireFlowField(std::span< const FlowGoal > goals)
Acquire an existing field for a canonical goal set without graph work.
float getFieldOriginX() const
Returns the field origin x.
Definition Crowd.cpp:98
int getFieldHeight() const
Returns the field height.
Definition Crowd.cpp:96
bool isAgentAlive(AgentRef reference) const noexcept
Whether the owner and generation still identify a live agent. @thread Simulation thread only; the cal...
Result< FlowSample > sampleFlowField(const FlowLease &lease, float x, float y) const
Sample a current lease; stale/foreign leases fail, unreachable locations return zero....
Result< FlowBuildProgress > advanceFlowBuild(FlowBuildPlan &plan, int maxWork)
Spend at most maxWork heap-pop/direction-cell units on owned request state.
Owning immutable field lease; copies pin storage, never the Crowd provider. @thread Copy/release/quer...
Definition CrowdTypes.h:48
constexpr bool isZero() const noexcept
Returns whether this value is zero.
EVENGINE_API_DOMAINS Result< void > configure(CrowdFlowNavigationSettings settings) noexcept
Change cheap quotas without losing jobs or the owner/tick spending latch. @ownership Stores values on...
EVENGINE_API_DOMAINS Result< void > pump(crowd::Crowd &crowd, const SimulationStep &step)
EVENGINE_API_DOMAINS void disable() noexcept
Disable policy and release jobs/leases while retaining the current spending boundary....
EVENGINE_API_DOMAINS Result< InputChange > begin(crowd::Crowd &crowd, const SimulationStep &step)
Reconcile owner/input epochs and retire unused goals; owner thread, no callbacks.
EVENGINE_API_DOMAINS CrowdFlowNavigationObservation observation() const noexcept
Observe bounded work metadata without field copies; owner thread only.
EVENGINE_API_DOMAINS Result< DriveState > steer(crowd::Crowd &crowd, WorldPosition position, WorldPosition target, float radius, crowd::MovementBinding movement, crowd::AgentUpdate &update)
EVENGINE_API_DOMAINS Result< void > request(crowd::Crowd &crowd, WorldPosition target, SimulationTick tick)
static Result< std::size_t > stepSharedFlow(const SimulationStep &step, crowd::Crowd &crowd, CrowdFlowNavigation &navigation)
Consume shared static-goal fields through a known owner-thread flow service.
Result< void > configureCrowdFlowNavigation(CrowdFlowNavigationSettings settings)
Enable shared-field steering for eligible linked movement and constrained formation slots.
CrowdFlowNavigationObservation getCrowdFlowNavigationStatus() const noexcept
Observe current work quotas/jobs without copying fields; owner thread only.
void clearCrowdFlowNavigation() noexcept
Disable shared-flow work and release jobs, retaining spending history; clear agent leases on next syn...
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Agent identity qualified by the Crowd instance that owns its registry. @ownership Value only; it neit...
Definition CrowdTypes.h:90
Caller-built atomic update batch; duplicate agent references are rejected.
Definition Crowd.h:173
std::vector< AgentUpdate > agents
Definition Crowd.h:174
Owned changes for one live agent. Absent fields keep their existing values.
Definition Crowd.h:161
std::optional< SteeringIntent > intent
Definition Crowd.h:170
std::optional< float > maxSpeed
Definition Crowd.h:165
std::optional< FlowLease > flow
Definition Crowd.h:162
NavigationSurfaceStamp surface
Definition Crowd.h:57
Agent-owned selection of a provider-defined movement policy. Zero identity and revision mean compatib...
Definition CrowdTypes.h:27
MovementClassId movement
Definition CrowdTypes.h:28
Owning shared-flow work observation, independent of render timing.
Definition RTS.h:58
Explicit shared-goal work quotas, consumed once per positive simulation tick.
Definition RTS.h:54
Two-dimensional deterministic RTS world position.
Definition RTSTypes.h:53