Back up save before overwrite

This commit is contained in:
2026-05-18 19:37:35 -07:00
parent 65599b9d2f
commit dfad8809c7
5 changed files with 89 additions and 1 deletions
@@ -10,6 +10,9 @@
#include "AgrarianSurvivalComponent.h"
#include "EngineUtils.h"
#include "Engine/World.h"
#include "HAL/FileManager.h"
#include "Misc/DateTime.h"
#include "Misc/Paths.h"
#include "GameFramework/PlayerState.h"
#include "Kismet/GameplayStatics.h"
@@ -33,6 +36,11 @@ UAgrarianSaveGame* UAgrarianPersistenceSubsystem::LoadOrCreateSave() const
bool UAgrarianPersistenceSubsystem::WriteSave(UAgrarianSaveGame* SaveGame) const
{
if (SaveGame && bBackupBeforeSave)
{
BackupExistingSave();
}
return SaveGame ? UGameplayStatics::SaveGameToSlot(SaveGame, DefaultSlotName, UserIndex) : false;
}
@@ -316,6 +324,25 @@ bool UAgrarianPersistenceSubsystem::LoadCurrentWorld(int32& RestoredPlayerCount,
return bRestoredWorldState;
}
bool UAgrarianPersistenceSubsystem::BackupExistingSave() const
{
const FString SaveFilePath = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("SaveGames"), DefaultSlotName + TEXT(".sav"));
if (!FPaths::FileExists(SaveFilePath))
{
return false;
}
const FString BackupDirectory = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("SaveGames"), TEXT("Backups"));
IFileManager::Get().MakeDirectory(*BackupDirectory, true);
const FString Timestamp = FDateTime::UtcNow().ToString(TEXT("%Y%m%dT%H%M%SZ"));
const FString BackupFileName = FString::Printf(TEXT("%s-%s.sav"), *DefaultSlotName, *Timestamp);
const FString BackupFilePath = FPaths::Combine(BackupDirectory, BackupFileName);
const bool bCopied = IFileManager::Get().Copy(*BackupFilePath, *SaveFilePath, true, true) == COPY_OK;
UE_LOG(LogTemp, Log, TEXT("Agrarian save backup %s: %s"), bCopied ? TEXT("created") : TEXT("failed"), *BackupFilePath);
return bCopied;
}
bool UAgrarianPersistenceSubsystem::CapturePlayerIntoSave(const AAgrarianGameCharacter* Character, UAgrarianSaveGame* SaveGame) const
{
const UAgrarianSurvivalComponent* SurvivalComponent = Character ? Character->GetSurvivalComponent() : nullptr;
@@ -23,6 +23,9 @@ public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Agrarian|Persistence")
int32 UserIndex = 0;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Agrarian|Persistence")
bool bBackupBeforeSave = true;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Agrarian|Persistence")
TMap<FName, TSubclassOf<AActor>> WorldActorClassRegistry;
@@ -78,6 +81,7 @@ public:
bool LoadCurrentWorld(int32& RestoredPlayerCount, int32& RestoredWorldActorCount, bool bClearExistingActors = true) const;
protected:
bool BackupExistingSave() const;
bool CapturePlayerIntoSave(const AAgrarianGameCharacter* Character, UAgrarianSaveGame* SaveGame) const;
bool RestorePlayerFromSave(AAgrarianGameCharacter* Character, const UAgrarianSaveGame* SaveGame) const;
void FindPersistentComponents(TArray<UAgrarianPersistentActorComponent*>& OutComponents) const;