载入中...
搜索中...
未找到
RTSEconomy.cpp
浏览该文件的文档.
1#include "rts/RTSEconomy.h"
2#include <algorithm>
3#include <cmath>
4#include <limits>
5#include <utility>
6#include "rts/RTSEffects.h"
7
8// RTSEconomy.cpp
9namespace eve::rts {
10
12
14
17 if (transactionId.empty()) transactionId = "rts.economy.payment";
19 eve::transaction::TransactionContext(std::move(transactionId)), account_, cost, effect);
20}
21
25
27 const eve::resource::CostSpec& cost, std::span<eve::transaction::ITransactionParticipant*> effects,
28 std::string transactionId) {
29 if (transactionId.empty()) transactionId = "rts.economy.payment";
31 eve::transaction::TransactionContext(std::move(transactionId)), account_, cost, effects);
32}
33
34} // namespace eve::rts
35
36// RTSEffects.cpp
37namespace eve::rts {
38namespace {
39
40const char* kindTag(RTSEffectKind kind) {
41 switch (kind) {
42 case RTSEffectKind::Morale: return "rts:morale";
43 case RTSEffectKind::Suppression: return "rts:suppression";
44 case RTSEffectKind::ProductionLock: return "rts:production-lock";
45 }
46 return "rts:unknown";
47}
48
49} // namespace
50
52 if (!std::isfinite(target.morale) || target.morale < 0.0 || target.morale > 100.0)
54 "RTS morale must be in [0,100]", "target.morale"));
56}
57
59 const effects::EffectInstance& effect) const {
60 auto valid = validate(target);
61 if (!valid) return valid;
62 if (effect.hasTag("rts:production-lock")) target.productionLocked = true;
64}
65
67 effects::EffectUpdateSummary lifecycle) const {
68 auto valid = validate(target);
71 result.lifecycle = std::move(lifecycle);
72 for (const auto& tick : result.lifecycle.periodicTicks) {
73 if (tick.stackCount == 0 || !std::isfinite(tick.magnitude) || tick.magnitude < 0.0)
75 eve::DiagnosticCode::InvalidArgument, "RTS periodic effect value is invalid", "periodic"));
76 const auto amount = tick.magnitude * static_cast<double>(tick.stackCount);
77 if (!std::isfinite(amount))
79 eve::DiagnosticCode::InvalidArgument, "RTS periodic effect overflows", "periodic"));
80 const auto tagged = [&tick](const char* tag) {
81 return std::find(tick.tags.begin(), tick.tags.end(), tag) != tick.tags.end();
82 };
83 if (tagged("rts:morale")) {
84 target.morale = std::max(0.0, target.morale - amount);
85 if (target.morale == 0.0) ++target.commandInterrupts;
86 } else if (tagged("rts:suppression")) {
87 if (target.suppression > std::numeric_limits<std::uint32_t>::max() - tick.stackCount)
89 eve::DiagnosticCode::InvalidArgument, "RTS suppression count overflows", "target.suppression"));
90 target.suppression += tick.stackCount;
91 } else if (tagged("rts:production-lock")) {
92 target.productionLocked = true;
93 ++result.commandInterrupts;
94 }
95 ++result.settled;
96 }
98}
99
102 if (definition.id.empty() || !subject.isValid())
104 eve::DiagnosticCode::InvalidArgument, "RTS effect requires an id and valid subject", "effect"));
106 common.id = definition.id;
107 common.stackKey = definition.id;
108 common.duration = definition.duration;
109 common.period = definition.period;
110 common.magnitude = definition.magnitude;
111 common.policy = definition.policy;
112 common.payload.setNumber("speedMultiplier", definition.speedMultiplier);
113 common.payload.setNumber("damageMultiplier", definition.damageMultiplier);
114 common.payload.setNumber("incomingDamageMultiplier", definition.incomingDamageMultiplier);
115 common.payload.setNumber("healingPerSecond", definition.healingPerSecond);
116 common.tags = definition.tags;
117 common.tags.push_back(kindTag(definition.kind));
118 auto valid = common.validate();
120 auto candidate = container_.clone();
121 auto applied = candidate.apply(common, subject.format(), definition.source);
123 const std::string id = std::move(applied).takeValue();
124 const auto* instance = candidate.find(id);
125 if (!instance)
127 eve::DiagnosticCode::InvariantViolation, "RTS effect candidate disappeared", "effect"));
128 auto targetCandidate = target_;
129 auto targetValid = executor_.applyImmediate(targetCandidate, *instance);
130 if (!targetValid) return eve::Result<effects::EffectHandle>::failure(targetValid.status());
131 auto handle = candidate.handleFor(id);
133 target_ = std::move(targetCandidate);
134 container_ = std::move(candidate);
135 return eve::Result<effects::EffectHandle>::success(std::move(handle).takeValue(),
137}
138
140 auto resolved = container_.resolve(handle);
141 if (!resolved) return eve::Result<void>::failure(resolved.status());
142 return container_.remove(handle.instanceId);
143}
144
146 auto candidate = container_.clone();
147 auto lifecycle = effects::EffectExecutor{}.advance(candidate, step);
148 if (!lifecycle) return eve::Result<RTSEffectUpdate>::failure(lifecycle.status());
149 auto targetCandidate = target_;
150 auto settled = executor_.settle(targetCandidate, std::move(lifecycle).takeValue());
151 if (!settled) return settled;
152 auto result = std::move(settled).takeValue();
153 target_ = std::move(targetCandidate);
154 container_ = std::move(candidate);
156}
157
158RTSEffectSnapshot RTSEffectAdapter::snapshot() const { return {container_.snapshot(), target_}; }
159
161 auto valid = executor_.validate(snapshotValue.target);
162 if (!valid) return valid;
163 auto restored = container_.restore(snapshotValue.effects);
164 if (!restored) return restored;
165 target_ = snapshotValue.target;
167}
168
169std::size_t RTSEffectAdapter::count() const noexcept { return static_cast<std::size_t>(container_.effectCount()); }
170
174
175double RTSEffectAdapter::multiplier(std::string_view field) const noexcept {
176 double result = 1.0;
177 for (int index = 0; index < container_.effectCount(); ++index) {
178 const auto* effect = container_.effectAt(index);
179 if (effect == nullptr) continue;
180 const auto found = effect->payload.object().find(std::string(field));
181 if (found == effect->payload.object().end()) continue;
182 if (const auto* real = found->second.getIf<double>())
183 result *= *real;
184 else if (const auto* integer = found->second.getIf<std::int64_t>())
185 result *= static_cast<double>(*integer);
186 }
187 return result;
188}
189
190double RTSEffectAdapter::additive(std::string_view field) const noexcept {
191 double result = 0.0;
192 for (int index = 0; index < container_.effectCount(); ++index) {
193 const auto* effect = container_.effectAt(index);
194 if (effect == nullptr) continue;
195 const auto found = effect->payload.object().find(std::string(field));
196 if (found == effect->payload.object().end()) continue;
197 if (const auto* real = found->second.getIf<double>())
198 result += *real;
199 else if (const auto* integer = found->second.getIf<std::int64_t>())
200 result += static_cast<double>(*integer);
201 }
202 return result;
203}
204
206 if (!subject.isValid())
208 eve::DiagnosticCode::InvalidArgument, "RTS effect component requires a valid subject", "subject"));
209 if (subject_.isValid() && subject_ != subject && adapter_.count() != 0)
212 "RTS effect component cannot change subject while effects are active", "subject"));
213 subject_ = subject;
215}
216
218 if (!subject_.isValid())
220 eve::DiagnosticCode::InvalidArgument, "RTS effect component has no bound subject", "subject"));
221 return adapter_.apply(definition, subject_);
222}
223
225
229
230} // namespace eve::rts
LogicalId target
int subject
Definition AnimSmr.cpp:163
bool applied
eve::resource::CostSpec cost
Poco::JSON::Object::Ptr result
bool valid
const std::string * tag
std::unique_ptr< ParticleEffect > effect
PrimitiveHandle handle
RTS composition adapter over the canonical EconomyLedger account.
RTS effect adapter with morale, suppression and production policies.
RoadNetwork resolved
bool found
std::string kind
SimulationTick tick
float step
Definition TreeMesh.cpp:451
uint32_t index
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
Strong, domain-neutral reference to a runtime subject.
Definition SubjectRef.h:26
bool isValid() const noexcept
Return whether this reference is valid and non-nil.
Definition SubjectRef.h:38
eve::Result< eve::resource::Receipt > credit(const eve::resource::CostSpec &cost) override
Atomically credit all items immediately.
单个玩家的资源账本:当前量、上限、收支与浪费统计。
EffectContainer snapshot() const
Capture an independent lifecycle snapshot for staging/restore.
eve::Result< const EffectInstance * > resolve(EffectHandle handle) const
Resolve a generation-qualified handle for this call.
eve::Result< void > remove(const std::string &id, const std::string &reason="removed")
Removes one active instance and emits a Removed event.
EffectContainer clone() const
Create an independent deep copy suitable for ECS staging.
int effectCount() const
Returns active instance count in deterministic creation order.
eve::Result< std::string > apply(const EffectDefinition &definition, const std::string &subject, const std::string &source={})
Applies a definition and returns the stable instance identifier.
eve::Result< void > restore(const EffectContainer &snapshot)
Restore a previously captured snapshot as one observable commit.
Executes lifecycle time progression for an EffectContainer.
eve::Result< EffectUpdateSummary > advance(EffectContainer &container, double dtSeconds) const
Advances one container by a legacy seconds delta.
void setNumber(const std::string &key, double value)
Sets a JSON number field.
Immutable canonical multi-resource cost.
Provider-neutral resource account contract.
eve::Result< eve::resource::Receipt > credit(const eve::resource::CostSpec &cost)
Credit the ledger through the common account protocol.
eve::resource::IResourceAccount & account() noexcept
Return the account view for direct reservation/credit operations.
eve::Result< eve::transaction::TransactionReceipt > pay(const eve::resource::CostSpec &cost, eve::transaction::ITransactionParticipant &effect, std::string transactionId={})
Atomically pay an RTS cost and publish its domain effect.
RTSEconomyAdapter(eve::economy::EconomyLedger &ledger)
Bind this adapter to a caller-owned RTS economy ledger.
RTSEffectSnapshot snapshot() const
Capture effects and domain target state.
double multiplier(std::string_view field) const noexcept
Multiply one numeric payload across all active canonical effect instances.
eve::Result< const effects::EffectInstance * > resolve(effects::EffectHandle handle) const
Resolve a live handle as a borrowed observation.
std::size_t count() const noexcept
Return the number of active effect instances.
double additive(std::string_view field) const noexcept
Sum one numeric payload across all active canonical effect instances.
eve::Result< RTSEffectUpdate > advance(const eve::SimulationStep &step)
Advance and settle RTS effects atomically.
eve::Result< void > restore(const RTSEffectSnapshot &snapshot)
Restore effects and target state, invalidating prior handles.
eve::Result< void > remove(effects::EffectHandle handle)
Remove one generation-qualified effect handle.
eve::Result< effects::EffectHandle > apply(const RTSEffectDefinition &definition, eve::SubjectRef subject)
Apply one typed effect to a stable subject.
eve::Result< effects::EffectHandle > apply(const RTSEffectDefinition &definition)
Apply a typed RTS effect to this entity's canonical lifecycle.
eve::Result< void > bindSubject(eve::SubjectRef subject)
Bind the owning entity subject before applying effects.
eve::Result< RTSEffectUpdate > advance(const eve::SimulationStep &step)
Advance this entity's effect lifecycle and settle domain state.
eve::Result< void > remove(effects::EffectHandle handle)
Remove one generation-qualified effect handle.
eve::Result< RTSEffectUpdate > settle(RTSEffectTarget &target, effects::EffectUpdateSummary lifecycle) const
Settle common periodic triggers using RTS-specific policies.
eve::Result< void > applyImmediate(RTSEffectTarget &target, const effects::EffectInstance &effect) const
Apply immediate production-lock semantics to a staged target.
eve::Result< void > validate(const RTSEffectTarget &target) const
Validate the target state before a staged application.
static eve::Result< TransactionReceipt > execute(const TransactionContext &context, std::span< ITransactionParticipant * > participants)
Execute already prepared domain participants as one transaction.
Synchronous participant contract for one coordinator transaction.
Immutable context shared by every participant of one transaction.
Definition Transaction.h:31
RTSEffectKind
RTS-specific interpretation of an effect instance.
Definition RTSEffects.h:24
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Immutable-by-convention template used to create effect instances.
std::vector< std::string > tags
double period
Period in seconds for domain executor settlement; zero disables periodic ticks.
eve::Result< void > validate() const
Validates definition fields without changing any state.
Generation-qualified local reference to a canonical effect instance.
One owned runtime effect fact.
Summary returned by the lifecycle executor after one simulation step.
Typed RTS definition projected to the common lifecycle schema.
Definition RTSEffects.h:35
Serializable in-memory RTS effect snapshot.
Definition RTSEffects.h:58
effects::EffectContainer effects
Definition RTSEffects.h:59
Mutable RTS state affected by the domain executor.
Definition RTSEffects.h:27
Result of one RTS lifecycle step and domain settlement.
Definition RTSEffects.h:51
effects::EffectUpdateSummary lifecycle
Definition RTSEffects.h:52