// sc2k/ui/commentary.hpp implementation. #include "sc2k/ui/commentary.hpp" #include #include #include 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(static_cast(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(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; if constexpr (std::is_same_v) { return false; } else if constexpr (std::is_same_v) 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; if constexpr (std::is_same_v) { 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(0, currentMonth); state.nextAmbientMonth = state.trackingStartMonth > std::numeric_limits::max() - 2 ? std::numeric_limits::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 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(&rule.trigger)) { if (cue->cue.value == 0) return CommentRuleDefinitionIssue::InvalidTrigger; } else if (const auto* range = std::get_if(&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; if constexpr (std::is_same_v) 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 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 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 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::min(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(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(index)); } else { ++index; } } for (const CommentRuleDefinition* rule : eligible) { if (decision.totalWeight > std::numeric_limits::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(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 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(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(cadenceRoll % 3); state.nextAmbientMonth = context.monthIndex > std::numeric_limits::max() - interval ? std::numeric_limits::max() : context.monthIndex + interval; if (state.emissionSequence != std::numeric_limits::max()) ++state.emissionSequence; return decision; } } // namespace sc2k::ui