Something went wrong. Try again.
[Mirror] Libreopolis is a cross-platform city simulation game fully compatible with SimCity 2000. gitlab.com/conasg/libreopolis
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322// sc2k/ui/commentary.hpp implementation.#include "sc2k/ui/commentary.hpp"#include <algorithm>#include <limits>#include <type_traits>
namespace sc2k::ui {namespace {
constexpr std::uint64_t mix_commentary(std::uint64_t value) noexcept { value += 0x9E3779B97F4A7C15ull; value = (value ^ (value >> 30)) * 0xBF58476D1CE4E5B9ull; value = (value ^ (value >> 27)) * 0x94D049BB133111EBull; return value ^ (value >> 31);}
constexpr std::uint64_t normalize_commentary_salt(std::uint64_t seed) noexcept { const std::uint64_t salt = mix_commentary(seed ^ 0x434F4D4D454E5453ull); return salt == 0 ? 0x9E3779B97F4A7C15ull : salt;}
constexpr std::uint64_t hash_commentary_component(std::uint64_t hash, std::uint64_t value) noexcept { return mix_commentary(hash ^ mix_commentary(value));}
constexpr std::uint64_t commentary_roll(std::uint64_t citySalt, std::int32_t month, std::uint64_t sequence, std::uint64_t domain, std::uint64_t identity = 0) noexcept { std::uint64_t hash = mix_commentary(citySalt ^ domain); hash = hash_commentary_component(hash, static_cast<std::uint64_t>(static_cast<std::int64_t>(month))); hash = hash_commentary_component(hash, sequence); return hash_commentary_component(hash, identity);}
bool trigger_is_active(const CommentTrigger& trigger, const CommentaryContext& context) noexcept { if (std::holds_alternative<AmbientCommentTrigger>(trigger)) return true; return std::any_of(context.activeCues.begin(), context.activeCues.end(), [&](CommentCueId cue) { return comment_trigger_matches_cue(trigger, cue); });}
} // namespace
bool comment_trigger_matches_cue( const CommentTrigger& trigger, CommentCueId cue) noexcept { return std::visit( [cue](const auto& typed) { using Trigger = std::decay_t<decltype(typed)>; if constexpr (std::is_same_v<Trigger, AmbientCommentTrigger>) { return false; } else if constexpr (std::is_same_v<Trigger, EventCueCommentTrigger>) return typed.cue == cue; else return cue >= typed.first && cue <= typed.last; }, trigger);}
namespace {
bool gate_is_open(const CommentGate& gate, const CommentaryContext& context) noexcept { return std::visit( [&](const auto& typed) { using Gate = std::decay_t<decltype(typed)>; if constexpr (std::is_same_v<Gate, CommentScalarGate>) { const std::int64_t value = comment_scalar(context, typed.scalar); return value >= typed.minimum && value <= typed.maximum; } else { return comment_flag(context, typed.flag) == typed.expected; } }, gate);}
std::int32_t last_rule_emission(const CommentaryState& state, CommentRuleId id) noexcept { std::int32_t result = kCommentMonthUnset; for (const CommentRuleCooldown& cooldown : state.ruleCooldowns) if (cooldown.id == id) result = std::max(result, cooldown.lastEmissionMonth); return result;}
bool cooldown_active(std::int32_t currentMonth, std::int32_t lastMonth, std::uint16_t cooldownMonths) noexcept { if (lastMonth == kCommentMonthUnset) return false; return std::int64_t(currentMonth) < std::int64_t(lastMonth) + cooldownMonths;}
} // namespace
CommentaryState make_commentary_state(CommentaryTrackingProvenance provenance, std::int32_t currentMonth, std::uint64_t seed) noexcept { CommentaryState state; state.citySalt = normalize_commentary_salt(seed); state.trackingProvenance = provenance; state.trackingStartMonth = std::max<std::int32_t>(0, currentMonth); state.nextAmbientMonth = state.trackingStartMonth > std::numeric_limits<std::int32_t>::max() - 2 ? std::numeric_limits<std::int32_t>::max() : state.trackingStartMonth + 2; if (provenance == CommentaryTrackingProvenance::FromCreation) for (CommentOccurrenceHistory& history : state.disasterHistory) history.knowledge = CommentHistoryKnowledge::KnownNever; return state;}
std::uint64_t commentary_salt_from_bytes(std::span<const std::uint8_t> bytes) noexcept { std::uint64_t hash = 0xCBF29CE484222325ull; for (const std::uint8_t byte : bytes) { hash ^= byte; hash *= 0x100000001B3ull; } hash = hash_commentary_component(hash, bytes.size()); return normalize_commentary_salt(hash);}
CommentRuleDefinitionIssue validate_comment_rule(const CommentRuleDefinition& rule) noexcept { if (rule.id.value == 0) return CommentRuleDefinitionIssue::InvalidId; if (!valid_comment_topic(rule.topic)) return CommentRuleDefinitionIssue::InvalidTopic; if (rule.weight == 0) return CommentRuleDefinitionIssue::ZeroWeight; if (rule.variantCount == 0) return CommentRuleDefinitionIssue::ZeroVariants;
if (const auto* cue = std::get_if<EventCueCommentTrigger>(&rule.trigger)) { if (cue->cue.value == 0) return CommentRuleDefinitionIssue::InvalidTrigger; } else if (const auto* range = std::get_if<EventCueRangeCommentTrigger>(&rule.trigger)) { if (range->first.value == 0 || range->last < range->first) return CommentRuleDefinitionIssue::InvalidTrigger; }
for (const CommentGate& gate : rule.gates) { const bool valid = std::visit( [](const auto& typed) { using Gate = std::decay_t<decltype(typed)>; if constexpr (std::is_same_v<Gate, CommentScalarGate>) return valid_comment_scalar(typed.scalar) && typed.minimum <= typed.maximum; else return valid_comment_flag(typed.flag); }, gate); if (!valid) return CommentRuleDefinitionIssue::InvalidGate; } return CommentRuleDefinitionIssue::None;}
CommentaryDecision evaluate_commentary(const CommentaryState& state, const CommentaryContext& context, std::span<const CommentRuleDefinition> rules) { CommentaryDecision decision; if (context.monthIndex < 0) { decision.blockReason = CommentaryBlockReason::InvalidContext; return decision; } if (context.monthIndex <= state.lastEvaluatedMonth) { decision.blockReason = CommentaryBlockReason::AlreadyEvaluatedMonth; return decision; } if (context.emergencyActive) { decision.blockReason = CommentaryBlockReason::EmergencyActive; return decision; } if (context.monthIndex < state.nextAmbientMonth) { decision.blockReason = CommentaryBlockReason::BeforeCadence; return decision; }
std::vector<const CommentRuleDefinition*> ordered; ordered.reserve(rules.size()); for (const CommentRuleDefinition& rule : rules) ordered.push_back(&rule); std::stable_sort(ordered.begin(), ordered.end(), [](const auto* left, const auto* right) { return left->id < right->id; });
std::vector<const CommentRuleDefinition*> eligible; eligible.reserve(ordered.size()); std::uint8_t highestPriority = 0; bool hasEligible = false;
decision.diagnostics.reserve(ordered.size()); for (std::size_t index = 0; index < ordered.size(); ++index) { const CommentRuleDefinition& rule = *ordered[index]; CommentRuleDiagnostic diagnostic{rule.id}; CommentRuleDefinitionIssue issue = validate_comment_rule(rule); if ((index > 0 && ordered[index - 1]->id == rule.id) || (index + 1 < ordered.size() && ordered[index + 1]->id == rule.id)) issue = CommentRuleDefinitionIssue::DuplicateId; if (issue != CommentRuleDefinitionIssue::None) { diagnostic.disposition = CommentRuleDisposition::RejectedInvalidDefinition; diagnostic.definitionIssue = issue; decision.diagnostics.push_back(diagnostic); continue; }
if (!trigger_is_active(rule.trigger, context)) { diagnostic.disposition = CommentRuleDisposition::RejectedTrigger; decision.diagnostics.push_back(diagnostic); continue; }
bool gatesOpen = true; for (std::size_t gateIndex = 0; gateIndex < rule.gates.size(); ++gateIndex) if (!gate_is_open(rule.gates[gateIndex], context)) { diagnostic.disposition = CommentRuleDisposition::RejectedGate; diagnostic.failedGate = static_cast<std::uint16_t>( std::min<std::size_t>(gateIndex, kNoFailedCommentGate - 1)); gatesOpen = false; break; } if (!gatesOpen) { decision.diagnostics.push_back(diagnostic); continue; }
if (cooldown_active(context.monthIndex, last_rule_emission(state, rule.id), rule.ruleCooldownMonths)) { diagnostic.disposition = CommentRuleDisposition::RejectedRuleCooldown; decision.diagnostics.push_back(diagnostic); continue; } const std::int32_t topicMonth = state.lastTopicEmissionMonth[static_cast<std::size_t>(rule.topic)]; if (cooldown_active(context.monthIndex, topicMonth, rule.topicCooldownMonths)) { diagnostic.disposition = CommentRuleDisposition::RejectedTopicCooldown; decision.diagnostics.push_back(diagnostic); continue; }
highestPriority = hasEligible ? std::max(highestPriority, rule.priority) : rule.priority; hasEligible = true; eligible.push_back(&rule); decision.diagnostics.push_back(diagnostic); }
if (!hasEligible) { decision.blockReason = CommentaryBlockReason::NoEligibleRules; return decision; }
for (std::size_t index = 0; index < eligible.size();) { const CommentRuleDefinition& rule = *eligible[index]; if (rule.priority != highestPriority) { const auto diagnostic = std::find_if(decision.diagnostics.begin(), decision.diagnostics.end(), [&](const CommentRuleDiagnostic& value) { return value.id == rule.id; }); if (diagnostic != decision.diagnostics.end()) diagnostic->disposition = CommentRuleDisposition::RejectedLowerPriority; eligible.erase(eligible.begin() + static_cast<std::ptrdiff_t>(index)); } else { ++index; } }
for (const CommentRuleDefinition* rule : eligible) { if (decision.totalWeight > std::numeric_limits<std::uint64_t>::max() - rule->weight) { decision.blockReason = CommentaryBlockReason::WeightOverflow; decision.totalWeight = 0; return decision; } decision.totalWeight += rule->weight; }
decision.ruleRoll = commentary_roll(state.citySalt, context.monthIndex, state.emissionSequence, 0x52554C4553454C45ull) % decision.totalWeight; std::uint64_t cursor = 0; const CommentRuleDefinition* selected = nullptr; for (const CommentRuleDefinition* rule : eligible) { cursor += rule->weight; if (decision.ruleRoll < cursor) { selected = rule; break; } }
if (!selected) { decision.blockReason = CommentaryBlockReason::WeightOverflow; decision.totalWeight = 0; return decision; }
decision.variantRoll = commentary_roll(state.citySalt, context.monthIndex, state.emissionSequence, 0x56415249414E5453ull, selected->id.value); decision.selection = CommentSelection{selected->id, selected->topic, static_cast<std::uint8_t>(decision.variantRoll % selected->variantCount), selected->priority}; const auto diagnostic = std::find_if(decision.diagnostics.begin(), decision.diagnostics.end(), [&](const CommentRuleDiagnostic& value) { return value.id == selected->id; }); if (diagnostic != decision.diagnostics.end()) diagnostic->disposition = CommentRuleDisposition::Selected; return decision;}
CommentaryDecision advance_commentary(CommentaryState& state, const CommentaryContext& context, std::span<const CommentRuleDefinition> rules) { CommentaryDecision decision = evaluate_commentary(state, context, rules); if (context.monthIndex < 0 || context.monthIndex <= state.lastEvaluatedMonth) return decision;
state.lastEvaluatedMonth = context.monthIndex; if (!decision.selection) return decision;
const CommentSelection& selection = *decision.selection; state.lastEmittedMonth = context.monthIndex; state.lastTopicEmissionMonth[static_cast<std::size_t>(selection.topic)] = context.monthIndex;
const auto cooldown = std::lower_bound(state.ruleCooldowns.begin(), state.ruleCooldowns.end(), selection.rule, [](const CommentRuleCooldown& value, CommentRuleId id) { return value.id < id; }); if (cooldown != state.ruleCooldowns.end() && cooldown->id == selection.rule) cooldown->lastEmissionMonth = context.monthIndex; else state.ruleCooldowns.insert(cooldown, CommentRuleCooldown{selection.rule, context.monthIndex});
const std::uint64_t cadenceRoll = commentary_roll(state.citySalt, context.monthIndex, state.emissionSequence, 0x434144454E434553ull, selection.rule.value); const std::int32_t interval = 2 + static_cast<std::int32_t>(cadenceRoll % 3); state.nextAmbientMonth = context.monthIndex > std::numeric_limits<std::int32_t>::max() - interval ? std::numeric_limits<std::int32_t>::max() : context.monthIndex + interval; if (state.emissionSequence != std::numeric_limits<std::uint64_t>::max()) ++state.emissionSequence; return decision;}
} // namespace sc2k::ui