diff --git a/Assets/Script/SaveGameCoordinator.cs b/Assets/Script/SaveGameCoordinator.cs new file mode 100644 index 0000000..74f5623 --- /dev/null +++ b/Assets/Script/SaveGameCoordinator.cs @@ -0,0 +1,181 @@ +using System; +using System.IO; +using UnityEngine; +using UnityEngine.SceneManagement; +using ZoneUA.Persistence; + +[DisallowMultipleComponent] +public sealed class SaveGameCoordinator : MonoBehaviour +{ + [SerializeField] private Transform playerRoot; + [SerializeField] private Health playerHealth; + [SerializeField] private WeaponSwitcher weaponSwitcher; + [SerializeField] private SceneBootstrapper sceneBootstrapper; + [SerializeField] private string defaultSlot = "autosave"; + [SerializeField] private int currentWorldSeed; + [SerializeField, Min(0f)] private float autosaveIntervalSeconds = 120f; + [SerializeField] private bool autosaveOnApplicationPause = true; + [SerializeField] private bool autosaveOnApplicationQuit = true; + + private SaveSlotStore store; + private SaveGameData pendingRestore; + private string pendingSlotId = string.Empty; + private float autosaveTimer; + + public int CurrentWorldSeed => currentWorldSeed; + public event Action Saved; + public event Action Loaded; + public event Action SaveFailed; + public event Action LoadFailed; + + private void Awake() + { + store = new SaveSlotStore(Path.Combine(Application.persistentDataPath, "Saves")); + ResolveReferences(); + } + + private void OnEnable() + { + if (sceneBootstrapper != null) sceneBootstrapper.SceneActivated += OnSceneActivated; + } + + private void OnDisable() + { + if (sceneBootstrapper != null) sceneBootstrapper.SceneActivated -= OnSceneActivated; + } + + private void Update() + { + if (autosaveIntervalSeconds <= 0f) return; + autosaveTimer += Time.unscaledDeltaTime; + if (autosaveTimer < autosaveIntervalSeconds) return; + autosaveTimer = 0f; + Save(defaultSlot); + } + + public void SetWorldSeed(int seed) => currentWorldSeed = seed; + + [ContextMenu("Save Default Slot")] + public void SaveDefault() => Save(defaultSlot); + + [ContextMenu("Load Default Slot")] + public void LoadDefault() => Load(defaultSlot); + + public bool Save(string slotId) + { + try + { + ResolveReferences(); + store.Save(slotId, Capture(slotId)); + Saved?.Invoke(slotId); + return true; + } + catch (Exception exception) + { + Debug.LogException(exception, this); + SaveFailed?.Invoke(exception.Message); + return false; + } + } + + public bool Load(string slotId) + { + if (!store.TryLoad(slotId, out SaveGameData data)) + { + LoadFailed?.Invoke($"Save slot '{slotId}' is missing or invalid."); + return false; + } + + pendingRestore = data; + pendingSlotId = slotId; + string currentScene = SceneManager.GetActiveScene().name; + if (sceneBootstrapper != null && !string.IsNullOrWhiteSpace(data.activeScene) && data.activeScene != currentScene) + { + if (!sceneBootstrapper.LoadScene(data.activeScene)) + { + pendingRestore = null; + pendingSlotId = string.Empty; + LoadFailed?.Invoke($"Could not start loading scene '{data.activeScene}'."); + return false; + } + return true; + } + + ApplyPendingRestore(); + return true; + } + + public bool Delete(string slotId) + { + store.Delete(slotId); + return !store.Exists(slotId); + } + + private SaveGameData Capture(string slotId) + { + var data = new SaveGameData + { + activeScene = SceneManager.GetActiveScene().name, + worldSeed = currentWorldSeed, + player = new PlayerSaveData() + }; + data.Stamp(slotId, DateTime.UtcNow); + if (playerRoot != null) + { + data.player.position = playerRoot.position; + data.player.rotationZ = playerRoot.eulerAngles.z; + } + if (playerHealth != null) + { + data.player.currentHealth = playerHealth.CurrentHealth; + data.player.maximumHealth = playerHealth.MaximumHealth; + } + if (weaponSwitcher != null) data.player.activeWeaponIndex = weaponSwitcher.ActiveWeaponIndex; + return data; + } + + private void ApplyPendingRestore() + { + if (pendingRestore == null) return; + ResolveReferences(); + currentWorldSeed = pendingRestore.worldSeed; + PlayerSaveData player = pendingRestore.player ?? new PlayerSaveData(); + if (playerRoot != null) + playerRoot.SetPositionAndRotation(player.position, Quaternion.Euler(0f, 0f, player.rotationZ)); + if (playerHealth != null) + { + playerHealth.SetMaximumHealth(player.maximumHealth); + playerHealth.SetHealth(player.currentHealth); + } + if (weaponSwitcher != null && player.activeWeaponIndex >= 0) + weaponSwitcher.RequestSwitch(player.activeWeaponIndex); + + string loadedSlot = pendingSlotId; + pendingRestore = null; + pendingSlotId = string.Empty; + Loaded?.Invoke(loadedSlot); + } + + private void OnSceneActivated(string sceneName) => ApplyPendingRestore(); + + private void ResolveReferences() + { + playerRoot ??= playerHealth != null ? playerHealth.transform : null; + if (playerRoot != null) + { + playerHealth ??= playerRoot.GetComponent(); + weaponSwitcher ??= playerRoot.GetComponent(); + } + sceneBootstrapper ??= SceneBootstrapper.Instance; + } + + private void OnApplicationPause(bool paused) + { + if (paused && autosaveOnApplicationPause) Save(defaultSlot); + } + + private void OnApplicationQuit() + { + if (autosaveOnApplicationQuit) Save(defaultSlot); + } +} diff --git a/Assets/Script/SaveGameCoordinator.cs.meta b/Assets/Script/SaveGameCoordinator.cs.meta new file mode 100644 index 0000000..2e059f6 --- /dev/null +++ b/Assets/Script/SaveGameCoordinator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e3cc48e7145944efa7f42891d44233b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: -1500 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Script/WeaponSwitcher.cs b/Assets/Script/WeaponSwitcher.cs index 4edb2bd..dedee92 100644 --- a/Assets/Script/WeaponSwitcher.cs +++ b/Assets/Script/WeaponSwitcher.cs @@ -26,6 +26,7 @@ public sealed class WeaponSwitcher : MonoBehaviour public GameObject SelectedWeapon => selectedWeapon; public WeaponController ActiveWeaponController { get; private set; } public bool IsSwitching => isSwitching; + public int ActiveWeaponIndex => Array.IndexOf(weapons, selectedWeapon); private void Awake() { @@ -34,11 +35,7 @@ private void Awake() for (int i = 0; i < weapons.Length; i++) { - if (weapons[i] == null) - { - continue; - } - + if (weapons[i] == null) continue; animators[i] = weapons[i].GetComponent(); controllers[i] = weapons[i].GetComponent(); } @@ -54,42 +51,22 @@ private void Start() return; } } - SetActiveWeapon(null, null); } public void RequestSwitch(int index) { - if (isSwitching || index < 0 || index >= weapons.Length || weapons[index] == null) - { - return; - } - - if (selectedWeapon == weapons[index]) - { - return; - } - - if (switchRoutine != null) - { - StopCoroutine(switchRoutine); - } - - switchRoutine = StartCoroutine(SwitchWeaponRoutine( - weapons[index], - animators[index], - controllers[index])); + if (isSwitching || index < 0 || index >= weapons.Length || weapons[index] == null) return; + if (selectedWeapon == weapons[index]) return; + if (switchRoutine != null) StopCoroutine(switchRoutine); + switchRoutine = StartCoroutine(SwitchWeaponRoutine(weapons[index], animators[index], controllers[index])); } - private IEnumerator SwitchWeaponRoutine( - GameObject newWeapon, - Animator newAnimator, - WeaponController newController) + private IEnumerator SwitchWeaponRoutine(GameObject newWeapon, Animator newAnimator, WeaponController newController) { isSwitching = true; ActiveWeaponController?.StopFire(); SetAllWeaponsActive(false); - newWeapon.SetActive(true); SetActiveWeapon(newWeapon, newController); @@ -99,18 +76,9 @@ private IEnumerator SwitchWeaponRoutine( newAnimator.SetTrigger(SwitchHash); } - if (switchingTime > 0f) - { - yield return new WaitForSeconds(switchingTime); - } - + if (switchingTime > 0f) yield return new WaitForSeconds(switchingTime); newController?.WeaponChanged(); - - if (newAnimator != null) - { - newAnimator.enabled = false; - } - + if (newAnimator != null) newAnimator.enabled = false; isSwitching = false; switchRoutine = null; } @@ -122,7 +90,6 @@ public void HideAllWeapons() StopCoroutine(switchRoutine); switchRoutine = null; } - ActiveWeaponController?.StopFire(); isSwitching = false; SetAllWeaponsActive(false); @@ -131,11 +98,7 @@ public void HideAllWeapons() private void SetActiveWeapon(GameObject weaponObject, WeaponController controller) { - if (selectedWeapon == weaponObject && ActiveWeaponController == controller) - { - return; - } - + if (selectedWeapon == weaponObject && ActiveWeaponController == controller) return; selectedWeapon = weaponObject; ActiveWeaponController = controller; ActiveWeaponChanged?.Invoke(controller); @@ -144,21 +107,10 @@ private void SetActiveWeapon(GameObject weaponObject, WeaponController controlle private void SetAllWeaponsActive(bool state) { for (int i = 0; i < weapons.Length; i++) - { - if (weapons[i] != null) - { - weapons[i].SetActive(state); - } - } + if (weapons[i] != null) weapons[i].SetActive(state); } - private void OnDisable() - { - ActiveWeaponController?.StopFire(); - } + private void OnDisable() => ActiveWeaponController?.StopFire(); - private void OnValidate() - { - switchingTime = Mathf.Max(0f, switchingTime); - } + private void OnValidate() => switchingTime = Mathf.Max(0f, switchingTime); } diff --git a/Assets/_ZoneUA/Runtime/Persistence.meta b/Assets/_ZoneUA/Runtime/Persistence.meta new file mode 100644 index 0000000..9b72e8a --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 53fd351065874dfaa36ce05250b7bdc3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs b/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs new file mode 100644 index 0000000..4eafc5d --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs @@ -0,0 +1,36 @@ +using System; +using UnityEngine; + +namespace ZoneUA.Persistence +{ + [Serializable] + public sealed class SaveGameData + { + public const int CurrentSchemaVersion = 2; + + public int schemaVersion = CurrentSchemaVersion; + public string saveId = string.Empty; + public string savedAtUtc = string.Empty; + public string activeScene = string.Empty; + public int worldSeed; + public PlayerSaveData player = new PlayerSaveData(); + + public void Stamp(string id, DateTime utcNow) + { + schemaVersion = CurrentSchemaVersion; + saveId = id ?? string.Empty; + savedAtUtc = utcNow.ToUniversalTime().ToString("O"); + player ??= new PlayerSaveData(); + } + } + + [Serializable] + public sealed class PlayerSaveData + { + public Vector3 position; + public float rotationZ; + public int currentHealth = 100; + public int maximumHealth = 100; + public int activeWeaponIndex = -1; + } +} diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs.meta b/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs.meta new file mode 100644 index 0000000..623ac49 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveGameData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 18f27aa5b38d4be9904bb7dc4b72c6a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs b/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs new file mode 100644 index 0000000..942d4ae --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs @@ -0,0 +1,27 @@ +using System; + +namespace ZoneUA.Persistence +{ + public static class SaveGameMigrator + { + public static SaveGameData Migrate(SaveGameData data) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + if (data.schemaVersion <= 0) data.schemaVersion = 1; + if (data.schemaVersion > SaveGameData.CurrentSchemaVersion) + throw new InvalidOperationException($"Save schema {data.schemaVersion} is newer than supported schema {SaveGameData.CurrentSchemaVersion}."); + + if (data.schemaVersion == 1) + { + data.player ??= new PlayerSaveData(); + if (data.player.maximumHealth <= 0) data.player.maximumHealth = Math.Max(1, data.player.currentHealth); + data.schemaVersion = 2; + } + + data.player ??= new PlayerSaveData(); + data.player.maximumHealth = Math.Max(1, data.player.maximumHealth); + data.player.currentHealth = Math.Clamp(data.player.currentHealth, 0, data.player.maximumHealth); + return data; + } + } +} diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs.meta b/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs.meta new file mode 100644 index 0000000..6162c92 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveGameMigrator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 93d3f03654ac491da63aa6d7c5cd9d74 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs b/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs new file mode 100644 index 0000000..bfb7814 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs @@ -0,0 +1,102 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using UnityEngine; + +namespace ZoneUA.Persistence +{ + [Serializable] + public sealed class SaveEnvelope + { + public string checksum = string.Empty; + public string payload = string.Empty; + } + + public sealed class SaveSlotStore + { + private readonly string rootDirectory; + + public SaveSlotStore(string rootDirectory) + { + this.rootDirectory = string.IsNullOrWhiteSpace(rootDirectory) + ? throw new ArgumentException("A save root directory is required.", nameof(rootDirectory)) + : rootDirectory; + } + + public string GetSlotPath(string slotId) => Path.Combine(rootDirectory, Sanitize(slotId) + ".json"); + public string GetBackupPath(string slotId) => GetSlotPath(slotId) + ".bak"; + + public void Save(string slotId, SaveGameData data) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + Directory.CreateDirectory(rootDirectory); + string payload = JsonUtility.ToJson(data, false); + var envelope = new SaveEnvelope { payload = payload, checksum = ComputeChecksum(payload) }; + string serialized = JsonUtility.ToJson(envelope, true); + string path = GetSlotPath(slotId); + string temp = path + ".tmp"; + string backup = GetBackupPath(slotId); + + File.WriteAllText(temp, serialized, Encoding.UTF8); + if (File.Exists(path)) File.Copy(path, backup, true); + if (File.Exists(path)) File.Delete(path); + File.Move(temp, path); + } + + public bool TryLoad(string slotId, out SaveGameData data) + { + if (TryLoadPath(GetSlotPath(slotId), out data)) return true; + return TryLoadPath(GetBackupPath(slotId), out data); + } + + public bool Exists(string slotId) => File.Exists(GetSlotPath(slotId)) || File.Exists(GetBackupPath(slotId)); + + public void Delete(string slotId) + { + DeleteIfExists(GetSlotPath(slotId)); + DeleteIfExists(GetBackupPath(slotId)); + DeleteIfExists(GetSlotPath(slotId) + ".tmp"); + } + + private static bool TryLoadPath(string path, out SaveGameData data) + { + data = null; + if (!File.Exists(path)) return false; + try + { + SaveEnvelope envelope = JsonUtility.FromJson(File.ReadAllText(path, Encoding.UTF8)); + if (envelope == null || string.IsNullOrEmpty(envelope.payload)) return false; + if (!string.Equals(envelope.checksum, ComputeChecksum(envelope.payload), StringComparison.OrdinalIgnoreCase)) return false; + data = SaveGameMigrator.Migrate(JsonUtility.FromJson(envelope.payload)); + return data != null; + } + catch + { + data = null; + return false; + } + } + + private static string ComputeChecksum(string value) + { + using (SHA256 sha = SHA256.Create()) + { + byte[] bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(value ?? string.Empty)); + return BitConverter.ToString(bytes).Replace("-", string.Empty); + } + } + + private static string Sanitize(string slotId) + { + string value = string.IsNullOrWhiteSpace(slotId) ? "autosave" : slotId.Trim(); + foreach (char invalid in Path.GetInvalidFileNameChars()) value = value.Replace(invalid, '_'); + return value; + } + + private static void DeleteIfExists(string path) + { + if (File.Exists(path)) File.Delete(path); + } + } +} diff --git a/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs.meta b/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs.meta new file mode 100644 index 0000000..552c872 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/SaveSlotStore.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 09e3f6df128b4498a87dd99944a27119 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef b/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef new file mode 100644 index 0000000..c24462a --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef @@ -0,0 +1,14 @@ +{ + "name": "ZoneUA.Persistence", + "rootNamespace": "ZoneUA.Persistence", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef.meta b/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef.meta new file mode 100644 index 0000000..cea57b5 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Persistence/ZoneUA.Persistence.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4b7ec35f64344d0e95ab7974b1233e5c +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs b/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs new file mode 100644 index 0000000..9190417 --- /dev/null +++ b/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs @@ -0,0 +1,109 @@ +using System; +using System.IO; +using NUnit.Framework; +using UnityEngine; +using ZoneUA.Persistence; + +namespace ZoneUA.Combat.Tests +{ + public sealed class SaveGamePersistenceTests + { + private string tempDirectory; + + [SetUp] + public void SetUp() + { + tempDirectory = Path.Combine(Path.GetTempPath(), "ZoneUA_SaveTests_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDirectory); + } + + [TearDown] + public void TearDown() + { + if (Directory.Exists(tempDirectory)) Directory.Delete(tempDirectory, true); + } + + [Test] + public void Migrate_VersionOne_UpgradesAndClampsHealth() + { + var data = new SaveGameData + { + schemaVersion = 1, + player = new PlayerSaveData { currentHealth = 150, maximumHealth = 0 } + }; + + SaveGameData migrated = SaveGameMigrator.Migrate(data); + + Assert.That(migrated.schemaVersion, Is.EqualTo(SaveGameData.CurrentSchemaVersion)); + Assert.That(migrated.player.maximumHealth, Is.EqualTo(150)); + Assert.That(migrated.player.currentHealth, Is.EqualTo(150)); + } + + [Test] + public void Migrate_FutureVersion_Throws() + { + var data = new SaveGameData { schemaVersion = SaveGameData.CurrentSchemaVersion + 1 }; + Assert.Throws(() => SaveGameMigrator.Migrate(data)); + } + + [Test] + public void Store_SaveAndLoad_RoundTripsSnapshot() + { + var store = new SaveSlotStore(tempDirectory); + var data = new SaveGameData + { + activeScene = "Production", + worldSeed = 42, + player = new PlayerSaveData + { + position = new Vector3(3f, 4f, 0f), + currentHealth = 73, + maximumHealth = 100, + activeWeaponIndex = 1 + } + }; + data.Stamp("slot-a", DateTime.UtcNow); + + store.Save("slot-a", data); + bool loaded = store.TryLoad("slot-a", out SaveGameData restored); + + Assert.That(loaded, Is.True); + Assert.That(restored.activeScene, Is.EqualTo("Production")); + Assert.That(restored.worldSeed, Is.EqualTo(42)); + Assert.That(restored.player.position, Is.EqualTo(new Vector3(3f, 4f, 0f))); + Assert.That(restored.player.currentHealth, Is.EqualTo(73)); + Assert.That(restored.player.activeWeaponIndex, Is.EqualTo(1)); + } + + [Test] + public void Store_CorruptedPrimary_FallsBackToBackup() + { + var store = new SaveSlotStore(tempDirectory); + var first = new SaveGameData { worldSeed = 10 }; + first.Stamp("slot", DateTime.UtcNow); + store.Save("slot", first); + + var second = new SaveGameData { worldSeed = 20 }; + second.Stamp("slot", DateTime.UtcNow); + store.Save("slot", second); + File.WriteAllText(store.GetSlotPath("slot"), "corrupted"); + + Assert.That(store.TryLoad("slot", out SaveGameData restored), Is.True); + Assert.That(restored.worldSeed, Is.EqualTo(10)); + } + + [Test] + public void Store_Delete_RemovesPrimaryAndBackup() + { + var store = new SaveSlotStore(tempDirectory); + var data = new SaveGameData(); + data.Stamp("slot", DateTime.UtcNow); + store.Save("slot", data); + store.Save("slot", data); + + store.Delete("slot"); + + Assert.That(store.Exists("slot"), Is.False); + } + } +} diff --git a/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs.meta b/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs.meta new file mode 100644 index 0000000..6c64365 --- /dev/null +++ b/Assets/_ZoneUA/Tests/EditMode/SaveGamePersistenceTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1f8350897cc245349464714ef75e64e2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef b/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef index 506e994..7999c47 100644 --- a/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef +++ b/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef @@ -10,7 +10,8 @@ "ZoneUA.World", "ZoneUA.Input", "ZoneUA.Performance", - "ZoneUA.SceneManagement" + "ZoneUA.SceneManagement", + "ZoneUA.Persistence" ], "includePlatforms": [ "Editor" diff --git a/Docs/SAVE_LOAD_PERSISTENT_STATE.md b/Docs/SAVE_LOAD_PERSISTENT_STATE.md new file mode 100644 index 0000000..c19b067 --- /dev/null +++ b/Docs/SAVE_LOAD_PERSISTENT_STATE.md @@ -0,0 +1,103 @@ +# Save/load and persistent state + +This module introduces a versioned save format and a single runtime coordinator for player-facing persistence. + +## Stored state + +`SaveGameData` currently stores: + +- schema version; +- save identifier and UTC timestamp; +- active gameplay scene; +- world seed; +- player position and Z rotation; +- current and maximum health; +- active weapon slot. + +The schema is intentionally explicit. New persistent fields must be added with a schema-version increment and a migration step. + +## Storage guarantees + +`SaveSlotStore` writes under: + +`Application.persistentDataPath/Saves` + +Each slot uses: + +- `.json` for the primary save; +- `.json.bak` for the previous valid save; +- `.json.tmp` during atomic replacement. + +The payload is wrapped in an envelope with a SHA-256 checksum. Loading tries the primary file first and falls back to the backup if the primary file is missing, truncated, malformed or fails checksum validation. + +## Bootstrap setup + +Add `SaveGameCoordinator` to the persistent Bootstrap root beside: + +- `GlobalSystem`; +- `SceneBootstrapper`. + +Assign: + +- player root; +- player `Health`; +- player `WeaponSwitcher`; +- `SceneBootstrapper`; +- default slot; +- autosave interval. + +The coordinator can resolve player references from the configured player root. For production, explicit Inspector references are preferred. + +## Scene transitions + +When a save references another gameplay scene, the coordinator asks `SceneBootstrapper` to load it. Player position, health and weapon slot are restored only after `SceneActivated` fires. + +Overlapping scene transitions are rejected by the existing scene state machine. A failed transition produces `LoadFailed` and does not apply a partial snapshot. + +## World seed integration + +The world generator should call: + +`SaveGameCoordinator.SetWorldSeed(resolvedSeed)` + +immediately after resolving or generating the seed. During load, read `CurrentWorldSeed` before regenerating the world. The world must finish deterministic generation before player-dependent simulation resumes. + +## Public API + +- `SaveDefault()` +- `LoadDefault()` +- `Save(slotId)` +- `Load(slotId)` +- `Delete(slotId)` +- `SetWorldSeed(seed)` + +Events: + +- `Saved` +- `Loaded` +- `SaveFailed` +- `LoadFailed` + +## Migration policy + +`SaveGameMigrator` upgrades old snapshots one version at a time. Saves from a newer unsupported schema are rejected rather than loaded partially. + +Never silently reinterpret a field. For renamed or structurally changed data, add an explicit migration and a test fixture representing the old schema. + +## Required Unity validation + +1. Open the project in Unity 6000.5.5f1. +2. Run all `SaveGamePersistenceTests`. +3. Add `SaveGameCoordinator` to Bootstrap. +4. Wire the production player references. +5. Save in Production, move and take damage, then load. +6. Save with weapon slot 2 active and verify restoration. +7. Save in another gameplay scene and verify additive transition before restore. +8. Corrupt the primary save and verify backup recovery. +9. Pause/resume on Android and verify pause autosave. +10. Verify quitting does not throw during Unity shutdown. +11. Verify the deterministic world seed is applied before player simulation. + +## Not yet persisted + +The current schema does not claim to persist every runtime object. NPC state, dropped items, constructed buildings, inventories and mutable world objects should be added through a separate stable-ID participant layer after their runtime ownership rules are finalised. diff --git a/Docs/SAVE_LOAD_PERSISTENT_STATE.md.meta b/Docs/SAVE_LOAD_PERSISTENT_STATE.md.meta new file mode 100644 index 0000000..116bb38 --- /dev/null +++ b/Docs/SAVE_LOAD_PERSISTENT_STATE.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 18818f55b7304db395c9d23f2a8c516d +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: