Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

23.4 KB
Raw Blame
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Statecraft.Sim
{
    public sealed class SaveException : Exception
    {
        /// <summary><see cref="Code"/> of a save made under the rules before this build's (a schema 1 save, or ruleset legacy
        /// in the GDD game): R-SAVE-001.</summary>
        public const string OlderRules = "older_rules";
        /// <summary><see cref="Code"/> of a save made by a newer version of the game: a newer schema, or a ruleset this build
        /// does not know (R-SAVE-002).</summary>
        public const string NewerVersion = "newer_version";

        /// <summary>1-based line of the save text the error is on (0 when it concerns the whole save).</summary>
        public int Line { get; }
        /// <summary>A stable refusal code the UI translates (<see cref="OlderRules"/>, <see cref="NewerVersion"/>), or null for a
        /// damaged save, whose reason the UI words itself. The English message never asks the player to start a new game:
        /// the UI says that once (N4).</summary>
        public string? Code { get; }
        public SaveException(int line, string message, string? code = null)
            : base(line > 0 ? FormattableString.Invariant($"line {line}: {message}") : message) { Line = line; Code = code; }
        /// <summary>A save whose replay threw <paramref name="inner"/>: kept, with its stack, for the log (#631).</summary>
        public SaveException(string message, Exception inner) : base(message, inner) { }
    }

    /// <summary>
    /// A save is seed + command log + content hash + schema version (spec section 3); loading replays it. Text format,
    /// one item per line:
    ///   statecraft-save 6          every ruleset (#2544); earlier: 5 for every ruleset (#2605), before that 3 for legacy and
    ///                              gdd-0.1, 4 for gdd-0.3, 1 with no ruleset line (legacy)
    ///   content &lt;hex&gt;             Content.Hash of the content it was played with
    ///   seed &lt;ulong&gt;  /  mode Historical
    ///   ruleset legacy|gdd-0.1|gdd-0.3  the rules it was played under (Content.Ruleset); another ruleset refuses it (R-SAVE-001),
    ///                              and one this build does not know was made by a newer version (R-SAVE-002)
    ///   turn                       starts the next turn's command list (one per Simulation.Step)
    ///   &lt;command&gt; ...              policy ID LEVEL | budget OFFICE=SHARE,... | event ID OPTION | mobilize LEVEL |
    ///                              security DELTA | appoint OFFICE PERSON | map ACTION Q R | work CITY ROLE N |
    ///                              train CITY TRACK N | untrain COHORT | pioneer UNIT ACTION SITE | stop UNIT |
    ///                              project KIND CITY Q R | unproject PROJECT | arms N | dollars N |
    ///                              capture SETTLEMENT OUTCOME
    ///   open                       starts the turn in progress's committed command list; it comes after every turn
    ///   end &lt;hex&gt;                 GameState.Hash() after the last turn (checks the replay)
    /// Doubles are IEEE bit patterns in hex, so replays are exact; strings are percent-escaped (Uri.EscapeDataString).
    /// </summary>
    public sealed class SaveGame
    {
        /// <summary>The schema every new save is written in, whatever its ruleset. #2605 made it 5 (the state records the soft
        /// events the cap left waiting); #2544 made it 6 (a player's order to a unit in an operation cancels the operation's
        /// remaining orders, R-ENEMY-009). Either way a replay of an older save can end elsewhere, and GameSession.Load says so
        /// instead of refusing (R-SAVE-005, R-SAVE-006).</summary>
        public const int SchemaVersion = 6;
        /// <summary>The schema #2605 introduced and every ruleset wrote until <see cref="SchemaVersion"/>. A save in it or later
        /// always has its ending cards (#2536) and lost markers (#2542), so GameSession.Load allows those differences only below it.</summary>
        public const int SoftEventCapSchemaVersion = 5;
        /// <summary>The last schema written before <see cref="SoftEventCapSchemaVersion"/>: legacy and gdd-0.1 wrote 3, gdd-0.3 wrote 4 (#1687).</summary>
        const int LegacyPreviousSchemaVersion = 3, Gdd03PreviousSchemaVersion = 4;
        /// <summary>The ruleset of the legacy loop (Content.Ruleset).</summary>
        public const string LegacyRuleset = "legacy";
        /// <summary>The ruleset of the GDD v0.1 loop (eras.yaml systems.loop: gdd).</summary>
        public const string GddRuleset = "gdd-0.1";
        /// <summary>GDD v0.3 save identity only; this does not switch the live simulation/content.</summary>
        public const string Gdd03Ruleset = "gdd-0.3";

        static bool KnownRuleset(string ruleset) => ruleset == LegacyRuleset || ruleset == GddRuleset || ruleset == Gdd03Ruleset;
        /// <summary>Turns are at least a week long, so 2000 turns is 38 years, far past any content; a save with more is hostile or damaged.</summary>
        public const int MaxTurns = 2000;
        const string Magic = "statecraft-save";

        /// <summary>Each turn as its canonical command lines. The save keeps text, not the caller's objects, so nothing
        /// outside can change a recorded turn; <see cref="Turns"/> parses fresh copies on demand.</summary>
        readonly List<List<string>> turns = new List<List<string>>();
        readonly List<string> open = new List<string>();

        /// <summary>The schema version parsed from this save; a new save uses <see cref="SchemaVersion"/>.</summary>
        public int Version { get; private set; }
        public string ContentHash { get; }
        public ulong Seed { get; }
        public Mode Mode { get; }
        /// <summary>The ruleset the game was played under: <see cref="LegacyRuleset"/>, <see cref="GddRuleset"/> or <see cref="Gdd03Ruleset"/> (R-SAVE-001).</summary>
        public string Ruleset { get; }
        /// <summary>The recorded turns as new command objects each time it is read (changing them changes nothing in the save).</summary>
        public IReadOnlyList<IReadOnlyList<Command>> Turns =>
            turns.Select(t => (IReadOnlyList<Command>)t.Select(l => ParseCommand(0, l)).ToList().AsReadOnly()).ToList().AsReadOnly();
        /// <summary>The open turn's committed orders as new command objects each time it is read (R-SAVE-003).</summary>
        public IReadOnlyList<Command> Open => open.Select(l => ParseCommand(0, l)).ToList().AsReadOnly();
        /// <summary>GameState.Hash() after the last recorded turn (the new game's hash before any turn).</summary>
        public string FinalHash { get; private set; }

        public SaveGame(string contentHash, ulong seed, Mode mode, string ruleset, string initialHash)
        {
            ContentHash = contentHash ?? throw new ArgumentNullException(nameof(contentHash));
            if (!KnownRuleset(ruleset)) throw new ArgumentException($"unknown ruleset '{ruleset}'", nameof(ruleset));
            Version = SchemaVersion; Seed = seed; Mode = mode; Ruleset = ruleset;
            FinalHash = initialHash ?? throw new ArgumentNullException(nameof(initialHash));
        }

        /// <summary>Appends one turn: the commands passed to Simulation.Step and the state it returned.</summary>
        internal void Record(IReadOnlyList<Command> commands, GameState after)
        {
            if (commands == null) throw new ArgumentNullException(nameof(commands));
            if (after == null) throw new ArgumentNullException(nameof(after));
            // A recorded turn is immutable: the caller keeps its own objects (an AllocateBudget's dictionary is theirs to reuse).
            turns.Add(commands.Select(Format).ToList());
            FinalHash = after.Hash();
            open.Clear();
        }

        /// <summary>Replaces the turn in progress with canonical copies of its committed orders (R-SAVE-003).</summary>
        internal void SetOpen(IReadOnlyList<Command> commands)
        {
            if (commands == null) throw new ArgumentNullException(nameof(commands));
            var lines = commands.Select(Format).ToList();
            open.Clear();
            open.AddRange(lines);
        }

        public string Write()
        {
            var sb = new StringBuilder();
            sb.Append(Magic).Append(' ').Append(SchemaVersion.ToString(CultureInfo.InvariantCulture)).Append('\n');
            sb.Append("content ").Append(ContentHash).Append('\n');
            sb.Append("seed ").Append(Seed.ToString(CultureInfo.InvariantCulture)).Append('\n');
            sb.Append("mode ").Append(Mode.ToString()).Append('\n');
            sb.Append("ruleset ").Append(Ruleset).Append('\n');
            foreach (var t in turns)
            {
                sb.Append("turn\n");
                foreach (var line in t) sb.Append(line).Append('\n');
            }
            if (open.Count > 0)
            {
                sb.Append("open\n");
                foreach (var line in open) sb.Append(line).Append('\n');
            }
            sb.Append("end ").Append(FinalHash).Append('\n');
            return sb.ToString();
        }

        static string Esc(string s) => SaveText.Escape(s);
        static string Num(double v) => BitConverter.DoubleToInt64Bits(v).ToString("X16", CultureInfo.InvariantCulture);
        static string Int(int v) => v.ToString(CultureInfo.InvariantCulture);

        static string Format(Command cmd) => cmd switch
        {
            SetPolicy p => $"policy {Esc(p.Policy)} {Num(p.Level)}",
            AllocateBudget b => "budget " + (b.Shares == null ? "~" : b.Shares.Count == 0 ? "-" :
                string.Join(",", b.Shares.OrderBy(kv => kv.Key, StringComparer.Ordinal).Select(kv => Esc(kv.Key) + "=" + Num(kv.Value)))),
            ChooseEventOption e => $"event {Esc(e.EventId)} {Esc(e.OptionId)}",
            SetMobilization m => $"mobilize {Num(m.Level)}",
            SecurityOrder o => $"security {Int(o.Delta)}",
            Appoint a => $"appoint {Esc(a.Office)} {Esc(a.Person)}",
            MapAction m => $"map {Esc(m.Action)} {Int(m.Q)} {Int(m.R)}",
            AssignWorkers w => $"work {Esc(w.City)} {Esc(w.Role)} {Int(w.Count)}",
            Train t => $"train {Esc(t.City)} {Esc(t.Track)} {Int(t.Count)}",
            CancelTraining t => $"untrain {Int(t.Cohort)}",
            ReturnCraftsmen r => $"retcraft {Esc(r.City)} {Int(r.Count)}",
            ReassignCraftsmen r => $"regcraft {Esc(r.City)} {Int(r.Count)}",
            ReassignPioneers r => $"regpioneer {Esc(r.City)} {Esc(r.Track)} {Int(r.Count)}",
            Reinforce r => $"reinforce {Int(r.Unit)} {Esc(r.City)} {Int(r.Count)}",
            PioneerWork p => $"pioneer {Int(p.Unit)} {Esc(p.Action)} {Esc(p.Site)}",
            StopWork w => $"stop {Int(w.Unit)}",
            UnitOrder o => $"order {Int(o.Unit)} {Esc(o.Order)}" + (o.Q is int q && o.R is int r ? $" {Int(q)} {Int(r)}" : ""),
            StartProject p => $"project {Esc(p.ProjectKind)} {Esc(p.City)} {Int(p.Q)} {Int(p.R)}",
            CancelProject p => $"unproject {Int(p.Project)}",
            Move m => $"move {Int(m.Unit)} {Int(m.Q)} {Int(m.R)}",
            BuyArms a => $"arms {Int(a.Count)}",
            ConvertDollars d => $"dollars {Int(d.Amount)}",
            ResolveCapture r => $"capture {Esc(r.Settlement)} {Esc(r.Outcome)}",
            EndOccupation e => $"endocc {Esc(e.Settlement)} {Esc(e.Outcome)}",
            _ => throw new ArgumentException($"Cannot save command kind '{cmd.Kind}'", nameof(cmd)),
        };

        /// <summary>Parses save text; any malformed line throws SaveException naming the line. When supplied, expectedRuleset enforces R-SAVE-001 before any replay.</summary>
        public static SaveGame Parse(string text, string? expectedRuleset = null)
        {
            if (text == null) throw new ArgumentNullException(nameof(text));
            if (expectedRuleset != null && !KnownRuleset(expectedRuleset))
                throw new ArgumentException($"unknown ruleset '{expectedRuleset}'", nameof(expectedRuleset));
            if (text.Length > 0 && text[0] == '\uFEFF') text = text.Substring(1);   // a byte-order mark is not part of the save
            var lines = text.Replace("\r\n", "\n").Split('\n');
            int n = lines.Length;
            while (n > 0 && lines[n - 1] == "") n--;
            if (n < 5) throw new SaveException(0, "Not a Statecraft save (too short)");
            if (lines.Take(n).Count(l => l == "turn") > MaxTurns)
                throw new SaveException(0, FormattableString.Invariant($"save has {lines.Take(n).Count(l => l == "turn")} turns; the most this game plays is {MaxTurns}"));
            string[] Head(int i, string key, int parts)
            {
                var f = lines[i].Split(' ');
                if (f[0] != key || f.Length != parts) throw new SaveException(i + 1, $"expected '{key}'");
                return f;
            }
            var magic = Head(0, Magic, 2);
            if (!int.TryParse(magic[1], NumberStyles.None, CultureInfo.InvariantCulture, out var version)) throw new SaveException(1, "bad schema version");
            if (version > SchemaVersion) throw new SaveException(1, FormattableString.Invariant($"save schema version {version} is newer than this game ({SchemaVersion})"), SaveException.NewerVersion);
            if (version < 1) throw new SaveException(1, FormattableString.Invariant($"unknown save schema version {version}"));
            var content = Head(1, "content", 2)[1];
            if (!IsHash(content)) throw new SaveException(2, "bad content hash");
            if (!ulong.TryParse(Head(2, "seed", 2)[1], NumberStyles.None, CultureInfo.InvariantCulture, out var seed)) throw new SaveException(3, "bad seed");
            var modeName = Head(3, "mode", 2)[1];
            if (!Enum.GetNames(typeof(Mode)).Contains(modeName)) throw new SaveException(4, "bad mode");   // names only: Enum.TryParse would accept "0"
            var mode = (Mode)Enum.Parse(typeof(Mode), modeName);
            if (mode == Mode.Open) throw new SaveException(4, "mode Open is not supported");   // Simulation.NewGame cannot start it before M4
            var first = 4;   // the first line after the header
            var ruleset = LegacyRuleset;
            if (version >= 2)
            {
                if (n < 6) throw new SaveException(0, "Not a Statecraft save (too short)");
                ruleset = Head(4, "ruleset", 2)[1];
                // R-SAVE-002 (N2): a ruleset this build does not know comes from a newer version, like a newer schema.
                if (!KnownRuleset(ruleset))
                    throw new SaveException(5, $"This save was made with a newer version of the game (ruleset '{ruleset}').", SaveException.NewerVersion);
                first = 5;
            }
            // #1687, #2605, R-SAVE-001/002: every ruleset wrote schema 5 (#2605) and now 6 (#2544). Before schema 5, schema 4
            // belonged only to the isolated gdd-0.3 envelope, legacy wrote 1 to 3 and gdd-0.1 2 to 3 (schema 1 has no ruleset
            // line, so it is legacy). No build wrote another pairing, so such a save was edited: damage, not older or newer rules.
            if (version < SoftEventCapSchemaVersion && (ruleset == Gdd03Ruleset ? version != Gdd03PreviousSchemaVersion : version > LegacyPreviousSchemaVersion))
                throw new SaveException(1, FormattableString.Invariant($"no version of the game wrote a {ruleset} save in schema {version}"));
            // Check compatibility before replay, including gdd-0.1 -> gdd-0.3 as earlier rules.
            if (expectedRuleset != null && ruleset != expectedRuleset)
                throw ruleset == LegacyRuleset || (ruleset == GddRuleset && expectedRuleset == Gdd03Ruleset)
                    ? new SaveException(0, "This save was made with an earlier version of the game's rules.", SaveException.OlderRules)
                    : new SaveException(0, "This save was made with a newer version of the game's rules.", SaveException.NewerVersion);
            var end = Head(n - 1, "end", 2)[1];
            if (!IsHash(end)) throw new SaveException(n, "bad end hash");
            var save = new SaveGame(content, seed, mode, ruleset, end);
            save.Version = version;
            List<string>? current = null;
            bool sawOpen = false;
            for (int i = first; i < n - 1; i++)
            {
                if (version >= 3 && lines[i] == "open")
                {
                    if (sawOpen) throw new SaveException(i + 1, "'open' must come last, once");
                    sawOpen = true; current = save.open; continue;
                }
                if (lines[i] == "turn")
                {
                    if (sawOpen) throw new SaveException(i + 1, "'open' must come last, once");
                    current = new List<string>(); save.turns.Add(current); continue;
                }
                if (current == null) throw new SaveException(i + 1, "command before the first 'turn'");
                var cmd = ParseCommand(i + 1, lines[i]);
                // The open turn holds committed orders only (R-TURN-004); a waiting order there means the save was edited.
                if (ReferenceEquals(current, save.open) && !Simulation.IsInstant(cmd))
                    throw new SaveException(i + 1, "only a move or a unit order other than Send home can be in the open turn");
                current.Add(Format(cmd));   // canonical form, validated now
            }
            return save;
        }

        static bool IsHash(string s) => s.Length == 64 && s.All(ch => (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f'));

        static Command ParseCommand(int line, string text)
        {
            var f = text.Split(' ');
            void Arity(int count) { if (f.Length != count) throw new SaveException(line, $"'{f[0]}' needs {count - 1} values"); }
            string Str(string s)
            {
                return SaveText.Unescape(s) ?? throw new SaveException(line, $"bad text '{s}'");
            }
            double Dbl(string s) => long.TryParse(s, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var bits) && s.Length == 16
                ? BitConverter.Int64BitsToDouble(bits) : throw new SaveException(line, $"bad number '{s}'");
            int I(string s) => int.TryParse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var v) ? v : throw new SaveException(line, $"bad integer '{s}'");
            switch (f[0])
            {
                case "policy": Arity(3); return new SetPolicy(Str(f[1]), Dbl(f[2]));
                case "budget":
                    Arity(2);
                    if (f[1] == "~") return new AllocateBudget(null!);          // a null budget: replays with the same rejection reason
                    var shares = new Dictionary<string, double>();
                    if (f[1] != "-")
                        foreach (var pair in f[1].Split(','))
                        {
                            var kv = pair.Split('=');
                            if (kv.Length != 2) throw new SaveException(line, $"bad budget share '{pair}'");
                            shares[Str(kv[0])] = Dbl(kv[1]);
                        }
                    return new AllocateBudget(shares);
                case "event": Arity(3); return new ChooseEventOption(Str(f[1]), Str(f[2]));
                case "mobilize": Arity(2); return new SetMobilization(Dbl(f[1]));
                case "security": Arity(2); return new SecurityOrder(I(f[1]));
                case "appoint": Arity(3); return new Appoint(Str(f[1]), Str(f[2]));
                case "map": Arity(4); return new MapAction(Str(f[1]), I(f[2]), I(f[3]));
                case "work": Arity(4); return new AssignWorkers(Str(f[1]), Str(f[2]), I(f[3]));
                case "train": Arity(4); return new Train(Str(f[1]), Str(f[2]), I(f[3]));
                case "untrain": Arity(2); return new CancelTraining(I(f[1]));
                case "retcraft": Arity(3); return new ReturnCraftsmen(Str(f[1]), I(f[2]));
                case "regcraft": Arity(3); return new ReassignCraftsmen(Str(f[1]), I(f[2]));
                case "regpioneer": Arity(4); return new ReassignPioneers(Str(f[1]), Str(f[2]), I(f[3]));
                case "reinforce": Arity(4); return new Reinforce(I(f[1]), Str(f[2]), I(f[3]));
                case "pioneer": Arity(4); return new PioneerWork(I(f[1]), Str(f[2]), Str(f[3]));
                case "stop": Arity(2); return new StopWork(I(f[1]));
                case "order":   // an attack carries its hex (R-COMBAT-001); fortify and hold none
                    if (f.Length != 5) Arity(3);
                    return f.Length == 5 ? new UnitOrder(I(f[1]), Str(f[2]), I(f[3]), I(f[4])) : new UnitOrder(I(f[1]), Str(f[2]));
                case "project": Arity(5); return new StartProject(Str(f[1]), Str(f[2]), I(f[3]), I(f[4]));
                case "unproject": Arity(2); return new CancelProject(I(f[1]));
                case "move": Arity(4); return new Move(I(f[1]), I(f[2]), I(f[3]));
                case "arms": Arity(2); return new BuyArms(I(f[1]));
                case "dollars": Arity(2); return new ConvertDollars(I(f[1]));
                case "capture": Arity(3); return new ResolveCapture(Str(f[1]), Str(f[2]));
                case "endocc": Arity(3); return new EndOccupation(Str(f[1]), Str(f[2]));
                default: throw new SaveException(line, $"unknown command '{f[0]}'");
            }
        }
    }

    /// <summary>The save format's own percent-encoding (RFC 3986: unreserved characters stay, everything else is %XX of its
    /// UTF-8 bytes), so a save does not depend on the runtime's Uri class (Mono and .NET differ).</summary>
    internal static class SaveText
    {
        static readonly System.Text.UTF8Encoding Strict = new System.Text.UTF8Encoding(false, true);

        static bool Unreserved(byte b) => (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') || b == '-' || b == '.' || b == '_' || b == '~';

        /// <summary>False for a string that is not valid Unicode text (a lone surrogate), which cannot be saved losslessly.</summary>
        public static bool IsEncodable(string s)
        {
            try { Strict.GetBytes(s); return true; }
            catch (System.Text.EncoderFallbackException) { return false; }
        }

        public static string Escape(string s)
        {
            var sb = new StringBuilder();
            foreach (var b in Strict.GetBytes(s))
            {
                if (Unreserved(b)) sb.Append((char)b);
                else sb.Append('%').Append("0123456789ABCDEF"[b >> 4]).Append("0123456789ABCDEF"[b & 15]);
            }
            return sb.ToString();
        }

        /// <summary>Null when the text has a malformed escape or is not valid UTF-8.</summary>
        public static string? Unescape(string s)
        {
            var bytes = new List<byte>();
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] != '%') { if (s[i] > 127) return null; bytes.Add((byte)s[i]); continue; }
                if (i + 2 >= s.Length) return null;
                int hi = HexVal(s[i + 1]), lo = HexVal(s[i + 2]);
                if (hi < 0 || lo < 0) return null;
                bytes.Add((byte)(hi * 16 + lo));
                i += 2;
            }
            try { return Strict.GetString(bytes.ToArray()); }
            catch (System.Text.DecoderFallbackException) { return null; }
        }

        static int HexVal(char c) => c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1;
    }
}