载入中...
搜索中...
未找到
ForgeBench.cpp
浏览该文件的文档.
1#include "rpg/ForgeBench.h"
2
3#include "inventory/Bag.h"
6#include "rpg/RPGActor.h"
8
9#include <utility>
10
11namespace eve::rpg {
12namespace {
13
14template <class T>
15eve::Result<T> failure(eve::DiagnosticCode code, std::string message, std::string path = {}) {
16 return eve::Result<T>::failure(eve::Diagnostic::error(code, std::move(message), std::move(path)));
17}
18
19std::string forgeTaskStateName(production::TaskState state) {
20 switch (state) {
21 case production::TaskState::Queued: return "queued";
22 case production::TaskState::Running: return "running";
23 case production::TaskState::Paused: return "paused";
24 case production::TaskState::ReadyToSettle: return "ready_to_settle";
25 case production::TaskState::SettlementFailed: return "settlement_failed";
26 case production::TaskState::Completed: return "completed";
27 case production::TaskState::Cancelled: return "cancelled";
28 case production::TaskState::Failed: return "failed";
29 }
30 return {};
31}
32
33eve::Result<CraftingRecipe> parseCraftRecipe(const eve::Value& root) {
34 const auto* object = root.getIf<eve::Value::Object>();
35 if (object == nullptr)
36 return failure<CraftingRecipe>(eve::DiagnosticCode::InvalidArgument, "craft recipe must be an object",
37 "recipe");
38 const auto id = object->find("id");
39 const auto process = object->find("process");
40 const auto ingredients = object->find("ingredients");
41 const auto outputs = object->find("outputs");
42 const auto duration = object->find("duration");
43 if (id == object->end() || !id->second.isString() || id->second.asString().empty() ||
44 ingredients == object->end() || outputs == object->end() || !outputs->second.isArray() ||
45 duration == object->end() || !duration->second.isNumeric())
46 return failure<CraftingRecipe>(eve::DiagnosticCode::InvalidArgument,
47 "craft recipe requires id, ingredients, outputs and duration", "recipe");
48 auto ingredientsJson = ingredients->second.toJson();
49 if (!ingredientsJson) return eve::Result<CraftingRecipe>::failure(ingredientsJson.status());
50 auto cost = transaction::AtomicBatch::parseCost(ingredientsJson.value());
51 if (!cost) return eve::Result<CraftingRecipe>::failure(cost.status());
52 auto seconds = Duration::fromSeconds(duration->second.isInt64() ? static_cast<double>(duration->second.asInt())
53 : duration->second.asDouble());
54 if (!seconds) return eve::Result<CraftingRecipe>::failure(seconds.status());
55 CraftingRecipe recipe;
56 recipe.id = id->second.asString();
57 recipe.process = (process != object->end() && process->second.isString() && !process->second.asString().empty())
58 ? process->second.asString()
59 : "craft";
60 recipe.ingredients = std::move(cost).takeValue();
61 recipe.duration = std::move(seconds).takeValue();
62 const auto* outputValues = outputs->second.getIf<eve::Value::Array>();
63 for (const auto& value : *outputValues) {
64 const auto* entry = value.getIf<eve::Value::Object>();
65 if (entry == nullptr)
66 return failure<CraftingRecipe>(eve::DiagnosticCode::InvalidArgument, "craft output must be an object",
67 "outputs");
68 const auto item = entry->find("item");
69 const auto quantity = entry->find("quantity");
70 if (item == entry->end() || !item->second.isString() || item->second.asString().empty() ||
71 quantity == entry->end() || !quantity->second.isInt64() || quantity->second.asInt() <= 0)
72 return failure<CraftingRecipe>(eve::DiagnosticCode::InvalidArgument,
73 "craft outputs require item and positive quantity", "outputs");
74 recipe.outputs.push_back({item->second.asString(), static_cast<int>(quantity->second.asInt())});
75 }
76 if (recipe.outputs.empty())
77 return failure<CraftingRecipe>(eve::DiagnosticCode::InvalidArgument, "craft recipe has no outputs", "outputs");
79}
80
81eve::Result<EquipmentUpgradeRecipe> parseUpgradeRecipe(const eve::Value& root) {
82 const auto* object = root.getIf<eve::Value::Object>();
83 if (object == nullptr)
84 return failure<EquipmentUpgradeRecipe>(eve::DiagnosticCode::InvalidArgument, "upgrade recipe must be an object",
85 "recipe");
86 const auto id = object->find("id");
87 const auto process = object->find("process");
88 const auto itemId = object->find("itemId");
89 const auto fromLevel = object->find("fromLevel");
90 const auto toLevel = object->find("toLevel");
91 const auto ingredients = object->find("ingredients");
92 const auto duration = object->find("duration");
93 if (id == object->end() || !id->second.isString() || id->second.asString().empty() || itemId == object->end() ||
94 !itemId->second.isString() || itemId->second.asString().empty() || fromLevel == object->end() ||
95 !fromLevel->second.isInt64() || toLevel == object->end() || !toLevel->second.isInt64() ||
96 ingredients == object->end() || duration == object->end() || !duration->second.isNumeric())
97 return failure<EquipmentUpgradeRecipe>(
99 "upgrade recipe requires id, itemId, fromLevel, toLevel, ingredients and duration", "recipe");
100 auto ingredientsJson = ingredients->second.toJson();
101 if (!ingredientsJson) return eve::Result<EquipmentUpgradeRecipe>::failure(ingredientsJson.status());
102 auto cost = transaction::AtomicBatch::parseCost(ingredientsJson.value());
104 auto seconds = Duration::fromSeconds(duration->second.isInt64() ? static_cast<double>(duration->second.asInt())
105 : duration->second.asDouble());
106 if (!seconds) return eve::Result<EquipmentUpgradeRecipe>::failure(seconds.status());
107 EquipmentUpgradeRecipe recipe;
108 recipe.id = id->second.asString();
109 recipe.process = (process != object->end() && process->second.isString() && !process->second.asString().empty())
110 ? process->second.asString()
111 : "upgrade";
112 recipe.itemId = itemId->second.asString();
113 recipe.fromLevel = static_cast<int>(fromLevel->second.asInt());
114 recipe.toLevel = static_cast<int>(toLevel->second.asInt());
115 recipe.ingredients = std::move(cost).takeValue();
116 recipe.duration = std::move(seconds).takeValue();
118}
119
120} // namespace
121
124 if (allocated) queueRef_ = std::move(allocated).takeValue();
125}
126
128 unbind();
129 if (queueRef_.isValid()) production::Production::release(queueRef_).ignore("forge bench queue release");
130 queueRef_ = {};
131}
132
134 : queueRef_(std::exchange(other.queueRef_, {})),
135 bag_(std::exchange(other.bag_, nullptr)),
136 equipment_(std::exchange(other.equipment_, nullptr)),
137 actor_(std::exchange(other.actor_, nullptr)),
138 tick_(other.tick_) {}
139
141 if (this == &other) return *this;
142 unbind();
143 if (queueRef_.isValid()) production::Production::release(queueRef_).ignore("forge bench queue release");
144 queueRef_ = std::exchange(other.queueRef_, {});
145 bag_ = std::exchange(other.bag_, nullptr);
146 equipment_ = std::exchange(other.equipment_, nullptr);
147 actor_ = std::exchange(other.actor_, nullptr);
148 tick_ = other.tick_;
149 return *this;
150}
151
153 if (bag == nullptr) return failure<void>(eve::DiagnosticCode::InvalidArgument, "forge bench requires a bag", "bag");
154 if (!queueRef_.isValid())
155 return failure<void>(eve::DiagnosticCode::Failed, "forge bench production queue is unavailable", "queue");
156 bag_ = bag;
157 equipment_ = equipment;
158 actor_ = actor;
160}
161
163 bag_ = nullptr;
164 equipment_ = nullptr;
165 actor_ = nullptr;
166}
167
168eve::ResultRef<production::WorkQueue> ForgeBench::queue() const {
169 if (!queueRef_.isValid())
171 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "forge bench queue is stale", "queue"));
172 return production::Production::resolve(queueRef_);
173}
174
176 if (bag_ == nullptr)
177 return failure<CraftingReceipt>(eve::DiagnosticCode::InvalidArgument, "forge bench is not bound", "bag");
178 auto queueView = queue();
179 if (!queueView) return eve::Result<CraftingReceipt>::failure(queueView.status());
182 request.production = &queueView.value().get();
183 request.ingredients = &account;
184 request.owner = bag_->getId().empty() ? "forge" : bag_->getId();
185 request.recipe = std::move(recipe);
186 request.batchSize = batchSize;
187 request.priority = priority;
188 return Crafting::begin(std::move(request));
189}
190
191eve::Result<CraftingReceipt> ForgeBench::craftFromJson(const std::string& json, std::uint32_t batchSize, int priority) {
192 auto value = eve::Value::fromJson(json);
194 auto recipe = parseCraftRecipe(value.value());
196 return craft(std::move(recipe).takeValue(), batchSize, priority);
197}
198
200 int expectedInstanceId, int priority) {
201 if (bag_ == nullptr)
202 return failure<EquipmentUpgradeReceipt>(eve::DiagnosticCode::InvalidArgument, "forge bench is not bound",
203 "bag");
204 auto queueView = queue();
205 if (!queueView) return eve::Result<EquipmentUpgradeReceipt>::failure(queueView.status());
208 request.production = &queueView.value().get();
209 request.ingredients = &account;
210 request.bag = bag_;
211 request.bagSlot = bagSlot;
212 request.expectedInstanceId = expectedInstanceId;
213 request.owner = bag_->getId().empty() ? "forge" : bag_->getId();
214 request.recipe = std::move(recipe);
215 request.priority = priority;
216 return EquipmentUpgrade::begin(std::move(request));
217}
218
220 int expectedInstanceId, int priority) {
221 auto value = eve::Value::fromJson(json);
223 auto recipe = parseUpgradeRecipe(value.value());
225 return upgrade(std::move(recipe).takeValue(), bagSlot, expectedInstanceId, priority);
226}
227
229 auto queueView = queue();
230 if (!queueView) return eve::Result<void>::failure(queueView.status());
231 auto advanced = queueView.value().get().advance({tick, dt});
232 if (!advanced) return advanced;
233 tick_ = tick;
234 return advanced;
235}
236
238 if (bag_ == nullptr) return failure<int>(eve::DiagnosticCode::InvalidArgument, "forge bench is not bound", "bag");
239 auto queueView = queue();
240 if (!queueView) return eve::Result<int>::failure(queueView.status());
241 auto task = queueView.value().get().find(taskId);
242 if (!task) return failure<int>(eve::DiagnosticCode::NotFound, "forge task was not found", "taskId");
243 auto settled = (task->get().kind == "upgrade") ? EquipmentUpgrade::settle(queueView.value().get(), *bag_, taskId)
244 : Crafting::settle(queueView.value().get(), *bag_, taskId);
245 if (settled) (void)syncEquipment();
246 return settled;
247}
248
250 if (bag_ == nullptr) return failure<int>(eve::DiagnosticCode::InvalidArgument, "forge bench is not bound", "bag");
251 auto queueView = queue();
252 if (!queueView) return eve::Result<int>::failure(queueView.status());
253 std::vector<std::string> ready;
254 for (int i = 0; i < queueView.value().get().taskCount(); ++i) {
255 const auto task = queueView.value().get().taskAt(i);
256 if (!task) continue;
257 if (task->get().state == production::TaskState::ReadyToSettle ||
258 task->get().state == production::TaskState::SettlementFailed)
259 ready.push_back(task->get().id);
260 }
261 int applied = 0;
262 for (const std::string& taskId : ready) {
263 auto settled = settle(taskId);
264 if (!settled) return settled;
265 if (settled.status().code() == eve::StatusCode::Applied) ++applied;
266 }
268}
269
270std::uint64_t ForgeBench::queueHandle() const noexcept { return queueRef_.isValid() ? queueRef_.packed() : 0; }
271
273 auto queueView = queue();
274 return queueView ? queueView.value().get().taskCount() : 0;
275}
276
277std::string ForgeBench::taskIdAt(int index) const {
278 auto queueView = queue();
279 if (!queueView) return {};
280 const auto task = queueView.value().get().taskAt(index);
281 return task ? task->get().id : std::string{};
282}
283
284std::string ForgeBench::taskStateAt(int index) const {
285 auto queueView = queue();
286 if (!queueView) return {};
287 const auto task = queueView.value().get().taskAt(index);
288 return task ? forgeTaskStateName(task->get().state) : std::string{};
289}
290
291std::string ForgeBench::taskKindAt(int index) const {
292 auto queueView = queue();
293 if (!queueView) return {};
294 const auto task = queueView.value().get().taskAt(index);
295 return task ? task->get().kind : std::string{};
296}
297
299 auto queueView = queue();
300 if (!queueView) return 0.f;
301 const auto task = queueView.value().get().taskAt(index);
302 return task ? static_cast<float>(task->get().progress.seconds()) : 0.f;
303}
304
306 auto queueView = queue();
307 if (!queueView) return 0.f;
308 const auto task = queueView.value().get().taskAt(index);
309 return task ? static_cast<float>(task->get().duration.seconds()) : 0.f;
310}
311
313 if (actor_ == nullptr || equipment_ == nullptr) return 0;
314 return EquipmentSystem::syncEquipModifiers(actor_, equipment_);
315}
316
317} // namespace eve::rpg
LogicalId itemId
float duration
int root
Definition AnimSmr.cpp:119
int priority
bool applied
eve::resource::CostSpec cost
eve::resource::IResourceAccount * account
装备加成:把已装备物品(inventory::EquipmentSet)的注册属性加成同步到 actor 的属性修改器上。
int toLevel
int fromLevel
int bagSlot
Script-facing forge that composes Crafting + EquipmentUpgrade over one bag.
std::string message
DiagnosticCode code
const GltfImportRequest & request
std::int32_t second
std::string id
double dt
BakeRecipe recipe
std::string path
Definition PlayHost.cpp:111
std::string taskId
Object::Ptr value
SimulationTick tick
Json object
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Signed, fixed-resolution simulation duration in nanoseconds.
Definition Time.h:43
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
格子型物品容器(脚本可直接操作)。
Definition Bag.h:22
std::string getId() const
容器 id(变更事件定位用)。
Definition Bag.h:36
EVENGINE_API_FOUNDATION public API.
Definition Equipment.h:19
Adapts one Bag's item quantities to the common resource protocol.
static eve::Result< WorkQueueHandleRef > newQueueHandle()
Allocates a production queue and returns its ownership reference.
static eve::Result< void > release(WorkQueueHandleRef reference)
Releases a module-owned queue.
static eve::ResultRef< WorkQueue > resolve(WorkQueueHandleRef reference)
Resolves a generation-qualified work-queue identity.
static eve::Result< int > settle(production::WorkQueue &queue, inventory::Bag &output, std::string_view taskId)
Publish every reserved recipe output and settle the task exactly once.
Definition Crafting.cpp:337
static eve::Result< CraftingReceipt > begin(CraftingRequest request)
Atomically debit ingredients and enqueue pinned recipe work.
Definition Crafting.cpp:282
static int syncEquipModifiers(RPGActor *actor, eve::inventory::EquipmentSet *equip)
把装备栏当前装备同步为 actor 属性修改器(先清旧再施加)。
static eve::Result< int > settle(production::WorkQueue &queue, inventory::Bag &bag, std::string_view taskId)
Apply the reserved enhance mutation and settle the task exactly once.
static eve::Result< EquipmentUpgradeReceipt > begin(EquipmentUpgradeRequest request)
Atomically debit materials and enqueue pinned upgrade work.
Owns a production WorkQueue and borrows bag / optional equipment+actor.
Definition ForgeBench.h:37
eve::Result< EquipmentUpgradeReceipt > upgradeFromJson(const std::string &json, int bagSlot, int expectedInstanceId, int priority=0)
Parse an upgrade recipe JSON object and enqueue it for one bag instance.
float taskDurationAt(int index) const
Task duration seconds at stable enumeration index.
std::string taskStateAt(int index) const
Task state name at stable enumeration index, or empty.
eve::SimulationTick tick() const noexcept
Last accepted simulation tick, or zero before the first advance.
Definition ForgeBench.h:98
int taskCount() const
Task count currently retained by the forge queue.
std::uint64_t queueHandle() const noexcept
Packed production handle for diagnostics (0 when unbound/released).
void unbind()
Clear borrowed collaborators without releasing the production queue.
eve::Result< int > settleReady()
Settle every ReadyToSettle / SettlementFailed task once.
std::string taskIdAt(int index) const
Task id at stable enumeration index, or empty.
ForgeBench & operator=(const ForgeBench &)=delete
eve::Result< void > bind(inventory::Bag *bag, inventory::EquipmentSet *equipment=nullptr, RPGActor *actor=nullptr)
Borrow the authoritative bag and optional gear/actor mirrors. @ownership Callers own bag/equipment/ac...
eve::Result< void > advance(eve::SimulationTick tick, eve::Duration dt)
Advance the owned forge queue by one deterministic simulation step.
eve::Result< int > settle(std::string_view taskId)
Settle one ready craft or upgrade task into the bound bag.
float taskProgressAt(int index) const
Task progress seconds at stable enumeration index.
int syncEquipment() const
Refresh actor equipment modifiers when actor+equipment are bound.
eve::Result< CraftingReceipt > craft(CraftingRecipe recipe, std::uint32_t batchSize=1, int priority=0)
Atomically pay materials and enqueue a craft recipe.
eve::Result< EquipmentUpgradeReceipt > upgrade(EquipmentUpgradeRecipe recipe, int bagSlot, int expectedInstanceId, int priority=0)
Atomically pay materials and enqueue an equipment upgrade.
eve::Result< CraftingReceipt > craftFromJson(const std::string &json, std::uint32_t batchSize=1, int priority=0)
Parse a craft recipe JSON object and enqueue it.
std::string taskKindAt(int index) const
Task kind at stable enumeration index, or empty.
属性 / 状态 / 技能三表合一的 ECS 实体。
Definition RPGActor.h:34
static Result< resource::CostSpec > parseCost(const std::string &json)
Parse a positive-integer resource cost object at the script boundary.
TaskState
Lifecycle state of a production task.
Definition Production.h:30
RPG 模块的基础实体:把属性 / 状态 / 技能三张表挂到一个 ECS 实体上。
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Validated recipe projection used by crafting, alchemy, brewing and cooking.
Definition Crafting.h:28
Borrowed inputs for atomically paying ingredients and enqueuing recipe work.
Definition Crafting.h:38
production::WorkQueue * production
Definition Crafting.h:39
Validated upgrade ladder step for one equipment instance.
Borrowed inputs for paying materials and enqueueing an upgrade job.
production::WorkQueue * production
constexpr bool isValid() const noexcept
Returns whether both the handle and its registry epoch are set.
constexpr std::uint64_t packed() const noexcept
Returns the packed slot/generation projection.