载入中...
搜索中...
未找到
Sensing.cpp
浏览该文件的文档.
78 std::none_of(values.begin(), values.end(), [token](const std::string& value) { return value == token; }))
112 return std::pow(cells, dimensions) <= 262144 && indexable(x + radius, y + radius, z + radius, cellSize) &&
126 std::invoke(std::forward<Release>(release), ref).ignore("rollback failed owned sensing allocation");
131 auto result = eve::script::projectStatusResult(vm, eve::Status::success(eve::StatusCode::Applied));
195eve::Result<QuerySpec> circleSpec(float x, float y, float radius, std::string_view requireTagsCsv,
201 "circle query requires finite coordinates, non-negative radius and limit", "query", {}, "sensing"));
219eve::Result<QuerySpec> boxSpec(float minX, float minY, float maxX, float maxY, std::string_view requireTagsCsv,
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",
243 if (axes > QueryAxes::XYZ || (axes == QueryAxes::XYZ && !std::holds_alternative<std::monostate>(shape) &&
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)",
260 eve::DiagnosticCode::InvalidArgument, "QuerySpec.minCount exceeds maxCount", "query.count", {}, "sensing"));
329eve::Result<void> SensingWorld::upsert(std::string_view id, float x, float y, std::string_view f, std::string_view t,
334Result<void> SensingWorld::upsertPosition(std::string_view id, float x, float y, float z, std::string_view f,
346 DiagnosticCode::InvalidArgument, "position exceeds index cell range", "subject.position", {}, "sensing"));
351 const bool positionChanged = found->second.x != x || found->second.y != y || found->second.z != z;
408eve::Result<void> SensingWorld::setMetrics(std::string_view id, float pathProgress, float strength) {
428bool SensingWorld::spatialIndexEnabled() const noexcept { return spatialIndex_ || spatialIndex3D_; }
431 if (kind > SpatialIndexKind::XYZ || (kind != SpatialIndexKind::None && (!finite(cellSize) || cellSize <= 0)))
433 DiagnosticCode::InvalidArgument, "invalid spatial index kind or cell size", "spatial", {}, "sensing"));
523 const float cellSize = spatialIndex3D_ ? spatialIndex3D_->getCellSize() : spatialIndex_->getCellSize();
534 const int count = spatialIndex3D_ ? spatialIndex3D_->getResultCount() : spatialIndex_->getResultCount();
536 const int id = spatialIndex3D_ ? spatialIndex3D_->getResultId(i) : spatialIndex_->getResultId(i);
563 if (const auto* circle = std::get_if<QueryCircle>(&spec.shape); circle && axes == QueryAxes::XY) {
567 const std::array<int, 4> cells{static_cast<int>(std::floor((circle->x - circle->radius) / cellSize)),
666 results_.push_back(Candidate{candidate.id, candidate.x, candidate.y, candidate.distance, candidate.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",
722 CandidateCollection{std::move(ranked), usedSpatial, static_cast<std::uint32_t>(candidates.size())});
725eve::Result<CandidateQueryResult> SensingWorld::query(const QueryOrigin& origin, const QuerySpec& spec) {
729Result<CandidateQueryResult> SensingWorld::query(const QueryOrigin& origin, const QuerySpec& spec,
741 auto from = origin.space == CoordinateSpace::World3D ? WorldPoint::world3D(origin.x, origin.y, origin.z)
751 auto sight = lineOfSight->get().query(TargetLocation{from.value()}, TargetLocation{to.value()});
854 if (sortPolicy == "furthest") return eve::Result<SortKey>::success(SortKey::DistanceDescending);
855 if (sortPolicy == "first") return eve::Result<SortKey>::success(SortKey::PathProgressDescending);
857 if (sortPolicy == "strongest") return eve::Result<SortKey>::success(SortKey::StrengthDescending);
862 "sortPolicy must be closest|furthest|first|last|strongest|weakest|distance|none", "query.sort", {},
868eve::Result<int> SensingWorld::circle(float x, float y, float radius, std::string_view r, std::string_view e,
877eve::Result<int> SensingWorld::circleSorted(float x, float y, float radius, std::string_view r, std::string_view e,
891eve::Result<int> SensingWorld::box(float a, float b, float c, float d, std::string_view r, std::string_view e,
902eve::Result<int> SensingWorld::executePreset(std::string_view presetId, float originX, float originY, float dirX,
926 return i >= 0 && size_t(i) < results_.size() ? eve::OptionalRef<const Candidate>(std::cref(results_[size_t(i)]))
934 << ",\"z\":" << lastQuery_.originZ << ",\"space\":" << quote(coordinateSpaceName(lastQuery_.space)) << '}'
959 o << "{\"id\":" << quote(id) << ",\"x\":" << std::setprecision(9) << s.x << ",\"y\":" << s.y << ",\"z\":" << s.z
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"));
982 (d.root().getInt("version") == 2 && !v.get("z").isNumber()) || next.subjects_.contains(v.getString("id")))
1025 eve::DiagnosticCode::StaleHandle, "Sensing module is no longer loaded", "world", {}, "sensing"));
1065 auto c = t.addClass<Candidate>("SensingCandidate", std::function<Candidate*()>([]() { return nullptr; }), false);
1082 w.addFunc("isStale", [](ScriptSensingWorld* value) { return !value || Sensing::isStale(value->reference); });
1115 w.addFunc("setZones", [vm](ScriptSensingWorld* value, const std::string& id, const std::string& zones) {
1127 w.addFunc("setMetrics", [vm](ScriptSensingWorld* value, const std::string& id, float pathProgress, float strength) {
1143 w.addFunc("circle", [vm, projectCount](ScriptSensingWorld* value, float x, float y, float radius,
1161 world->circle(x, y, radius, required, excluded, includedFactions, excludedFactions, visibleTo, limit));
1163 w.addFunc("circleSorted", [vm, projectCount](ScriptSensingWorld* value, float x, float y, float radius,
1181 return projectCount(world->circleSorted(x, y, radius, required, excluded, includedFactions, excludedFactions,
1184 w.addFunc("box", [vm, projectCount](ScriptSensingWorld* value, float minX, float minY, float maxX, float maxY,
1201 return projectCount(world->box(minX, minY, maxX, maxY, required, excluded, includedFactions, excludedFactions,
1204 w.addFunc("executePreset", [vm, projectCount](ScriptSensingWorld* value, const std::string& presetId, float originX,
1221 w.addFunc("queryPositions", [vm](ScriptSensingWorld* value, float originX, float originY, float targetX,
1226 Result<Value>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "sensing world proxy is null",
1233 Result<Value>::failure(Diagnostic::error(DiagnosticCode::StaleHandle, "sensing world handle is stale",
1237 vm, world->queryPositions(originX, originY, targetX, targetY, radius, samples, limit, requireLineOfSight),
1261 return eve::script::projectResult(vm, eve::Result<std::string>::success(world->snapshotJson()),
1276 w.addFunc("setSpatialIndexEnabled", [vm](ScriptSensingWorld* value, bool enabled, float cellSize) {
1307 return eve::script::projectResult(vm, eve::Result<std::string>::success(world->debugLastQueryJson()),
1317 vm, Sensing::newWorld(), [](SensingWorldHandleRef reference) { return Sensing::release(reference); });
Strong identity values shared by persistence, content and logical-name APIs.
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
让脚本实现 ISensingCandidateProvider(阶段 5:第三个落地的插座)。
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
The single Squirrel projection for common Result, Status and Value.
Ordered Select/Filter/Sort task pipeline over SensingWorld candidates.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Definition Diagnostic.cpp:21
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
Non-owning observation of a registry-owned object.
Definition RuntimeBorrow.h:27
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
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
SensingWorld()
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
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...
Definition TargetingPipeline.cpp:240
Result< CandidateQueryResult > executePreset(TargetingSourceContext &context, std::string_view presetId) const
Looks up a preset by id and executes it.
Definition TargetingPipeline.cpp:348
static Result< WorldPoint > world3D(float x, float y, float z)
Creates a finite 3D world point.
Definition Targeting.cpp:135
static Result< WorldPoint > world2D(float x, float y)
Creates a finite 2D world point.
Definition Targeting.cpp:128
Uniform-grid spatial hash for 2D AABB queries (map / particle / entity culling). Items are registered...
Definition SpatialHash2D.h:18
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.
Definition SpatialHash2D.cpp:68
Snapshot project(Files files, Object::Ptr stats, std::string defaultProjectId, std::string projectDir)
Build a candidate evidence graph without touching the published snapshot.
Definition ProjectIndexGraph.cpp:144
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.
Definition GridGraphAlgorithms.cpp:226
ssq::Table makeOwnedProxy(HSQUIRRELVM vm, eve::Result< Ref > &&reference, Release &&release)
Definition ProcgenScriptSupport.h:200
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
Definition SquirrelBinding.cpp:524
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Definition SquirrelBinding.cpp:540
Definition RTSSystems.h:258
@ StrengthDescending
@ DistanceAscending
@ PathProgressAscending
@ StrengthAscending
@ DistanceDescending
@ PathProgressDescending
EVENGINE_API_PLATFORM void withdrawScriptSensingCandidateSeam()
撤回接缝与仍然在位的脚本适配器(由 Sensing 模块析构时调用)。
Definition SensingScriptCandidateSeam.cpp:437
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` 可以由脚本提供"这条接缝。
Definition SensingScriptCandidateSeam.cpp:403
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.
Definition Targeting.cpp:561
@ 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.
Definition SensingQueryBinding.cpp:55
SpatialIndexKind
Broad-phase implementation; selecting an index never changes query semantics.
Definition Sensing.h:115
@ InvalidArgument
@ NotFound
@ PreconditionViolation
@ Unsupported
@ Failed
@ ParseError
@ StaleHandle
@ Applied
std::optional< std::reference_wrapper< T > > OptionalRef
Optional borrowed reference; it does not extend T's lifetime.
Definition BorrowedRef.h:24
Definition Container.h:602
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
std::vector< std::string > excludedTags
Definition Sensing.h:133
std::vector< std::string > excludeFactions
Definition Sensing.h:135
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::vector< std::string > includeFactions
Definition Sensing.h:134
One ranked candidate produced by SensingWorld::query.
Definition Sensing.h:159
Runtime source for one pipeline execution.
Definition TargetingPipeline.h:60
bool intersectsCircle(float cx, float cy, float radius) const
True if the circle overlaps this 2D box.
Definition Bounds.h:44