载入中...
搜索中...
未找到
CrowdInternal.h
浏览该文件的文档.
1// eve-hot-path
2#pragma once
3
4#include "crowd/Crowd.h"
7
8#include <algorithm>
9#include <cmath>
10#include <functional>
11#include <string_view>
12#include <unordered_map>
13#include <vector>
14
15namespace eve::crowd {
16bool validAgentUpdate(const AgentUpdate& update);
17
23[[nodiscard]] Result<std::vector<int>> canonicalFlowCoordinates(std::span<const FlowGoal> goals,
24 const CrowdField& field);
25
29bool isFlowPointReachable(const CrowdField& field, float x, float y) noexcept;
30
32void exposeAgentBatches(ssq::Class& cls);
34void exposeNavigationRequests(ssq::Class& cls);
39[[nodiscard]] Result<FlowLease> resolveFlowRequestLease(Crowd& crowd, const ssq::Table& token);
40
42bool isTerrainClear(const CrowdField& field, bool clamp, float x, float y, float radius);
44InteractionPolicy canonicalInteraction(AgentInteraction policy);
46bool validInteraction(InteractionPolicy policy);
48InteractionPolicy parseInteractionPolicy(ssq::Table table);
50MovementBinding parseMovementBinding(const ssq::Table& table);
52std::uint64_t namedTieValue(std::string_view identity);
53
60 struct Entry {
62 std::optional<FlowLease> lease;
63 std::uint32_t generation = 1;
64 bool occupied = false;
65 };
66 std::vector<Entry> entries;
71 [[nodiscard]] Result<std::reference_wrapper<Entry>> resolve(std::uint64_t owner, const ssq::Table& token);
72};
73
79 std::shared_ptr<CrowdWorkScheduler> workScheduler;
80 void dispatchWork(std::size_t items, const std::function<void(std::size_t, std::size_t)>& body);
81
82 void applyAgentUpdate(const AgentUpdate& update, std::size_t slot);
83 struct AdvanceGuard;
84 Impl();
86 std::uint32_t generation = 1;
87 int denseIndex = -1;
88 };
89 std::uint64_t owner;
90 std::vector<RegistryEntry> registry;
91 std::vector<std::uint32_t> denseToRegistry, freeRegistry;
92 void reserveAgentAppend();
93 void appendAgentIdentity(int denseIndex);
94 void eraseAgentIdentity(int denseIndex);
96 int resolveAgent(AgentRef reference) const noexcept;
100 std::shared_ptr<const CrowdField> field;
101 std::weak_ptr<const void> pins;
103 std::uint64_t input = 0, generation = 0, bytes = 0;
106 };
107 static std::uint64_t retainedFlowBytes(const CrowdField& value);
108 static bool isFlowKeyBefore(const FlowCacheEntry& a, const FlowCacheEntry& b);
113 [[nodiscard]] Result<std::vector<FlowCacheEntry>> stageFlowCache(std::uint64_t budget, std::uint64_t bytes,
114 size_t count) const;
116 std::vector<FlowCacheEntry> flowCache;
117 std::uint64_t flowCacheBudget = 64 * 1024 * 1024, nextFlowGeneration = 1;
118 bool isFlowLeaseCurrent(const FlowLease& lease) const noexcept {
119 return lease.field_ && lease.owner_ == owner && lease.input_ == field.inputRevision() &&
120 lease.field_->isBuilt() && lease.algorithm_ == flowBuildAlgorithmVersion;
121 }
122
124 std::vector<float> xs, ys, headings, vxs, vys, speeds, wanderPhases;
128 std::optional<ClockAuthority> clock;
130 bool budgetActive = false;
131
132 float defaultSpeed = 120.f;
133 float defaultRadius = 6.f;
134 float defaultTurnRate = 6.f;
135 float arriveRadius = 64.f;
136 float sepRadius = 28.f;
137 float perceiveRadius = 64.f;
138 float sepWeight = 1.f;
139 float alignWeight = 0.f;
140 float cohesionWeight = 0.f;
141 float wanderWeight = 0.f;
142 float goalWeight = 1.f;
143 bool resolveOverlaps = true;
144 bool clampToField = true;
145 int maxAgents = 100000;
146 float simTime = 0.f;
148 std::int64_t avoidanceChecks = 0;
153 size_t slot;
154 double distance2;
155 };
160 std::vector<std::vector<AvoidanceNeighbor>> predictionNeighbors;
161
166 // SOA 单位存储(id = 槽位索引)。
167 std::vector<float> xs, ys, headings, vxs, vys, speeds;
170 std::vector<float> radii, maxSpeeds, maxAccels, turnRates;
171 std::vector<int32_t> actions, datas, avoidancePriorities;
172 std::vector<uint8_t> hasTargets;
173 std::vector<InteractionPolicy> interactions;
174 std::vector<MovementBinding> movements;
175 std::vector<FlowLease> flows;
176 std::vector<float> targetXs, targetYs;
177 std::vector<float> wanderPhases;
178 std::vector<std::string> stableIds;
180 std::vector<TieKey> tieKeys;
181 std::unordered_map<std::uint64_t, int> namedTieKeys;
182 std::uint64_t nextAnonymousTieKey = 1;
183 std::unordered_map<std::string, int> namedAgents;
184
186 struct ContactPair {
188 };
190 float leftX = 0.f, leftY = 0.f, rightX = 0.f, rightY = 0.f;
191 float penetration = 0.f;
192 };
193 std::vector<ContactPair> contactPairs;
194 std::vector<ContactDelta> contactDeltas;
195 std::vector<std::size_t> incidentStarts, incidentPairs;
196 std::vector<std::size_t> pairCounts, pairStarts;
197
198 bool validId(int id) const { return id >= 0 && id < int(actions.size()); }
199 bool isMovementCompatible(size_t index) const {
200 if (flows[index].field_ && !isFlowLeaseCurrent(flows[index])) return false;
201 const auto& binding = movements[index];
202 const bool explicitClass = binding.movement.value() != 0;
203 if (field.navigationCost_.empty()) return !explicitClass;
205 (!explicitClass ||
207 }
208
209 int navigationMismatchCount() const noexcept {
210 int count = 0;
211 for (size_t index = 0; index < actions.size(); ++index)
212 if (actions[index] == static_cast<int>(AgentAction::Flow) && !isMovementCompatible(index)) ++count;
213 return count;
214 }
215
221 const CrowdField* navigationField(size_t index) const noexcept {
222 if (!isMovementCompatible(index)) return nullptr;
223 if (flows[index].field_) return flows[index].field_.get();
224 return field.isBuilt() ? &field : nullptr;
225 }
226
227 bool canContact(size_t a, size_t b) const {
228 return (interactions[a].contactLayer & interactions[b].contactMask) != 0 &&
229 (interactions[b].contactLayer & interactions[a].contactMask) != 0;
230 }
231 bool canAvoid(size_t a, size_t b) const {
232 return (interactions[a].avoidanceLayer & interactions[b].avoidanceMask) != 0 &&
233 (interactions[b].avoidanceLayer & interactions[a].avoidanceMask) != 0;
234 }
235
236 std::vector<std::size_t> preferredCounts, preferredStarts;
237 std::vector<int> preferredNeighbors;
239 float x = 0.f, y = 0.f, arrive = 1.f;
240 };
241 std::vector<PreferredFlow> preferredFlows;
242 void spendPreferredWork(std::int64_t amount);
244 void preparePreferredVelocities(float dt);
245 void rebuildGrid();
246
247 template <typename Fn>
248 void forEachNeighbor(float qx, float qy, float radius, Fn&& fn, StepReport* partitionReport = nullptr) const {
249 const double r2 = double(radius) * radius;
250 StepReport& counters = partitionReport == nullptr ? workReport : *partitionReport;
251 const auto baseSpatial = partitionReport == nullptr ? 0 : workReport.spatialVisits;
252 const auto baseCandidates = partitionReport == nullptr ? 0 : workReport.candidatesVisited;
254 qx, qy, radius,
255 budgetActive ? activeBudget.maxSpatialVisits - baseSpatial : std::numeric_limits<std::int64_t>::max(),
256 counters.spatialVisits, counters.cellsVisited, [&](int j) {
257 if (budgetActive && counters.candidatesVisited >= activeBudget.maxNeighborVisits - baseCandidates)
258 throw WorkLimit{"Crowd neighbor visit budget exhausted"};
259 ++counters.candidatesVisited;
260 const double dx = double(xs[size_t(j)]) - qx, dy = double(ys[size_t(j)]) - qy;
261 if (dx * dx + dy * dy <= r2) fn(j);
262 });
263 }
264
265 void stepAgents(float dt);
267 void selectAvoidanceVelocity(size_t index, float dt, float& vx, float& vy);
268
269 float resolveOverlapsPass();
270
271 void resolveWalls();
272};
273
274} // namespace eve::crowd
double y
double x
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
HSQOBJECT cls
Definition ECS.cpp:39
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanGpuFrameToken token
std::shared_ptr< OceanGpuSpectrum > owner
glm::dvec3 dx
double dt
eve::action::ActionVfxBinding binding
PrefabLease lease
std::string body
Object::Ptr value
std::string slot
float dy
Definition Shadow.cpp:151
int count
uint32_t index
uint64_t identity
Signed, fixed-resolution simulation duration in nanoseconds.
Definition Time.h:43
Move-only operation result carrying either a value or Status.
Definition Result.h:176
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
连续流场(flow field)。
Definition CrowdField.h:25
bool isBuilt() const
Whether directions were built for the current terrain and goals.
Definition CrowdField.h:104
std::uint64_t inputRevision() const noexcept
Navigation geometry/cost/rule epoch; goal edits and field publications do not change it.
Definition CrowdField.h:108
Owning sparse broadphase workspace; integer cell/row order and stable tie-key bucket order....
void visit(double x, double y, double radius, std::int64_t maxVisits, std::int64_t &visits, std::int64_t &visitedCells, Fn &&fn) const
Enumerate conservative candidates in a query box with explicit lookup-work charging....
Move-only navigation workstate; contains no borrowed provider pointers.
Definition Crowd.h:309
Owning immutable field lease; copies pin storage, never the Crowd provider. @thread Copy/release/quer...
Definition CrowdTypes.h:48
Result< FlowLease > resolveFlowRequestLease(Crowd &crowd, const ssq::Table &token)
Resolve a checked request-owned lease without retaining script table references.
constexpr std::uint32_t flowBuildAlgorithmVersion
Increment when the navigation construction algorithm changes its observable output.
Definition CrowdTypes.h:41
CrowdExecution
Explicit execution selection; serial does not require a provider.
MovementBinding parseMovementBinding(const ssq::Table &table)
Decode exact integer movement identities; no floating-point identity coercion.
void exposeAgentBatches(ssq::Class &cls)
Compose public numeric identity/batch bindings without accessing private storage.
bool validAgentUpdate(const AgentUpdate &update)
Result< std::vector< int > > canonicalFlowCoordinates(std::span< const FlowGoal > goals, const CrowdField &field)
Copy validated goals into their unique canonical coordinates.
bool validInteraction(InteractionPolicy policy)
Check finite mobility and nonnegative filter masks without modifying state.
InteractionPolicy parseInteractionPolicy(ssq::Table table)
Decode a canonical policy at the script boundary; throws on missing or wrongly typed fields.
void exposeNavigationRequests(ssq::Class &cls)
Register generation-qualified transient navigation request bindings.
InteractionPolicy canonicalInteraction(AgentInteraction policy)
Normalize a compatibility filter into the canonical two-filter policy.
bool isFlowPointReachable(const CrowdField &field, float x, float y) noexcept
Observe exact containing-cell reachability, independent of interpolation across blocked cells....
std::uint64_t namedTieValue(std::string_view identity)
Hash UTF-8 identity bytes once at admission; collisions are rejected by the registry.
bool isTerrainClear(const CrowdField &field, bool clamp, float x, float y, float radius)
Shared exact-placement geometry predicate for creation and relocation transactions.
Definition CrowdSpawn.cpp:6
SettlementPipeline::Stage fn
Deterministic operation budgets; exhaustion rejects the entire step before publication.
Definition Crowd.h:71
std::int64_t maxSpatialVisits
Query row/cell/binary-search work.
Definition Crowd.h:78
std::int64_t maxNeighborVisits
Definition Crowd.h:75
Agent identity qualified by the Crowd instance that owns its registry. @ownership Value only; it neit...
Definition CrowdTypes.h:90
Owned changes for one live agent. Absent fields keep their existing values.
Definition Crowd.h:161
Optional bounded velocity sampling for RTS local avoidance.
Definition Crowd.h:129
Canonical in-process tie ordering; named identities sort before anonymous admission ordinals.
std::shared_ptr< const CrowdField > field
std::weak_ptr< const void > pins
std::uint64_t nextAnonymousTieKey
std::vector< std::size_t > preferredStarts
bool isMovementCompatible(size_t index) const
std::vector< std::size_t > preferredCounts
std::vector< float > xs
SOA agent storage, indexed by compact slot id. @cost Linear in agent count; mutation keeps all owned ...
FlowLease leaseFor(FlowCacheEntry &entry)
std::vector< float > preferredVys
std::vector< MovementBinding > movements
CrowdExecution execution
std::vector< float > headings
std::vector< float > maxSpeeds
std::vector< std::size_t > incidentStarts
std::shared_ptr< CrowdWorkScheduler > workScheduler
int navigationMismatchCount() const noexcept
std::vector< float > correctionXs
struct eve::crowd::Crowd::Impl::MotionBackup rollback
std::vector< std::size_t > pairStarts
std::vector< FlowLease > flows
std::vector< RegistryEntry > registry
std::vector< float > vys
std::vector< float > ys
std::vector< std::size_t > pairCounts
std::vector< std::size_t > incidentPairs
std::vector< std::uint32_t > denseToRegistry
std::vector< float > turnRates
bool validId(int id) const
std::vector< float > preferredVxs
bool canContact(size_t a, size_t b) const
std::vector< float > targetYs
void spendPreferredWork(std::int64_t amount)
bool canAvoid(size_t a, size_t b) const
void eraseAgentIdentity(int denseIndex)
std::vector< int > preferredNeighbors
NavigationSurfaceStamp surfaceStamp
std::vector< ContactPair > contactPairs
std::vector< int32_t > datas
std::uint64_t nextFlowGeneration
std::vector< std::uint32_t > freeRegistry
void dispatchWork(std::size_t items, const std::function< void(std::size_t, std::size_t)> &body)
std::vector< float > maxAccels
std::uint64_t flowCacheBudget
std::unordered_map< std::string, int > namedAgents
std::vector< TieKey > tieKeys
void forEachNeighbor(float qx, float qy, float radius, Fn &&fn, StepReport *partitionReport=nullptr) const
AvoidanceSettings avoidance
bool isFlowLeaseCurrent(const FlowLease &lease) const noexcept
Result< std::vector< FlowCacheEntry > > stageFlowCache(std::uint64_t budget, std::uint64_t bytes, size_t count) const
Stage cache metadata and deterministic unleased evictions without live mutation. @ownership Returns o...
std::vector< FlowCacheEntry > flowCache
std::vector< float > correctionYs
std::vector< InteractionPolicy > interactions
void appendAgentIdentity(int denseIndex)
static bool isFlowKeyBefore(const FlowCacheEntry &a, const FlowCacheEntry &b)
std::optional< ClockAuthority > clock
std::vector< float > wanderPhases
int resolveAgent(AgentRef reference) const noexcept
const CrowdField * navigationField(size_t index) const noexcept
Observe the selected compatible built field, or null when unavailable. @ownership Borrowed read-only ...
void preparePreferredVelocities(float dt)
static std::uint64_t retainedFlowBytes(const CrowdField &value)
std::unordered_map< std::uint64_t, int > namedTieKeys
std::vector< PreferredFlow > preferredFlows
std::vector< float > arriveFactors
std::vector< float > nextVys
std::vector< float > nextVxs
std::vector< ContactDelta > contactDeltas
std::vector< float > vxs
std::vector< int32_t > avoidancePriorities
CrowdSpatialIndex spatialIndex
std::vector< std::vector< AvoidanceNeighbor > > predictionNeighbors
Per-step avoidance neighbor scratch space. @cost Linear in checked neighbors and bounded by avoidance...
void applyAgentUpdate(const AgentUpdate &update, std::size_t slot)
void selectAvoidanceVelocity(size_t index, float dt, float &vx, float &vy)
std::vector< int32_t > actions
std::vector< uint8_t > hasTargets
std::vector< float > radii
std::vector< float > targetXs
std::vector< std::string > stableIds
std::vector< float > speeds
Private crowd runtime storage. @cost Linear in agent count for SOA vectors and transient broadphase/a...
Result< std::reference_wrapper< Entry > > resolve(std::uint64_t owner, const ssq::Table &token)
Resolve exact token identity without mutation. @ownership Borrow registry entry only until structural...
Provenance of one immutable navigation projection.
Definition CrowdTypes.h:33
Owning observations of one completed advance; simulation-thread only.
Definition Crowd.h:94
std::int64_t cellsVisited
Occupied cells enumerated by all neighborhood queries.
Definition Crowd.h:105
std::int64_t spatialVisits
Query row/cell enumeration and binary-search comparisons.
Definition Crowd.h:108
std::int64_t candidatesVisited
Bucket entries inspected before radius or interaction filtering.
Definition Crowd.h:111
Non-allocating internal unwind signal, translated at the checked simulation boundary.