载入中...
搜索中...
未找到
RTSMining.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <cmath>
3#include "common/Profile.h"
5namespace eve::rts {
10 EV_PROFILE_MODULE("rts", "WorkerAssignmentSystem::step");
11 struct Candidate {
12 ResourceNode* node = nullptr;
13 float distance = 0.0f;
14 };
15 std::size_t assigned = 0;
16 auto workers = ecs::View<Unit, Unit::Identity, Unit::Motion, Unit::Orders, Unit::Worker>();
17 for (auto it = workers.begin(); it != workers.end(); ++it) {
18 auto [identity, motion, orders, worker] = *it;
19 auto* unit = identity == nullptr ? nullptr : dynamic_cast<Unit*>(ecs::try_get(identity->self));
20 if (unit == nullptr || &*unit->identity() != identity) continue;
21 if (!worker->autoAssign || worker->capacity <= 0.0f || worker->gatherRate <= 0.0f ||
22 worker->resourceType.empty() || !orders->values.empty() || !worker->dropoff.isBound() ||
23 worker->dropoff.isStale())
24 continue;
25
26 std::vector<Candidate> candidates;
29 for (auto nodeIt = nodes.begin(); nodeIt != nodes.end(); ++nodeIt) {
30 auto [nodeIdentity, position, stock, harvest] = *nodeIt;
31 auto* node =
32 nodeIdentity == nullptr ? nullptr : dynamic_cast<ResourceNode*>(ecs::try_get(nodeIdentity->self));
33 if (node == nullptr || stock->resourceType != worker->resourceType ||
34 (!stock->infinite && stock->remaining <= 0.0f))
35 continue;
36 harvest->workers.erase(
37 std::remove_if(harvest->workers.begin(), harvest->workers.end(),
38 [](const ecs::EntityHandle& handle) { return ecs::try_get(handle) == nullptr; }),
39 harvest->workers.end());
40 const auto handle = ecs::handle_of(unit);
41 const bool registered = std::any_of(harvest->workers.begin(), harvest->workers.end(),
42 [&](const auto& existing) { return isSameHandle(existing, handle); });
43 if (harvest->workers.size() >= harvest->capacity && !registered) continue;
44 candidates.push_back({node, distanceSquared(motion->x, motion->y, position->x, position->y)});
45 }
46 std::sort(candidates.begin(), candidates.end(), [](const Candidate& left, const Candidate& right) {
47 if (left.distance != right.distance) return left.distance < right.distance;
48 return left.node->identity()->self.id < right.node->identity()->self.id;
49 });
50 if (candidates.empty()) continue;
51 ResourceNode* node = candidates.front().node;
52 auto link = ResourceNodeLink::bind(ecs::handle_of(node));
53 if (!link) return Result<std::size_t>::failure(link.status());
54 worker->resourceNode = std::move(link).takeValue();
55 const auto handle = ecs::handle_of(unit);
56 if (std::none_of(node->harvest()->workers.begin(), node->harvest()->workers.end(),
57 [&](const auto& existing) { return isSameHandle(existing, handle); }))
58 node->harvest()->workers.push_back(handle);
59 CommandSpec command;
60 command.kind = OrderKind::Gather;
61 command.target = {node->position()->x, node->position()->y};
62 command.targetEntity = ecs::handle_of(node);
63 auto queued = orders->values.enqueue(command);
64 if (!queued) return Result<std::size_t>::failure(queued.status());
65 std::move(queued).takeValue();
66 ++assigned;
67 }
68 return Result<std::size_t>::success(assigned,
70}
71
73 EV_PROFILE_MODULE("rts", "MiningSystem::step");
74 if (step.delta.nanoseconds() < 0 || !credit)
77 "RTS mining requires non-negative time and a resource credit callback", "mining"));
78 std::size_t processed = 0;
79 auto workers = ecs::View<Unit, Unit::Identity, Unit::Motion, Unit::Orders, Unit::Worker>();
80 for (auto it = workers.begin(); it != workers.end(); ++it) {
81 auto [identity, motion, orders, worker] = *it;
82 auto* unit = identity == nullptr ? nullptr : dynamic_cast<Unit*>(ecs::try_get(identity->self));
83 if (unit == nullptr || &*unit->identity() != identity) continue;
84 auto current = readCurrent(orders->values);
85 if (!current) return Result<std::size_t>::failure(current.status());
86 auto record = std::move(current).takeValue();
87 if (!record) continue;
88
89 if (record->kind == OrderKind::Gather && motion->arrived) {
90 auto* node = dynamic_cast<ResourceNode*>(worker->resourceNode.resolve());
91 if (node == nullptr) {
92 auto failed = orders->values.fail(record->id, "resource node is stale");
93 if (!failed) return Result<std::size_t>::failure(failed.status());
94 worker->resourceNode.reset();
95 continue;
96 }
97 const float room = std::max(0.0f, worker->capacity - worker->cargo);
98 float amount = std::min(room, worker->gatherRate * static_cast<float>(step.delta.seconds()));
99 if (!node->stock()->infinite) amount = std::min(amount, node->stock()->remaining);
100 worker->cargo += amount;
101 if (!node->stock()->infinite) node->stock()->remaining -= amount;
102 if (worker->cargo >= worker->capacity || (!node->stock()->infinite && node->stock()->remaining <= 0.0f)) {
103 auto* dropoff = dynamic_cast<Building*>(worker->dropoff.resolve());
104 if (dropoff == nullptr) {
105 auto failed = orders->values.fail(record->id, "dropoff is stale");
106 if (!failed) return Result<std::size_t>::failure(failed.status());
107 continue;
108 }
109 auto completed = orders->values.complete(record->id);
110 if (!completed) return Result<std::size_t>::failure(completed.status());
111 CommandSpec returning;
112 returning.kind = OrderKind::ReturnCargo;
113 returning.target = {dropoff->placement()->worldX, dropoff->placement()->worldY};
114 returning.targetEntity = ecs::handle_of(dropoff);
115 auto queued = orders->values.enqueue(returning);
116 if (!queued) return Result<std::size_t>::failure(queued.status());
117 std::move(queued).takeValue();
118 }
119 ++processed;
120 } else if (record->kind == OrderKind::ReturnCargo && motion->arrived && worker->cargo >= 1.0f) {
121 const auto whole = static_cast<std::int64_t>(std::floor(worker->cargo));
122 auto cost = resource::CostSpec::single(worker->resourceType, whole);
123 if (!cost) return Result<std::size_t>::failure(cost.status());
124 auto credited = credit(*unit, cost.value());
125 if (!credited) return Result<std::size_t>::failure(credited.status());
126 worker->cargo -= static_cast<float>(whole);
127 auto completed = orders->values.complete(record->id);
128 if (!completed) return Result<std::size_t>::failure(completed.status());
129 auto* node = dynamic_cast<ResourceNode*>(worker->resourceNode.resolve());
130 if (node != nullptr && (node->stock()->infinite || node->stock()->remaining > 0.0f)) {
131 CommandSpec gather;
132 gather.kind = OrderKind::Gather;
133 gather.target = {node->position()->x, node->position()->y};
134 gather.targetEntity = ecs::handle_of(node);
135 auto queued = orders->values.enqueue(gather);
136 if (!queued) return Result<std::size_t>::failure(queued.status());
137 std::move(queued).takeValue();
138 } else {
139 worker->resourceNode.reset();
140 }
141 ++processed;
142 }
143 }
144 return Result<std::size_t>::success(processed,
146}
147
148} // namespace eve::rts
eve::resource::CostSpec cost
ScriptComponentRecord record
Definition ECS.cpp:228
HexVec3 left
HexVec3 right
PhysicsJointLink link
std::array< float, 3 > position
std::map< std::string, Node > nodes
float distance
size_t queued
Definition OnnxGpgpu.cpp:60
PrimitiveHandle handle
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
const RoadNode * node
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
double current
TacticalUnit * unit
float step
Definition TreeMesh.cpp:451
uint64_t identity
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
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static eve::Result< CostSpec > single(std::string_view resource, std::int64_t amount)
Build a one-resource cost.
RTS building domain root with placement and production composition.
Definition RTSTypes.h:852
static Result< std::size_t > step(const SimulationStep &step, const ResourceCredit &credit)
Gather stock or deliver integral cargo through the injected canonical credit boundary.
Definition RTSMining.cpp:72
Harvestable RTS resource node; deposited balances are owned by an external resource account.
Definition RTSTypes.h:1085
RTS unit domain root.
Definition RTSTypes.h:501
static Result< std::size_t > step()
Assign nearest available nodes and enqueue Gather orders.
Definition RTSMining.cpp:9
float distanceSquared(float ax, float ay, float bx, float by)
Result< std::optional< OrderRecord > > readCurrent(OrderComponent &orders)
bool isSameHandle(const ecs::EntityHandle &left, const ecs::EntityHandle &right)
std::function< Result< resource::Receipt >(Unit &, const resource::CostSpec &)> ResourceCredit
Callback that credits gathered resources to the authoritative account selected by the game.
Definition RTSSystems.h:389
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
One domain-neutral command submitted to a unit's generic order queue.
Definition RTSTypes.h:106
ecs::EntityHandle targetEntity
Definition RTSTypes.h:112
WorldPosition target
Definition RTSTypes.h:108
Concurrent worker capacity and current generation-checked assignments.
Definition RTSTypes.h:1113
Runtime and persistent identity.
Definition RTSTypes.h:1094
Authoritative world position and interaction radius.
Definition RTSTypes.h:1100
Authoritative remaining resource stock.
Definition RTSTypes.h:1106