14void emit(Match& match, std::string
kind, Faction* faction,
int team, std::string reason = {}) {
15 auto state = match.state();
16 match.events()->values.push_back({++
state->updateSequence, std::move(
kind),
17 faction ==
nullptr ?
SubjectRef{} : faction->identity()->subject,
18 team, std::move(reason)});
21Match::Participants::Entry* participant(Match& match, Faction& faction) {
22 const auto found = std::find_if(match.participants()->entries.begin(), match.participants()->entries.end(),
23 [&](
auto&
value) { return value.faction.resolve() == &faction; });
24 return found == match.participants()->entries.end() ? nullptr : &*
found;
27const Match::Participants::Entry* participantByFactionSubject(Match& match, SubjectRef
subject) {
28 for (
const auto& entry : match.participants()->
entries) {
29 auto* faction =
dynamic_cast<Faction*
>(entry.faction.resolve());
30 if (faction !=
nullptr && faction->identity()->subject ==
subject)
return &entry;
35bool teamIsLive(Match& match,
int team) {
36 for (
const auto& entry : match.participants()->
entries)
37 if (!entry.eliminated && entry.team == team && entry.faction.resolve() != nullptr) return true;
41void eliminate(Match& match, Match::Participants::Entry& entry, std::string reason,
bool surrendered =
false) {
42 if (entry.eliminated)
return;
43 entry.eliminated =
true;
44 entry.surrendered = surrendered;
45 entry.reason = reason;
46 auto* faction =
dynamic_cast<Faction*
>(entry.faction.resolve());
47 emit(match,
"faction_eliminated", faction, entry.team, std::move(reason));
52bool factionHasPresence(Faction& faction) {
53 auto units = ecs::View<Unit, Unit::Faction, Unit::Durability>();
54 for (
auto it =
units.begin(); it !=
units.end(); ++it) {
55 auto [
owner, durability] = *it;
56 if (owns(
owner->link, faction) && durability->alive && durability->state.health > 0.0)
return true;
58 auto buildings = ecs::View<Building, Building::Faction, Building::Integrity>();
59 for (
auto it = buildings.begin(); it != buildings.end(); ++it) {
60 auto [
owner, integrity] = *it;
61 if (owns(
owner->link, faction) && integrity->alive && integrity->state.health > 0.0)
return true;
66bool survives(Faction& faction,
const Match::Rules& rules) {
68 auto buildings = ecs::View<
Building, Building::Definition, Building::Faction, Building::Integrity,
69 Building::Construction>();
70 for (
auto it = buildings.begin(); it != buildings.end(); ++it) {
71 auto [definition,
owner, integrity, construction] = *it;
72 if (owns(
owner->link, faction) && integrity->alive && integrity->state.health > 0.0 &&
73 construction->progress >= 1.0f && definition->id.name() == rules.archetype)
78 return factionHasPresence(faction);
81bool teamHasPresence(Match& match,
int team) {
82 for (
auto& entry : match.participants()->
entries) {
83 if (entry.eliminated || entry.team != team)
continue;
84 auto* faction =
dynamic_cast<Faction*
>(entry.faction.resolve());
85 if (faction !=
nullptr && factionHasPresence(*faction))
return true;
90void destroyFactionEntities(Faction& faction) {
91 auto units = ecs::View<Unit, Unit::Faction, Unit::Durability>();
92 for (
auto it =
units.begin(); it !=
units.end(); ++it) {
93 auto [
owner, durability] = *it;
94 if (owns(
owner->link, faction)) {
95 durability->alive =
false;
96 durability->state.health = 0.0;
99 auto buildings = ecs::View<Building, Building::Faction, Building::Integrity>();
100 for (
auto it = buildings.begin(); it != buildings.end(); ++it) {
101 auto [
owner, integrity] = *it;
102 if (owns(
owner->link, faction)) {
103 integrity->alive =
false;
104 integrity->state.health = 0.0;
109void settleTeams(Match& match, std::string reason =
"last_team_standing") {
111 for (
auto& entry : match.participants()->
entries)
112 if (!entry.eliminated && entry.faction.resolve() != nullptr) teams.insert(entry.team);
113 if (teams.size() > 1)
return;
115 match.state()->winningTeam = teams.empty() ? -1 : *teams.begin();
116 emit(match, teams.empty() ?
"match_draw" :
"match_won", nullptr, match.
state()->winningTeam,
117 teams.empty() ?
"no_survivors" :
std::move(reason));
120Match::Scores::Entry* scoreEntry(Match& match,
int team) {
121 auto&
entries = match.scores()->entries;
122 const auto found = std::find_if(
entries.begin(),
entries.end(), [&](
const auto& entry) { return entry.team == team; });
126Result<void> addScore(Match& match,
int team,
double amount) {
127 if (!std::isfinite(amount) || amount == 0.0)
129 "RTS match score credit must be a finite non-zero amount",
130 "score", {},
"rts.match"));
131 auto* entry = scoreEntry(match, team);
132 if (entry ==
nullptr) {
133 match.scores()->entries.push_back({team, 0.0});
134 std::sort(match.scores()->entries.begin(), match.scores()->entries.end(),
135 [](
const auto&
left,
const auto&
right) { return left.team < right.team; });
136 entry = scoreEntry(match, team);
138 if (entry ==
nullptr)
140 "RTS match score entry was not created",
"score", {},
142 const double next = entry->value + amount;
143 if (!std::isfinite(next))
145 "RTS match score overflowed",
"score", {},
"rts.match"));
150std::map<int, double> liveTeamScores(Match& match) {
151 std::map<int, double> scores;
152 for (
const auto& entry : match.participants()->
entries) {
153 if (entry.eliminated || entry.faction.resolve() ==
nullptr)
continue;
154 scores.emplace(entry.team, 0.0);
156 for (
const auto& entry : match.scores()->
entries) {
157 auto found = scores.find(entry.team);
158 if (
found != scores.end())
found->second = entry.value;
163void finishWithTeam(Match& match,
int team, std::string reason) {
165 match.state()->winningTeam = team;
166 emit(match, team < 0 ?
"match_draw" :
"match_won", nullptr, team,
std::move(reason));
169void settleHighestScore(Match& match,
const std::map<int, double>& scores, std::string reason) {
170 if (scores.empty()) {
171 finishWithTeam(match, -1, std::move(reason));
174 double best = -std::numeric_limits<double>::infinity();
177 for (
const auto& [team,
value] : scores) {
186 finishWithTeam(match, tie ? -1 :
winner,
std::move(reason));
193 "resources", {},
"rts.match"));
194 std::map<int, double> totals;
195 for (
auto& entry : match.participants()->
entries) {
196 if (entry.eliminated)
continue;
197 auto* faction =
dynamic_cast<Faction*
>(entry.faction.resolve());
198 if (faction ==
nullptr)
continue;
199 auto balance =
resources(*faction, match.rules()->archetype);
201 totals[entry.team] += balance.value();
203 settleHighestScore(match, totals,
"time_expired");
207Result<std::size_t> accrueControlPoints(Match& match,
const SimulationStep&
step) {
209 const double seconds =
step.delta.seconds();
210 if (!(seconds > 0.0) || !std::isfinite(seconds))
213 "step.delta", {},
"rts.match"));
214 std::map<Faction*, int> factionTeams;
215 for (
auto& entry : match.participants()->
entries) {
216 if (entry.eliminated)
continue;
217 auto* faction =
dynamic_cast<Faction*
>(entry.faction.resolve());
218 if (faction ==
nullptr)
continue;
219 factionTeams.emplace(faction, entry.team);
221 std::size_t credited = 0;
223 ecs::View<Building, Building::Faction, Building::Capture, Building::Integrity, Building::Construction>();
224 for (
auto it = buildings.begin(); it != buildings.end(); ++it) {
225 auto [
owner, capture, integrity, construction] = *it;
226 if (!std::isfinite(capture->scorePerSecond) || capture->scorePerSecond <= 0.0f)
continue;
227 if (!integrity->alive || integrity->state.health <= 0.0 || construction->progress < 1.0f)
continue;
228 auto* faction =
dynamic_cast<Faction*
>(
owner->link.resolve());
229 if (faction ==
nullptr)
continue;
230 const auto team = factionTeams.find(faction);
231 if (team == factionTeams.end())
continue;
232 const double amount =
static_cast<double>(capture->scorePerSecond) * seconds;
233 auto creditedScore = addScore(match, team->second, amount);
241bool needsScoreAccrual(Match& match) {
248bool subjectAlive(SubjectRef
subject) {
249 if (!
subject.isValid())
return false;
250 auto units = ecs::View<Unit, Unit::Identity, Unit::Durability>();
251 for (
auto it =
units.begin(); it !=
units.end(); ++it) {
253 if (
identity->subject ==
subject)
return durability->alive && durability->state.health > 0.0;
255 auto buildings = ecs::View<Building, Building::Identity, Building::Integrity>();
256 for (
auto it = buildings.begin(); it != buildings.end(); ++it) {
258 if (
identity->subject ==
subject)
return integrity->alive && integrity->state.health > 0.0;
263bool factionOnTeam(Match& match, Faction* faction,
int team) {
264 if (faction ==
nullptr)
return false;
265 for (
const auto& entry : match.participants()->
entries) {
266 if (entry.eliminated || entry.team != team)
continue;
267 if (entry.faction.resolve() == faction)
return true;
274Result<ObjectiveProgress> evaluateObjective(Match& match,
const MissionObjectiveSpec& spec,
278 const auto*
target = participantByFactionSubject(match, spec.targetFaction);
281 auto* faction =
dynamic_cast<Faction*
>(
target->faction.resolve());
282 if (faction ==
nullptr ||
target->eliminated || !factionHasPresence(*faction))
287 if (spec.targetSubject.isValid()) {
291 const auto*
target = participantByFactionSubject(match, spec.targetFaction);
294 auto* faction =
dynamic_cast<Faction*
>(
target->faction.resolve());
295 if (faction ==
nullptr)
297 auto buildings = ecs::View<
Building, Building::Definition, Building::Faction, Building::Integrity,
298 Building::Construction>();
299 for (
auto it = buildings.begin(); it != buildings.end(); ++it) {
300 auto [definition,
owner, integrity, construction] = *it;
301 if (!owns(
owner->link, *faction))
continue;
302 if (!integrity->alive || integrity->state.health <= 0.0 || construction->progress < 1.0f)
continue;
303 if (definition->id.name() == spec.archetype)
309 if (!teamIsLive(match, spec.beneficiaryTeam) || !teamHasPresence(match, spec.beneficiaryTeam))
311 if (match.state()->elapsed >= spec.requiredDuration)
316 for (
const auto&
subject : spec.requiredSubjects)
319 if (!spec.requiredDuration.isZero() && match.state()->elapsed >= spec.requiredDuration)
321 if (spec.requiredDuration.isZero())
326 if (spec.requiredSubjects.empty()) {
328 ecs::View<
Building, Building::Definition, Building::Faction, Building::Integrity,
329 Building::Construction, Building::Capture>();
330 for (
auto it = buildings.begin(); it != buildings.end(); ++it) {
331 auto [definition,
owner, integrity, construction, capture] = *it;
332 if (!spec.archetype.empty() && definition->id.name() != spec.archetype)
continue;
333 if (spec.archetype.empty() &&
334 (!std::isfinite(capture->scorePerSecond) || capture->scorePerSecond <= 0.0f))
336 if (!integrity->alive || integrity->state.health <= 0.0 || construction->progress < 1.0f)
continue;
337 if (factionOnTeam(match,
dynamic_cast<Faction*
>(
owner->link.resolve()), spec.beneficiaryTeam))
342 for (
const auto&
subject : spec.requiredSubjects) {
345 ecs::View<
Building, Building::Identity, Building::Faction, Building::Integrity,
346 Building::Construction>();
347 for (
auto it = buildings.begin(); it != buildings.end(); ++it) {
350 if (!integrity->alive || integrity->state.health <= 0.0 || construction->progress < 1.0f)
352 owned = factionOnTeam(match,
dynamic_cast<Faction*
>(
owner->link.resolve()),
353 spec.beneficiaryTeam);
361 const auto scores = liveTeamScores(match);
362 const auto found = scores.find(spec.beneficiaryTeam);
364 if (
value >= spec.targetValue)
372 "resource mission objective requires an authoritative economy query",
"resources", {},
374 for (
auto& entry : match.participants()->
entries) {
375 if (entry.eliminated || entry.team != spec.beneficiaryTeam)
continue;
376 auto* faction =
dynamic_cast<Faction*
>(entry.faction.resolve());
377 if (faction ==
nullptr)
continue;
378 auto balance =
resources(*faction, spec.resourceType);
380 if (balance.value() >= spec.targetValue)
389struct ObjectiveSettlement {
395 ObjectiveSettlement settlement;
396 for (
auto& objective : match.objectives()->values) {
398 auto progress = evaluateObjective(match, objective.spec,
resources);
400 if (progress.value() == ObjectiveProgress::Pending && atTimeout && objective.spec.failsMatch &&
405 if (progress.value() == ObjectiveProgress::Pending)
continue;
406 settlement.changed =
true;
407 if (progress.value() == ObjectiveProgress::Completed) {
409 objective.completedSequence = match.state()->updateSequence + 1;
410 emit(match,
"objective_completed",
nullptr, objective.spec.beneficiaryTeam, objective.spec.id);
411 if (objective.spec.endsMatch) {
412 finishWithTeam(match, objective.spec.beneficiaryTeam,
"objective:" + objective.spec.id);
413 settlement.ended =
true;
418 objective.completedSequence = match.state()->updateSequence + 1;
419 emit(match,
"objective_failed",
nullptr, objective.spec.beneficiaryTeam, objective.spec.id);
420 if (objective.spec.failsMatch) {
421 finishWithTeam(match, -1,
"objective_failed:" + objective.spec.id);
422 settlement.ended =
true;
431Result<void> validateObjective(Match& match,
const MissionObjectiveSpec& objective) {
432 if (objective.id.empty())
434 "RTS mission objective requires a non-empty id",
"objective.id",
436 bool knownTeam =
false;
437 for (
const auto& entry : match.participants()->
entries)
438 if (entry.team == objective.beneficiaryTeam) knownTeam = true;
442 "objective.beneficiaryTeam", {},
"rts.match"));
443 switch (objective.kind) {
445 if (!objective.targetFaction.isValid() || participantByFactionSubject(match, objective.targetFaction) ==
nullptr)
448 "objective.targetFaction", {},
"rts.match"));
451 if (!objective.targetSubject.isValid() &&
452 (objective.archetype.empty() || !objective.targetFaction.isValid() ||
453 participantByFactionSubject(match, objective.targetFaction) ==
nullptr))
456 "RTS destroy-building objective requires a subject or archetype+target faction",
"objective", {},
460 if (objective.requiredDuration.isZero() || objective.requiredDuration.nanoseconds() < 0)
463 "objective.requiredDuration", {},
"rts.match"));
466 if (objective.requiredSubjects.empty())
469 "objective.requiredSubjects", {},
"rts.match"));
472 if (objective.requiredSubjects.empty() && objective.archetype.empty())
475 "RTS occupy objective requires building subjects or an archetype",
"objective", {},
"rts.match"));
478 if (!(objective.targetValue > 0.0) || !std::isfinite(objective.targetValue))
481 "objective.targetValue", {},
"rts.match"));
484 if (objective.resourceType.empty() || !(objective.targetValue > 0.0) ||
485 !std::isfinite(objective.targetValue))
488 "RTS reach-resource objective requires a resource and positive target",
"objective", {},
501 if (participant(match, faction) !=
nullptr)
503 "faction", {},
"rts.match"));
506 match.participants()->entries.push_back({std::move(
link).takeValue(), team,
false,
false, {}});
515 auto validated = validateObjective(match, objective);
516 if (!validated)
return validated;
517 const auto duplicate = std::find_if(match.objectives()->values.begin(), match.objectives()->values.end(),
518 [&](
const auto&
value) { return value.spec.id == objective.id; });
519 if (duplicate != match.objectives()->values.end())
521 "RTS mission objective id already exists",
"objective.id", {},
537 if (match.participants()->entries.size() < 2)
539 "RTS match requires at least two factions",
"participants", {},
541 for (
const auto& entry : match.participants()->entries)
542 if (entry.faction.resolve() ==
nullptr)
545 const auto& rules = *match.rules();
550 (rules.archetype.empty() || rules.targetValue <= 0.0 || !std::isfinite(rules.targetValue)))
557 const bool hasTerminal = std::any_of(match.objectives()->values.begin(), match.objectives()->values.end(),
558 [](
const auto&
value) { return value.spec.endsMatch || value.spec.failsMatch; });
562 "RTS mission victory requires at least one terminal objective",
"objectives", {},
"rts.match"));
564 if (rules.timeLimit.nanoseconds() < 0)
568 if (rules.suddenDeath && rules.timeLimit.isZero())
576 "RTS sudden death applies only to annihilation or headquarters victory",
"rules.suddenDeath", {},
578 for (
const auto& objective : match.objectives()->values) {
579 auto validated = validateObjective(match, objective.spec);
580 if (!validated)
return validated;
583 match.state()->winningTeam = -1;
585 match.state()->suddenDeathActive =
false;
586 emit(match,
"match_started",
nullptr, -1);
594 auto* entry = participant(match, faction);
595 if (entry ==
nullptr || entry->eliminated)
598 destroyFactionEntities(faction);
599 eliminate(match, *entry,
"surrender",
true);
608 bool knownTeam =
false;
609 for (
const auto& entry : match.participants()->entries) {
610 if (!entry.eliminated && entry.team == team) {
619 return addScore(match, team, amount);
623 const auto* entry = scoreEntry(match, team);
636 if (!
step.delta.isZero()) {
637 auto nextElapsed = match.state()->elapsed.tryAdd(
step.delta);
639 match.state()->elapsed = std::move(nextElapsed).takeValue();
643 if (needsScoreAccrual(match) && !match.state()->suddenDeathActive) {
644 auto accrued = accrueControlPoints(match,
step);
655 const bool timedOut = !match.rules()->timeLimit.isZero() &&
656 match.state()->elapsed >= match.rules()->timeLimit && !match.state()->suddenDeathActive;
658 if (match.rules()->suddenDeath) {
659 match.state()->suddenDeathActive =
true;
660 emit(match,
"sudden_death",
nullptr, -1,
"time_expired");
662 }
else if (match.rules()->rule ==
VictoryRule::Mission || !match.objectives()->values.empty()) {
663 auto atTimeout = evaluateObjectives(match,
resources,
true);
665 if (atTimeout.value().ended)
668 finishWithTeam(match, -1,
"time_expired");
672 settleHighestScore(match, liveTeamScores(match),
"time_expired");
675 auto settled = settleTimedResource(match,
resources);
680 for (
const auto& entry : match.participants()->entries)
681 if (!entry.eliminated && entry.faction.resolve() !=
nullptr) teams.insert(entry.team);
682 finishWithTeam(match, teams.size() == 1 ? *teams.begin() : -1,
"time_expired");
692 const auto scores = liveTeamScores(match);
693 for (
const auto& [team,
value] : scores) {
694 if (
value >= match.rules()->targetValue) {
695 finishWithTeam(match, team,
"score_target");
703 std::size_t eliminated = 0;
708 "resources", {},
"rts.match"));
709 for (
auto& entry : match.participants()->entries) {
710 if (entry.eliminated)
continue;
711 auto* faction =
dynamic_cast<Faction*
>(entry.faction.resolve());
712 if (faction ==
nullptr) {
713 eliminate(match, entry,
"stale_faction");
717 auto balance =
resources(*faction, match.rules()->archetype);
719 if (balance.value() >= match.rules()->targetValue) {
721 match.state()->winningTeam = entry.team;
722 emit(match,
"match_won", faction, entry.team,
"resource_target");
727 for (
auto& entry : match.participants()->entries) {
728 if (entry.eliminated)
continue;
729 auto* faction =
dynamic_cast<Faction*
>(entry.faction.resolve());
730 if (faction ==
nullptr || !survives(*faction, *match.rules())) {
731 eliminate(match, entry, faction ==
nullptr ?
"stale_faction" :
739 const std::size_t total =
changed + eliminated;
std::unordered_map< std::string, QuestRuntime > entries
std::shared_ptr< OceanGpuSpectrum > owner
std::vector< std::weak_ptr< DeviceBytes > > resources
std::set< std::string > values
Deterministic match lifecycle and victory systems.
std::map< Cell, int > best
std::vector< UnitCandidate > units
Battle::Objectives objectives
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static constexpr Duration zero() noexcept
Return zero duration.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Strong, domain-neutral reference to a runtime subject.
static Result< EntityLink > bind(ecs::EntityHandle handle)
Bind a live ECS handle, rejecting a null or stale handle.
Faction domain root; membership is a set of typed runtime handles.
static Result< std::size_t > step(Match &match, const SimulationStep &step={}, const MatchResourceQuery &resources={})
Advance the match clock, evaluate objectives/victory, and settle a winner or draw.
static Result< void > addObjective(Match &match, MissionObjectiveSpec objective)
Register one campaign objective while the match is in setup. @cost Linear in existing objectives for ...
static Result< void > start(Match &match)
Validate rules/participants/objectives and transition Setup to Running.
static Result< double > teamScore(Match &match, int team) noexcept
Read one team's match-owned score; missing teams return 0.
static Result< void > creditScore(Match &match, int team, double amount)
Credit a finite team score while the match is running. @cost Linear in the number of score entries (t...
static Result< void > addParticipant(Match &match, Faction &faction, int team)
Add one live faction before match start.
static Result< void > surrender(Match &match, Faction &faction)
Eliminate a participant and all of its live RTS entities.
Independent match composition root; factions may participate in different matches.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
eve::Result< void > success()
MissionObjectiveKind
Deterministic campaign objective kinds owned by a Match.
std::function< Result< double >(Faction &, std::string_view)> MatchResourceQuery
Reads a resource balance from the game-owned canonical economy account.
EntityLink< FactionLinkTag > FactionLink
@ Mission
Campaign/mission mode: Match::Objectives own completion and failure settlement.
::eve::SubjectRef SubjectRef
Strong reference to a runtime subject.
StatusCode
Stable outcome category for an operation.
One deterministic fixed-step emitted by SimulationClock.
Persistent mission objective definition using stable subjects and team ids.
std::vector< SubjectRef > requiredSubjects