Files
grass-cutters/Assets/Scripts/Core/SaveSlots.cs
NiemandKG d1c3761e58 Grass Cutters Together: the project as of moon-sweepers f3666f0
A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and
Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date.
Images, audio, models and binaries go through Git LFS (.gitattributes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 18:44:40 +06:00

225 lines
10 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
namespace GrassCutter
{
public struct SlotInfo
{
public bool used;
public double money, shipped, mown;
public DateTime when;
public Difficulty level;
}
/// <summary>
/// Five saves on disk, each in a folder of its own: the game, the mow map and up to five backups, the first a minute in and
/// then one every half hour. A save that can't be read is put right from its newest good backup.
/// Each Steam account has its own folder, <c>saves/&lt;SteamID64&gt;</c>, which Steam Auto-Cloud syncs as
/// <c>WinAppDataLocalLow / GreenHaul/Grass Cutters Together/saves/{64BitSteamID}</c>: two people on one PC never share saves.
/// </summary>
public static class SaveSlots
{
public const int Count = 5, Backups = 5;
const string GameFile = "game.json", MapFile = "mow.bin", OldKey = "grasscutter_save_v2";
[Serializable] class Head { public double money, shipped, mown; public int level; public int[] tiles; }
public static int Current { get; set; }
/// <summary>The game used to be called Grass Cutter and so did its folder. The saves come over once, and the old ones stay where they were.</summary>
static void TakeOldFolder()
{
var old = Path.Combine(Path.GetDirectoryName(Application.persistentDataPath), "Grass Cutter", "saves");
if (Dev || Directory.Exists(Shared) || !Directory.Exists(old)) return;
foreach (var file in Directory.GetFiles(old, "*", SearchOption.AllDirectories))
{
var to = Shared + file.Substring(old.Length);
Directory.CreateDirectory(Path.GetDirectoryName(to));
File.Copy(file, to);
}
}
/// <summary>
/// Slots from before saves were kept per Steam account sit straight in <c>saves</c>. The first account to start the game
/// takes them into its own folder; anyone after starts with empty slots. Checked slot by slot, not by the folder: Steam
/// makes the account folder itself (for <c>steam_autocloud.vdf</c>) before the game ever runs. A slot already played in
/// the account folder stays, and the old one waits under the next free number, or where it is if none is free.
/// </summary>
static void TakeSharedSlots(string mine)
{
if (!Directory.Exists(Shared)) return;
for (int i = 0; i < Count; i++)
{
var from = Path.Combine(Shared, "slot" + (i + 1));
if (!Directory.Exists(from)) continue;
int to = Directory.Exists(Path.Combine(mine, "slot" + (i + 1))) ? FreeSlot(mine) : i;
if (to < 0) { Debug.LogWarning("[Save] no free slot for old slot " + (i + 1) + ", left in " + Shared); continue; }
Directory.CreateDirectory(mine);
Directory.Move(from, Path.Combine(mine, "slot" + (to + 1)));
Debug.Log("[Save] old slot " + (i + 1) + " moved into " + mine + " as slot " + (to + 1));
}
}
static int FreeSlot(string root)
{
for (int i = 0; i < Count; i++) if (!Directory.Exists(Path.Combine(root, "slot" + (i + 1)))) return i;
return -1;
}
static bool Dev => CommandLine.Has("-autodemo") || CommandLine.Has("-mpdemo");
/// <summary>Without Steam (and in test runs) the slots sit straight in here.</summary>
static string Shared => Path.Combine(Application.persistentDataPath, Dev ? "saves_dev" : "saves");
static string _ready;
static string Root
{
get
{
var root = !Dev && SteamManager.Initialized ? Path.Combine(Shared, SteamManager.MySteamId.m_SteamID.ToString()) : Shared;
if (_ready != root)
{
_ready = root;
try
{
TakeOldFolder();
if (root != Shared) TakeSharedSlots(root);
}
catch (IOException e) { Debug.LogWarning("[Save] couldn't bring old saves over: " + e.Message); }
}
return root;
}
}
static string Folder(int slot) => Path.Combine(Root, "slot" + (slot + 1));
static string Copy(int slot, int n) => Path.Combine(Folder(slot), "backup" + (n + 1));
public static string MapPath => Path.Combine(Folder(Current), MapFile);
public static string GamePath => Path.Combine(Folder(Current), GameFile);
// ───────────────────────── writing ─────────────────────────
public static void Write(string json, byte[] map)
{
var dir = Folder(Current);
Directory.CreateDirectory(dir);
Put(Path.Combine(dir, GameFile), Encoding.UTF8.GetBytes(json));
Put(Path.Combine(dir, MapFile), map);
}
/// <summary>Written whole or not at all: a crash halfway leaves the last save as it was.</summary>
static void Put(string path, byte[] data)
{
string tmp = path + ".tmp";
File.WriteAllBytes(tmp, data);
if (File.Exists(path)) File.Delete(path);
File.Move(tmp, path);
}
/// <summary>The current save goes over the oldest of its backups.</summary>
public static void Backup()
{
var dir = Folder(Current);
var game = Path.Combine(dir, GameFile);
if (!File.Exists(game)) return;
int pick = 0;
var oldest = DateTime.MaxValue;
for (int n = 0; n < Backups; n++)
{
var path = Path.Combine(Copy(Current, n), GameFile);
var when = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue;
if (when < oldest) { oldest = when; pick = n; }
}
var to = Copy(Current, pick);
Directory.CreateDirectory(to);
File.Copy(game, Path.Combine(to, GameFile), true);
File.SetLastWriteTimeUtc(Path.Combine(to, GameFile), DateTime.UtcNow);
var map = Path.Combine(dir, MapFile);
if (File.Exists(map)) File.Copy(map, Path.Combine(to, MapFile), true);
}
// ───────────────────────── reading ─────────────────────────
static string Text(string path)
{
try { return File.Exists(path) ? File.ReadAllText(path) : null; }
catch (IOException e) { Debug.LogWarning("[Save] can't read " + path + ": " + e.Message); return null; }
}
static Head Parse(string json)
{
if (string.IsNullOrEmpty(json)) return null;
try
{
var h = JsonUtility.FromJson<Head>(json);
return h != null && h.tiles != null && h.tiles.Length > 0 ? h : null;
}
catch (ArgumentException) { return null; }
}
/// <summary>Backups of a slot, the newest first.</summary>
static List<string> Newest(int slot)
{
var list = new List<string>();
for (int n = 0; n < Backups; n++)
if (File.Exists(Path.Combine(Copy(slot, n), GameFile))) list.Add(Copy(slot, n));
list.Sort((a, b) => File.GetLastWriteTimeUtc(Path.Combine(b, GameFile)).CompareTo(File.GetLastWriteTimeUtc(Path.Combine(a, GameFile))));
return list;
}
/// <summary>The save to load, or null for a new game. A bad one is replaced from its backups first.</summary>
public static string Read()
{
Migrate();
var dir = Folder(Current);
var json = Text(Path.Combine(dir, GameFile));
if (Parse(json) != null) return json;
foreach (var copy in Newest(Current))
{
var old = Text(Path.Combine(copy, GameFile));
if (Parse(old) == null) continue;
Debug.LogWarning("[Save] the save was damaged, restored from " + copy);
File.Copy(Path.Combine(copy, GameFile), Path.Combine(dir, GameFile), true);
if (File.Exists(Path.Combine(copy, MapFile))) File.Copy(Path.Combine(copy, MapFile), Path.Combine(dir, MapFile), true);
return old;
}
return null;
}
/// <summary>Mow maps to fall back on when the slot's own won't load, the newest first.</summary>
public static IEnumerable<string> OlderMaps()
{
foreach (var copy in Newest(Current)) yield return Path.Combine(copy, MapFile);
}
public static SlotInfo Info(int slot)
{
var path = Path.Combine(Folder(slot), GameFile);
var h = Parse(Text(path));
if (h == null) return new SlotInfo { used = File.Exists(path) };
return new SlotInfo { used = true, money = h.money, shipped = h.shipped, mown = h.mown, level = (Difficulty)h.level, when = File.GetLastWriteTime(path) };
}
public static void Delete(int slot)
{
if (Directory.Exists(Folder(slot))) Directory.Delete(Folder(slot), true);
}
/// <summary>Saves from before the slots lived in the registry: they become the first slot.</summary>
static void Migrate()
{
if (Dev || !PlayerPrefs.HasKey(OldKey)) return;
var dir = Folder(0);
if (!File.Exists(Path.Combine(dir, GameFile)))
{
Directory.CreateDirectory(dir);
File.WriteAllText(Path.Combine(dir, GameFile), PlayerPrefs.GetString(OldKey));
var map = Path.Combine(Application.persistentDataPath, MapFile);
if (File.Exists(map)) File.Move(map, Path.Combine(dir, MapFile));
}
PlayerPrefs.DeleteKey(OldKey);
PlayerPrefs.Save();
}
}
}