载入中...
搜索中...
未找到
Class.cpp
浏览该文件的文档.
1#include "rpg/Class.h"
2
3#include "common/Json.h"
4
5#include <algorithm>
6
7namespace eve::rpg {
8
10
11bool ClassDefinition::hasTag(const std::string &tag) const {
12 return std::find(tags.begin(), tags.end(), tag) != tags.end();
13}
14
15std::string ClassDefinition::getExtra(const std::string &key, const std::string &fallback) const {
16 auto it = extra.find(key);
17 return it == extra.end() ? fallback : it->second;
18}
19
20namespace {
21std::unordered_map<std::string, ClassDefinition> &classTable() {
22 static std::unordered_map<std::string, ClassDefinition> t;
23 return t;
24}
25} // namespace
26
28 if (def.id.empty()) return;
29 classTable()[def.id] = def;
30}
31
32const ClassDefinition *ClassRegistry::find(const std::string &id) {
33 auto &t = classTable();
34 auto it = t.find(id);
35 return it == t.end() ? nullptr : &it->second;
36}
37
38bool ClassRegistry::remove(const std::string &id) { return classTable().erase(id) > 0; }
39
40void ClassRegistry::clear() { classTable().clear(); }
41
42int ClassRegistry::count() { return int(classTable().size()); }
43
44int ClassRegistry::loadFromJson(const std::string &json, std::string *error) {
45 std::string err;
46 const eve::json::Document doc = eve::json::Document::parse(json, &err);
47 if (!doc.valid()) {
48 if (error) *error = err.empty() ? "invalid json" : err;
49 return 0;
50 }
51 const Value root = doc.root();
52 int n = 0;
53 const auto parseOne = [&](Value o) {
54 if (!o.isObject()) return;
56 def.id = o.getString("id");
57 if (def.id.empty()) return;
58 def.displayName = o.getString("displayName");
59 def.tags = o.getStringArray("tags");
60 def.extra = o.getStringMap("extra");
61 def.traits = o.getStringArray("traits");
62 const Value learn = o.get("learnSkills");
63 for (size_t i = 0; i < learn.size(); ++i) {
64 const Value e = learn.at(i);
66 ls.skillId = e.getString("skillId");
67 ls.level = e.getInt("level", 1);
68 if (ls.level <= 0) ls.level = 1;
69 if (ls.skillId.empty()) continue;
70 def.learnSkills.push_back(std::move(ls));
71 }
72 classTable()[def.id] = std::move(def);
73 ++n;
74 };
75 if (root.isArray()) {
76 for (size_t i = 0; i < root.size(); ++i) parseOne(root.at(i));
77 } else if (root.isObject()) {
78 parseOne(root);
79 }
80 return n;
81}
82
83} // namespace eve::rpg
84
85// ClassSystem implementation (previously ClassSystem.cpp).
86#include "rpg/ClassSystem.h"
87
88#include "rpg/Class.h"
89#include "rpg/LevelSystem.h"
90#include "rpg/RPGActor.h"
91#include "rpg/SkillSystem.h"
92#include "rpg/TraitSystem.h"
93
94#include <algorithm>
95
96namespace eve::rpg {
97
98bool ClassSystem::setClass(RPGActor *actor, const std::string &classId) {
99 if (!actor) return false;
101 if (!def) return false;
102 auto &ci = *actor->classInfo();
103 // 撤销旧职业特征
104 if (!ci.classId.empty()) {
105 TraitSystem::removeBySource(actor, "class:" + ci.classId);
106 }
107 ci.classId = classId;
108 ci.skillsSyncedUpTo = 0;
109 // 施加新职业特征
110 for (const auto &traitId : def->traits) {
111 TraitSystem::apply(actor, traitId, "class:" + classId);
112 }
113 checkLevelSkills(actor);
114 return true;
115}
116
117std::string ClassSystem::getClassId(RPGActor *actor) { return actor ? actor->classInfo()->classId : std::string{}; }
118
119bool ClassSystem::hasClass(RPGActor *actor, const std::string &classId) {
120 return actor && actor->classInfo()->classId == classId;
121}
122
124 if (!actor) return 0;
125 const ClassDefinition *def = ClassRegistry::find(actor->classInfo()->classId);
126 if (!def) return 0;
127 auto &ci = *actor->classInfo();
128 const int level = LevelSystem::getLevel(actor);
129 int learned = 0;
130 for (const auto &ls : def->learnSkills) {
131 if (ls.level <= ci.skillsSyncedUpTo) continue; // 已处理
132 if (ls.level <= level) {
133 if (!SkillSystem::knows(actor, ls.skillId)) {
134 SkillSystem::learn(actor, ls.skillId);
135 ++learned;
136 }
137 }
138 }
139 ci.skillsSyncedUpTo = std::max(ci.skillsSyncedUpTo, level);
140 return learned;
141}
142
144 if (!actor) return 0;
145 const ClassDefinition *def = ClassRegistry::find(actor->classInfo()->classId);
146 return def ? int(def->learnSkills.size()) : 0;
147}
148
150 if (!actor) return {};
151 const ClassDefinition *def = ClassRegistry::find(actor->classInfo()->classId);
152 if (!def || index < 0 || size_t(index) >= def->learnSkills.size()) return {};
153 return def->learnSkills[size_t(index)].skillId;
154}
155
157 if (!actor) return 0;
158 const ClassDefinition *def = ClassRegistry::find(actor->classInfo()->classId);
159 if (!def || index < 0 || size_t(index) >= def->learnSkills.size()) return 0;
160 return def->learnSkills[size_t(index)].level;
161}
162
163} // namespace eve::rpg
164
165// LevelSystem implementation (previously LevelSystem.cpp).
166#include "rpg/LevelSystem.h"
167
168#include "rpg/RPGActor.h"
169
170#include <cmath>
171
172namespace eve::rpg {
173
174namespace {
175std::vector<LevelUpEvent> &levelUpEvents() {
176 static std::vector<LevelUpEvent> events;
177 return events;
178}
179} // namespace
180
181int LevelSystem::getLevel(RPGActor *actor) { return actor ? actor->progression()->level : 1; }
182
183double LevelSystem::getXp(RPGActor *actor) { return actor ? actor->progression()->xp : 0.0; }
184
185double LevelSystem::getXpToNext(RPGActor *actor) { return actor ? actor->progression()->xpToNext : 100.0; }
186
188 if (!actor) return;
189 actor->progression()->xpToNext = value > 0.0 ? value : 0.0;
190}
191
193 if (!actor) return;
194 actor->progression()->level = level > 0 ? level : 1;
195}
196
197eve::Result<void> LevelSystem::restoreProgression(RPGActor *actor, int level, double xp, double xpToNext) {
198 if (!actor)
200 "progression restore requires an actor", "actor"));
201 if (level < 1)
203 "progression level must be positive", "level"));
204 if (!std::isfinite(xp) || xp < 0.0)
206 eve::DiagnosticCode::InvalidArgument, "progression xp must be finite and non-negative", "xp"));
207 if (!std::isfinite(xpToNext) || xpToNext <= 0.0 || xp >= xpToNext)
210 "progression threshold must be finite, positive and greater than current xp", "xpToNext"));
211 auto candidate = *actor->progression();
212 candidate.level = level;
213 candidate.xp = xp;
214 candidate.xpToNext = xpToNext;
215 *actor->progression() = candidate;
217}
218
219bool LevelSystem::gainXp(RPGActor *actor, double amount, double xpGrowth) {
220 auto prepared = prepareGainXp(actor, amount, xpGrowth);
221 if (!prepared.ok()) return false;
222 auto committed = commitGainXp(std::move(prepared).takeValue());
223 return committed.ok() && std::move(committed).takeValue() > 0;
224}
225
227 if (!actor)
229 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "XP gain requires an actor", "actor"));
230 if (!std::isfinite(amount) || amount <= 0.0)
232 eve::DiagnosticCode::InvalidArgument, "XP gain must be finite and positive", "amount"));
233 if (!std::isfinite(xpGrowth) || xpGrowth < 1.0)
235 eve::DiagnosticCode::InvalidArgument, "XP growth must be finite and at least one", "xpGrowth"));
236 const auto &current = *actor->progression();
237 if (current.level < 1 || !std::isfinite(current.xp) || current.xp < 0.0 || !std::isfinite(current.xpToNext) ||
238 current.xpToNext <= 0.0 || current.xp >= current.xpToNext)
240 eve::DiagnosticCode::InvariantViolation, "actor progression is not valid for XP gain", "progression"));
241
243 prepared.actor_ = actor;
244 prepared.previousLevel_ = current.level;
245 prepared.previousXp_ = current.xp;
246 prepared.previousXpToNext_ = current.xpToNext;
247 prepared.nextLevel_ = current.level;
248 prepared.nextXp_ = current.xp + amount;
249 prepared.nextXpToNext_ = current.xpToNext;
250 if (!std::isfinite(prepared.nextXp_))
252 eve::DiagnosticCode::InvalidArgument, "XP gain would overflow progression", "amount"));
253 constexpr int maxLevelsPerGain = 10000;
254 int levels = 0;
255 while (prepared.nextXp_ >= prepared.nextXpToNext_) {
256 if (++levels > maxLevelsPerGain)
259 "XP gain exceeds the maximum levels allowed in one transaction", "amount"));
260 prepared.nextXp_ -= prepared.nextXpToNext_;
261 ++prepared.nextLevel_;
262 prepared.nextXpToNext_ *= xpGrowth;
263 if (!std::isfinite(prepared.nextXpToNext_) || prepared.nextXpToNext_ <= 0.0)
265 eve::DiagnosticCode::InvalidArgument, "XP growth would overflow progression", "xpGrowth"));
266 }
267 return eve::Result<PreparedProgressionGain>::success(std::move(prepared),
269}
270
272 if (!prepared.actor_)
274 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "prepared XP gain is empty", "prepared"));
275 auto &current = *prepared.actor_->progression();
276 if (current.level != prepared.previousLevel_ || current.xp != prepared.previousXp_ ||
277 current.xpToNext != prepared.previousXpToNext_)
279 eve::DiagnosticCode::Conflict, "actor progression changed after XP preparation", "progression"));
280 current.level = prepared.nextLevel_;
281 current.xp = prepared.nextXp_;
282 current.xpToNext = prepared.nextXpToNext_;
283 const int levels = prepared.nextLevel_ - prepared.previousLevel_;
284 for (int offset = 0; offset < levels; ++offset) {
285 LevelUpEvent event;
286 event.actor = prepared.actor_;
287 event.previousLevel = prepared.previousLevel_ + offset;
288 event.newLevel = event.previousLevel + 1;
289 levelUpEvents().push_back(std::move(event));
290 }
292}
293
294void LevelSystem::pollLevelUps(std::vector<LevelUpEvent> &out) {
295 out.clear();
296 out = std::move(levelUpEvents());
297 levelUpEvents().clear();
298}
299
300} // namespace eve::rpg
int root
Definition AnimSmr.cpp:119
职业系统:设定职业、施加职业基础特征、按等级自动学习技能。
职业(Class)定义:可学技能(升级解锁)与职业基础特征,进程级注册表。
bool committed
SQObjectPtr key
Definition ECS.cpp:155
glm::vec3 n
Definition Grass.cpp:63
size_t offset
角色成长:等级 / 经验 / 升级。
int level
const std::string * tag
std::string error
Definition Package.cpp:174
std::vector< particles::ParticleRecordEvent > events
Object::Ptr value
float t
ScriptStructure out
double current
特征系统:施加/移除运行时特征,并提供耐性/特殊参数/攻击附加等查询。
float size
Definition TreeMesh.cpp:158
std::uint32_t classId
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
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
Value get(const char *key) const
Returns the value.
Definition Json.cpp:337
size_t size() const
Returns the size of .
Definition Json.cpp:352
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
static const ClassDefinition * find(const std::string &id)
Find a registered class definition by id.
Definition Class.cpp:32
static void registerClass(const ClassDefinition &def)
Registers class.
Definition Class.cpp:27
static void clear()
Clears .
Definition Class.cpp:40
static int loadFromJson(const std::string &json, std::string *error=nullptr)
从 JSON 数组/对象批量注册。元素形如: { "id":"warrior","displayName":"战士", "traits":["mighty"], "learnSkills":[{"ski...
Definition Class.cpp:44
static bool remove(const std::string &id)
Remove a class by id (compatibility facade returning whether it was present).
Definition Class.cpp:38
static int count()
Returns the number of .
Definition Class.cpp:42
static int getLearnLevelAt(RPGActor *actor, int index)
Returns the learn level at.
Definition Class.cpp:156
static bool hasClass(RPGActor *actor, const std::string &classId)
是否已设定指定职业。
Definition Class.cpp:119
static std::string getClassId(RPGActor *actor)
当前职业 id(无则空)。
Definition Class.cpp:117
static std::string getLearnSkillIdAt(RPGActor *actor, int index)
Returns the learn skill id at.
Definition Class.cpp:149
static int getLearnCount(RPGActor *actor)
职业定义中可学技能总数。
Definition Class.cpp:143
static int checkLevelSkills(RPGActor *actor)
按当前等级补学尚未学过的升级技能。
Definition Class.cpp:123
static bool setClass(RPGActor *actor, const std::string &classId)
设定职业并施加职业基础特征(compatibility facade (脚本兼容门面);成功返回 true)。
Definition Class.cpp:98
static eve::Result< PreparedProgressionGain > prepareGainXp(RPGActor *actor, double amount, double xpGrowth=1.2)
Validate an XP gain and calculate its complete progression candidate without mutation/events.
Definition Class.cpp:226
static void setXpToNext(RPGActor *actor, double value)
设置当前等级的升级阈值。
Definition Class.cpp:187
static void pollLevelUps(std::vector< LevelUpEvent > &out)
取出并清空自上次调用以来累积的升级事件(push/poll 风格)。
Definition Class.cpp:294
static eve::Result< int > commitGainXp(PreparedProgressionGain prepared)
Commit a prepared XP gain if actor progression is still unchanged.
Definition Class.cpp:271
static double getXpToNext(RPGActor *actor)
升级所需经验。
Definition Class.cpp:185
static double getXp(RPGActor *actor)
当前经验。
Definition Class.cpp:183
static eve::Result< void > restoreProgression(RPGActor *actor, int level, double xp, double xpToNext)
Atomically restore one validated progression checkpoint.
Definition Class.cpp:197
static bool gainXp(RPGActor *actor, double amount, double xpGrowth=1.2)
增加经验;每跨过阈值升一级并发出 LevelUpEvent(compatibility facade (脚本兼容门面))。
Definition Class.cpp:219
static int getLevel(RPGActor *actor)
当前等级(无 progression 时返回 1)。
Definition Class.cpp:181
static void setLevel(RPGActor *actor, int level)
直接设定等级(不改经验;用于读档/初始化)。
Definition Class.cpp:192
Move-only progression gain prepared against one actor revision.
Definition LevelSystem.h:25
属性 / 状态 / 技能三表合一的 ECS 实体。
Definition RPGActor.h:34
static void learn(RPGActor *actor, const std::string &skillId)
Learn.
static bool knows(RPGActor *actor, const std::string &skillId)
Knows.
static int removeBySource(RPGActor *actor, const std::string &source)
移除该 actor 上所有来自 source 的特征;返回移除数。
Definition Trait.cpp:127
static int apply(RPGActor *actor, const std::string &traitId, const std::string &source="")
施加一个特征。
Definition Trait.cpp:96
RPG 模块的基础实体:把属性 / 状态 / 技能三张表挂到一个 ECS 实体上。
数据驱动的职业模板。
Definition Class.h:27
bool hasTag(const std::string &tag) const
True when tag.
Definition Class.cpp:11
std::vector< std::string > traits
职业基础特征 id(施加于 actor)
Definition Class.h:31
std::vector< std::string > tags
Definition Class.h:32
std::string getExtra(const std::string &key, const std::string &fallback={}) const
Returns the extra.
Definition Class.cpp:15
std::unordered_map< std::string, std::string > extra
Definition Class.h:33
std::vector< ClassLearnSkill > learnSkills
Definition Class.h:30
std::string displayName
Definition Class.h:29
一条"升到 level 级可学 skillId"的规格。
Definition Class.h:21
std::string skillId
Definition Class.h:22
升级事件。
Definition LevelSystem.h:44
class RPGActor * actor
Definition LevelSystem.h:45