256 lines
13 KiB
C#
256 lines
13 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using KernelPanic.Combat;
|
|
using KernelPanic.Core;
|
|
using KernelPanic.Data;
|
|
using KernelPanic.Meta;
|
|
using UnityEngine;
|
|
|
|
namespace KernelPanic.Run
|
|
{
|
|
/// <summary>A repository or quiescent player-planning checkpoint.</summary>
|
|
[Serializable]
|
|
public sealed class RunCheckpoint
|
|
{
|
|
public int version = 1;
|
|
public string runId;
|
|
public string savedUtc;
|
|
public string distroId;
|
|
public int distroVersion;
|
|
public Language primaryLanguage;
|
|
public Language secondaryLanguage;
|
|
public int seed;
|
|
public List<string> startingCards = new();
|
|
public List<RunBuildPackageSaveEntry> packages = new();
|
|
public List<CheckpointCard> deck = new();
|
|
public List<CheckpointOffer> offers = new();
|
|
public List<string> soldKeys = new();
|
|
public int wave;
|
|
public int wavesCleared;
|
|
public int bits;
|
|
public int bandwidth;
|
|
public int entropy;
|
|
public int maxUptimeBonus;
|
|
public int maxCyclesBonus;
|
|
public int ramBonus;
|
|
public int rerolls;
|
|
public int shopRandomDraws;
|
|
public CheckpointCombat combat;
|
|
public CombatSnapshot fullCombat;
|
|
public bool inCombat;
|
|
public RunJourney journey;
|
|
public RunPerformanceSnapshot performance;
|
|
|
|
public ResolvedRunCheckpoint Resolve(DistroDatabase distros, CardDatabase cards,
|
|
LanguageDeckDatabase languages, PackageDatabase packageDatabase)
|
|
{
|
|
Require(version >= 1 && version <= 6, "This checkpoint needs a different game version.");
|
|
// JsonUtility can materialize empty nested objects for a serialized null. The explicit
|
|
// discriminator also keeps checkpoints written before combat saving unambiguous.
|
|
if (!inCombat) fullCombat = null;
|
|
Require(!inCombat || (version >= 6 && fullCombat != null), "Unsupported combat checkpoint.");
|
|
Require(version < 2 || journey != null, "Missing saved route decisions.");
|
|
if (fullCombat == null) { journey?.Validate(wave); journey?.ValidateMap(seed, wave); }
|
|
else
|
|
{
|
|
Require(journey != null && journey.pendingRewardWave == 0, "Missing combat route or unclaimed reward.");
|
|
var boundary = journey.Copy();
|
|
if (wave == 1)
|
|
{
|
|
Require(boundary.visits != null && boundary.visits.Count == 0 && boundary.selectedNodeId == 0, "Invalid initial route.");
|
|
boundary.mapRevision = 0;
|
|
boundary.Validate(wave);
|
|
}
|
|
else
|
|
{
|
|
if (boundary.mapRevision > 0)
|
|
{
|
|
var visit = boundary.visits?.LastOrDefault();
|
|
Require(visit != null && visit.wave == wave && !visit.cleared && visit.nodeId == boundary.selectedNodeId
|
|
&& visit.route == boundary.activeRoute && visit.route == boundary.selectedRoute, "Missing active route visit.");
|
|
boundary.visits.RemoveAt(boundary.visits.Count - 1);
|
|
}
|
|
boundary.Validate(wave); boundary.ValidateMap(seed, wave);
|
|
}
|
|
}
|
|
Require(Guid.TryParseExact(runId, "N", out _), "Invalid run identity.");
|
|
Require(wave >= (fullCombat == null ? 2 : 1) && wave <= 100000 && wavesCleared == wave - 1, "Invalid checkpoint wave.");
|
|
Require(bits >= 0 && bandwidth >= 0 && entropy >= 0 && rerolls >= 0, "Invalid checkpoint balances.");
|
|
Require(maxUptimeBonus >= 0 && maxCyclesBonus >= 0 && ramBonus >= 0, "Invalid run upgrades.");
|
|
Require(shopRandomDraws >= 0 && shopRandomDraws <= 10000000, "Invalid shop random cursor.");
|
|
Require(Enum.IsDefined(typeof(Language), primaryLanguage) && Enum.IsDefined(typeof(Language), secondaryLanguage)
|
|
&& primaryLanguage != secondaryLanguage, "Invalid checkpoint languages.");
|
|
Require(distroVersion >= 1 && distroVersion <= GachaTuning.MaxVersion, "Invalid distro version.");
|
|
DistroDefinition distro = distros == null ? null : distros.FindById(distroId);
|
|
Require(distro != null, $"Checkpoint distro '{distroId}' is unavailable. Save was left unchanged.");
|
|
Require(deck != null && deck.Count > 0 && deck.Count <= 10000 && startingCards != null
|
|
&& startingCards.Count > 0 && startingCards.Count <= 10000, "Invalid checkpoint deck.");
|
|
Require(packages != null && packages.Count <= 3 && offers != null && offers.Count <= 100
|
|
&& soldKeys != null && soldKeys.Count <= 10000, "Invalid repository snapshot.");
|
|
Require(combat != null, "Missing combat checkpoint.");
|
|
combat.Validate();
|
|
|
|
CardDefinition FindCard(string id)
|
|
{
|
|
CardDefinition result = cards == null ? null : cards.FindById(id);
|
|
result ??= distro.ExclusiveCards.FirstOrDefault(card => card != null && string.Equals(card.Id, id, StringComparison.OrdinalIgnoreCase));
|
|
foreach (Language language in new[] { primaryLanguage, secondaryLanguage })
|
|
{
|
|
LanguageDeckDefinition languageDeck = languages == null ? null : languages.FindByLanguage(language);
|
|
if (result == null && languageDeck != null)
|
|
result = languageDeck.Entries.Select(entry => entry.Card).FirstOrDefault(card => card != null && string.Equals(card.Id, id, StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
Require(result != null, $"Checkpoint card '{id}' is unavailable. Save was left unchanged.");
|
|
return result;
|
|
}
|
|
|
|
List<PackageInstance> equipped = new();
|
|
HashSet<PackageSlot> slots = new();
|
|
foreach (RunBuildPackageSaveEntry entry in packages)
|
|
{
|
|
PackageDefinition package = entry == null || packageDatabase == null ? null : packageDatabase.FindById(entry.packageId);
|
|
Require(package != null && package.AcceptsSavedSlot(entry.slot) && slots.Add(entry.slot), "A checkpoint package is missing or invalid.");
|
|
Require(entry.upgradeLevel >= 0 && entry.upgradeLevel <= PackageTuning.MaxPackageLevel, "Invalid package level.");
|
|
equipped.Add(new PackageInstance(package, entry.upgradeLevel) { SavedSlot = entry.slot });
|
|
}
|
|
var config = new RunConfig(distro, primaryLanguage, secondaryLanguage, startingCards.Select(FindCard).ToList(), equipped, seed, distroVersion);
|
|
List<CardInstance> restoredDeck = deck.Select(entry => RestoreCard(entry, FindCard)).ToList();
|
|
Require(restoredDeck.Select(card => card.InstanceId).Distinct().Count() == restoredDeck.Count, "Duplicate run card identity.");
|
|
List<RepositoryOffer> restoredOffers = new();
|
|
foreach (CheckpointOffer entry in offers)
|
|
{
|
|
Require(entry != null && entry.price >= 0 && Enum.IsDefined(typeof(RepositoryOfferKind), entry.kind), "Invalid repository offer.");
|
|
RepositoryOffer offer;
|
|
switch (entry.kind)
|
|
{
|
|
case RepositoryOfferKind.NewCard:
|
|
offer = RepositoryOffer.NewCard(FindCard(entry.cardId), entry.price);
|
|
break;
|
|
case RepositoryOfferKind.CardUpgrade:
|
|
Require(Enum.IsDefined(typeof(CardUpgradeKind), entry.cardUpgrade), "Invalid card upgrade.");
|
|
CardInstance target = restoredDeck.FirstOrDefault(card => card.InstanceId == entry.targetId)
|
|
?? RestoreCard(entry.detachedTarget, FindCard);
|
|
offer = RepositoryOffer.CardUpgrade(target, entry.cardUpgrade, entry.price);
|
|
break;
|
|
default:
|
|
Require(Enum.IsDefined(typeof(RunStatUpgradeKind), entry.statUpgrade), "Invalid stat upgrade.");
|
|
offer = RepositoryOffer.StatUpgrade(entry.statUpgrade, entry.price);
|
|
break;
|
|
}
|
|
if (entry.sold) offer.MarkSold();
|
|
restoredOffers.Add(offer);
|
|
}
|
|
fullCombat?.Prepare(FindCard, restoredDeck);
|
|
return new ResolvedRunCheckpoint(this, config, restoredDeck, restoredOffers);
|
|
}
|
|
|
|
private static CardInstance RestoreCard(CheckpointCard entry, Func<string, CardDefinition> find)
|
|
{
|
|
Require(entry != null && Guid.TryParseExact(entry.instanceId, "N", out _), "Invalid run card.");
|
|
Require(entry.costDelta <= 0 && entry.magnitude >= 0 && entry.drawRider >= 0 && entry.upgradeLevel >= 0,
|
|
"Invalid card upgrades.");
|
|
CardInstance card = new(find(entry.cardId));
|
|
card.RestoreRunState(entry.instanceId, entry.costDelta, entry.magnitude, entry.drawRider, entry.upgradeLevel);
|
|
return card;
|
|
}
|
|
|
|
internal static void Require(bool valid, string message)
|
|
{
|
|
if (!valid) throw new InvalidDataException(message);
|
|
}
|
|
}
|
|
|
|
public sealed class ResolvedRunCheckpoint
|
|
{
|
|
public RunCheckpoint Snapshot { get; }
|
|
public RunConfig Config { get; }
|
|
public IReadOnlyList<CardInstance> Deck { get; }
|
|
public IReadOnlyList<RepositoryOffer> Offers { get; }
|
|
internal ResolvedRunCheckpoint(RunCheckpoint snapshot, RunConfig config, List<CardInstance> deck, List<RepositoryOffer> offers)
|
|
{ Snapshot = snapshot; Config = config; Deck = deck; Offers = offers; }
|
|
}
|
|
|
|
[Serializable]
|
|
public sealed class CheckpointCard
|
|
{
|
|
public string cardId, instanceId;
|
|
public int costDelta, magnitude, drawRider, upgradeLevel;
|
|
public static CheckpointCard Capture(CardInstance card) => new()
|
|
{
|
|
cardId = card.Definition.Id, instanceId = card.InstanceId, costDelta = card.PermanentCostDelta,
|
|
magnitude = card.MagnitudeBonus, drawRider = card.DrawRider, upgradeLevel = card.UpgradeLevel
|
|
};
|
|
}
|
|
|
|
[Serializable]
|
|
public sealed class CheckpointOffer
|
|
{
|
|
public RepositoryOfferKind kind;
|
|
public string cardId, targetId;
|
|
public CheckpointCard detachedTarget;
|
|
public CardUpgradeKind cardUpgrade;
|
|
public RunStatUpgradeKind statUpgrade;
|
|
public int price;
|
|
public bool sold;
|
|
}
|
|
|
|
[Serializable]
|
|
public sealed class CheckpointCombat
|
|
{
|
|
public int uptime, shield, cycles;
|
|
public int randomSeed, randomDraws;
|
|
public bool ubuntuRefillUsed, interpreterShieldUsed, nativeDamageUsed;
|
|
public float fedoraCrashChance;
|
|
public int javaCardsPlayed, rawhideCharges, repeatCharges, nextTurnCycles;
|
|
public List<CheckpointDelayedEffect> delayed = new();
|
|
|
|
internal void Validate()
|
|
{
|
|
RunCheckpoint.Require(uptime > 0 && shield >= 0 && cycles >= 0 && randomDraws >= 0 && randomDraws <= 10000000,
|
|
"Invalid combat boundary state.");
|
|
RunCheckpoint.Require(!float.IsNaN(fedoraCrashChance) && !float.IsInfinity(fedoraCrashChance)
|
|
&& fedoraCrashChance >= 0 && fedoraCrashChance <= 100 && javaCardsPlayed >= 0 && rawhideCharges >= 0
|
|
&& repeatCharges >= 0 && nextTurnCycles >= 0 && delayed != null && delayed.Count <= 10000, "Invalid carried combat effects.");
|
|
foreach (CheckpointDelayedEffect effect in delayed)
|
|
RunCheckpoint.Require(effect != null && (effect.kind == 0 || effect.kind == 1) && effect.rounds > 0
|
|
&& effect.amount >= 0, "Invalid delayed effect.");
|
|
}
|
|
}
|
|
|
|
[Serializable]
|
|
public sealed class CheckpointDelayedEffect { public int kind, amount, rounds; }
|
|
|
|
public static class RunCheckpointService
|
|
{
|
|
public static void SaveAndSuspend(SaveService saves, RunManager run, CombatManager combat)
|
|
{
|
|
RunCheckpoint.Require(run.CurrentConfig?.IsTutorial != true, "Training uses its separate shop checkpoint.");
|
|
RunCheckpoint snapshot = run.CaptureCheckpoint(combat);
|
|
SaveData data = saves.Load();
|
|
data.activeRun = snapshot;
|
|
LanguageUnlock.RecordCampaignClear(data, run.CurrentConfig, run.Journey, run.WavesCleared);
|
|
saves.Save(data);
|
|
run.MarkSuspended(); // Never suppress settlement or leave the scene on a failed save.
|
|
}
|
|
|
|
public static ResolvedRunCheckpoint PrepareResume(SaveService saves, DistroDatabase distros, CardDatabase cards,
|
|
LanguageDeckDatabase languages, PackageDatabase packages)
|
|
{
|
|
RunCheckpoint snapshot = saves.Load().activeRun;
|
|
RunCheckpoint.Require(snapshot != null, "No saved run is available.");
|
|
return snapshot.Resolve(distros, cards, languages, packages);
|
|
}
|
|
|
|
public static void Consume(SaveService saves, ResolvedRunCheckpoint resume)
|
|
{
|
|
SaveData data = saves.Load();
|
|
RunCheckpoint.Require(data.activeRun != null && data.activeRun.runId == resume.Snapshot.runId
|
|
&& data.activeRun.savedUtc == resume.Snapshot.savedUtc, "The saved run changed. Return to the menu and retry.");
|
|
data.activeRun = null;
|
|
saves.Save(data); // Claim once before play, preventing replaying the same banked rewards.
|
|
}
|
|
}
|
|
}
|