载入中...
搜索中...
未找到
Sensing.cpp
浏览该文件的文档.
1// eve-hot-path
2#include "sensing/Sensing.h"
3#include "common/Identity.h"
4#include "common/Profile.h"
11
12#include <algorithm>
13#include <array>
14#include <cmath>
15#include <cstdint>
16#include <functional>
17#include <iomanip>
18#include <limits>
19#include <set>
20#include <simplesquirrel/simplesquirrel.hpp>
21#include <sstream>
22#include <type_traits>
23#include <utility>
24#include <variant>
25#include "common/Json.h"
26
27namespace eve::sensing {
28namespace {
29struct SpatialCellQueryCache {
30 const SensingWorld* owner = nullptr;
32 std::map<std::array<int, 4>, std::vector<const Subject*>> candidates;
33 std::size_t candidateCount = 0;
34
35 void invalidate(const SensingWorld* world) {
36 if (owner != world) return;
37 candidates.clear();
39 }
40
41 void select(const SensingWorld* world, const eve::spatial::SpatialHash2D* currentIndex) {
42 if (owner == world && index == currentIndex) return;
43 candidates.clear();
45 owner = world;
46 index = currentIndex;
47 }
48};
49
50// Queries are owner-thread-only; one bounded scratch cache avoids changing SensingWorld's ABI.
51thread_local SpatialCellQueryCache spatialCellQueryCache;
52
53std::set<std::string> csv(std::string_view s) {
54 std::set<std::string> out;
55 std::stringstream in{std::string(s)};
56 std::string v;
57 while (std::getline(in, v, ','))
58 if (!v.empty()) out.insert(v);
59 return out;
60}
61bool csvMatches(std::string_view text, const std::set<std::string>& values) {
62 const auto containsToken = [text](std::string_view value) {
63 auto remaining = text;
64 while (!remaining.empty()) {
65 const auto comma = remaining.find(',');
66 if (remaining.substr(0, comma) == value) return true;
67 if (comma == std::string_view::npos) break;
68 remaining.remove_prefix(comma + 1);
69 }
70 return false;
71 };
72 for (const auto& value : values)
73 if (!containsToken(value)) return false;
74 while (!text.empty()) {
75 const auto comma = text.find(',');
76 const auto token = text.substr(0, comma);
77 if (!token.empty() &&
78 std::none_of(values.begin(), values.end(), [token](const std::string& value) { return value == token; }))
79 return false;
80 if (comma == std::string_view::npos) break;
81 text.remove_prefix(comma + 1);
82 }
83 return true;
84}
85std::string quote(std::string_view s) {
86 std::ostringstream o;
87 o << '"';
88 for (char c : s) {
89 if (c == '"' || c == '\\') o << '\\';
90 o << c;
91 }
92 return o.str() + '"';
93}
94std::string join(const std::set<std::string>& s) {
95 std::string o;
96 for (auto& v : s) {
97 if (!o.empty()) o += ',';
98 o += v;
99 }
100 return o;
101}
102bool finite(float v) { return std::isfinite(v); }
103// Keep float-to-cell conversion within int and bound query-cell traversal.
104bool indexable(float x, float y, float z, float cellSize) {
105 const double limit = double(std::numeric_limits<int>::max()) - 2;
106 return std::abs(double(x) / cellSize) < limit && std::abs(double(y) / cellSize) < limit &&
107 std::abs(double(z) / cellSize) < limit;
108}
109bool boundedQuery(float x, float y, float z, float radius, float cellSize, int dimensions) {
110 if (!indexable(x, y, z, cellSize) || !std::isfinite(radius)) return false;
111 const double cells = 2 * std::ceil(double(radius) / cellSize) + 3;
112 return std::pow(cells, dimensions) <= 262144 && indexable(x + radius, y + radius, z + radius, cellSize) &&
113 indexable(x - radius, y - radius, z - radius, cellSize);
114}
115
116
117template <class Ref, class Proxy, class Release>
118ssq::Table makeOwnedProxy(HSQUIRRELVM vm, eve::Result<Ref>&& reference, Release&& release) {
120
121 const Ref ref = std::move(reference).takeValue();
122 auto object = eve::script::makeOwnedSquirrelInstance<Proxy>(vm, std::make_unique<Proxy>(ref));
123 if (!object) {
124 const eve::Status status = object.status();
125 object.ignore("failed to create owned sensing proxy");
126 std::invoke(std::forward<Release>(release), ref).ignore("rollback failed owned sensing allocation");
128 }
129
130 ssq::Object owned = std::move(object).takeValue();
132 result.set("value", owned);
133 result.set("ownership", std::string("owned"));
134 result.set("ownerEpoch", static_cast<std::int64_t>(ref.ownerEpoch));
135 result.set("handle", static_cast<std::int64_t>(ref.packed()));
136 return result;
137}
138} // namespace
140SensingWorld::SensingWorld(SensingWorld&&) noexcept = default;
141SensingWorld& SensingWorld::operator=(SensingWorld&&) noexcept = default;
142SensingWorld::~SensingWorld() { spatialCellQueryCache.invalidate(this); }
143
144namespace {
145std::vector<std::string> toVector(const std::set<std::string>& values) {
146 return std::vector<std::string>(values.begin(), values.end());
147}
148
149bool insideCone(float px, float py, const QueryCone& cone) {
150 const float dx = px - cone.x;
151 const float dy = py - cone.y;
152 const float distSq = dx * dx + dy * dy;
153 if (distSq > cone.range * cone.range) return false;
154 if (distSq == 0.f) return true;
155 const float facingLen = std::hypot(cone.dirX, cone.dirY);
156 if (!(facingLen > 0.f)) return false;
157 const float invDist = 1.f / std::sqrt(distSq);
158 const float nx = dx * invDist;
159 const float ny = dy * invDist;
160 const float fx = cone.dirX / facingLen;
161 const float fy = cone.dirY / facingLen;
162 const float dot = std::clamp(nx * fx + ny * fy, -1.f, 1.f);
163 return std::acos(dot) <= cone.halfAngle;
164}
165
166std::pair<float, float> project(float x, float y, float z, QueryAxes axes) {
167 if (axes == QueryAxes::XZ) return {x, z};
168 if (axes == QueryAxes::YZ) return {y, z};
169 return {x, y};
170}
171
172bool insideShape(const Subject& subject, const QueryShape& shape, QueryAxes axes) {
173 const auto [px, py] = project(subject.x, subject.y, subject.z, axes);
174 return std::visit(
175 [&](const auto& value) -> bool {
176 using T = std::decay_t<decltype(value)>;
177 if constexpr (std::is_same_v<T, std::monostate>) {
178 return true;
179 } else if constexpr (std::is_same_v<T, QueryCircle>) {
180 const float dx = px - value.x;
181 const float dy = py - value.y;
182 return dx * dx + dy * dy <= value.radius * value.radius;
183 } else if constexpr (std::is_same_v<T, QueryBox>) {
184 return px >= value.minX && px <= value.maxX && py >= value.minY && py <= value.maxY;
185 } else if constexpr (std::is_same_v<T, QuerySphere>) {
186 return std::hypot(double(subject.x) - value.x, double(subject.y) - value.y,
187 double(subject.z) - value.z) <= value.radius;
188 } else {
189 return insideCone(px, py, value);
190 }
191 },
192 shape);
193}
194
195eve::Result<QuerySpec> circleSpec(float x, float y, float radius, std::string_view requireTagsCsv,
196 std::string_view excludeTagsCsv, std::string_view includeFactionsCsv,
197 std::string_view excludeFactionsCsv, std::string_view visibleTo, int limit) {
198 if (!finite(x) || !finite(y) || !finite(radius) || radius < 0.f || limit < 0) {
201 "circle query requires finite coordinates, non-negative radius and limit", "query", {}, "sensing"));
202 }
203 QuerySpec spec;
204 spec.shape = QueryCircle{x, y, radius};
205 spec.requiredTags = toVector(csv(requireTagsCsv));
206 spec.excludedTags = toVector(csv(excludeTagsCsv));
207 spec.includeFactions = toVector(csv(includeFactionsCsv));
208 spec.excludeFactions = toVector(csv(excludeFactionsCsv));
209 if (!visibleTo.empty()) spec.visibleTo = std::string(visibleTo);
210 spec.minRange = 0.f;
211 spec.maxRange = radius;
212 spec.minCount = 0;
213 spec.maxCount = static_cast<std::uint32_t>(limit);
214 spec.countPolicy = CountPolicy::TruncateToMax;
215 spec.sortKey = SortKey::DistanceAscending;
216 return eve::Result<QuerySpec>::success(std::move(spec));
217}
218
219eve::Result<QuerySpec> boxSpec(float minX, float minY, float maxX, float maxY, std::string_view requireTagsCsv,
220 std::string_view excludeTagsCsv, std::string_view includeFactionsCsv,
221 std::string_view excludeFactionsCsv, std::string_view visibleTo, int limit) {
222 if (!finite(minX) || !finite(minY) || !finite(maxX) || !finite(maxY) || minX > maxX || minY > maxY || limit < 0) {
224 eve::DiagnosticCode::InvalidArgument, "box query requires finite ordered bounds and a non-negative limit",
225 "query", {}, "sensing"));
226 }
227 QuerySpec spec;
228 spec.shape = QueryBox{minX, minY, maxX, maxY};
229 spec.requiredTags = toVector(csv(requireTagsCsv));
230 spec.excludedTags = toVector(csv(excludeTagsCsv));
231 spec.includeFactions = toVector(csv(includeFactionsCsv));
232 spec.excludeFactions = toVector(csv(excludeFactionsCsv));
233 if (!visibleTo.empty()) spec.visibleTo = std::string(visibleTo);
234 spec.minCount = 0;
235 spec.maxCount = static_cast<std::uint32_t>(limit);
236 spec.countPolicy = CountPolicy::TruncateToMax;
237 spec.sortKey = SortKey::DistanceAscending;
238 return eve::Result<QuerySpec>::success(std::move(spec));
239}
240} // namespace
241
243 if (axes > QueryAxes::XYZ || (axes == QueryAxes::XYZ && !std::holds_alternative<std::monostate>(shape) &&
244 !std::holds_alternative<QuerySphere>(shape)))
246 "XYZ queries require a sphere or range-only shape", "query.axes",
247 {}, "sensing"));
248 if (!std::isfinite(minRange) || minRange < 0.f) {
250 "QuerySpec.minRange must be finite and >= 0",
251 "query.minRange", {}, "sensing"));
252 }
253 if (!(std::isfinite(maxRange) || maxRange == std::numeric_limits<float>::infinity()) || maxRange < minRange) {
255 eve::DiagnosticCode::InvalidArgument, "QuerySpec.maxRange must be >= minRange (finite or +inf)",
256 "query.maxRange", {}, "sensing"));
257 }
258 if (minCount > maxCount) {
260 eve::DiagnosticCode::InvalidArgument, "QuerySpec.minCount exceeds maxCount", "query.count", {}, "sensing"));
261 }
262 for (const auto& tag : requiredTags) {
263 if (tag.empty())
265 "requiredTags cannot contain empty keys",
266 "query.requiredTags", {}, "sensing"));
267 }
268 for (const auto& tag : excludedTags) {
269 if (tag.empty())
271 "excludedTags cannot contain empty keys",
272 "query.excludedTags", {}, "sensing"));
273 }
274 for (const auto& faction : includeFactions) {
275 if (faction.empty())
277 "includeFactions cannot contain empty keys",
278 "query.includeFactions", {}, "sensing"));
279 }
280 for (const auto& faction : excludeFactions) {
281 if (faction.empty())
283 "excludeFactions cannot contain empty keys",
284 "query.excludeFactions", {}, "sensing"));
285 }
286 if (visibleTo && visibleTo->empty()) {
288 "visibleTo cannot be empty when set",
289 "query.visibleTo", {}, "sensing"));
290 }
291 const auto shapeOk = std::visit(
292 [](const auto& value) -> eve::Result<void> {
293 using T = std::decay_t<decltype(value)>;
294 if constexpr (std::is_same_v<T, QueryCircle> || std::is_same_v<T, QuerySphere>) {
295 if constexpr (std::is_same_v<T, QuerySphere>) {
296 if (!finite(value.z))
298 DiagnosticCode::InvalidArgument, "sphere Z must be finite", "query.shape", {}, "sensing"));
299 }
300 if (!finite(value.x) || !finite(value.y) || !finite(value.radius) || value.radius < 0.f) {
303 "QueryCircle requires finite center and non-negative radius", "query.shape", {}, "sensing"));
304 }
305 } else if constexpr (std::is_same_v<T, QueryBox>) {
306 if (!finite(value.minX) || !finite(value.minY) || !finite(value.maxX) || !finite(value.maxY) ||
307 value.minX > value.maxX || value.minY > value.maxY) {
309 "QueryBox requires finite ordered bounds",
310 "query.shape", {}, "sensing"));
311 }
312 } else if constexpr (std::is_same_v<T, QueryCone>) {
313 if (!finite(value.x) || !finite(value.y) || !finite(value.dirX) || !finite(value.dirY) ||
314 !finite(value.halfAngle) || !finite(value.range) || value.halfAngle < 0.f ||
315 value.halfAngle > 3.14159265f || value.range < 0.f || !(std::hypot(value.dirX, value.dirY) > 0.f)) {
318 "QueryCone requires finite apex/dir, halfAngle in [0,pi], non-negative range, non-zero dir",
319 "query.shape", {}, "sensing"));
320 }
321 }
323 },
324 shape);
325 if (!shapeOk) return eve::Result<void>::failure(shapeOk.status());
327}
328
329eve::Result<void> SensingWorld::upsert(std::string_view id, float x, float y, std::string_view f, std::string_view t,
330 std::string_view v) {
331 return upsertPosition(id, x, y, 0.f, f, t, v);
332}
333
334Result<void> SensingWorld::upsertPosition(std::string_view id, float x, float y, float z, std::string_view f,
335 std::string_view t, std::string_view v) {
336 if (id.empty() || !finite(x) || !finite(y) || !finite(z)) {
338 "subject id and finite coordinates are required",
339 "subject", {}, "sensing"));
340 }
341 const float cellSize = spatialIndex3D_ ? spatialIndex3D_->getCellSize()
342 : spatialIndex_ ? spatialIndex_->getCellSize()
343 : 1.f;
344 if (spatialIndexEnabled() && !indexable(x, y, z, cellSize))
346 DiagnosticCode::InvalidArgument, "position exceeds index cell range", "subject.position", {}, "sensing"));
347 const std::string key(id);
348 auto found = subjects_.find(key);
349 if (found != subjects_.end() && found->second.zones.empty() && found->second.faction == f &&
350 csvMatches(t, found->second.tags) && csvMatches(v, found->second.visibleTo)) {
351 const bool positionChanged = found->second.x != x || found->second.y != y || found->second.z != z;
352 found->second.x = x;
353 found->second.y = y;
354 found->second.z = z;
355 if (spatialIndexEnabled() && positionChanged) indexSubject(found->second);
357 }
358 Subject subject{key, x, y, std::string(f), csv(t), csv(v), {}, z};
359 if (found != subjects_.end()) {
360 // Zones stay owned by setZones: upsert clears them. Preserve TD metrics only.
361 subject.pathProgress = found->second.pathProgress;
362 subject.strength = found->second.strength;
363 }
364 const bool positionChanged =
365 found == subjects_.end() || found->second.x != x || found->second.y != y || found->second.z != z;
366 if (found == subjects_.end()) {
367 const auto key = subject.id;
368 found = subjects_.emplace(key, std::move(subject)).first;
369 } else {
370 found->second = std::move(subject);
371 }
372 if (spatialIndexEnabled() && positionChanged) indexSubject(found->second);
374}
375
377 results_.clear();
378 const std::string key(id);
379 if (!subjects_.contains(key))
381 eve::DiagnosticCode::NotFound, "subject is not registered", "subject.id", {}, "sensing"));
382 unindexSubject(key);
383 subjects_.erase(key);
385}
386
387eve::Result<void> SensingWorld::setZones(std::string_view id, std::string_view zonesCsv) {
388 const std::string key(id);
389 auto it = subjects_.find(key);
390 if (it == subjects_.end())
392 eve::DiagnosticCode::NotFound, "subject is not registered", "subject.id", {}, "sensing"));
393 auto zones = csv(zonesCsv);
394 for (const auto& zone : zones) {
395 if (zone.empty())
397 "zones cannot contain empty keys", "subject.zones",
398 {}, "sensing"));
399 if (!eve::LogicalId::parse(zone))
401 "zones entries must be valid LogicalId texts",
402 "subject.zones", {}, "sensing"));
403 }
404 it->second.zones = std::move(zones);
406}
407
408eve::Result<void> SensingWorld::setMetrics(std::string_view id, float pathProgress, float strength) {
409 if (!finite(pathProgress) || !finite(strength))
411 "pathProgress and strength must be finite",
412 "subject.metrics", {}, "sensing"));
413 const std::string key(id);
414 auto it = subjects_.find(key);
415 if (it == subjects_.end())
417 eve::DiagnosticCode::NotFound, "subject is not registered", "subject.id", {}, "sensing"));
418 it->second.pathProgress = pathProgress;
419 it->second.strength = strength;
421}
422
426
427SpatialIndexKind SensingWorld::indexKind() const noexcept { return indexKind_; }
428bool SensingWorld::spatialIndexEnabled() const noexcept { return spatialIndex_ || spatialIndex3D_; }
429
431 if (kind > SpatialIndexKind::XYZ || (kind != SpatialIndexKind::None && (!finite(cellSize) || cellSize <= 0)))
433 DiagnosticCode::InvalidArgument, "invalid spatial index kind or cell size", "spatial", {}, "sensing"));
434 for (const auto& [id, subject] : subjects_) {
435 if (kind != SpatialIndexKind::None && !indexable(subject.x, subject.y, subject.z, cellSize))
437 "subject exceeds index cell range", id, {}, "sensing"));
438 }
439 // Build in a separate owner; allocation failure cannot replace the current derived index.
440 SensingWorld next;
441 next.subjects_ = subjects_;
442 next.indexKind_ = kind;
444 next.spatialIndex3D_ = std::make_unique<spatial::SpatialHash3D>(cellSize);
445 else if (kind != SpatialIndexKind::None)
446 next.spatialIndex_ = std::make_unique<spatial::SpatialHash2D>(cellSize);
447 next.rebuildSpatialIndex();
448 for (const auto& [id, sid] : next.subjectSpatialIds_) next.spatialIdSubjects_.at(sid) = &subjects_.at(id);
449 spatialCellQueryCache.invalidate(this);
450 spatialIndex_ = std::move(next.spatialIndex_);
451 spatialIndex3D_ = std::move(next.spatialIndex3D_);
452 indexKind_ = kind;
453 subjectSpatialIds_ = std::move(next.subjectSpatialIds_);
454 spatialIdSubjects_ = std::move(next.spatialIdSubjects_);
455 nextSpatialId_ = next.nextSpatialId_;
457}
458
459void SensingWorld::clearSpatialIndex() {
460 spatialCellQueryCache.invalidate(this);
461 spatialIndex_.reset();
462 spatialIndex3D_.reset();
463 indexKind_ = SpatialIndexKind::None;
464 subjectSpatialIds_.clear();
465 spatialIdSubjects_.clear();
466 nextSpatialId_ = 1;
467}
468
469void SensingWorld::rebuildSpatialIndex() {
470 spatialCellQueryCache.invalidate(this);
471 subjectSpatialIds_.clear();
472 spatialIdSubjects_.clear();
473 nextSpatialId_ = 1;
474 if (!spatialIndexEnabled()) return;
475 if (spatialIndex_) spatialIndex_->clear();
476 if (spatialIndex3D_) spatialIndex3D_->clear();
477 for (const auto& [id, subject] : subjects_) {
478 (void)id;
479 indexSubject(subject);
480 }
481}
482
483void SensingWorld::indexSubject(const Subject& subject) {
484 if (!spatialIndexEnabled()) return;
485 spatialCellQueryCache.invalidate(this);
486 auto [it, inserted] = subjectSpatialIds_.try_emplace(subject.id, nextSpatialId_);
487 if (inserted) ++nextSpatialId_;
488 const int sid = it->second;
489 spatialIdSubjects_[sid] = &subject;
490 if (spatialIndex3D_) {
491 spatialIndex3D_->insert(sid, subject.x, subject.y, subject.z, subject.x, subject.y, subject.z);
492 } else {
493 const auto axes = indexKind_ == SpatialIndexKind::XZ ? QueryAxes::XZ
494 : indexKind_ == SpatialIndexKind::YZ ? QueryAxes::YZ
496 const auto [x, y] = project(subject.x, subject.y, subject.z, axes);
497 spatialIndex_->insert(sid, x, y, x, y);
498 }
499}
500
501void SensingWorld::unindexSubject(const std::string& id) {
502 auto it = subjectSpatialIds_.find(id);
503 if (it == subjectSpatialIds_.end()) return;
504 spatialCellQueryCache.invalidate(this);
505 const int sid = it->second;
506 if (spatialIndex_) spatialIndex_->remove(sid);
507 if (spatialIndex3D_) spatialIndex3D_->remove(sid);
508 spatialIdSubjects_.erase(sid);
509 subjectSpatialIds_.erase(it);
510}
511
512bool SensingWorld::trySpatialBroadphase(const QueryOrigin& origin, const QuerySpec& spec,
513 std::vector<const Subject*>& out) const {
514 if (!spatialIndexEnabled()) return false;
515 // A bounded 3D sphere can be conservatively projected into any planar index.
516 const auto* sphere = std::get_if<QuerySphere>(&spec.shape);
517 const bool range3D = spec.axes == QueryAxes::XYZ && std::isfinite(spec.maxRange);
518 if (sphere || range3D) {
519 const float x = sphere ? sphere->x : origin.x;
520 const float y = sphere ? sphere->y : origin.y;
521 const float z = sphere ? sphere->z : origin.z;
522 const float r = sphere ? sphere->radius : spec.maxRange;
523 const float cellSize = spatialIndex3D_ ? spatialIndex3D_->getCellSize() : spatialIndex_->getCellSize();
524 if (!boundedQuery(x, y, z, r, cellSize, spatialIndex3D_ ? 3 : 2)) return false;
525 if (spatialIndex3D_)
526 spatialIndex3D_->querySphere(x, y, z, r);
527 else {
528 const auto axes = indexKind_ == SpatialIndexKind::XZ ? QueryAxes::XZ
529 : indexKind_ == SpatialIndexKind::YZ ? QueryAxes::YZ
531 const auto [u, v] = project(x, y, z, axes);
532 spatialIndex_->queryCircle(u, v, r);
533 }
534 const int count = spatialIndex3D_ ? spatialIndex3D_->getResultCount() : spatialIndex_->getResultCount();
535 for (int i = 0; i < count; ++i) {
536 const int id = spatialIndex3D_ ? spatialIndex3D_->getResultId(i) : spatialIndex_->getResultId(i);
537 out.push_back(spatialIdSubjects_.at(id));
538 }
539 return true;
540 }
541 // Unbounded height cannot be culled by a different plane or a finite 3D volume.
542 const auto axes = indexKind_ == SpatialIndexKind::XZ ? QueryAxes::XZ
543 : indexKind_ == SpatialIndexKind::YZ ? QueryAxes::YZ
545 if (!spatialIndex_ || spec.axes != axes) return false;
546 const auto [originU, originV] = project(origin.x, origin.y, origin.z, axes);
547 const bool bounded = std::visit(
548 [&](const auto& shape) {
549 using T = std::decay_t<decltype(shape)>;
550 const float size = spatialIndex_->getCellSize();
551 if constexpr (std::is_same_v<T, std::monostate>)
552 return boundedQuery(originU, originV, 0, spec.maxRange, size, 2);
553 else if constexpr (std::is_same_v<T, QueryBox>)
554 return boundedQuery(shape.minX, shape.minY, 0,
555 std::max(shape.maxX - shape.minX, shape.maxY - shape.minY), size, 2);
556 else if constexpr (std::is_same_v<T, QueryCone>)
557 return boundedQuery(shape.x, shape.y, 0, shape.range, size, 2);
558 else
559 return boundedQuery(shape.x, shape.y, 0, shape.radius, size, 2);
560 },
561 spec.shape);
562 if (!bounded) return false;
563 if (const auto* circle = std::get_if<QueryCircle>(&spec.shape); circle && axes == QueryAxes::XY) {
564 spatialCellQueryCache.select(this, spatialIndex_.get());
565 auto& cache = spatialCellQueryCache;
566 const float cellSize = spatialIndex_->getCellSize();
567 const std::array<int, 4> cells{static_cast<int>(std::floor((circle->x - circle->radius) / cellSize)),
568 static_cast<int>(std::floor((circle->y - circle->radius) / cellSize)),
569 static_cast<int>(std::floor((circle->x + circle->radius) / cellSize)),
570 static_cast<int>(std::floor((circle->y + circle->radius) / cellSize))};
571 constexpr std::size_t maxCachedCells = 256;
572 constexpr std::size_t maxCachedIdsPerCellRange = 512;
573 constexpr std::size_t maxCachedIds = 32768;
574 std::vector<const Subject*> uncached;
575 const std::vector<const Subject*>* subjects = nullptr;
576 const auto cached = cache.candidates.find(cells);
577 if (cached != cache.candidates.end()) {
578 subjects = &cached->second;
579 } else {
580 spatialIndex_->queryRect(cells[0] * cellSize, cells[1] * cellSize,
581 static_cast<float>((static_cast<double>(cells[2]) + 1.0) * cellSize),
582 static_cast<float>((static_cast<double>(cells[3]) + 1.0) * cellSize));
583 uncached.reserve(static_cast<std::size_t>(spatialIndex_->getResultCount()));
584 for (int i = 0; i < spatialIndex_->getResultCount(); ++i) {
585 const auto found = spatialIdSubjects_.find(spatialIndex_->getResultId(i));
586 if (found != spatialIdSubjects_.end()) uncached.push_back(found->second);
587 }
588 if (uncached.size() <= maxCachedIdsPerCellRange) {
589 if (cache.candidates.size() == maxCachedCells ||
590 cache.candidateCount + uncached.size() > maxCachedIds) {
591 cache.candidates.clear();
592 cache.candidateCount = 0;
593 }
594 cache.candidateCount += uncached.size();
595 subjects = &cache.candidates.emplace(cells, std::move(uncached)).first->second;
596 } else {
597 subjects = &uncached;
598 }
599 }
600 out.clear();
601 out.reserve(subjects->size());
602 for (const Subject* subject : *subjects) {
604 circle->x, circle->y, circle->radius))
605 out.push_back(subject);
606 }
607 return true;
608 }
609 const bool ran = std::visit(
610 [&](const auto& value) -> bool {
611 using T = std::decay_t<decltype(value)>;
612 if constexpr (std::is_same_v<T, std::monostate>) {
613 if (!(std::isfinite(spec.maxRange))) return false;
614 spatialIndex_->queryCircle(originU, originV, spec.maxRange);
615 return true;
616 } else if constexpr (std::is_same_v<T, QueryCircle>) {
617 spatialIndex_->queryCircle(value.x, value.y, value.radius);
618 return true;
619 } else if constexpr (std::is_same_v<T, QueryBox>) {
620 spatialIndex_->queryRect(value.minX, value.minY, value.maxX, value.maxY);
621 return true;
622 } else if constexpr (std::is_same_v<T, QuerySphere>) {
623 return false;
624 } else {
625 spatialIndex_->queryCircle(value.x, value.y, value.range);
626 return true;
627 }
628 },
629 spec.shape);
630 if (!ran) return false;
631 out.clear();
632 out.reserve(static_cast<std::size_t>(spatialIndex_->getResultCount()));
633 for (int i = 0; i < spatialIndex_->getResultCount(); ++i) {
634 const int sid = spatialIndex_->getResultId(i);
635 const auto map = spatialIdSubjects_.find(sid);
636 if (map == spatialIdSubjects_.end()) continue;
637 out.push_back(map->second);
638 }
639 return true;
640}
641
642bool SensingWorld::accepts(const Subject& subject, const QuerySpec& spec) const {
643 if (!spec.includeFactions.empty()) {
644 bool included = false;
645 for (const auto& faction : spec.includeFactions)
646 if (subject.faction == faction) {
647 included = true;
648 break;
649 }
650 if (!included) return false;
651 }
652 for (const auto& faction : spec.excludeFactions)
653 if (subject.faction == faction) return false;
654 for (const auto& tag : spec.requiredTags)
655 if (!subject.tags.count(tag)) return false;
656 for (const auto& tag : spec.excludedTags)
657 if (subject.tags.count(tag)) return false;
658 if (spec.visibleTo && !subject.visibleTo.count(*spec.visibleTo)) return false;
659 return insideShape(subject, spec.shape, spec.axes);
660}
661
662void SensingWorld::publishResults(std::vector<RankedCandidate> ranked) {
663 results_.clear();
664 results_.reserve(ranked.size());
665 for (const auto& candidate : ranked)
666 results_.push_back(Candidate{candidate.id, candidate.x, candidate.y, candidate.distance, candidate.z});
667 lastQuery_.ranked = std::move(ranked);
668 lastQuery_.accepted = static_cast<std::uint32_t>(lastQuery_.ranked.size());
669}
670
672 const QuerySpec& spec) const {
673 auto valid = spec.validate();
675 if (!finite(origin.x) || !finite(origin.y) || !finite(origin.z) ||
678 (origin.z != 0 || spec.axes != QueryAxes::XY || std::holds_alternative<QuerySphere>(spec.shape)))) {
680 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "QueryOrigin coordinates must be finite",
681 "query.origin", {}, "sensing"));
682 }
683
684 std::vector<const Subject*> candidates;
685 const bool usedSpatial = trySpatialBroadphase(origin, spec, candidates);
686 if (!usedSpatial) {
687 candidates.clear();
688 candidates.reserve(subjects_.size());
689 for (const auto& [id, subject] : subjects_) {
690 (void)id;
691 candidates.push_back(&subject);
692 }
693 }
694
695 std::vector<RankedCandidate> ranked;
696 ranked.reserve(candidates.size());
697 for (const Subject* subjectPtr : candidates) {
698 const Subject& subject = *subjectPtr;
699 if (origin.subjectId && subject.id == *origin.subjectId) continue;
700 if (!accepts(subject, spec)) continue;
701 const auto [sx, sy] = project(subject.x, subject.y, subject.z, spec.axes);
702 const auto [ox, oy] = project(origin.x, origin.y, origin.z, spec.axes);
703 const float distance = spec.axes == QueryAxes::XYZ
704 ? std::hypot(subject.x - origin.x, subject.y - origin.y, subject.z - origin.z)
705 : std::hypot(sx - ox, sy - oy);
706 if (distance < spec.minRange || distance > spec.maxRange) continue;
707 RankedCandidate candidate;
708 candidate.id = subject.id;
709 candidate.x = subject.x;
710 candidate.y = subject.y;
711 candidate.z = subject.z;
712 candidate.space = origin.space;
713 candidate.distance = distance;
714 candidate.pathProgress = subject.pathProgress;
715 candidate.strength = subject.strength;
716 candidate.score = -distance;
717 candidate.scoreReason = "distance";
718 ranked.push_back(std::move(candidate));
719 }
720
722 CandidateCollection{std::move(ranked), usedSpatial, static_cast<std::uint32_t>(candidates.size())});
723}
724
728
731 EV_PROFILE_MODULE("sensing", "SensingWorld::query");
732 if (spec.requireLineOfSight && !lineOfSight)
734 "query requires a line-of-sight provider",
735 "query.lineOfSight", {}, "sensing"));
736 auto collected = collectCandidates(origin, spec);
737 if (!collected) return eve::Result<CandidateQueryResult>::failure(collected.status());
738 auto collection = std::move(collected).takeValue();
739 auto ranked = std::move(collection.candidates);
740 if (spec.requireLineOfSight) {
743 if (!from) return Result<CandidateQueryResult>::failure(from.status());
744 std::vector<RankedCandidate> visible;
745 for (auto& candidate : ranked) {
746 auto to = candidate.space == CoordinateSpace::World3D
747 ? WorldPoint::world3D(candidate.x, candidate.y, candidate.z)
748 : WorldPoint::world2D(candidate.x, candidate.y);
749 if (!to) return Result<CandidateQueryResult>::failure(to.status());
750 try {
751 auto sight = lineOfSight->get().query(TargetLocation{from.value()}, TargetLocation{to.value()});
752 if (!sight) return Result<CandidateQueryResult>::failure(sight.status());
753 if (sight.value().visible) visible.push_back(std::move(candidate));
754 } catch (const std::exception& error) {
756 Diagnostic::error(DiagnosticCode::Failed, error.what(), "query.lineOfSight", {}, "sensing"));
757 }
758 }
759 ranked = std::move(visible);
760 }
761 auto byScoreThenId = [](const RankedCandidate& a, const RankedCandidate& b) {
762 if (a.score != b.score) return a.score > b.score;
763 return a.id < b.id;
764 };
765 switch (spec.sortKey) {
767 for (auto& candidate : ranked) {
768 candidate.score = -candidate.distance;
769 candidate.scoreReason = "distance";
770 }
771 std::sort(ranked.begin(), ranked.end(), byScoreThenId);
772 break;
774 for (auto& candidate : ranked) {
775 candidate.score = candidate.distance;
776 candidate.scoreReason = "distanceDescending";
777 }
778 std::sort(ranked.begin(), ranked.end(), byScoreThenId);
779 break;
781 for (auto& candidate : ranked) {
782 candidate.score = candidate.pathProgress;
783 candidate.scoreReason = "pathProgress";
784 }
785 std::sort(ranked.begin(), ranked.end(), byScoreThenId);
786 break;
788 for (auto& candidate : ranked) {
789 candidate.score = -candidate.pathProgress;
790 candidate.scoreReason = "pathProgressAscending";
791 }
792 std::sort(ranked.begin(), ranked.end(), byScoreThenId);
793 break;
795 for (auto& candidate : ranked) {
796 candidate.score = candidate.strength;
797 candidate.scoreReason = "strength";
798 }
799 std::sort(ranked.begin(), ranked.end(), byScoreThenId);
800 break;
802 for (auto& candidate : ranked) {
803 candidate.score = -candidate.strength;
804 candidate.scoreReason = "strengthAscending";
805 }
806 std::sort(ranked.begin(), ranked.end(), byScoreThenId);
807 break;
808 case SortKey::None:
809 std::sort(ranked.begin(), ranked.end(),
810 [](const RankedCandidate& a, const RankedCandidate& b) { return a.id < b.id; });
811 break;
812 }
813
815 if (ranked.size() > static_cast<std::size_t>(spec.maxCount)) ranked.resize(static_cast<std::size_t>(spec.maxCount));
816 if (ranked.size() < static_cast<std::size_t>(spec.minCount)) {
819 "candidate count is below QuerySpec.minCount after truncation", "query.count", {}, "sensing"));
820 }
821 } else if (ranked.size() < static_cast<std::size_t>(spec.minCount) ||
822 ranked.size() > static_cast<std::size_t>(spec.maxCount)) {
825 "candidate count violates QuerySpec count policy", "query.count", {}, "sensing"));
826 }
827
828 lastQuery_.usedSpatial = collection.usedSpatial;
829 lastQuery_.scanned = collection.scanned;
830 lastQuery_.originX = origin.x;
831 lastQuery_.originY = origin.y;
832 lastQuery_.originZ = origin.z;
833 lastQuery_.space = origin.space;
834 lastQuery_.shapeKind = std::visit(
835 [](const auto& value) -> std::string {
836 using T = std::decay_t<decltype(value)>;
837 if constexpr (std::is_same_v<T, QueryCircle>) return "circle";
838 if constexpr (std::is_same_v<T, QueryBox>) return "box";
839 if constexpr (std::is_same_v<T, QueryCone>) return "cone";
840 if constexpr (std::is_same_v<T, QuerySphere>) return "sphere";
841 return "none";
842 },
843 spec.shape);
844
845 publishResults(ranked);
847}
848
849namespace {
850
851eve::Result<SortKey> parseSortPolicy(std::string_view sortPolicy) {
852 if (sortPolicy.empty() || sortPolicy == "distance" || sortPolicy == "closest")
854 if (sortPolicy == "furthest") return eve::Result<SortKey>::success(SortKey::DistanceDescending);
855 if (sortPolicy == "first") return eve::Result<SortKey>::success(SortKey::PathProgressDescending);
856 if (sortPolicy == "last") return eve::Result<SortKey>::success(SortKey::PathProgressAscending);
857 if (sortPolicy == "strongest") return eve::Result<SortKey>::success(SortKey::StrengthDescending);
858 if (sortPolicy == "weakest") return eve::Result<SortKey>::success(SortKey::StrengthAscending);
859 if (sortPolicy == "none") return eve::Result<SortKey>::success(SortKey::None);
862 "sortPolicy must be closest|furthest|first|last|strongest|weakest|distance|none", "query.sort", {},
863 "sensing"));
864}
865
866} // namespace
867
868eve::Result<int> SensingWorld::circle(float x, float y, float radius, std::string_view r, std::string_view e,
869 std::string_view i, std::string_view ef, std::string_view v, int limit) {
870 auto spec = circleSpec(x, y, radius, r, e, i, ef, v, limit);
871 if (!spec) return eve::Result<int>::failure(spec.status());
872 auto result = query(QueryOrigin{x, y, std::nullopt}, std::move(spec).takeValue());
873 if (!result) return eve::Result<int>::failure(result.status());
874 return eve::Result<int>::success(static_cast<int>(std::move(result).takeValue().size()));
875}
876
877eve::Result<int> SensingWorld::circleSorted(float x, float y, float radius, std::string_view r, std::string_view e,
878 std::string_view i, std::string_view ef, std::string_view v, int limit,
879 std::string_view sortPolicy) {
880 auto sort = parseSortPolicy(sortPolicy);
881 if (!sort) return eve::Result<int>::failure(sort.status());
882 auto spec = circleSpec(x, y, radius, r, e, i, ef, v, limit);
883 if (!spec) return eve::Result<int>::failure(spec.status());
884 auto value = std::move(spec).takeValue();
885 value.sortKey = sort.value();
886 auto result = query(QueryOrigin{x, y, std::nullopt}, std::move(value));
887 if (!result) return eve::Result<int>::failure(result.status());
888 return eve::Result<int>::success(static_cast<int>(std::move(result).takeValue().size()));
889}
890
891eve::Result<int> SensingWorld::box(float a, float b, float c, float d, std::string_view r, std::string_view e,
892 std::string_view i, std::string_view ef, std::string_view v, int limit) {
893 auto spec = boxSpec(a, b, c, d, r, e, i, ef, v, limit);
894 if (!spec) return eve::Result<int>::failure(spec.status());
895 const float originX = (a + c) * 0.5f;
896 const float originY = (b + d) * 0.5f;
897 auto result = query(QueryOrigin{originX, originY, std::nullopt}, std::move(spec).takeValue());
898 if (!result) return eve::Result<int>::failure(result.status());
899 return eve::Result<int>::success(static_cast<int>(std::move(result).takeValue().size()));
900}
901
902eve::Result<int> SensingWorld::executePreset(std::string_view presetId, float originX, float originY, float dirX,
903 float dirY) {
905 context.world = this;
906 context.origin = QueryOrigin{originX, originY, std::nullopt};
907 context.dirX = dirX;
908 context.dirY = dirY;
909 auto executed = TargetingPipeline::sharedBuiltins().executePreset(context, presetId);
910 if (!executed) return eve::Result<int>::failure(executed.status());
911 auto rankedResult = std::move(executed).takeValue();
912 std::vector<RankedCandidate> ranked(rankedResult.ranked().begin(), rankedResult.ranked().end());
913 const int count = static_cast<int>(ranked.size());
914 lastQuery_.usedSpatial = context.usedSpatial;
915 lastQuery_.scanned = context.scanned;
916 lastQuery_.originX = originX;
917 lastQuery_.originY = originY;
918 lastQuery_.originZ = 0.f;
919 lastQuery_.space = CoordinateSpace::World2D;
920 lastQuery_.shapeKind = "preset";
921 publishResults(std::move(ranked));
923}
924
926 return i >= 0 && size_t(i) < results_.size() ? eve::OptionalRef<const Candidate>(std::cref(results_[size_t(i)]))
928}
930 std::ostringstream o;
931 o << std::setprecision(9);
932 o << "{\"schema\":\"eve.sensing.lastQuery\",\"version\":1"
933 << ",\"origin\":{\"x\":" << lastQuery_.originX << ",\"y\":" << lastQuery_.originY
934 << ",\"z\":" << lastQuery_.originZ << ",\"space\":" << quote(coordinateSpaceName(lastQuery_.space)) << '}'
935 << ",\"shape\":" << quote(lastQuery_.shapeKind)
936 << ",\"spatial\":{\"enabled\":" << (spatialIndexEnabled() ? "true" : "false")
937 << ",\"used\":" << (lastQuery_.usedSpatial ? "true" : "false") << ",\"scanned\":" << lastQuery_.scanned
938 << ",\"accepted\":" << lastQuery_.accepted << '}' << ",\"ranked\":[";
939 bool first = true;
940 for (const auto& candidate : lastQuery_.ranked) {
941 if (!first) o << ',';
942 first = false;
943 o << "{\"id\":" << quote(candidate.id) << ",\"x\":" << candidate.x << ",\"y\":" << candidate.y
944 << ",\"z\":" << candidate.z << ",\"space\":" << quote(coordinateSpaceName(candidate.space))
945 << ",\"distance\":" << candidate.distance << ",\"score\":" << candidate.score
946 << ",\"scoreReason\":" << quote(candidate.scoreReason) << '}';
947 }
948 o << "],\"environment\":" << lastEnvironmentQuery_ << '}';
949 return o.str();
950}
951
952std::string SensingWorld::snapshotJson() const {
953 std::ostringstream o;
954 o << "{\"schema\":\"eve.sensing.world\",\"version\":2,\"subjects\":[";
955 bool first = true;
956 for (auto& [id, s] : subjects_) {
957 if (!first) o << ',';
958 first = false;
959 o << "{\"id\":" << quote(id) << ",\"x\":" << std::setprecision(9) << s.x << ",\"y\":" << s.y << ",\"z\":" << s.z
960 << ",\"faction\":" << quote(s.faction) << ",\"tags\":" << quote(join(s.tags))
961 << ",\"visibleTo\":" << quote(join(s.visibleTo)) << ",\"zones\":" << quote(join(s.zones)) << '}';
962 }
963 return o.str() + "]}";
964}
966 std::string err;
967 auto d = eve::json::Document::parse(j, &err);
968 if (!d.valid() || !d.root().isObject() || d.root().getString("schema") != "eve.sensing.world" ||
969 (d.root().getInt("version") != 1 && d.root().getInt("version") != 2) || !d.root().get("subjects").isArray()) {
971 eve::DiagnosticCode::ParseError, err.empty() ? "invalid snapshot" : err, {}, {}, "sensing.restore"));
972 }
973 SensingWorld next;
974 auto a = d.root().get("subjects");
975 for (size_t n = 0; n < a.size(); ++n) {
976 auto v = a.at(n);
977 if (!v.isObject()) {
979 eve::DiagnosticCode::InvalidArgument, "invalid snapshot subject", {}, {}, "sensing.restore"));
980 }
981 if (!v.get("x").isNumber() || !v.get("y").isNumber() ||
982 (d.root().getInt("version") == 2 && !v.get("z").isNumber()) || next.subjects_.contains(v.getString("id")))
984 "invalid or duplicate snapshot position", "subjects", {},
985 "sensing.restore"));
986 auto subject = next.upsertPosition(v.getString("id"), float(v.getDouble("x")), float(v.getDouble("y")),
987 d.root().getInt("version") == 1 ? 0.f : float(v.getDouble("z")),
988 v.getString("faction"), v.getString("tags"), v.getString("visibleTo"));
989 if (!subject.ok())
991 eve::DiagnosticCode::InvalidArgument, "invalid snapshot subject", {}, {}, "sensing.restore"));
992 if (v.has("zones")) {
993 auto zones = next.setZones(v.getString("id"), v.getString("zones"));
994 if (!zones.ok())
996 eve::DiagnosticCode::InvalidArgument, "invalid snapshot subject zones", {}, {},
997 "sensing.restore"));
998 }
999 }
1000 const float size = spatialIndex3D_ ? spatialIndex3D_->getCellSize()
1001 : spatialIndex_ ? spatialIndex_->getCellSize()
1002 : 1.f;
1003 auto rebuilt = next.rebuildIndex(indexKind_, size);
1004 if (!rebuilt) return Result<void>::failure(rebuilt.status());
1005 spatialCellQueryCache.invalidate(this);
1006 *this = std::move(next);
1007 results_.clear();
1008 lastQuery_ = {};
1009 lastEnvironmentQuery_ = "null";
1011}
1013 return Sensing::create()->worlds_.emplace(std::make_unique<SensingWorld>());
1014}
1015
1017 Sensing* module = ModuleManager::getInstance<Sensing>("Sensing");
1018 return module ? module->worlds_.resolve(reference) : eve::script::Borrowed<SensingWorld>();
1019}
1020
1022 Sensing* module = ModuleManager::getInstance<Sensing>("Sensing");
1023 if (!module)
1025 eve::DiagnosticCode::StaleHandle, "Sensing module is no longer loaded", "world", {}, "sensing"));
1026 return module->worlds_.erase(reference);
1027}
1028
1030 if (!reference.isValid()) return false;
1031 Sensing* module = ModuleManager::getInstance<Sensing>("Sensing");
1032 return !module || module->worlds_.isStale(reference);
1033}
1034
1035
1037 eve::cap::provide<eve::ISensingQuery>(this);
1039}
1040
1043 eve::cap::revoke<eve::ISensingQuery>(this);
1044}
1045
1047 int count = 0;
1048 worlds_.forEachLive([&](std::uint32_t, const SensingWorld&) { ++count; });
1049 return count;
1050}
1051
1052std::vector<eve::SensingWorldQuery> Sensing::lastQueries() const {
1053 std::vector<eve::SensingWorldQuery> queries;
1054 worlds_.forEachLive([&](std::uint32_t index, const SensingWorld& world) {
1056 entry.index = static_cast<int>(index);
1057 entry.lastQueryJson = world.debugLastQueryJson();
1058 queries.push_back(std::move(entry));
1059 });
1060 return queries;
1061}
1062
1064void Sensing::expose(ssq::Table& t) {
1065 auto c = t.addClass<Candidate>("SensingCandidate", std::function<Candidate*()>([]() { return nullptr; }), false);
1066 c.addFunc("getId", [](Candidate* v) { return v ? v->id : std::string{}; });
1067 c.addFunc("getX", [](Candidate* v) { return v ? v->x : 0.f; });
1068 c.addFunc("getY", [](Candidate* v) { return v ? v->y : 0.f; });
1069 c.addFunc("getZ", [](Candidate* v) { return v ? v->z : 0.f; });
1070 c.addFunc("getDistance", [](Candidate* v) { return v ? v->distance : 0.f; });
1071 const HSQUIRRELVM vm = t.getHandle();
1072 auto w = t.addClass<ScriptSensingWorld>("SensingWorld",
1073 std::function<ScriptSensingWorld*()>([]() { return nullptr; }), false);
1075 w.addFunc("ownership", [](ScriptSensingWorld*) { return std::string("owned"); });
1076 w.addFunc("ownerEpoch", [](ScriptSensingWorld* value) {
1077 return value ? static_cast<std::int64_t>(value->reference.ownerEpoch) : std::int64_t{0};
1078 });
1079 w.addFunc("handle", [](ScriptSensingWorld* value) {
1080 return value ? static_cast<std::int64_t>(value->reference.packed()) : std::int64_t{0};
1081 });
1082 w.addFunc("isStale", [](ScriptSensingWorld* value) { return !value || Sensing::isStale(value->reference); });
1083 w.addFunc("release", [vm](ScriptSensingWorld* value) {
1084 if (!value)
1087 "sensing world proxy must not be null", "world", {}, "sensing")));
1089 });
1090 w.addFunc("upsert", [vm](ScriptSensingWorld* value, const std::string& id, float x, float y,
1091 const std::string& faction, const std::string& tags, const std::string& visibleTo) {
1092 if (!value)
1095 "sensing world proxy must not be null", "world", {}, "sensing")));
1096 auto world = Sensing::resolve(value->reference);
1097 if (!world.isBound())
1100 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")));
1101 return eve::script::projectResult(vm, world->upsert(id, x, y, faction, tags, visibleTo));
1102 });
1103 w.addFunc("remove", [vm](ScriptSensingWorld* value, const std::string& id) {
1104 if (!value)
1107 "sensing world proxy must not be null", "world", {}, "sensing")));
1108 auto world = Sensing::resolve(value->reference);
1109 if (!world.isBound())
1112 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")));
1113 return eve::script::projectResult(vm, world->remove(id));
1114 });
1115 w.addFunc("setZones", [vm](ScriptSensingWorld* value, const std::string& id, const std::string& zones) {
1116 if (!value)
1119 "sensing world proxy must not be null", "world", {}, "sensing")));
1120 auto world = Sensing::resolve(value->reference);
1121 if (!world.isBound())
1124 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")));
1125 return eve::script::projectResult(vm, world->setZones(id, zones));
1126 });
1127 w.addFunc("setMetrics", [vm](ScriptSensingWorld* value, const std::string& id, float pathProgress, float strength) {
1128 if (!value)
1131 "sensing world proxy must not be null", "world", {}, "sensing")));
1132 auto world = Sensing::resolve(value->reference);
1133 if (!world.isBound())
1136 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")));
1137 return eve::script::projectResult(vm, world->setMetrics(id, pathProgress, strength));
1138 });
1139 auto projectCount = [vm](eve::Result<int>&& result) {
1140 return eve::script::projectResult(vm, std::move(result),
1141 [](int count) { return eve::Value(static_cast<std::int64_t>(count)); });
1142 };
1143 w.addFunc("circle", [vm, projectCount](ScriptSensingWorld* value, float x, float y, float radius,
1144 const std::string& required, const std::string& excluded,
1145 const std::string& includedFactions, const std::string& excludedFactions,
1146 const std::string& visibleTo, int limit) {
1147 if (!value)
1151 "sensing world proxy must not be null", "world", {}, "sensing")),
1152 [](int count) { return eve::Value(static_cast<std::int64_t>(count)); });
1153 auto world = Sensing::resolve(value->reference);
1154 if (!world.isBound())
1156 vm,
1158 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")),
1159 [](int count) { return eve::Value(static_cast<std::int64_t>(count)); });
1160 return projectCount(
1161 world->circle(x, y, radius, required, excluded, includedFactions, excludedFactions, visibleTo, limit));
1162 });
1163 w.addFunc("circleSorted", [vm, projectCount](ScriptSensingWorld* value, float x, float y, float radius,
1164 const std::string& required, const std::string& excluded,
1165 const std::string& includedFactions,
1166 const std::string& excludedFactions, const std::string& visibleTo,
1167 int limit, const std::string& sortPolicy) {
1168 if (!value)
1172 "sensing world proxy must not be null", "world", {}, "sensing")),
1173 [](int count) { return eve::Value(static_cast<std::int64_t>(count)); });
1174 auto world = Sensing::resolve(value->reference);
1175 if (!world.isBound())
1177 vm,
1179 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")),
1180 [](int count) { return eve::Value(static_cast<std::int64_t>(count)); });
1181 return projectCount(world->circleSorted(x, y, radius, required, excluded, includedFactions, excludedFactions,
1182 visibleTo, limit, sortPolicy));
1183 });
1184 w.addFunc("box", [vm, projectCount](ScriptSensingWorld* value, float minX, float minY, float maxX, float maxY,
1185 const std::string& required, const std::string& excluded,
1186 const std::string& includedFactions, const std::string& excludedFactions,
1187 const std::string& visibleTo, int limit) {
1188 if (!value)
1192 "sensing world proxy must not be null", "world", {}, "sensing")),
1193 [](int count) { return eve::Value(static_cast<std::int64_t>(count)); });
1194 auto world = Sensing::resolve(value->reference);
1195 if (!world.isBound())
1197 vm,
1199 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")),
1200 [](int count) { return eve::Value(static_cast<std::int64_t>(count)); });
1201 return projectCount(world->box(minX, minY, maxX, maxY, required, excluded, includedFactions, excludedFactions,
1202 visibleTo, limit));
1203 });
1204 w.addFunc("executePreset", [vm, projectCount](ScriptSensingWorld* value, const std::string& presetId, float originX,
1205 float originY, float dirX, float dirY) {
1206 if (!value)
1210 "sensing world proxy must not be null", "world", {}, "sensing")),
1211 [](int count) { return eve::Value(static_cast<std::int64_t>(count)); });
1212 auto world = Sensing::resolve(value->reference);
1213 if (!world.isBound())
1215 vm,
1217 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")),
1218 [](int count) { return eve::Value(static_cast<std::int64_t>(count)); });
1219 return projectCount(world->executePreset(presetId, originX, originY, dirX, dirY));
1220 });
1221 w.addFunc("queryPositions", [vm](ScriptSensingWorld* value, float originX, float originY, float targetX,
1222 float targetY, float radius, int samples, int limit, bool requireLineOfSight) {
1223 if (!value)
1225 vm,
1227 "world", {}, "sensing")),
1228 [](Value data) { return data; });
1229 auto world = Sensing::resolve(value->reference);
1230 if (!world.isBound())
1232 vm,
1234 "world", {}, "sensing")),
1235 [](Value data) { return data; });
1237 vm, world->queryPositions(originX, originY, targetX, targetY, radius, samples, limit, requireLineOfSight),
1238 [](Value data) { return data; });
1239 });
1240 w.addFunc("resultAt", [](ScriptSensingWorld* value, int i) -> Candidate* {
1241 if (!value) return nullptr;
1242 auto world = Sensing::resolve(value->reference);
1243 if (!world.isBound()) return nullptr;
1244 auto candidate = world->resultAt(i);
1245 return candidate ? const_cast<Candidate*>(&candidate->get()) : nullptr;
1246 });
1247 w.addFunc("snapshotJson", [vm](ScriptSensingWorld* value) {
1248 if (!value)
1252 "sensing world proxy must not be null", "world", {}, "sensing")),
1253 [](std::string text) { return eve::Value(std::move(text)); });
1254 auto world = Sensing::resolve(value->reference);
1255 if (!world.isBound())
1257 vm,
1259 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")),
1260 [](std::string text) { return eve::Value(std::move(text)); });
1262 [](std::string text) { return eve::Value(std::move(text)); });
1263 });
1264 w.addFunc("restoreJson", [vm](ScriptSensingWorld* value, const std::string& json) {
1265 if (!value)
1268 "sensing world proxy must not be null", "world", {}, "sensing")));
1269 auto world = Sensing::resolve(value->reference);
1270 if (!world.isBound())
1273 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")));
1274 return eve::script::projectResult(vm, world->restoreJson(json));
1275 });
1276 w.addFunc("setSpatialIndexEnabled", [vm](ScriptSensingWorld* value, bool enabled, float cellSize) {
1277 if (!value)
1280 "sensing world proxy must not be null", "world", {}, "sensing")));
1281 auto world = Sensing::resolve(value->reference);
1282 if (!world.isBound())
1285 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")));
1286 return eve::script::projectResult(vm, world->setSpatialIndexEnabled(enabled, cellSize));
1287 });
1288 w.addFunc("spatialIndexEnabled", [](ScriptSensingWorld* value) {
1289 if (!value) return false;
1290 auto world = Sensing::resolve(value->reference);
1291 return world.isBound() && world->spatialIndexEnabled();
1292 });
1293 w.addFunc("debugLastQueryJson", [vm](ScriptSensingWorld* value) {
1294 if (!value)
1298 "sensing world proxy must not be null", "world", {}, "sensing")),
1299 [](std::string text) { return eve::Value(std::move(text)); });
1300 auto world = Sensing::resolve(value->reference);
1301 if (!world.isBound())
1303 vm,
1305 eve::DiagnosticCode::StaleHandle, "sensing world handle is stale", "world", {}, "sensing")),
1306 [](std::string text) { return eve::Value(std::move(text)); });
1307 return eve::script::projectResult(vm, eve::Result<std::string>::success(world->debugLastQueryJson()),
1308 [](std::string text) { return eve::Value(std::move(text)); });
1309 });
1310 auto cls = t.addClass(name, Sensing::create, false);
1311 expose(cls);
1312}
1313void Sensing::expose(ssq::Class& c) {
1314 c.addFunc("getName", &Sensing::getName);
1315 c.addFunc("newWorld", [vm = c.getHandle()](Sensing*) {
1316 return makeOwnedProxy<SensingWorldHandleRef, ScriptSensingWorld>(
1317 vm, Sensing::newWorld(), [](SensingWorldHandleRef reference) { return Sensing::release(reference); });
1318 });
1319}
1320} // namespace eve::sensing
double z
double y
double x
float w
Definition AnimClip.cpp:738
int subject
Definition AnimSmr.cpp:163
ActiveSource owned
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
const std::string & s
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
float strength
ShaderImageInput shape
wgpu::PopErrorScopeStatus status
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
double r
float v
std::int32_t c
std::int32_t first
Strong identity values shared by persistence, content and logical-name APIs.
std::vector< Colorf > px
char quote
bool required
std::string to
std::string from
std::string id
Poco::JSON::Object::Ptr result
bool valid
std::unordered_set< std::string > tags
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
const std::string * accepts
const std::string * tag
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
OceanGpuFrameToken token
std::shared_ptr< OceanGpuSpectrum > owner
glm::dvec3 origin
glm::dvec3 dx
bool finite
std::string error
Definition Package.cpp:174
float f
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
std::set< std::string > values
Object::Ptr value
float d
float t
float distSq
bool found
std::array< std::array< double, 3 >, 3 > axes
std::string text
ScriptStructure out
std::string kind
让脚本实现 ISensingCandidateProvider(阶段 5:第三个落地的插座)。
std::size_t candidateCount
Definition Sensing.cpp:33
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
float dy
Definition Shadow.cpp:151
int count
The single Squirrel projection for common Result, Status and Value.
float targetX
Ordered Select/Filter/Sort task pipeline over SensingWorld candidates.
bool visible
int limit
Definition TreeMesh.cpp:166
float size
Definition TreeMesh.cpp:158
uint32_t index
double oy
double ox
const VegetationPresetContext & context
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
virtual std::string getName() const =0
Returns the name.
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
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
Non-owning observation of a registry-owned object.
Owning ranked result; does not assign a primary target.
Definition Sensing.h:173
Mirrored world positions and query composition; consumers decide gameplay actions from results.
Definition Sensing.h:197
eve::Result< CandidateQueryResult > query(const QueryOrigin &origin, const QuerySpec &spec)
Runs a configurable candidate query.
Definition Sensing.cpp:725
eve::Result< void > restoreJson(const std::string &json)
Restores a snapshot transactionally.
Definition Sensing.cpp:965
const std::map< std::string, Subject > & subjects() const noexcept
Returns a borrowed view of stored subjects for adapters; valid until mutation.
Definition Sensing.h:345
eve::Result< void > setSpatialIndexEnabled(bool enabled, float cellSize=64.f)
Enables or disables an compatibility-only XY broadphase; delegates to rebuildIndex (off by default).
Definition Sensing.cpp:423
eve::Result< int > circle(float x, float y, float radius, std::string_view requireTagsCsv, std::string_view excludeTagsCsv, std::string_view includeFactionsCsv, std::string_view excludeFactionsCsv, std::string_view visibleTo, int limit)
Queries a circle. Filters are CSV; empty fields disable that filter.
Definition Sensing.cpp:868
eve::Result< void > setZones(std::string_view id, std::string_view zonesCsv)
Replaces logical zone membership for an existing subject.
Definition Sensing.cpp:387
std::string snapshotJson() const
Exports deterministic JSON.
Definition Sensing.cpp:952
eve::Result< int > executePreset(std::string_view presetId, float originX, float originY, float dirX, float dirY)
Runs a registered TargetingPreset against this world and refreshes resultAt().
Definition Sensing.cpp:902
std::string debugLastQueryJson() const
Deterministic JSON dump of the last successful query for MCP/debug overlays.
Definition Sensing.cpp:929
eve::Result< void > setMetrics(std::string_view id, float pathProgress, float strength)
Updates route/threat metrics used by TD-style SortKey policies.
Definition Sensing.cpp:408
eve::Result< void > upsert(std::string_view id, float x, float y, std::string_view faction, std::string_view tagsCsv, std::string_view visibleToCsv)
Compatibility-only XY insertion; delegates to upsertPosition with Z zero.
Definition Sensing.cpp:329
eve::Result< int > box(float minX, float minY, float maxX, float maxY, std::string_view requireTagsCsv, std::string_view excludeTagsCsv, std::string_view includeFactionsCsv, std::string_view excludeFactionsCsv, std::string_view visibleTo, int limit)
Queries an axis-aligned box with the same filters as circle().
Definition Sensing.cpp:891
Result< void > upsertPosition(std::string_view id, float x, float y, float z, std::string_view faction, std::string_view tagsCsv, std::string_view visibleToCsv)
Inserts actual XYZ coordinates and metadata; owns copies, no retained arguments.
Definition Sensing.cpp:334
Result< void > rebuildIndex(SpatialIndexKind kind, float cellSize)
Rebuilds the derived index from owned facts; no coordinate conversion is stored.
Definition Sensing.cpp:430
eve::Result< int > circleSorted(float x, float y, float radius, std::string_view requireTagsCsv, std::string_view excludeTagsCsv, std::string_view includeFactionsCsv, std::string_view excludeFactionsCsv, std::string_view visibleTo, int limit, std::string_view sortPolicy)
Circle query with an explicit targeting sort policy.
Definition Sensing.cpp:877
SpatialIndexKind indexKind() const noexcept
Current broad-phase selection, independent of query distance semantics.
Definition Sensing.cpp:427
eve::Result< void > remove(std::string_view id)
Removes mirrored facts, or returns NotFound when the id is absent.
Definition Sensing.cpp:376
eve::Result< CandidateCollection > collectCandidates(const QueryOrigin &origin, const QuerySpec &spec) const
Collects matching facts without sorting, truncation or result-cache mutation.
Definition Sensing.cpp:671
eve::OptionalRef< const Candidate > resultAt(int index) const
Returns a candidate from the most recent query, or null for an invalid index.
Definition Sensing.cpp:925
bool spatialIndexEnabled() const noexcept
Reports whether the optional spatial broadphase is active.
Definition Sensing.cpp:428
Script factory for independent sensing worlds.
Definition Sensing.h:401
~Sensing() override
Sensing.
Definition Sensing.cpp:1041
static eve::Result< SensingWorldHandleRef > newWorld()
Script factory for independent sensing worlds.
Definition Sensing.cpp:1012
static bool isStale(SensingWorldHandleRef reference) noexcept
Reports whether a world reference is stale.
Definition Sensing.cpp:1029
int worldCount() const override
Number of live sensing worlds created by the project.
Definition Sensing.cpp:1046
Sensing()
Registers the read-only sensing capability for automation hosts.
Definition Sensing.cpp:1036
static eve::script::Borrowed< SensingWorld > resolve(SensingWorldHandleRef reference) noexcept
Resolves a live sensing world as a non-owning observation.
Definition Sensing.cpp:1016
std::vector< eve::SensingWorldQuery > lastQueries() const override
Last completed query of every live world, in slot order.
Definition Sensing.cpp:1052
static eve::Result< void > release(SensingWorldHandleRef reference)
Releases a module-owned sensing world and invalidates its handle.
Definition Sensing.cpp:1021
static TargetingPipeline & sharedBuiltins()
Process-local builtins pipeline used by SensingWorld::executePreset. @ownership Process lifetime; cal...
Result< CandidateQueryResult > executePreset(TargetingSourceContext &context, std::string_view presetId) const
Looks up a preset by id and executes it.
static Result< WorldPoint > world3D(float x, float y, float z)
Creates a finite 3D world point.
static Result< WorldPoint > world2D(float x, float y)
Creates a finite 2D world point.
Uniform-grid spatial hash for 2D AABB queries (map / particle / entity culling). Items are registered...
bool insert(int id, float minX, float minY, float maxX, float maxY)
Inserts an item AABB; false if out of bounds or id already present.
Snapshot project(Files files, Object::Ptr stats, std::string defaultProjectId, std::string projectDir)
Build a candidate evidence graph without touching the published snapshot.
Result< Grid2D > select(const Grid2D &input, std::string_view operation, int mode, int count, float weight, std::uint64_t seed, std::string_view rule)
Select.
ssq::Table makeOwnedProxy(HSQUIRRELVM vm, eve::Result< Ref > &&reference, Release &&release)
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
EVENGINE_API_PLATFORM void withdrawScriptSensingCandidateSeam()
撤回接缝与仍然在位的脚本适配器(由 Sensing 模块析构时调用)。
std::variant< WorldPoint, GridPoint > TargetLocation
Either a world point or a grid point, with the tag retained.
Definition Targeting.h:190
EVENGINE_API_PLATFORM void declareScriptSensingCandidateSeam()
声明"`ISensingCandidateProvider` 可以由脚本提供"这条接缝。
QueryAxes
Independent distance/projection semantics; planar shapes use these two axes.
Definition Sensing.h:113
std::variant< std::monostate, QueryCircle, QueryBox, QueryCone, QuerySphere > QueryShape
Optional broad-phase shape; monostate means range-only around the origin.
Definition Sensing.h:118
std::string_view coordinateSpaceName(CoordinateSpace space) noexcept
Returns the stable protocol name for a coordinate space.
@ TruncateToMax
Keep the best maxCount candidates after sorting (legacy circle/box limit).
void exposeSensingQueries(ssq::Table &table, ssq::Class &worldClass)
Registers spatial queries and owned environment plans at the Squirrel boundary.
SpatialIndexKind
Broad-phase implementation; selecting an index never changes query semantics.
Definition Sensing.h:115
std::optional< std::reference_wrapper< T > > OptionalRef
Optional borrowed reference; it does not extend T's lifetime.
Definition BorrowedRef.h:24
bool enabled
Last completed query of one live sensing world.
std::string lastQueryJson
Owning broad-phase output; collection never publishes or applies result limits.
Definition Sensing.h:190
A deterministic candidate returned by a spatial query.
Definition Sensing.h:53
World origin used for range tests, distance sorting and LOS.
Definition Sensing.h:150
Configurable candidate query against SensingWorld.
Definition Sensing.h:128
std::vector< std::string > excludedTags
Definition Sensing.h:133
CountPolicy countPolicy
Definition Sensing.h:139
std::vector< std::string > excludeFactions
Definition Sensing.h:135
std::uint32_t minCount
Definition Sensing.h:137
EVENGINE_API_PLATFORM eve::Result< void > validate() const
Validates ranges, counts, tags and shape invariants.
Definition Sensing.cpp:242
std::vector< std::string > requiredTags
Definition Sensing.h:132
std::uint32_t maxCount
Definition Sensing.h:138
std::optional< std::string > visibleTo
Definition Sensing.h:136
std::vector< std::string > includeFactions
Definition Sensing.h:134
One ranked candidate produced by SensingWorld::query.
Definition Sensing.h:159
Mirrored gameplay facts used by candidate queries.
Definition Sensing.h:40
Runtime source for one pipeline execution.
Axis-aligned 2D bounding box (min/max inclusive).
Definition Bounds.h:10
bool intersectsCircle(float cx, float cy, float radius) const
True if the circle overlaps this 2D box.
Definition Bounds.h:44