载入中...
搜索中...
未找到
RTSMatch.cpp
浏览该文件的文档.
1#include "rts/RTSMatch.h"
2
3#include <algorithm>
4#include <cmath>
5#include <limits>
6#include <map>
7#include <set>
8#include <string>
9#include <utility>
10
11namespace eve::rts {
12namespace {
13
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)});
19}
20
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;
25}
26
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;
31 }
32 return nullptr;
33}
34
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;
38 return false;
39}
40
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));
48}
49
50bool owns(const FactionLink& link, Faction& faction) { return link.resolve() == &faction; }
51
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;
57 }
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;
62 }
63 return false;
64}
65
66bool survives(Faction& faction, const Match::Rules& rules) {
67 if (rules.rule == VictoryRule::DestroyHeadquarters) {
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)
74 return true;
75 }
76 return false;
77 }
78 return factionHasPresence(faction);
79}
80
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;
86 }
87 return false;
88}
89
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;
97 }
98 }
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;
105 }
106 }
107}
108
109void settleTeams(Match& match, std::string reason = "last_team_standing") {
110 std::set<int> teams;
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;
114 match.state()->phase = MatchPhase::Finished;
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));
118}
119
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; });
123 return found == entries.end() ? nullptr : &*found;
124}
125
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);
137 }
138 if (entry == nullptr)
140 "RTS match score entry was not created", "score", {},
141 "rts.match"));
142 const double next = entry->value + amount;
143 if (!std::isfinite(next))
145 "RTS match score overflowed", "score", {}, "rts.match"));
146 entry->value = next;
148}
149
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);
155 }
156 for (const auto& entry : match.scores()->entries) {
157 auto found = scores.find(entry.team);
158 if (found != scores.end()) found->second = entry.value;
159 }
160 return scores;
161}
162
163void finishWithTeam(Match& match, int team, std::string reason) {
164 match.state()->phase = MatchPhase::Finished;
165 match.state()->winningTeam = team;
166 emit(match, team < 0 ? "match_draw" : "match_won", nullptr, team, std::move(reason));
167}
168
169void settleHighestScore(Match& match, const std::map<int, double>& scores, std::string reason) {
170 if (scores.empty()) {
171 finishWithTeam(match, -1, std::move(reason));
172 return;
173 }
174 double best = -std::numeric_limits<double>::infinity();
175 int winner = -1;
176 bool tie = false;
177 for (const auto& [team, value] : scores) {
178 if (value > best) {
179 best = value;
180 winner = team;
181 tie = false;
182 } else if (value == best) {
183 tie = true;
184 }
185 }
186 finishWithTeam(match, tie ? -1 : winner, std::move(reason));
187}
188
189Result<void> settleTimedResource(Match& match, const MatchResourceQuery& resources) {
190 if (!resources)
192 DiagnosticCode::PreconditionViolation, "resource victory requires an authoritative economy query",
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);
200 if (!balance) return Result<void>::failure(balance.status());
201 totals[entry.team] += balance.value();
202 }
203 settleHighestScore(match, totals, "time_expired");
205}
206
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))
212 DiagnosticCode::InvalidArgument, "RTS match control-point accrual requires a positive finite delta",
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);
220 }
221 std::size_t credited = 0;
222 auto buildings =
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);
234 if (!creditedScore) return Result<std::size_t>::failure(creditedScore.status());
235 ++credited;
236 }
237 return Result<std::size_t>::success(credited,
239}
240
241bool needsScoreAccrual(Match& match) {
242 if (match.rules()->rule == VictoryRule::ScoreTarget) return true;
243 for (const auto& objective : match.objectives()->values)
244 if (objective.spec.kind == MissionObjectiveKind::ReachScore) return true;
245 return false;
246}
247
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) {
252 auto [identity, durability] = *it;
253 if (identity->subject == subject) return durability->alive && durability->state.health > 0.0;
254 }
255 auto buildings = ecs::View<Building, Building::Identity, Building::Integrity>();
256 for (auto it = buildings.begin(); it != buildings.end(); ++it) {
257 auto [identity, integrity] = *it;
258 if (identity->subject == subject) return integrity->alive && integrity->state.health > 0.0;
259 }
260 return false;
261}
262
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;
268 }
269 return false;
270}
271
272enum class ObjectiveProgress : std::uint8_t { Pending, Completed, Failed };
273
274Result<ObjectiveProgress> evaluateObjective(Match& match, const MissionObjectiveSpec& spec,
276 switch (spec.kind) {
278 const auto* target = participantByFactionSubject(match, spec.targetFaction);
279 if (target == nullptr)
280 return Result<ObjectiveProgress>::success(ObjectiveProgress::Completed);
281 auto* faction = dynamic_cast<Faction*>(target->faction.resolve());
282 if (faction == nullptr || target->eliminated || !factionHasPresence(*faction))
283 return Result<ObjectiveProgress>::success(ObjectiveProgress::Completed);
284 return Result<ObjectiveProgress>::success(ObjectiveProgress::Pending);
285 }
287 if (spec.targetSubject.isValid()) {
288 return Result<ObjectiveProgress>::success(subjectAlive(spec.targetSubject) ? ObjectiveProgress::Pending
289 : ObjectiveProgress::Completed);
290 }
291 const auto* target = participantByFactionSubject(match, spec.targetFaction);
292 if (target == nullptr)
293 return Result<ObjectiveProgress>::success(ObjectiveProgress::Completed);
294 auto* faction = dynamic_cast<Faction*>(target->faction.resolve());
295 if (faction == nullptr)
296 return Result<ObjectiveProgress>::success(ObjectiveProgress::Completed);
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)
304 return Result<ObjectiveProgress>::success(ObjectiveProgress::Pending);
305 }
306 return Result<ObjectiveProgress>::success(ObjectiveProgress::Completed);
307 }
309 if (!teamIsLive(match, spec.beneficiaryTeam) || !teamHasPresence(match, spec.beneficiaryTeam))
310 return Result<ObjectiveProgress>::success(ObjectiveProgress::Failed);
311 if (match.state()->elapsed >= spec.requiredDuration)
312 return Result<ObjectiveProgress>::success(ObjectiveProgress::Completed);
313 return Result<ObjectiveProgress>::success(ObjectiveProgress::Pending);
314 }
316 for (const auto& subject : spec.requiredSubjects)
317 if (!subjectAlive(subject))
318 return Result<ObjectiveProgress>::success(ObjectiveProgress::Failed);
319 if (!spec.requiredDuration.isZero() && match.state()->elapsed >= spec.requiredDuration)
320 return Result<ObjectiveProgress>::success(ObjectiveProgress::Completed);
321 if (spec.requiredDuration.isZero())
322 return Result<ObjectiveProgress>::success(ObjectiveProgress::Pending);
323 return Result<ObjectiveProgress>::success(ObjectiveProgress::Pending);
324 }
326 if (spec.requiredSubjects.empty()) {
327 auto buildings =
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))
335 continue;
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))
338 return Result<ObjectiveProgress>::success(ObjectiveProgress::Completed);
339 }
340 return Result<ObjectiveProgress>::success(ObjectiveProgress::Pending);
341 }
342 for (const auto& subject : spec.requiredSubjects) {
343 bool owned = false;
344 auto buildings =
345 ecs::View<Building, Building::Identity, Building::Faction, Building::Integrity,
346 Building::Construction>();
347 for (auto it = buildings.begin(); it != buildings.end(); ++it) {
348 auto [identity, owner, integrity, construction] = *it;
349 if (identity->subject != subject) continue;
350 if (!integrity->alive || integrity->state.health <= 0.0 || construction->progress < 1.0f)
351 return Result<ObjectiveProgress>::success(ObjectiveProgress::Pending);
352 owned = factionOnTeam(match, dynamic_cast<Faction*>(owner->link.resolve()),
353 spec.beneficiaryTeam);
354 break;
355 }
356 if (!owned) return Result<ObjectiveProgress>::success(ObjectiveProgress::Pending);
357 }
358 return Result<ObjectiveProgress>::success(ObjectiveProgress::Completed);
359 }
361 const auto scores = liveTeamScores(match);
362 const auto found = scores.find(spec.beneficiaryTeam);
363 const double value = found == scores.end() ? 0.0 : found->second;
364 if (value >= spec.targetValue)
365 return Result<ObjectiveProgress>::success(ObjectiveProgress::Completed);
366 return Result<ObjectiveProgress>::success(ObjectiveProgress::Pending);
367 }
369 if (!resources)
372 "resource mission objective requires an authoritative economy query", "resources", {},
373 "rts.match"));
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);
379 if (!balance) return Result<ObjectiveProgress>::failure(balance.status());
380 if (balance.value() >= spec.targetValue)
381 return Result<ObjectiveProgress>::success(ObjectiveProgress::Completed);
382 }
383 return Result<ObjectiveProgress>::success(ObjectiveProgress::Pending);
384 }
385 }
386 return Result<ObjectiveProgress>::success(ObjectiveProgress::Pending);
387}
388
389struct ObjectiveSettlement {
390 bool changed = false;
391 bool ended = false;
392};
393
394Result<ObjectiveSettlement> evaluateObjectives(Match& match, const MatchResourceQuery& resources, bool atTimeout) {
395 ObjectiveSettlement settlement;
396 for (auto& objective : match.objectives()->values) {
397 if (objective.status != MissionObjectiveStatus::Pending) continue;
398 auto progress = evaluateObjective(match, objective.spec, resources);
399 if (!progress) return Result<ObjectiveSettlement>::failure(progress.status());
400 if (progress.value() == ObjectiveProgress::Pending && atTimeout && objective.spec.failsMatch &&
401 objective.spec.endsMatch && objective.spec.kind != MissionObjectiveKind::SurviveDuration &&
402 objective.spec.kind != MissionObjectiveKind::ProtectSubjects) {
403 progress = Result<ObjectiveProgress>::success(ObjectiveProgress::Failed);
404 }
405 if (progress.value() == ObjectiveProgress::Pending) continue;
406 settlement.changed = true;
407 if (progress.value() == ObjectiveProgress::Completed) {
408 objective.status = MissionObjectiveStatus::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;
415 }
416 } else {
417 objective.status = MissionObjectiveStatus::Failed;
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;
424 }
425 }
426 }
428 settlement, Status::success(settlement.changed ? StatusCode::Applied : StatusCode::NoOp));
429}
430
431Result<void> validateObjective(Match& match, const MissionObjectiveSpec& objective) {
432 if (objective.id.empty())
434 "RTS mission objective requires a non-empty id", "objective.id",
435 {}, "rts.match"));
436 bool knownTeam = false;
437 for (const auto& entry : match.participants()->entries)
438 if (entry.team == objective.beneficiaryTeam) knownTeam = true;
439 if (!knownTeam)
441 DiagnosticCode::NotFound, "RTS mission objective beneficiary team is not a participant team",
442 "objective.beneficiaryTeam", {}, "rts.match"));
443 switch (objective.kind) {
445 if (!objective.targetFaction.isValid() || participantByFactionSubject(match, objective.targetFaction) == nullptr)
447 DiagnosticCode::NotFound, "RTS eliminate objective requires a participating target faction",
448 "objective.targetFaction", {}, "rts.match"));
449 break;
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", {},
457 "rts.match"));
458 break;
460 if (objective.requiredDuration.isZero() || objective.requiredDuration.nanoseconds() < 0)
462 DiagnosticCode::InvalidArgument, "RTS survive objective requires a positive duration",
463 "objective.requiredDuration", {}, "rts.match"));
464 break;
466 if (objective.requiredSubjects.empty())
468 DiagnosticCode::InvalidArgument, "RTS protect objective requires subjects",
469 "objective.requiredSubjects", {}, "rts.match"));
470 break;
472 if (objective.requiredSubjects.empty() && objective.archetype.empty())
475 "RTS occupy objective requires building subjects or an archetype", "objective", {}, "rts.match"));
476 break;
478 if (!(objective.targetValue > 0.0) || !std::isfinite(objective.targetValue))
480 DiagnosticCode::InvalidArgument, "RTS reach-score objective requires a positive target",
481 "objective.targetValue", {}, "rts.match"));
482 break;
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", {},
489 "rts.match"));
490 break;
491 }
493}
494
495} // namespace
496
498 if (match.state()->phase != MatchPhase::Setup)
500 DiagnosticCode::Conflict, "cannot add an RTS participant after match start", "match", {}, "rts.match"));
501 if (participant(match, faction) != nullptr)
502 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Conflict, "RTS faction is already a participant",
503 "faction", {}, "rts.match"));
504 auto link = FactionLink::bind(ecs::handle_of(&faction));
505 if (!link) return Result<void>::failure(link.status());
506 match.participants()->entries.push_back({std::move(link).takeValue(), team, false, false, {}});
508}
509
511 if (match.state()->phase != MatchPhase::Setup)
513 DiagnosticCode::Conflict, "cannot add an RTS mission objective after match start", "match.phase", {},
514 "rts.match"));
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", {},
522 "rts.match"));
523 std::sort(objective.requiredSubjects.begin(), objective.requiredSubjects.end(),
524 [](const SubjectRef& left, const SubjectRef& right) { return left.format() < right.format(); });
525 objective.requiredSubjects.erase(
526 std::unique(objective.requiredSubjects.begin(), objective.requiredSubjects.end(),
527 [](const SubjectRef& left, const SubjectRef& right) { return left == right; }),
528 objective.requiredSubjects.end());
529 match.objectives()->values.push_back({std::move(objective), MissionObjectiveStatus::Pending, 0});
531}
532
534 if (match.state()->phase != MatchPhase::Setup)
536 Diagnostic::error(DiagnosticCode::Conflict, "RTS match is not in setup", "match.phase", {}, "rts.match"));
537 if (match.participants()->entries.size() < 2)
539 "RTS match requires at least two factions", "participants", {},
540 "rts.match"));
541 for (const auto& entry : match.participants()->entries)
542 if (entry.faction.resolve() == nullptr)
544 DiagnosticCode::StaleHandle, "RTS match contains a stale faction", "participants", {}, "rts.match"));
545 const auto& rules = *match.rules();
546 if (rules.rule == VictoryRule::DestroyHeadquarters && rules.archetype.empty())
548 DiagnosticCode::InvalidArgument, "headquarters victory requires an archetype", "rules", {}, "rts.match"));
549 if (rules.rule == VictoryRule::ResourceTarget &&
550 (rules.archetype.empty() || rules.targetValue <= 0.0 || !std::isfinite(rules.targetValue)))
552 DiagnosticCode::InvalidArgument, "resource victory requires a positive target", "rules", {}, "rts.match"));
553 if (rules.rule == VictoryRule::ScoreTarget && (rules.targetValue <= 0.0 || !std::isfinite(rules.targetValue)))
555 DiagnosticCode::InvalidArgument, "score victory requires a positive target", "rules", {}, "rts.match"));
556 if (rules.rule == VictoryRule::Mission) {
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; });
559 if (!hasTerminal)
562 "RTS mission victory requires at least one terminal objective", "objectives", {}, "rts.match"));
563 }
564 if (rules.timeLimit.nanoseconds() < 0)
566 DiagnosticCode::InvalidArgument, "RTS match time limit cannot be negative", "rules.timeLimit", {},
567 "rts.match"));
568 if (rules.suddenDeath && rules.timeLimit.isZero())
570 DiagnosticCode::InvalidArgument, "RTS sudden death requires a positive time limit", "rules.suddenDeath",
571 {}, "rts.match"));
572 if (rules.suddenDeath && (rules.rule == VictoryRule::ScoreTarget || rules.rule == VictoryRule::ResourceTarget ||
573 rules.rule == VictoryRule::Mission))
576 "RTS sudden death applies only to annihilation or headquarters victory", "rules.suddenDeath", {},
577 "rts.match"));
578 for (const auto& objective : match.objectives()->values) {
579 auto validated = validateObjective(match, objective.spec);
580 if (!validated) return validated;
581 }
582 match.state()->phase = MatchPhase::Running;
583 match.state()->winningTeam = -1;
584 match.state()->elapsed = Duration::zero();
585 match.state()->suddenDeathActive = false;
586 emit(match, "match_started", nullptr, -1);
588}
589
591 if (match.state()->phase != MatchPhase::Running)
593 Diagnostic::error(DiagnosticCode::Conflict, "RTS match is not running", "match.phase", {}, "rts.match"));
594 auto* entry = participant(match, faction);
595 if (entry == nullptr || entry->eliminated)
597 DiagnosticCode::NotFound, "RTS faction is not an active participant", "faction", {}, "rts.match"));
598 destroyFactionEntities(faction);
599 eliminate(match, *entry, "surrender", true);
600 settleTeams(match);
602}
603
604Result<void> MatchSystem::creditScore(Match& match, int team, double amount) {
605 if (match.state()->phase != MatchPhase::Running)
607 Diagnostic::error(DiagnosticCode::Conflict, "RTS match is not running", "match.phase", {}, "rts.match"));
608 bool knownTeam = false;
609 for (const auto& entry : match.participants()->entries) {
610 if (!entry.eliminated && entry.team == team) {
611 knownTeam = true;
612 break;
613 }
614 }
615 if (!knownTeam)
617 DiagnosticCode::NotFound, "RTS match score team is not an active participant team", "team", {},
618 "rts.match"));
619 return addScore(match, team, amount);
620}
621
622Result<double> MatchSystem::teamScore(Match& match, int team) noexcept {
623 const auto* entry = scoreEntry(match, team);
624 return Result<double>::success(entry == nullptr ? 0.0 : entry->value, Status::success(StatusCode::Applied));
625}
626
630
632 if (match.state()->phase != MatchPhase::Running)
634
635 std::size_t changed = 0;
636 if (!step.delta.isZero()) {
637 auto nextElapsed = match.state()->elapsed.tryAdd(step.delta);
638 if (!nextElapsed) return Result<std::size_t>::failure(nextElapsed.status());
639 match.state()->elapsed = std::move(nextElapsed).takeValue();
640 ++changed;
641 }
642
643 if (needsScoreAccrual(match) && !match.state()->suddenDeathActive) {
644 auto accrued = accrueControlPoints(match, step);
645 if (!accrued) return Result<std::size_t>::failure(accrued.status());
646 changed += accrued.value();
647 }
648
649 auto objectives = evaluateObjectives(match, resources, false);
651 if (objectives.value().changed) ++changed;
652 if (objectives.value().ended)
654
655 const bool timedOut = !match.rules()->timeLimit.isZero() &&
656 match.state()->elapsed >= match.rules()->timeLimit && !match.state()->suddenDeathActive;
657 if (timedOut) {
658 if (match.rules()->suddenDeath) {
659 match.state()->suddenDeathActive = true;
660 emit(match, "sudden_death", nullptr, -1, "time_expired");
661 ++changed;
662 } else if (match.rules()->rule == VictoryRule::Mission || !match.objectives()->values.empty()) {
663 auto atTimeout = evaluateObjectives(match, resources, true);
664 if (!atTimeout) return Result<std::size_t>::failure(atTimeout.status());
665 if (atTimeout.value().ended)
667 if (match.rules()->rule == VictoryRule::Mission) {
668 finishWithTeam(match, -1, "time_expired");
670 }
671 } else if (match.rules()->rule == VictoryRule::ScoreTarget) {
672 settleHighestScore(match, liveTeamScores(match), "time_expired");
674 } else if (match.rules()->rule == VictoryRule::ResourceTarget) {
675 auto settled = settleTimedResource(match, resources);
676 if (!settled) return Result<std::size_t>::failure(settled.status());
678 } else {
679 std::set<int> teams;
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");
684 }
685 }
686
687 if (match.rules()->rule == VictoryRule::Mission)
690
691 if (match.rules()->rule == VictoryRule::ScoreTarget) {
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");
697 }
698 }
701 }
702
703 std::size_t eliminated = 0;
704 if (match.rules()->rule == VictoryRule::ResourceTarget) {
705 if (!resources)
707 DiagnosticCode::PreconditionViolation, "resource victory requires an authoritative economy query",
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");
714 ++eliminated;
715 continue;
716 }
717 auto balance = resources(*faction, match.rules()->archetype);
718 if (!balance) return Result<std::size_t>::failure(balance.status());
719 if (balance.value() >= match.rules()->targetValue) {
720 match.state()->phase = MatchPhase::Finished;
721 match.state()->winningTeam = entry.team;
722 emit(match, "match_won", faction, entry.team, "resource_target");
724 }
725 }
726 } else {
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" :
732 match.rules()->rule == VictoryRule::DestroyHeadquarters ? "headquarters_destroyed" :
733 "annihilated");
734 ++eliminated;
735 }
736 }
737 }
738 settleTeams(match);
739 const std::size_t total = changed + eliminated;
741}
742
743} // namespace eve::rts
LogicalId target
int subject
Definition AnimSmr.cpp:163
ActiveSource owned
std::unordered_map< std::string, QuestRuntime > entries
bool changed
HexVec3 left
HexVec3 right
PhysicsJointLink link
bool ended
std::shared_ptr< OceanGpuSpectrum > owner
std::vector< std::weak_ptr< DeviceBytes > > resources
Definition OnnxGpgpu.cpp:55
std::set< std::string > values
Object::Ptr value
int winner
Deterministic match lifecycle and victory systems.
bool found
std::string kind
std::map< Cell, int > best
std::vector< UnitCandidate > units
Battle::Objectives objectives
float step
Definition TreeMesh.cpp:451
uint64_t identity
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.
Definition Time.h:60
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
Strong, domain-neutral reference to a runtime subject.
Definition SubjectRef.h:26
Faction domain root; membership is a set of typed runtime handles.
Definition RTSTypes.h:1192
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.
Definition RTSMatch.cpp:631
static Result< void > addObjective(Match &match, MissionObjectiveSpec objective)
Register one campaign objective while the match is in setup. @cost Linear in existing objectives for ...
Definition RTSMatch.cpp:510
static Result< void > start(Match &match)
Validate rules/participants/objectives and transition Setup to Running.
Definition RTSMatch.cpp:533
static Result< double > teamScore(Match &match, int team) noexcept
Read one team's match-owned score; missing teams return 0.
Definition RTSMatch.cpp:622
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...
Definition RTSMatch.cpp:604
static Result< void > addParticipant(Match &match, Faction &faction, int team)
Add one live faction before match start.
Definition RTSMatch.cpp:497
static Result< void > surrender(Match &match, Faction &faction)
Eliminate a participant and all of its live RTS entities.
Definition RTSMatch.cpp:590
Independent match composition root; factions may participate in different matches.
Definition RTSTypes.h:1476
eve::Result< T > Result
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
eve::Result< void > success()
MissionObjectiveKind
Deterministic campaign objective kinds owned by a Match.
Definition RTSTypes.h:1319
std::function< Result< double >(Faction &, std::string_view)> MatchResourceQuery
Reads a resource balance from the game-owned canonical economy account.
Definition RTSMatch.h:16
EntityLink< FactionLinkTag > FactionLink
Definition RTSTypes.h:290
@ Mission
Campaign/mission mode: Match::Objectives own completion and failure settlement.
::eve::SubjectRef SubjectRef
Strong reference to a runtime subject.
Definition Targeting.h:68
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Persistent mission objective definition using stable subjects and team ids.
Definition RTSTypes.h:1332
std::vector< SubjectRef > requiredSubjects
Definition RTSTypes.h:1342