载入中...
搜索中...
未找到
CrowdBatch.cpp
浏览该文件的文档.
2#include "common/Assert.h"
3
4#include <new>
5
6namespace eve::crowd {
7namespace {
8Result<AgentBatchReceipt> failed(DiagnosticCode code, const char* message) {
10}
11bool nonNegative(const std::optional<float>& value) { return !value || (std::isfinite(*value) && *value >= 0.f); }
12bool validUpdate(const AgentUpdate& update) {
13 if (update.movement && ((update.movement->movement.value() == 0) != (update.movement->revision == 0))) return false;
14 if (!nonNegative(update.maxSpeed) || !nonNegative(update.maxAcceleration) || !nonNegative(update.headingTurnRate) ||
15 !nonNegative(update.radius))
16 return false;
17 if ((update.interaction && update.holdPosition) || (update.policy && update.holdPosition) ||
18 (update.interaction && update.policy))
19 return false;
20 if (update.interaction) {
21 const auto& value = *update.interaction;
22 if (!std::isfinite(value.pushability) || value.pushability < 0.f || value.pushability > 1.f ||
23 value.layer < 0 || value.mask < 0)
24 return false;
25 }
26 if (update.policy && !validInteraction(*update.policy)) return false;
27 if (update.intent) {
28 const auto& value = *update.intent;
29 if (value.action < AgentAction::Idle || value.action > AgentAction::Boids || !std::isfinite(value.targetX) ||
30 !std::isfinite(value.targetY))
31 return false;
32 }
33 return true;
34}
35bool duplicates(std::vector<std::uint64_t>& identities) {
36 std::sort(identities.begin(), identities.end());
37 return std::adjacent_find(identities.begin(), identities.end()) != identities.end();
38}
39} // namespace
40
41bool validAgentUpdate(const AgentUpdate& update) { return validUpdate(update); }
43 auto prepared = prepareAgentUpdates(batch);
44 if (!prepared) return Result<AgentBatchReceipt>::failure(prepared.status());
45 return commitAgentUpdates(std::move(prepared).takeValue(), {});
46}
47void Crowd::Impl::applyAgentUpdate(const AgentUpdate& update, std::size_t slot) {
48 auto& d = *this;
49 if (update.maxSpeed) d.maxSpeeds[slot] = *update.maxSpeed;
50 if (update.maxAcceleration) d.maxAccels[slot] = *update.maxAcceleration;
51 if (update.headingTurnRate) d.turnRates[slot] = *update.headingTurnRate;
52 if (update.radius) d.radii[slot] = *update.radius;
53 if (update.flow) d.flows[slot] = *update.flow;
54 if (update.movement) d.movements[slot] = *update.movement;
55 if (update.avoidancePriority) d.avoidancePriorities[slot] = *update.avoidancePriority;
56 if (update.data) d.datas[slot] = *update.data;
57 if (update.interaction) d.interactions[slot] = canonicalInteraction(*update.interaction);
58 if (update.policy) d.interactions[slot] = *update.policy;
59 if (update.holdPosition) d.interactions[slot].holdPosition = *update.holdPosition;
60 if (d.interactions[slot].holdPosition) d.vxs[slot] = d.vys[slot] = d.speeds[slot] = 0.f;
61 if (update.intent) {
62 d.actions[slot] = static_cast<std::int32_t>(update.intent->action);
63 d.hasTargets[slot] = static_cast<std::uint8_t>(update.intent->hasTarget);
64 d.targetXs[slot] = update.intent->targetX;
65 d.targetYs[slot] = update.intent->targetY;
66 }
67
68}
69
71 std::vector<std::uint64_t> identities;
72 try {
73 identities.reserve(batch.agents.size());
74 for (const auto& reference : batch.agents) {
75 if (!isAgentAlive(reference)) return failed(DiagnosticCode::NotFound, "Stale or wrong-owner removal");
76 identities.push_back(reference.handle.packed());
77 }
78 } catch (const std::bad_alloc&) {
79 return failed(DiagnosticCode::Failed, "Cannot allocate removal validation workspace");
80 }
81 if (duplicates(identities)) return failed(DiagnosticCode::Conflict, "Duplicate agent removal");
82 // All allocation and reference validation completed. Re-resolve after every swap-pop.
83 for (const auto& reference : batch.agents) {
84 const bool removed = removeAgent(impl_->resolveAgent(reference));
85 EV_ASSERT(removed, "Validated Crowd removal must succeed without reentry");
86 }
87 return Result<AgentBatchReceipt>::success({batch.agents.size()});
88}
89
91 try {
92 destination.agents.reserve(impl_->xs.size());
93 } catch (const std::bad_alloc&) {
94 return failed(DiagnosticCode::Failed, "Cannot reserve output frame storage");
95 }
96 destination.agents.resize(impl_->xs.size());
97 for (std::size_t slot = 0; slot < impl_->xs.size(); ++slot) {
98 const auto registryIndex = impl_->denseToRegistry[slot];
99 destination.agents[slot] = {
100 {AgentHandle(registryIndex, impl_->registry[registryIndex].generation), impl_->owner},
101 getAgentState(static_cast<int>(slot))};
102 }
103 destination.simulationSeconds = impl_->elapsed.seconds();
104 destination.tick = impl_->tick;
105 return Result<AgentBatchReceipt>::success({destination.agents.size()});
106}
107
108Result<AgentBatchReceipt> Crowd::copyAgentStates(std::span<const AgentRef> references, AgentFrame& destination) const {
109 for (const auto reference : references)
110 if (!isAgentAlive(reference)) return failed(DiagnosticCode::NotFound, "Stale or wrong-owner frame reference");
111 try {
112 destination.agents.reserve(references.size());
113 } catch (const std::bad_alloc&) {
114 return failed(DiagnosticCode::Failed, "Cannot reserve selected output frame storage");
115 }
116 destination.agents.resize(references.size());
117 for (std::size_t index = 0; index < references.size(); ++index)
118 destination.agents[index] = {references[index], getAgentState(impl_->resolveAgent(references[index]))};
119 destination.simulationSeconds = impl_->elapsed.seconds();
120 destination.tick = impl_->tick;
121 return Result<AgentBatchReceipt>::success({references.size()});
122}
123
124} // namespace eve::crowd
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
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
std::string message
DiagnosticCode code
std::set< std::string > identities
Object::Ptr value
float d
std::string slot
int removed
uint32_t index
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
bool removeAgent(int id)
删除单位(swap-pop O(1))。
Definition Crowd.cpp:191
AgentState getAgentState(int id) const
读取单位状态快照(非法 id 返回 action=-1)。
Definition Crowd.cpp:369
Result< AgentBatchReceipt > updateAgents(const AgentUpdateBatch &batch)
Compatibility-only one-call facade over canonical prepareAgentUpdates/commitAgentUpdates....
Result< AgentUpdatePlan > prepareAgentUpdates(const AgentUpdateBatch &batch) const
Canonically validate and own a batch before a later nonallocating commit. @ownership Copies values; r...
Result< AgentBatchReceipt > commitAgentUpdates(AgentUpdatePlan &&plan, std::span< const std::uint8_t > selection)
Validate all identities then apply selected prepared updates without allocating success-path workspac...
bool isAgentAlive(AgentRef reference) const noexcept
Whether the owner and generation still identify a live agent. @thread Simulation thread only; the cal...
Result< AgentBatchReceipt > removeAgents(const AgentRemovalBatch &batch)
Atomically remove live references; every reference is checked before any removal. @ownership Borrows ...
Result< AgentBatchReceipt > copyAgentFrame(AgentFrame &destination) const
Copy one owning frame into reusable caller storage; allocation failure preserves the output....
Result< AgentBatchReceipt > copyAgentStates(std::span< const AgentRef > references, AgentFrame &destination) const
Copy a selected owning frame in request order; stale input preserves the destination....
RuntimeHandle< CrowdAgentTag > AgentHandle
Generation-qualified runtime agent identity; never persist its packed representation.
Definition CrowdTypes.h:82
bool validAgentUpdate(const AgentUpdate &update)
bool validInteraction(InteractionPolicy policy)
Check finite mobility and nonnegative filter masks without modifying state.
InteractionPolicy canonicalInteraction(AgentInteraction policy)
Normalize a compatibility filter into the canonical two-filter policy.
Result< T > failed(Status status, eve::DiagnosticCode code, RuleId rule, std::string message)
Construct a failed editing result with explicit status and diagnostic categories.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Caller-owned frame storage; no pointers into Crowd are retained.
Definition Crowd.h:200
double simulationSeconds
Definition Crowd.h:202
std::vector< AgentFrameEntry > agents
Definition Crowd.h:201
SimulationTick tick
Definition Crowd.h:203
Owned identities to remove atomically; duplicate and stale references are rejected.
Definition Crowd.h:177
std::vector< AgentRef > agents
Definition Crowd.h:178
Caller-built atomic update batch; duplicate agent references are rejected.
Definition Crowd.h:173
Owned changes for one live agent. Absent fields keep their existing values.
Definition Crowd.h:161
std::optional< int > avoidancePriority
Definition Crowd.h:166
std::optional< SteeringIntent > intent
Definition Crowd.h:170
std::optional< AgentInteraction > interaction
Definition Crowd.h:167
std::optional< float > maxSpeed
Definition Crowd.h:165
std::optional< InteractionPolicy > policy
Definition Crowd.h:168
std::optional< float > headingTurnRate
Definition Crowd.h:165
std::optional< float > radius
Definition Crowd.h:165
std::optional< MovementBinding > movement
Definition Crowd.h:164
std::optional< int > data
Definition Crowd.h:166
std::optional< float > maxAcceleration
Definition Crowd.h:165
std::optional< FlowLease > flow
Definition Crowd.h:162
std::optional< bool > holdPosition
Definition Crowd.h:169
void applyAgentUpdate(const AgentUpdate &update, std::size_t slot)