载入中...
搜索中...
未找到
RTSStageBindings.cpp
浏览该文件的文档.
1#include <simplesquirrel/simplesquirrel.hpp>
3#include "rts/RTS.h"
6
8namespace {
9Result<void> bind(RTS& rts, transaction::AtomicBatch& batch, Faction& faction) {
10 auto account = rts.scriptAccount(faction);
11 if (!account) return batch.reject(account.status());
12 const auto handle = ecs::handle_of(&faction);
13 const auto tick = rts.scriptTick();
14 const auto expected = reinterpret_cast<std::uintptr_t>(&account.value().get());
15 auto guarded = batch.guard([&rts, handle, tick, expected]() -> Result<void> {
16 auto* faction = handle.table == ecs::current() ? dynamic_cast<Faction*>(ecs::try_get(handle)) : nullptr;
17 if (!faction || rts.scriptTick() != tick)
19 Diagnostic::error(DiagnosticCode::StaleHandle, "batch simulation context changed", "account"));
20 auto current = rts.scriptAccount(*faction);
21 if (!current) return Result<void>::failure(current.status());
22 if (reinterpret_cast<std::uintptr_t>(&current.value().get()) != expected)
24 Diagnostic::error(DiagnosticCode::StaleHandle, "batch account was replaced", "account"));
25 return Result<void>::success();
26 });
27 if (!guarded) return guarded;
28 return batch.bindAccount(account.value().get(), [&rts, handle](std::string_view name) -> std::optional<Value> {
29 auto* faction = handle.table == ecs::current() ? dynamic_cast<Faction*>(ecs::try_get(handle)) : nullptr;
30 if (!faction) return std::nullopt;
31 auto balance = rts.scriptResource(*faction, name);
32 if (!balance) {
33 balance.ignore("condition resource is unavailable");
34 return std::nullopt;
35 }
36 return Value(balance.value());
37 });
38}
39
40} // namespace
41void exposeStageBindings(ssq::Class& cls) {
42 const auto vm = cls.getHandle();
43 cls.addFunc("stageAbility", [vm](RTS* self, transaction::AtomicBatch* batch, const std::string& casterText,
44 const std::string& ability, const std::string& targetText, float x, float y) {
45 auto result = [&]() -> Result<void> {
46 auto retained = batch->retainScriptOwner(vm);
47 if (!retained) return retained;
48 auto id = parseScriptSubject(casterText, "caster");
49 if (!id) return batch->reject(id.status());
50 auto* caster = self->findUnit(id.value());
51 if (!caster)
52 return batch->reject(
53 Status::failure(Diagnostic::error(DiagnosticCode::NotFound, "caster is absent", "caster")));
54 auto* faction = dynamic_cast<Faction*>(caster->faction()->link.resolve());
55 if (!faction)
56 return batch->reject(
57 Status::failure(Diagnostic::error(DiagnosticCode::StaleHandle, "faction is stale", "caster")));
58 auto payer = bind(*self, *batch, *faction);
59 if (!payer) return payer;
61 if (!targetText.empty()) {
62 auto parsed = parseScriptSubject(targetText, "target");
63 if (!parsed) return batch->reject(parsed.status());
64 target = parsed.value();
65 }
66 auto staged = self->prepareScriptAbility(*caster, ability, target, {x, y});
67 if (!staged) return batch->reject(staged.status());
68 auto stage = std::move(staged).takeValue();
69 std::vector<std::unique_ptr<transaction::ITransactionParticipant>> effects;
70 effects.push_back(std::move(stage.effect));
71 return batch->add(std::move(effects), std::move(stage.cost));
72 }();
73 return script::projectResult(vm, std::move(result));
74 });
75 cls.addFunc("stageProduction", [vm](RTS* self, transaction::AtomicBatch* batch, const std::string& producerText,
76 const std::string& unitText, const std::string& definitionText) {
77 auto result = [&]() -> Result<void> {
78 auto retained = batch->retainScriptOwner(vm);
79 if (!retained) return retained;
80 auto producerId = parseScriptSubject(producerText, "producer"),
81 unitId = parseScriptSubject(unitText, "unit");
82 if (!producerId) return batch->reject(producerId.status());
83 if (!unitId) return batch->reject(unitId.status());
84 auto definition = LogicalId::parse(definitionText);
85 if (!definition)
86 return batch->reject(Status::failure(
87 Diagnostic::error(DiagnosticCode::InvalidArgument, "definition is invalid", "definition")));
88 auto* producer = self->findBuilding(producerId.value());
89 if (!producer)
90 return batch->reject(
91 Status::failure(Diagnostic::error(DiagnosticCode::NotFound, "producer is absent", "producer")));
92 auto* faction = dynamic_cast<Faction*>(producer->faction()->link.resolve());
93 if (!faction)
94 return batch->reject(
95 Status::failure(Diagnostic::error(DiagnosticCode::StaleHandle, "faction is stale", "producer")));
96 auto payer = bind(*self, *batch, *faction);
97 if (!payer) return payer;
98 auto staged = self->prepareScriptUnit(*producer, unitId.value(), *definition);
99 if (!staged) return batch->reject(staged.status());
100 auto stage = std::move(staged).takeValue();
101 for (const auto& [name, policy] : faction->productionPolicy()->resourceReserves) {
102 if (policy.minimumPriority <= 0) continue;
103 auto floor = resource::ResourceCost::create(name, policy.amount);
104 if (!floor) return batch->reject(floor.status());
105 auto protectedCost = batch->protect(std::move(floor).takeValue());
106 if (!protectedCost) return protectedCost;
107 }
108 return batch->add(std::move(stage.stage.effects), std::move(stage.cost));
109 }();
110 return script::projectResult(vm, std::move(result));
111 });
112 cls.addFunc("stagePayment", [vm](RTS* self, transaction::AtomicBatch* batch, const std::string& factionText,
113 const std::string& json) {
114 auto result = [&]() -> Result<void> {
115 auto retained = batch->retainScriptOwner(vm);
116 if (!retained) return retained;
117 auto id = parseScriptSubject(factionText, "faction");
118 if (!id) return batch->reject(id.status());
119 auto* faction = self->findFaction(id.value());
120 if (!faction)
121 return batch->reject(
122 Status::failure(Diagnostic::error(DiagnosticCode::NotFound, "faction is absent", "faction")));
123 auto payer = bind(*self, *batch, *faction);
124 if (!payer) return payer;
126 if (!cost) return batch->reject(cost.status());
127 return batch->add({}, std::move(cost).takeValue());
128 }();
129 return script::projectResult(vm, std::move(result));
130 });
131}
132} // namespace eve::rts::script_internal
double y
double x
LogicalId target
eve::resource::CostSpec cost
eve::resource::IResourceAccount * account
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
wgpu::PopErrorScopeStatus status
Poco::JSON::Object::Ptr result
PrimitiveHandle handle
Object::Ptr value
RTS module owner and phase-one composition profile entry point.
double current
The single Squirrel projection for common Result, Status and Value.
SimulationTick tick
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
void value() const
Mark a successful void operation as checked.
Definition Result.h:560
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 failure(StatusCode code, Diagnostic diagnostic)
Construct a failed status with one diagnostic.
Definition Status.cpp:28
Strong, domain-neutral reference to a runtime subject.
Definition SubjectRef.h:26
Faction domain root; membership is a set of typed runtime handles.
Definition RTSTypes.h:1192
Owns RTS root entities and coordinates the phase-one systems.
Definition RTS.h:105
Result< RTSPreparedAbility > prepareScriptAbility(Unit &caster, std::string ability, SubjectRef target, WorldPosition point)
Stage ability admission for an outer card/resource transaction. @cost Linear in caster cooldown count...
Building * findBuilding(SubjectRef subject) const noexcept
Resolve a module-owned building by persistent subject identity.
Definition RTS.cpp:980
Unit * findUnit(SubjectRef subject) const noexcept
Resolve a module-owned unit by persistent subject identity.
Definition RTS.cpp:978
Faction * findFaction(SubjectRef subject) const noexcept
Resolve a module-owned faction by persistent subject identity.
Definition RTS.cpp:3592
Result< RTSPreparedProduction > prepareScriptUnit(Building &producer, SubjectRef unitSubject, LogicalId unitDefinition, int priority=0)
Queue one data-defined unit through canonical production, action and economy providers....
Single-use composition of domain participants and one payer's costs. Owns staged participants,...
Definition AtomicBatch.h:19
Result< void > reject(Status status)
Preserve the first admission error and reject further execution.
static Result< resource::CostSpec > parseCost(const std::string &json)
Parse a positive-integer resource cost object at the script boundary.
Result< void > retainScriptOwner(void *vm)
Retain the current native script method's self for staged lifetimes.
Result< void > add(std::vector< std::unique_ptr< ITransactionParticipant > > effects, std::optional< resource::CostSpec > cost={})
Append owning effects and optional cost without executing them. @cost Linear in effect/cost count; st...
Result< void > protect(resource::ResourceCost floor)
Preserve a resource floor after the complete merged payment. Multiple contributors combine floors by ...
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
Result< SubjectRef > parseScriptSubject(std::string_view text, std::string_view path)
void exposeStageBindings(ssq::Class &cls)
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
static eve::Result< ResourceCost > create(std::string_view resourceId, std::int64_t amountValue)
Construct and validate one cost item.