载入中...
搜索中...
未找到
LootSystem.cpp
浏览该文件的文档.
1#include "rpg/LootSystem.h"
2
3#include "common/Json.h"
4#include "inventory/Bag.h"
6
7#include <cmath>
8#include <limits>
9#include <unordered_map>
10
11namespace eve::rpg {
12
14
15namespace {
16std::unordered_map<std::string, LootTableDefinition> &lootTables() {
17 static std::unordered_map<std::string, LootTableDefinition> t;
18 return t;
19}
20
21bool parseSelectMode(const std::string &text, LootSelectMode &out) {
22 if (text.empty() || text == "independent") {
24 return true;
25 }
26 if (text == "weighted") {
28 return true;
29 }
30 return false;
31}
32} // namespace
33
35 if (def.id.empty()) return;
36 lootTables()[def.id] = def;
37}
38
39int LootSystem::registerTablesFromJson(const std::string &json) {
40 std::string err;
41 const eve::json::Document doc = eve::json::Document::parse(json, &err);
42 if (!doc.valid()) return 0;
43 const Value root = doc.root();
44 int n = 0;
45 const auto parseTable = [&](Value o) {
46 if (!o.isObject()) return;
48 def.id = o.getString("id");
49 if (def.id.empty()) return;
51 if (!parseSelectMode(o.getString("selectMode", "independent"), mode)) return;
52 def.selectMode = mode;
53 const Value entries = o.get("entries");
54 for (size_t i = 0; i < entries.size(); ++i) {
55 const Value e = entries.at(i);
56 LootEntry entry;
57 entry.itemId = e.getString("itemId");
58 entry.chance = e.getDouble("chance", 0.0);
59 entry.minQty = e.getInt("minQty", 1);
60 entry.maxQty = e.getInt("maxQty", 1);
61 entry.weight = e.getDouble("weight", 0.0);
62 entry.unique = e.getBool("unique", false);
63 if (entry.itemId.empty()) continue;
64 if (entry.maxQty < entry.minQty) entry.maxQty = entry.minQty;
65 if (entry.maxQty <= 0) entry.maxQty = 1;
66 if (entry.minQty <= 0) entry.minQty = 1;
67 def.entries.push_back(std::move(entry));
68 }
69 lootTables()[def.id] = std::move(def);
70 ++n;
71 };
72 if (root.isArray()) {
73 for (size_t i = 0; i < root.size(); ++i) parseTable(root.at(i));
74 } else if (root.isObject()) {
75 parseTable(root);
76 }
77 return n;
78}
79
80const LootTableDefinition *LootSystem::find(const std::string &id) {
81 auto &t = lootTables();
82 auto it = t.find(id);
83 return it == t.end() ? nullptr : &it->second;
84}
85
86void LootSystem::clear() { lootTables().clear(); }
87
88int LootSystem::count() { return int(lootTables().size()); }
89
90namespace {
91bool alreadyOwnedOrQueued(const inventory::Bag &bag, const std::vector<inventory::InventoryItemGrant> &grants,
92 const std::string &itemId) {
93 if (bag.countItem(itemId) > 0) return true;
94 for (const auto &grant : grants) {
95 if (grant.itemId == itemId) return true;
96 }
97 return false;
98}
99
100eve::Result<int> rollAtomic(const LootTableDefinition &definition, inventory::Bag &bag, std::mt19937 &rng,
101 const LootRollRequest &request) {
102 if (!std::isfinite(request.luck) || request.luck < -1.0)
104 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "loot luck must be finite and >= -1", "luck"));
105
106 // Snapshot before inventory policy/hook callbacks can reload the registry.
107 const auto entries = definition.entries;
108 if (entries.size() > static_cast<std::size_t>(std::numeric_limits<int>::max()))
111 for (const auto &entry : entries) {
112 if (entry.itemId.empty() || !std::isfinite(entry.chance) || entry.chance < 0.0 || entry.chance > 1.0 ||
113 !std::isfinite(entry.weight) || entry.weight < 0.0 || entry.minQty <= 0 || entry.maxQty < entry.minQty)
115 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "Invalid loot entry", entry.itemId));
116 }
117
118 auto candidateRng = rng;
119 std::vector<inventory::InventoryItemGrant> grants;
120
121 if (definition.selectMode == LootSelectMode::Weighted) {
122 double totalWeight = 0.0;
123 for (const auto &entry : entries) {
124 if (entry.weight > 0.0) totalWeight += entry.weight;
125 }
126 if (!(totalWeight > 0.0))
128 eve::DiagnosticCode::InvalidArgument, "weighted loot table has no positive weights", definition.id));
129 std::uniform_real_distribution<double> pickDist(0.0, totalWeight);
130 double pick = pickDist(candidateRng);
131 const LootEntry *chosen = nullptr;
132 for (const auto &entry : entries) {
133 if (!(entry.weight > 0.0)) continue;
134 if (pick < entry.weight) {
135 chosen = &entry;
136 break;
137 }
138 pick -= entry.weight;
139 }
140 if (!chosen) chosen = &entries.back();
141 if (!(chosen->unique && alreadyOwnedOrQueued(bag, grants, chosen->itemId))) {
142 std::uniform_int_distribution<int> qtyDist(chosen->minQty, chosen->maxQty);
143 grants.push_back({chosen->itemId, qtyDist(candidateRng)});
144 }
145 } else {
146 std::uniform_real_distribution<double> chanceDist(0.0, 1.0);
147 for (const auto &entry : entries) {
148 const double scale = 1.0 + request.luck;
149 const double effective = std::min(1.0, std::max(0.0, entry.chance * scale));
150 if (chanceDist(candidateRng) >= effective) continue;
151 if (entry.unique && alreadyOwnedOrQueued(bag, grants, entry.itemId)) continue;
152 std::uniform_int_distribution<int> qtyDist(entry.minQty, entry.maxQty);
153 grants.push_back({entry.itemId, qtyDist(candidateRng)});
154 }
155 }
156
157 if (grants.empty()) {
158 rng = candidateRng;
160 }
161 auto prepared = inventory::InventorySystem::prepareAddBatch(&bag, grants);
162 if (!prepared) return eve::Result<int>::failure(prepared.status());
163 const auto before = rng;
164 // Publish the random stream before inventory's post-commit hooks run.
165 rng = candidateRng;
166 auto committed = inventory::InventorySystem::commitAddBatch(std::move(prepared).takeValue());
167 if (!committed) {
168 rng = before;
169 return eve::Result<int>::failure(committed.status());
170 }
171 return eve::Result<int>::success(static_cast<int>(grants.size()));
172}
173} // namespace
174
175int LootSystem::roll(const std::string &tableId, eve::inventory::Bag *bag, std::mt19937 &rng) {
176 auto result = rollDetailed(tableId, bag, rng, {});
177 if (!result) return 0;
178 return result.value();
179}
180
181eve::Result<int> LootSystem::rollDetailed(const std::string &tableId, eve::inventory::Bag *bag, std::mt19937 &rng,
182 const LootRollRequest &request) {
183 if (!bag)
185 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "loot roll requires a bag", "bag"));
186 const auto *definition = find(tableId);
187 if (!definition)
189 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "loot table not found", tableId));
190 return rollAtomic(*definition, *bag, rng, request);
191}
192
193} // namespace eve::rpg
LogicalId itemId
int root
Definition AnimSmr.cpp:119
std::unordered_map< std::string, QuestRuntime > entries
bool committed
const GltfImportRequest & request
glm::vec3 n
Definition Grass.cpp:63
std::array< float, 3 > scale
掉落表:按概率或权重随机掉落物品到背包。
Poco::JSON::Object::Ptr result
float t
std::string text
ScriptStructure out
float size
Definition TreeMesh.cpp:158
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
格子型物品容器(脚本可直接操作)。
Definition Bag.h:22
int countItem(const std::string &itemId) const
Returns the number of item.
Definition Bag.cpp:87
static eve::Result< int > commitAddBatch(PreparedInventoryAdd prepared)
Commit one prepared addition and then publish its change events.
static eve::Result< PreparedInventoryAdd > prepareAddBatch(Bag *bag, const std::vector< InventoryItemGrant > &grants)
Validate a multi-item addition against a private candidate Bag.
EVENGINE_API_FOUNDATION public API.
Definition Json.h:137
bool valid() const
Valid.
Definition Json.h:158
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
Value root() const
Root.
Definition Json.h:160
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
bool getBool(const char *key, bool fallback=false) const
Returns the bool.
Definition Json.cpp:422
Value get(const char *key) const
Returns the value.
Definition Json.cpp:337
Value at(size_t index) const
At.
Definition Json.cpp:359
int getInt(const char *key, int fallback=0) const
Returns the int.
Definition Json.cpp:423
std::string getString(const char *key, const std::string &fallback={}) const
Returns the string.
Definition Json.cpp:428
double getDouble(const char *key, double fallback=0.0) const
Returns the double.
Definition Json.cpp:425
static int registerTablesFromJson(const std::string &json)
Registers tables from json.
static const LootTableDefinition * find(const std::string &id)
Finds .
static eve::Result< int > rollDetailed(const std::string &tableId, eve::inventory::Bag *bag, std::mt19937 &rng, const LootRollRequest &request={})
Structured loot roll with luck / diagnostics.
static void registerTable(const LootTableDefinition &def)
Registers table.
static int count()
Returns the number of .
static void clear()
Clears .
static int roll(const std::string &tableId, eve::inventory::Bag *bag, std::mt19937 &rng)
兼容入口:随机抽取后原子入包,内部使用 Result 事务路径。
const HouseComponent * pick(const std::vector< std::reference_wrapper< const HouseComponent > > &choices, std::mt19937 &rng)
Borrow a weighted component from library-backed choices. @ownership Borrowed; the session's library o...
RPG 模块的基础实体:把属性 / 状态 / 技能三张表挂到一个 ECS 实体上。
LootSelectMode
How a loot table chooses among its entries.
Definition LootSystem.h:27
int weight
生成权重(越大越常被选中)。
掉落表里的一条掉落。
Definition LootSystem.h:33
double chance
[0,1],Independent 模式下 roll 值小于 chance 才掉落
Definition LootSystem.h:35
double weight
Weighted 模式下的相对权重(必须 > 0 才参与)
Definition LootSystem.h:38
std::string itemId
Definition LootSystem.h:34
Optional modifiers for a single loot roll.
Definition LootSystem.h:50
std::vector< LootEntry > entries
Definition LootSystem.h:45