载入中...
搜索中...
未找到
RPGBalance.cpp
浏览该文件的文档.
2
3#include "agent/Balance.h"
5#include "rpg/Battle.h"
6#include "rpg/BattleSystem.h"
7#include "rpg/Class.h"
8#include "rpg/ClassSystem.h"
9#include "rpg/Effect.h"
10#include "rpg/EquipmentSystem.h"
11#include "rpg/RPGActor.h"
13#include "rpg/Skill.h"
14#include "rpg/SkillSystem.h"
15#include "rpg/StatusSystem.h"
16#include "rpg/VitalsSystem.h"
17
18#include <algorithm>
19#include <charconv>
20#include <cmath>
21#include <map>
22#include <set>
23#include <stdexcept>
24
26namespace {
27struct Invalid : std::runtime_error {
28 using std::runtime_error::runtime_error;
29};
30using Object = Value::Object;
31const Object& object(const Value& v, std::initializer_list<std::string_view> fields) {
32 const auto* o = v.getIf<Object>();
33 if (!o) throw Invalid("Expected object");
34 for (const auto& [key, value] : *o)
35 if (std::find(fields.begin(), fields.end(), key) == fields.end()) throw Invalid("Unknown suite field: " + key);
36 return *o;
37}
38const Value& required(const Object& o, const char* key) {
39 auto i = o.find(key);
40 if (i == o.end()) throw Invalid(std::string("Missing field: ") + key);
41 return i->second;
42}
43std::string text(const Value& v) {
44 const auto* s = v.getIf<std::string>();
45 if (!s || s->empty() || s->size() > 128) throw Invalid("Expected nonempty string up to 128 bytes");
46 return *s;
47}
48double number(const Value& v) {
49 double n;
50 if (const auto* x = v.getIf<double>())
51 n = *x;
52 else if (const auto* x = v.getIf<std::int64_t>())
53 n = double(*x);
54 else
55 throw Invalid("Expected number");
56 if (!std::isfinite(n) || std::abs(n) > 1e6) throw Invalid("Nonfinite or oversized number");
57 return n;
58}
59double optionalNumber(const Object& o, const char* key, double fallback) {
60 auto i = o.find(key);
61 return i == o.end() ? fallback : number(i->second);
62}
63const Value::Array& array(const Value& v, std::size_t limit) {
64 const auto* a = v.getIf<Value::Array>();
65 if (!a || a->empty() || a->size() > limit) throw Invalid("Invalid or oversized array");
66 return *a;
67}
68std::vector<std::string> strings(const Value& v, std::size_t limit) {
69 std::vector<std::string> result;
70 std::set<std::string> seen;
71 for (const auto& x : array(v, limit)) {
72 auto s = text(x);
73 if (!seen.insert(s).second) throw Invalid("Duplicate string: " + s);
74 result.push_back(std::move(s));
75 }
76 return result;
77}
78std::vector<std::uint64_t> readSeeds(const Value& v) {
79 std::vector<std::uint64_t> result;
80 std::set<std::uint64_t> seen;
81 for (const auto& item : array(v, 16)) {
82 std::uint64_t seed = 0;
83 if (const auto* n = item.getIf<std::int64_t>()) {
84 if (*n < 0) throw Invalid("Negative seed");
85 seed = std::uint64_t(*n);
86 } else {
87 auto s = text(item);
88 auto parsed = std::from_chars(s.data(), s.data() + s.size(), seed);
89 if (parsed.ec != std::errc{} || parsed.ptr != s.data() + s.size()) throw Invalid("Invalid seed");
90 }
91 if (!seen.insert(seed).second) throw Invalid("Duplicate seed");
92 result.push_back(seed);
93 }
94 return result;
95}
96Diagnostic diagnostic(std::string message) {
97 return Diagnostic::error(DiagnosticCode::InvalidArgument, std::move(message), {}, {}, "rpg.balance");
98}
99struct Gear {
100 std::string slot;
101 std::vector<EquipmentStat> stats;
102};
103struct Build {
104 std::string id, classId;
105 std::map<std::string, double> attributes;
106 std::vector<std::string> skills;
107 std::vector<Gear> gear;
108};
109struct Strategy {
110 std::string id;
111 std::vector<std::string> priority;
112 double healBelow = 0.5, reserveMana = 0;
113};
114struct Scenario {
115 std::string id;
116 double healthScale = 1, manaScale = 1, manaRegen = 0;
117};
118struct Binding {
120};
121struct Edge {
122 std::size_t left = 0, right = 0;
123 agent::balance::Target target;
124};
125struct Config {
126 Value source;
127 std::vector<Build> builds;
128 std::vector<Strategy> strategies;
129 std::vector<Scenario> scenarios;
130 std::vector<Binding> bindings;
131 std::vector<Edge> edges;
132 std::set<std::string> parameters;
133};
134std::size_t buildIndex(const Config& c, const std::string& id) {
135 auto it = std::find_if(c.builds.begin(), c.builds.end(), [&](const Build& b) { return b.id == id; });
136 if (it == c.builds.end()) throw Invalid("Unknown build: " + id);
137 return std::size_t(it - c.builds.begin());
138}
139void validateSkills(const Config& c) {
140 for (const auto& b : c.builds) {
141 if (!ClassRegistry::find(b.classId)) throw Invalid("Unknown class: " + b.classId);
142 for (const auto& id : b.skills) {
143 const auto* skill = SkillRegistry::find(id);
144 if (!skill) throw Invalid("Unknown skill: " + id);
145 if (skill->castTime != 0) throw Invalid("Turn-based balance requires instant skills: " + id);
146 if (skill->targetType != "self" && skill->targetType != "enemySingle" && skill->targetType != "single" &&
147 skill->targetType != "allySingle")
148 throw Invalid("Unsupported duel target type: " + id);
149 for (const auto& effect : skill->grantedEffects)
150 if (!EffectRegistry::find(effect)) throw Invalid("Unknown granted effect: " + effect);
151 const auto* damage = BattleSystem::findSkillDamage(id);
152 if (!damage && skill->grantedEffects.empty()) throw Invalid("Skill has no damage or effects: " + id);
153 }
154 }
155}
156Config decode(const Value& value) {
157 const auto& root =
158 object(value, {"schema", "version", "builds", "strategies", "scenarios", "bindings", "matchups"});
159 if (text(required(root, "schema")) != "evengine.rpg.balance.suite" || number(required(root, "version")) != 1)
160 throw Invalid("Unsupported RPG balance schema/version");
161 Config c;
162 c.source = value;
163 std::set<std::string> ids;
164 for (const auto& v : array(required(root, "builds"), 8)) {
165 const auto& o = object(v, {"id", "classId", "attributes", "skills", "equipment"});
166 Build b;
167 b.id = text(required(o, "id"));
168 if (b.id.find('>') != std::string::npos || !ids.insert(b.id).second)
169 throw Invalid("Invalid/duplicate build id");
170 b.classId = text(required(o, "classId"));
171 const auto* attrs = required(o, "attributes").getIf<Object>();
172 if (!attrs || attrs->size() > 32) throw Invalid("Invalid attributes");
173 for (const auto& [name, n] : *attrs) {
174 if (name.empty() || name.size() > 128) throw Invalid("Invalid attribute name");
175 b.attributes.emplace(name, number(n));
176 }
177 if (!b.attributes.contains("hp") || b.attributes.at("hp") <= 0 || !b.attributes.contains("mana") ||
178 b.attributes.at("mana") < 0)
179 throw Invalid("Build requires positive hp and nonnegative mana");
180 b.skills = strings(required(o, "skills"), 16);
181 if (auto it = o.find("equipment"); it != o.end()) {
182 std::set<std::string> slots;
183 for (const auto& item : array(it->second, 8)) {
184 const auto& g = object(item, {"slot", "stats"});
185 Gear gear;
186 gear.slot = text(required(g, "slot"));
187 if (!slots.insert(gear.slot).second) throw Invalid("Duplicate equipment slot");
188 for (const auto& itemStat : array(required(g, "stats"), 16)) {
189 const auto& s = object(itemStat, {"attribute", "op", "value"});
190 EquipmentStat stat{text(required(s, "attribute")), text(required(s, "op")),
191 number(required(s, "value")), 0};
192 auto parsed = attributes::parseAttributeOperation(stat.op, stat.value);
193 if (!parsed) throw Invalid("Unknown equipment operation: " + stat.op);
194 gear.stats.push_back(std::move(stat));
195 }
196 b.gear.push_back(std::move(gear));
197 }
198 }
199 c.builds.push_back(std::move(b));
200 }
201 if (c.builds.size() < 2) throw Invalid("At least two builds required");
202 ids.clear();
203 for (const auto& v : array(required(root, "strategies"), 4)) {
204 const auto& o = object(v, {"id", "priority", "healBelow", "reserveMana"});
205 Strategy s{text(required(o, "id")), strings(required(o, "priority"), 16), optionalNumber(o, "healBelow", 0.5),
206 optionalNumber(o, "reserveMana", 0)};
207 if (!ids.insert(s.id).second || s.healBelow < 0 || s.healBelow > 1 || s.reserveMana < 0 || s.reserveMana > 1)
208 throw Invalid("Invalid strategy");
209 c.strategies.push_back(std::move(s));
210 }
211 ids.clear();
212 for (const auto& v : array(required(root, "scenarios"), 4)) {
213 const auto& o = object(v, {"id", "healthScale", "manaScale", "manaRegen"});
214 Scenario s{text(required(o, "id")), optionalNumber(o, "healthScale", 1), optionalNumber(o, "manaScale", 1),
215 optionalNumber(o, "manaRegen", 0)};
216 if (!ids.insert(s.id).second || s.healthScale <= 0 || s.healthScale > 10 || s.manaScale < 0 ||
217 s.manaScale > 10 || s.manaRegen < 0 || s.manaRegen > 1000)
218 throw Invalid("Invalid scenario");
219 c.scenarios.push_back(std::move(s));
220 }
221 for (const auto& v : array(required(root, "bindings"), 64)) {
222 const auto& o = object(v, {"parameter", "build", "attribute", "slot"});
223 Binding b{text(required(o, "parameter")), text(required(o, "build")), text(required(o, "attribute")), {}};
224 auto& build = c.builds[buildIndex(c, b.build)];
225 if (auto it = o.find("slot"); it != o.end()) b.slot = text(it->second);
226 if (b.slot.empty()) {
227 if (!build.attributes.contains(b.attribute) || b.attribute == "hp" || b.attribute == "mana")
228 throw Invalid("Binding must name a declared non-resource attribute");
229 } else {
230 auto gear =
231 std::find_if(build.gear.begin(), build.gear.end(), [&](const Gear& g) { return g.slot == b.slot; });
232 if (gear == build.gear.end() ||
233 std::count_if(gear->stats.begin(), gear->stats.end(),
234 [&](const EquipmentStat& s) { return s.attribute == b.attribute; }) != 1)
235 throw Invalid("Gear binding must name exactly one stat in its slot");
236 }
237 for (const auto& old : c.bindings)
238 if (old.build == b.build && old.attribute == b.attribute && old.slot == b.slot)
239 throw Invalid("Two parameters cannot own the same attribute binding");
240 c.parameters.insert(b.parameter);
241 c.bindings.push_back(std::move(b));
242 }
243 ids.clear();
244 for (const auto& v : array(required(root, "matchups"), 64)) {
245 const auto& o = object(v, {"left", "right", "min", "max", "weight"});
246 const auto left = text(required(o, "left")), right = text(required(o, "right"));
247 const auto name = left + ">" + right;
248 Edge edge{buildIndex(c, left),
249 buildIndex(c, right),
250 {name, number(required(o, "min")), number(required(o, "max")), 1, optionalNumber(o, "weight", 1)}};
251 if (edge.left == edge.right || !ids.insert(name).second || edge.target.minimum < 0 || edge.target.maximum > 1 ||
252 edge.target.minimum > edge.target.maximum || edge.target.weight <= 0)
253 throw Invalid("Invalid directed matchup target");
254 for (const auto& old : c.edges)
255 if (old.left == edge.right && old.right == edge.left &&
256 (old.target.minimum > 1 - edge.target.minimum || old.target.maximum < 1 - edge.target.maximum))
257 throw Invalid("Contradictory reverse matchup targets");
258 c.edges.push_back(std::move(edge));
259 }
260 const auto cells =
261 c.builds.size() * (c.builds.size() - 1) / 2 * c.strategies.size() * c.strategies.size() * c.scenarios.size();
262 if (cells > 128) throw Invalid("Suite exceeds 128 strategy/scenario matchup cells");
263 validateSkills(c);
264 return c;
265}
266std::string choose(RPGActor& actor, const Build& build, const Strategy& strategy, double capacity) {
267 const double ratio = VitalsSystem::getCurrent(&actor, "hp") / VitalsSystem::getMax(&actor, "hp");
268 for (const auto& tag : strategy.priority)
269 for (const auto& id : build.skills) {
270 const auto* skill = SkillRegistry::find(id);
271 if (!skill || !skill->hasTag(tag) || !SkillSystem::canCast(&actor, id)) continue;
272 const auto* damage = BattleSystem::findSkillDamage(id);
273 const bool healing = damage && damage->damageType == "hpHeal";
274 if (healing && ratio >= strategy.healBelow) continue;
275 if (!healing && skill->cost && AttributeSystem::getFinal(&actor, "mana") < capacity * strategy.reserveMana)
276 continue;
277 return id;
278 }
279 return {}; // An explicitly modeled basic attack when no prioritized skill is legal.
280}
281struct Bout {
282 int winner = -1, rounds = 0;
284 std::map<std::string, int> skills;
285 double mana = 0;
286};
287Result<Bout> fight(const Build& left, const Build& right, const Strategy& ls, const Strategy& rs,
288 const Scenario& scenario, std::uint64_t seed, bool reverse, double dt, int limit, bool evidence) {
289 ecs::Table world;
290 ecs::ScopedTable selected(world);
291 detail::SimulationEvents events;
292 detail::SimulationEventScope eventScope(events);
293 // Components are all materialized before rounds; no ECS System or structural mutation while iterating.
294 auto* a = RPGActor::createActor();
295 auto* b = RPGActor::createActor();
296 const auto prepare = [&](RPGActor& actor, const Build& build) -> Result<void> {
297 for (const auto& [name, value] : build.attributes) AttributeSystem::setBase(&actor, name, value);
298 if (!ClassSystem::setClass(&actor, build.classId))
299 return Result<void>::failure(diagnostic("Class assignment failed"));
300 for (const auto& gear : build.gear) {
301 auto result = EquipmentSystem::projectSlot(actor, gear.slot, gear.stats);
302 if (!result) return Result<void>::failure(result.status());
303 }
304 AttributeSystem::setBase(&actor, "hp", build.attributes.at("hp") * scenario.healthScale);
305 AttributeSystem::setBase(&actor, "mana", build.attributes.at("mana") * scenario.manaScale);
306 if (AttributeSystem::getFinal(&actor, "hp") <= 0 || AttributeSystem::getFinal(&actor, "mana") < 0)
307 return Result<void>::failure(diagnostic("Projected build has invalid resource capacity"));
308 for (const auto& id : build.skills) SkillSystem::learn(&actor, id);
309 VitalsSystem::revive(&actor, "hp");
310 return Result<void>::success();
311 };
312 auto prepared = prepare(*a, left);
313 if (!prepared) return Result<Bout>::failure(prepared.status());
314 prepared = prepare(*b, right);
315 if (!prepared) return Result<Bout>::failure(prepared.status());
316 const double capacityA = AttributeSystem::getFinal(a, "mana"), capacityB = AttributeSystem::getFinal(b, "mana");
317 Battle battle;
318 battle.addActor(reverse ? b : a, reverse ? 1 : 0);
319 battle.addActor(reverse ? a : b, reverse ? 0 : 1);
320 auto seeded = battle.configureSeed(seed);
321 if (!seeded) return Result<Bout>::failure(seeded.status());
322 Bout result;
323 for (int round = 0; round < limit && !battle.isFinished(); ++round) {
324 const auto queue = [&](RPGActor& actor, RPGActor& other, const Build& build, const Strategy& policy,
325 double capacity) -> Result<void> {
326 auto id = choose(actor, build, policy, capacity);
327 const auto* def = id.empty() ? nullptr : SkillRegistry::find(id);
328 auto* target = def && (def->targetType == "self" || def->targetType == "allySingle") ? &actor : &other;
329 return battle.setActionChecked(&actor, id, target);
330 };
331 auto queued = reverse ? queue(*b, *a, right, rs, capacityB) : queue(*a, *b, left, ls, capacityA);
332 if (!queued) return Result<Bout>::failure(queued.status());
333 queued = reverse ? queue(*a, *b, left, ls, capacityA) : queue(*b, *a, right, rs, capacityB);
334 if (!queued) return Result<Bout>::failure(queued.status());
335 const double beforeMana = AttributeSystem::getFinal(a, "mana") + AttributeSystem::getFinal(b, "mana");
336 battle.startRound();
337 while (battle.executeNextAction()) {
338 }
339 result.mana += beforeMana - AttributeSystem::getFinal(a, "mana") - AttributeSystem::getFinal(b, "mana");
340 battle.pollEvents();
341 for (int i = 0; i < battle.getEventCount(); ++i) {
342 const auto e = battle.getEvent(i);
343 if (e.action == "settlementFailed")
344 return Result<Bout>::failure(diagnostic("Canonical battle settlement failed"));
345 if (e.action == "actionStart") ++result.skills[e.skillId.empty() ? "basic" : e.skillId];
346 if (evidence && result.trace.size() < 24 && e.action != "roundStart")
347 result.trace.push_back(Value::object({{"round", round + 1},
348 {"action", e.action},
349 {"skill", e.skillId},
350 {"source", e.caster == a ? left.id
351 : e.caster == b ? right.id
352 : ""},
353 {"target", e.target == a ? left.id
354 : e.target == b ? right.id
355 : ""},
356 {"amount", e.amount}}));
357 }
358 SkillSystem::update(float(dt));
359 auto advanced = StatusSystem::update(dt);
360 if (!advanced) return Result<Bout>::failure(advanced.status());
361 std::vector<StatusTickEvent> ticks;
363 for (const auto& tick : ticks) {
364 auto settled = battle.settleStatusTick(tick, {}, SimulationTick(std::uint64_t(round + 1)));
365 if (!settled) return Result<Bout>::failure(settled.status());
366 for (const auto& item : settled.value())
367 if (!item.result) return Result<Bout>::failure(diagnostic("Periodic settlement failed"));
368 }
369 battle.pollEvents();
370 for (int i = 0; i < battle.getEventCount(); ++i) {
371 const auto e = battle.getEvent(i);
372 if (e.action == "settlementFailed")
373 return Result<Bout>::failure(diagnostic("Canonical periodic settlement failed"));
374 if (evidence && result.trace.size() < 24)
375 result.trace.push_back(Value::object({{"round", round + 1},
376 {"action", e.action},
377 {"skill", e.skillId},
378 {"source", e.caster == a ? left.id
379 : e.caster == b ? right.id
380 : ""},
381 {"target", e.target == a ? left.id
382 : e.target == b ? right.id
383 : ""},
384 {"amount", e.amount}}));
385 }
386 if (scenario.manaRegen > 0) {
387 const auto regenerate = [&](RPGActor* actor, double capacity) {
388 const double base = AttributeSystem::getBase(actor, "mana");
389 const double final = AttributeSystem::getFinal(actor, "mana");
390 AttributeSystem::setBase(actor, "mana",
391 base + std::min(dt * scenario.manaRegen, std::max(0.0, capacity - final)));
392 };
393 regenerate(a, capacityA);
394 regenerate(b, capacityB);
395 }
396 events.casts.clear();
397 events.vitals.clear();
398 events.changes.clear();
399 result.rounds = round + 1;
400 if (VitalsSystem::isDead(a, "hp") || VitalsSystem::isDead(b, "hp")) break;
401 }
402 const bool deadA = VitalsSystem::isDead(a, "hp"), deadB = VitalsSystem::isDead(b, "hp");
403 result.winner = deadA == deadB ? -1 : deadA ? 1 : 0;
404 return Result<Bout>::success(std::move(result));
405}
406Value interval(double score, int count) {
407 // Wilson interval for bounded match scores (draws contribute half); descriptive, not independent trials proof.
408 const double z2 = 3.841458820694124;
409 const double center = (score + z2 / (2 * count)) / (1 + z2 / count);
410 const double radius =
411 std::sqrt(score * (1 - score) / count + z2 / (4 * count * count)) * std::sqrt(z2) / (1 + z2 / count);
412 return Value::array({Value(std::max(0.0, center - radius)), Value(std::min(1.0, center + radius))});
413}
414} // namespace
415
417 std::optional<Config> config;
418 bool active = false;
419};
420RPGBalanceSuite::RPGBalanceSuite() : impl_(std::make_unique<Impl>()) {}
422
424 if (impl_->active)
426 try {
427 auto c = decode(input);
428 impl_->config = std::move(c);
429 return Result<void>::success();
430 } catch (const Invalid& error) {
431 return Result<void>::failure(diagnostic(error.what()));
432 }
433}
435 if (!impl_->config) return Result<Value>::failure(diagnostic("Configure suite first"));
437 for (const auto& edge : impl_->config->edges)
438 targets.push_back(Value::object({{"name", edge.target.name},
439 {"min", edge.target.minimum},
440 {"max", edge.target.maximum},
441 {"scale", 0.25},
442 {"weight", edge.target.weight}}));
443 return Result<Value>::success(Value(std::move(targets)));
444}
445Result<Value> RPGBalanceSuite::measure(const Value& parameters, const Value& seedsValue, double dt, int rounds) {
446 if (impl_->active) return Result<Value>::failure(Diagnostic::error(DiagnosticCode::Conflict, "Tournament reentry"));
447 if (!impl_->config) return Result<Value>::failure(diagnostic("Configure suite first"));
448 struct Guard {
449 bool& active;
450 explicit Guard(bool& a) : active(a) { active = true; }
451 ~Guard() { active = false; }
452 } guard(impl_->active);
453 try {
454 const auto& c = *impl_->config;
455 validateSkills(c);
456 const auto seeds = readSeeds(seedsValue);
457 if (!std::isfinite(dt) || dt <= 0 || dt > 60 || rounds < 1 || rounds > 128)
458 throw Invalid("Invalid simulation time budget");
459 const auto* params = parameters.getIf<Object>();
460 if (!params || params->size() != c.parameters.size())
461 throw Invalid("Candidate keys must match bindings exactly");
462 for (const auto& name : c.parameters) (void)number(required(*params, name.c_str()));
463 auto builds = c.builds;
464 for (const auto& binding : c.bindings) {
465 auto& b = builds[buildIndex(c, binding.build)];
466 const auto value = number(params->at(binding.parameter));
467 if (binding.slot.empty())
468 b.attributes[binding.attribute] = value;
469 else
470 for (auto& g : b.gear)
471 if (g.slot == binding.slot)
472 for (auto& s : g.stats)
473 if (s.attribute == binding.attribute) s.value = value;
474 }
476 std::vector<std::vector<double>> scores(builds.size(), std::vector<double>(builds.size(), 0.5));
477 int matches = 0, draws = 0;
478 for (std::size_t l = 0; l < builds.size(); ++l)
479 for (std::size_t r = l + 1; r < builds.size(); ++r) {
480 double totalScore = 0;
481 int totalCount = 0;
482 for (const auto& scenario : c.scenarios)
483 for (const auto& ls : c.strategies)
484 for (const auto& rs : c.strategies) {
485 int wins = 0, losses = 0, ties = 0, turns = 0;
486 double spent = 0;
487 std::map<std::string, int> usage;
489 for (auto seed : seeds)
490 for (bool reverse : {false, true}) {
491 auto bout = fight(builds[l], builds[r], ls, rs, scenario, seed, reverse, dt, rounds,
492 trace.empty());
493 if (!bout) return Result<Value>::failure(bout.status());
494 const auto& b = bout.value();
495 if (b.winner == 0)
496 ++wins;
497 else if (b.winner == 1)
498 ++losses;
499 else
500 ++ties;
501 turns += b.rounds;
502 spent += b.mana;
503 for (const auto& [id, count] : b.skills) usage[id] += count;
504 if (trace.empty()) trace = b.trace;
505 }
506 const int count = wins + losses + ties;
507 const double score = (wins + 0.5 * ties) / count;
508 totalScore += wins + 0.5 * ties;
509 totalCount += count;
510 matches += count;
511 draws += ties;
513 for (const auto& [name, count] : usage) skills.emplace(name, Value(count));
514 cells.push_back(Value::object({{"left", builds[l].id},
515 {"right", builds[r].id},
516 {"leftStrategy", ls.id},
517 {"rightStrategy", rs.id},
518 {"scenario", scenario.id},
519 {"wins", wins},
520 {"losses", losses},
521 {"draws", ties},
522 {"score", score},
523 {"scoreInterval", interval(score, count)},
524 {"meanRounds", double(turns) / count},
525 {"meanManaSpent", spent / count},
526 {"skills", std::move(skills)},
527 {"trace", std::move(trace)},
528 {"traceSeed", std::to_string(seeds.front())},
529 {"traceReverse", false},
530 {"traceEventLimit", 24}}));
531 }
532 scores[l][r] = totalScore / totalCount;
533 scores[r][l] = 1 - scores[l][r];
534 }
535 Object metrics;
536 for (const auto& edge : c.edges) metrics.emplace(edge.target.name, Value(scores[edge.left][edge.right]));
537 Value::Array names;
538 for (const auto& build : builds) names.emplace_back(build.id);
539 for (const auto& row : scores) {
541 for (auto score : row) values.emplace_back(score);
542 matrix.emplace_back(std::move(values));
543 }
545 Value::object({{"schema", "evengine.rpg.balance.report"},
546 {"version", 1},
547 {"suite", c.source},
548 {"parameters", parameters},
549 {"seeds", seedsValue},
550 {"dt", dt},
551 {"rounds", rounds},
552 {"builds", std::move(names)},
553 {"matrix", std::move(matrix)},
554 {"metrics", std::move(metrics)},
555 {"cells", std::move(cells)},
556 {"matches", matches},
557 {"draws", draws},
558 {"intervalNote",
559 "Wilson approximation on paired bounded scores; samples share seeds and are correlated"}}));
560 } catch (const Invalid& error) {
561 return Result<Value>::failure(diagnostic(error.what()));
562 } catch (const std::exception& error) {
564 Diagnostic::error(DiagnosticCode::CallbackFailure, error.what(), {}, {}, "rpg.balance"));
565 }
566}
567} // namespace eve::rpg::balance
double x
LogicalId target
bool & active
double score
Definition Agent.cpp:51
Trace trace
Definition Agent.cpp:50
int root
Definition AnimSmr.cpp:119
std::string selected
std::string usage
RPG's thin compatibility facade over the attributes module.
const std::string & s
伤害公式 DSL 与技能伤害注册。
回合制战斗对象:参战者、行动顺序、目标选取、行动执行。
int priority
职业系统:设定职业、施加职业基础特征、按等级自动学习技能。
职业(Class)定义:可学技能(升级解锁)与职业基础特征,进程级注册表。
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
装备加成:把已装备物品(inventory::EquipmentSet)的注册属性加成同步到 actor 的属性修改器上。
EvpackChunkInput input
Definition Evpack.cpp:170
std::vector< FieldTarget > targets
std::string message
float maximum[3]
float minimum[3]
tensor::Graph g
Definition GpuGraph.cpp:7
std::uint32_t capacity
glm::vec3 n
Definition Grass.cpp:63
double r
float v
HexVec3 left
HexVec3 right
std::int32_t second
std::int32_t c
float ratio
bool required
std::vector< Edge > edges
std::string evidence
std::string id
Poco::JSON::Object::Ptr result
std::vector< RecipeParam > params
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
const std::string * tag
glm::dvec2 center
double dt
size_t queued
Definition OnnxGpgpu.cpp:60
std::string error
Definition Package.cpp:174
std::vector< particles::ParticleRecordEvent > events
std::unique_ptr< ParticleEffect > effect
eve::action::ActionVfxBinding binding
std::array< uint32_t, 9 > parameters
std::vector< ParticleBakeMaterial > bindings
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::set< std::string > values
Object::Ptr value
std::map< std::string, double > attributes
std::string build
double healthScale
std::vector< std::string > skills
std::string slot
std::vector< Scenario > scenarios
std::vector< Strategy > strategies
std::vector< EquipmentStat > stats
double healBelow
double mana
std::vector< Gear > gear
std::string parameter
std::vector< Build > builds
int rounds
double manaRegen
int winner
double manaScale
double reserveMana
std::string attribute
double number
glm::dmat4 matrix
std::string text
std::string_view source
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
int count
SimulationTick tick
std::uint64_t round
Json object
int limit
Definition TreeMesh.cpp:166
uint32_t seed
Definition TreeMesh.cpp:276
std::uint32_t classId
int turns
当前资源(hp/mana...)的受伤 / 治疗 / 复活 / 死亡。
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
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
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
static Value array(Array value)
Compatibility factory for an array value.
Definition Value.cpp:128
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
static void setBase(RPGActor *actor, const std::string &attribute, double value)
Set a base value; invalid actor or attribute is a compatibility no-op.
static double getBase(RPGActor *actor, const std::string &attribute)
Read a base value, returning zero for a missing actor/attribute.
static double getFinal(RPGActor *actor, const std::string &attribute)
Compute the final value through the canonical attributes engine.
static const SkillDamageSpec * findSkillDamage(const std::string &skillId)
Finds skill damage.
static const ClassDefinition * find(const std::string &id)
Find a registered class definition by id.
Definition Class.cpp:32
static bool setClass(RPGActor *actor, const std::string &classId)
设定职业并施加职业基础特征(compatibility facade (脚本兼容门面);成功返回 true)。
Definition Class.cpp:98
static eve::Result< int > projectSlot(RPGActor &actor, std::string_view slot, std::span< const EquipmentStat > stats)
Atomically replace one equipment slot's modifier projection from an owning definition's stats.
static RPGActor * createActor()
创建一个空白 actor(三张表均为空,按需惰性写入)。
Definition RPGActor.cpp:14
static const SkillDefinition * find(const std::string &id)
Find a registered skill definition by id.
Definition Skill.cpp:98
static void update(float dt)
遍历存活 RPGActor(liveActors / View):冷却倒计时 + 读条推进/结算。
static void learn(RPGActor *actor, const std::string &skillId)
Learn.
static bool canCast(RPGActor *actor, const std::string &skillId, std::string *reason=nullptr)
检查冷却/消耗/学会状态/自定义条件,不产生任何副作用。
static void pollTicks(std::vector< StatusTickEvent > &out)
取出并清空自上次调用以来累积的周期 tick 事件(push/poll 风格,见 event 模块)。
static eve::Result< StatusUpdateSummary > update(double dt)
Advance all live RPG status executors with an injected simulation delta.
static double getCurrent(RPGActor *actor, const std::string &resource)
当前值(无 vitals/资源时 0)。
static void revive(RPGActor *actor, const std::string &resource, double amount=-1.0)
复活:把资源设为 amount(默认当前上限),并清掉死亡状态。
static double getMax(RPGActor *actor, const std::string &resource)
上限:取 actor 同名最终属性(getFinalAttribute),无则 0。
static bool isDead(RPGActor *actor, const std::string &resource)
是否死亡:max > 0 且 current <= 0。
Result< Value > targets() const
Project directed target graph edges into BalanceSearch metric targets. @cost Linear in target edges; ...
~RPGBalanceSuite()
Release configuration; no game world state is owned between calls.
Result< void > configure(const Value &suite)
Validate and atomically copy version-1 suite data; unknown fields/versions are rejected.
RPGBalanceSuite()
Create an unconfigured suite.
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
Strategy
Explicit algorithm choice, also used for equal-budget random baselines.
Definition Agent.h:47
eve::Result< ParsedAttributeOperation > parseAttributeOperation(std::string_view operation, double value)
Parse a built-in operation spelling used by existing data and APIs.
char * decode(std::string format, const char *src, size_t srclen, size_t &dstlen)
Decodes a text buffer (hex / base64) back into raw bytes.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
eve::Result< T > Result
std::vector< int64_t > attrs(const Node &n, const char *key, std::vector< int64_t > fallback)
Attrs.
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31