载入中...
搜索中...
未找到
GpuAgentSimulation.cpp
浏览该文件的文档.
2#include <cmath>
3#include <functional>
4#include <simplesquirrel/simplesquirrel.hpp>
5#include <string>
6#include <utility>
7#include "common/Assert.h"
8#include "common/Diagnostic.h"
10#include "gpuagents/GpuAgents.h"
17
18// GpuAgentSimulation.cpp
19namespace eve::gpuagents {
20
21Result<void> GpuAgentSimulation::makeDefaultSolver() {
22 switch (profile_.kind) {
23 case EffectKind::Fish: solver_ = std::make_unique<FishSolver>(); break;
24 case EffectKind::LifeNetwork: solver_ = std::make_unique<LifeNetworkSolver>(); break;
25 case EffectKind::Bird: solver_ = std::make_unique<BirdSolver>(); break;
26 case EffectKind::Petal: solver_ = std::make_unique<PetalSolver>(); break;
27 default:
29 Diagnostic::error(DiagnosticCode::InvalidArgument, "unknown EffectKind", "kind", {}, "gpuagents"));
30 }
31 return Result<void>::success();
32}
33
35 if (profile.base().maxAgents <= 0) {
37 "maxAgents", {}, "gpuagents"));
38 }
39 if (profile.base().fixedDt <= 0.f) {
41 Diagnostic::error(DiagnosticCode::InvalidArgument, "fixedDt must be positive", "fixedDt", {}, "gpuagents"));
42 }
43 profile_ = profile;
44 capacity_ = profile.base().maxAgents;
45 buffers_[0].assign(static_cast<size_t>(capacity_), AgentState{});
46 buffers_[1].assign(static_cast<size_t>(capacity_), AgentState{});
47 front_ = 0;
48 accumulator_ = 0.f;
49 simTime_ = 0.f;
50 stepCount_ = 0;
51 configured_ = true;
52 auto solverRes = makeDefaultSolver();
53 if (!solverRes.ok()) {
54 configured_ = false;
55 return solverRes;
56 }
57 return Result<void>::success();
58}
59
60Result<void> GpuAgentSimulation::setSolver(std::unique_ptr<IAgentSolver> solver) {
61 if (!solver) {
63 Diagnostic::error(DiagnosticCode::InvalidArgument, "solver is null", "solver", {}, "gpuagents"));
64 }
65 if (configured_ && solver->kind() != profile_.kind) {
67 Diagnostic::error(DiagnosticCode::InvalidArgument, "solver kind mismatch", "solver", {}, "gpuagents"));
68 }
69 solver_ = std::move(solver);
70 return Result<void>::success();
71}
72
73Result<void> GpuAgentSimulation::initialize(int count, const std::function<AgentState(int)>& spawnFn) {
74 if (!configured_) {
76 "simulation not configured", "configure", {}, "gpuagents"));
77 }
78 if (!spawnFn) {
80 Diagnostic::error(DiagnosticCode::InvalidArgument, "spawnFn is empty", "spawnFn", {}, "gpuagents"));
81 }
82 if (count < 0 || count > capacity_) {
83 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "initialize count out of range",
84 "count", {}, "gpuagents"));
85 }
86 auto& buf = buffers_[front_];
87 for (int i = 0; i < capacity_; ++i) {
88 if (i < count) {
89 AgentState s = spawnFn(i);
90 s.alive = 1;
91 buf[static_cast<size_t>(i)] = s;
92 } else {
93 buf[static_cast<size_t>(i)] = AgentState{};
94 }
95 }
96 buffers_[1 - front_] = buf;
97 accumulator_ = 0.f;
98 return Result<void>::success();
99}
100
102 if (!configured_) return;
103 for (auto& b : buffers_) {
104 for (auto& s : b) s = AgentState{};
105 }
106 accumulator_ = 0.f;
107 simTime_ = 0.f;
108 stepCount_ = 0;
109}
110
112 int n = 0;
113 for (const auto& s : buffers_[front_]) {
114 if (s.alive) ++n;
115 }
116 return n;
117}
118
120 if (!configured_ || !solver_) {
122 "simulation not configured", "configure", {}, "gpuagents"));
123 }
124 EV_PARAM_CHECK(dt >= 0.f);
125 accumulator_ += dt;
126 const float fixed = profile_.base().fixedDt;
127 int guard = 0;
128 while (accumulator_ + 1e-8f >= fixed && guard < 8) {
129 const int read = front_;
130 const int write = 1 - front_;
131 solver_->step(buffers_[read], buffers_[write], profile_, env, fixed);
132 front_ = write;
133 accumulator_ -= fixed;
134 simTime_ += fixed;
135 ++stepCount_;
136 ++guard;
137 }
138 return Result<void>::success();
139}
140
141} // namespace eve::gpuagents
142
143// GpuAgentWorld.cpp
144namespace eve::gpuagents {
145
147 if (name.empty()) {
149 Diagnostic::error(DiagnosticCode::InvalidArgument, "backend name is empty", "name", {}, "gpuagents"));
150 }
151 if (!backend) {
153 Diagnostic::error(DiagnosticCode::InvalidArgument, "backend is null", "backend", {}, "gpuagents"));
154 }
155 if (backends_.count(name) != 0) {
157 Diagnostic::error(DiagnosticCode::AlreadyExists, "backend name already registered", name, {}, "gpuagents"));
158 }
159 backends_.emplace(std::move(name), backend);
160 return Result<void>::success();
161}
162
164 if (backends_.erase(name) == 0) {
166 Diagnostic::error(DiagnosticCode::NotFound, "backend not registered", name, {}, "gpuagents"));
167 }
168 return Result<void>::success();
169}
170
171EffectBackend* GpuAgentWorld::find(const std::string& name) const {
172 const auto it = backends_.find(name);
173 return it == backends_.end() ? nullptr : it->second;
174}
175
178 snap.waterCurrent = waterCurrent_;
179 snap.windVelocity = wind_;
180 snap.groundY = groundY_;
181 snap.ceilingY = ceilingY_;
182 snap.goals = goals_;
183 snap.dangers = dangers_;
184 snap.nutrients = nutrients_;
185 snap.obstacles = &obstacles_;
186 snap.surface = includeSurface ? const_cast<SurfaceField*>(&surface_) : nullptr;
187 return snap;
188}
189
191 for (auto& [name, backend] : backends_) {
192 (void)name;
193 if (!backend) {
195 "registered backend is null", name, {}, "gpuagents"));
196 }
197 const bool needSurface = backend->kind() == EffectKind::LifeNetwork;
198 EnvironmentSnapshot snap = makeSnapshot(needSurface);
199 auto stepped = backend->step(dt, snap);
200 if (!stepped.ok()) return stepped;
201 }
202 return Result<void>::success();
203}
204
205} // namespace eve::gpuagents
206
207// GpuAgents.cpp
208namespace eve::gpuagents {
209namespace {
210
211glm::vec3 unitFromIndex(int i, std::uint32_t seed) {
212 const float a = static_cast<float>((static_cast<std::uint32_t>(i) * 1103515245u + seed) & 0xFFFFu) / 65535.f;
213 const float b = static_cast<float>(((static_cast<std::uint32_t>(i) * 12345u) ^ seed) & 0xFFFFu) / 65535.f;
214 const float theta = a * 6.2831853f;
215 const float u = b * 2.f - 1.f;
216 const float r = std::sqrt(std::max(0.f, 1.f - u * u));
217 return glm::vec3(r * std::cos(theta), u, r * std::sin(theta));
218}
219
220} // namespace
221
223
225
226EffectProfile GpuAgents::makeProfile(int kind, int maxAgents) const {
227 switch (static_cast<EffectKind>(kind)) {
228 case EffectKind::LifeNetwork: return EffectProfile::makeLife(maxAgents);
229 case EffectKind::Bird: return EffectProfile::makeBird(maxAgents);
230 case EffectKind::Petal: return EffectProfile::makePetal(maxAgents);
231 case EffectKind::Fish:
232 default: return EffectProfile::makeFish(maxAgents);
233 }
234}
235
237 auto backend = std::make_unique<EffectBackend>();
238 auto profile = makeProfile(kind, maxAgents);
239 auto cfg = backend->configure(profile);
240 if (!cfg.ok()) return nullptr;
241 return backend.release();
242}
243
244Result<void> GpuAgents::spawnCloud(EffectBackend* backend, int count, float centerX, float centerY, float centerZ,
245 float spread) const {
246 if (!backend) {
248 Diagnostic::error(DiagnosticCode::InvalidArgument, "backend is null", "backend", {}, "gpuagents"));
249 }
250 if (!backend->simulation().isConfigured()) {
252 "configure", {}, "gpuagents"));
253 }
254 const glm::vec3 center(centerX, centerY, centerZ);
255 const auto& base = backend->simulation().profile().base();
256 const EffectKind kind = backend->kind();
257 return backend->simulation().initialize(count, [&](int i) {
259 const glm::vec3 dir = unitFromIndex(i, base.seed);
260 s.position = center + dir * spread;
261 switch (kind) {
262 case EffectKind::Fish: s.velocity = dir * 2.f; break;
263 case EffectKind::Bird: s.velocity = glm::normalize(dir + glm::vec3(0.f, 0.2f, 0.f)) * 6.f; break;
265 s.velocity = glm::vec3(dir.x, -1.f, dir.z);
266 s.customData[1] = 0.75f + 0.5f * (static_cast<float>(i % 10) / 10.f);
267 s.rotation = lookRotation(glm::vec3(0.f, -1.f, 0.f));
268 break;
270 s.position.y = centerY;
271 s.velocity = glm::normalize(glm::vec3(dir.x, 0.f, dir.z) + glm::vec3(1e-3f, 0.f, 0.f)) * 1.5f;
272 break;
273 }
274 s.rotation = lookRotation(glm::length(s.velocity) > 1e-4f ? s.velocity : glm::vec3(0.f, 0.f, 1.f));
275 return s;
276 });
277}
278
280 const std::vector<std::uint32_t>& indices, float originX, float originY,
281 float originZ, float worldSize, int resolution) const {
282 if (!world) {
284 Diagnostic::error(DiagnosticCode::InvalidArgument, "world is null", "world", {}, "gpuagents"));
285 }
286 if (positions.size() % 3 != 0) {
288 DiagnosticCode::InvalidArgument, "positions must be interleaved xyz floats", "positions", {}, "gpuagents"));
289 }
290 std::vector<glm::vec3> verts;
291 verts.reserve(positions.size() / 3);
292 for (size_t i = 0; i + 2 < positions.size(); i += 3) {
293 verts.emplace_back(positions[i], positions[i + 1], positions[i + 2]);
294 }
295 return SurfaceCapture::captureFromTriangles(world->surface(), verts, indices, glm::vec3(originX, originY, originZ),
296 worldSize, resolution, originY);
297}
298
300 if (!world || !binding) {
302 Diagnostic::error(DiagnosticCode::InvalidArgument, "world or binding is null", "binding", {}, "gpuagents"));
303 }
304 return binding->syncFrom(world->surface());
305}
306
307void GpuAgents::expose(ssq::Table& table) {
308 auto cls = table.addClass(name, GpuAgents::create, false);
309 expose(cls);
310
311 auto world = table.addClass<GpuAgentWorld>(
312 "GpuAgentWorld", std::function<GpuAgentWorld*()>([]() -> GpuAgentWorld* { return nullptr; }), true);
313 world.addFunc("setWaterCurrent", &GpuAgentWorld::setWaterCurrent);
314 world.addFunc("setWind", &GpuAgentWorld::setWind);
315 world.addFunc("setVerticalBounds", &GpuAgentWorld::setVerticalBounds);
316 world.addFunc("backendCount", &GpuAgentWorld::backendCount);
317 world.addFunc("stepAll", [](GpuAgentWorld* w, float dt) {
318 if (!w) return false;
319 return w->stepAll(dt).ok();
320 });
321 world.addFunc("bakeEmptyObstacles",
322 [](GpuAgentWorld* w, float ox, float oy, float oz, int dx, int dy, int dz, float cell) {
323 if (!w) return;
324 w->obstacles().bakeEmpty(glm::vec3(ox, oy, oz), glm::ivec3(dx, dy, dz), cell);
325 });
326 world.addFunc("carveSphere", [](GpuAgentWorld* w, float x, float y, float z, float r) {
327 if (!w) return;
328 w->obstacles().carveSphere(glm::vec3(x, y, z), r);
329 });
330 world.addFunc("initFlatSurface", [](GpuAgentWorld* w, float ox, float oy, float oz, float size, int res) {
331 if (!w) return;
332 w->surface().initFlat(glm::vec3(ox, oy, oz), size, res, oy);
333 });
334
335 auto backend = table.addClass<EffectBackend>(
336 "GpuAgentEffectBackend", std::function<EffectBackend*()>([]() -> EffectBackend* { return nullptr; }), true);
337 backend.addFunc("kind", [](EffectBackend* b) { return b ? static_cast<int>(b->kind()) : -1; });
338 backend.addFunc("aliveCount", [](EffectBackend* b) { return b ? b->simulation().aliveCount() : 0; });
339 backend.addFunc("instanceCount", [](EffectBackend* b) { return b ? b->renderer().instanceCount() : 0; });
340 backend.addFunc("reset", [](EffectBackend* b) {
341 if (b) b->reset();
342 });
343 backend.addFunc("step", [](EffectBackend* b, GpuAgentWorld* w, float dt) {
344 if (!b || !w) return false;
345 const bool needSurface = b->kind() == EffectKind::LifeNetwork;
346 return b->step(dt, w->makeSnapshot(needSurface)).ok();
347 });
348}
349
350void GpuAgents::expose(ssq::Class& cls) {
351 cls.addFunc("newWorld", &GpuAgents::newWorld);
352 cls.addFunc("newBackend", &GpuAgents::newBackend);
353 cls.addFunc("spawnCloud", [](GpuAgents* m, EffectBackend* b, int count, float x, float y, float z, float spread) {
354 if (!m) return false;
355 return m->spawnCloud(b, count, x, y, z, spread).ok();
356 });
357 cls.addFunc("registerBackend", [](GpuAgents*, GpuAgentWorld* w, const std::string& name, EffectBackend* b) {
358 if (!w || !b) return false;
359 // Borrowed: script / VM retains ownership of the backend.
360 return w->registerBackend(name, b).ok();
361 });
362 cls.addFunc("captureSurface", [](GpuAgents* m, GpuAgentWorld* w, ssq::Array positions, ssq::Array indices, float ox,
363 float oy, float oz, float size, int res) {
364 if (!m || !w) return false;
365 std::vector<float> pos;
366 pos.reserve(positions.size());
367 for (size_t i = 0; i < positions.size(); ++i) pos.push_back(positions.get<float>(i));
368 std::vector<std::uint32_t> idx;
369 idx.reserve(indices.size());
370 for (size_t i = 0; i < indices.size(); ++i) idx.push_back(static_cast<std::uint32_t>(indices.get<int>(i)));
371 return m->captureSurface(w, pos, idx, ox, oy, oz, size, res).ok();
372 });
373}
374
375} // namespace eve::gpuagents
double z
double y
double m[16]
double x
float w
Definition AnimClip.cpp:738
EVEngine assertion entry point, backed by zeroerr.
#define EV_PARAM_CHECK(cond,...)
Validate a function parameter / public API precondition.
Definition Assert.h:30
const std::string & s
std::vector< std::uint32_t > verts
Definition Builder.cpp:27
Stable, structured diagnostics shared by engine modules.
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
double r
std::vector< std::uint32_t > indices
std::vector< float > positions
std::function< void(b3JointId, const Numbers &)> write
std::function< Numbers(b3JointId)> read
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
OceanRenderBackend backend
glm::dvec2 center
glm::dvec3 dx
glm::dvec3 dz
double dt
eve::action::ActionVfxBinding binding
int idx
std::string kind
float dy
Definition Shadow.cpp:151
int count
Cell cell
uint32_t seed
Definition TreeMesh.cpp:276
float size
Definition TreeMesh.cpp:158
V3 dir
Definition TreeMesh.cpp:151
double oy
double ox
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
Binds an EffectProfile to a GpuAgentSimulation and optional renderer.
const EffectProfile & profile() const
Bound profile.
Result< void > setSolver(std::unique_ptr< IAgentSolver > solver)
Replace the solver instance (tests / custom kernels). @ownership Simulation takes ownership.
Result< void > initialize(int count, const std::function< AgentState(int)> &spawnFn)
Spawn count alive agents using spawnFn(index) -> AgentState.
void reset()
Clear all agents and the time accumulator.
int aliveCount() const
Number of alive agents.
Result< void > configure(const EffectProfile &profile)
Configure capacity and bind a solver for the profile kind.
Result< void > step(float dt, const EnvironmentSnapshot &env)
Advance wall-clock dt via fixed substeps.
World-level registry for GPU agent simulations and environment semantics.
EffectBackend * find(const std::string &name) const
Look up a registered backend by name. @ownership Borrowed; World does not own the returned pointer....
Result< void > unregisterBackend(const std::string &name)
Remove a named backend registration without destroying the backend. @ownership Does not take or relea...
int backendCount() const
Number of registered backends.
EnvironmentSnapshot makeSnapshot(bool includeSurface) const
Build an environment snapshot for the current World state.
Result< void > registerBackend(std::string name, EffectBackend *backend)
Register a borrowed backend under a unique name.
void setWaterCurrent(float x, float y, float z)
Set uniform water current.
void setWind(float x, float y, float z)
Set uniform wind.
Result< void > stepAll(float dt)
Step every registered backend with a shared environment snapshot.
void setVerticalBounds(float groundY, float ceilingY)
Set ground / ceiling heights for bird clearance.
GPU Agents module — extensible fixed-step agent FX simulation.
Definition GpuAgents.h:29
Result< void > captureSurface(GpuAgentWorld *world, const std::vector< float > &positions, const std::vector< std::uint32_t > &indices, float originX, float originY, float originZ, float worldSize, int resolution) const
Orthographic triangle bake into a world's surface field.
EffectBackend * newBackend(int kind, int maxAgents)
Create a configured EffectBackend.
EffectProfile makeProfile(int kind, int maxAgents) const
Build a default EffectProfile value for script helpers.
GpuAgentWorld * newWorld()
Create an empty World. @ownership Caller / script VM owns the returned world; delete or let the VM fr...
Result< void > syncLifeFieldBinding(GpuAgentWorld *world, LifeFieldMaterialBinding *binding) const
Pack a world's surface into CPU LifeField / SurfaceData RGBA buffers.
Result< void > spawnCloud(EffectBackend *backend, int count, float centerX, float centerY, float centerZ, float spread) const
Spawn a simple school / flock / petal cloud into a backend.
Packs SurfaceField channels into Graphics-uploadable RGBA8 textures.
static Result< void > captureFromTriangles(SurfaceField &out, std::span< const glm::vec3 > positions, std::span< const std::uint32_t > indices, const glm::vec3 &originMin, float worldSize, int resolution, float baseHeight=0.f)
Bake triangle positions into out over the given XZ domain.
2.5D surface + life-field textures for Life Network.
glm::quat lookRotation(const glm::vec3 &forward, const glm::vec3 &upHint=glm::vec3(0.f, 1.f, 0.f))
Builds a facing quaternion from a unit forward and approximate up.
Definition AgentState.h:36
EffectKind
Effect kind selecting the solver kernel.
Definition AgentState.h:22
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
Standardized per-agent simulation output shared by all effect kinds.
Definition AgentState.h:12
Type-erased profile bundle owned by an EffectBackend.
static EffectProfile makePetal(int maxAgents=512)
Factory for a default petal profile.
const EffectProfileBase & base() const
Returns the shared base slice for the active kind.
static EffectProfile makeBird(int maxAgents=256)
Factory for a default bird profile.
static EffectProfile makeFish(int maxAgents=256)
Factory for a default fish profile.
static EffectProfile makeLife(int maxAgents=128, int resolution=64)
Factory for a default life-network profile.
Read-only environment semantics prepared by GpuAgentWorld each tick.
std::vector< EnvironmentMarker > nutrients
SurfaceField * surface
optional; Life Network writes trails here
std::vector< EnvironmentMarker > goals
std::vector< EnvironmentMarker > dangers