-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSaveManager.cs
More file actions
703 lines (598 loc) · 27.7 KB
/
SaveManager.cs
File metadata and controls
703 lines (598 loc) · 27.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
// MIT License - Copyright (c) 2025 BUCK Design LLC - https://github.com/buck-co
using System;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Buck.SaveAsync
{
[AddComponentMenu("SaveAsync/SaveManager")]
public class SaveManager : Singleton<SaveManager>
{
[SerializeField, Tooltip("Background threads are still an experimental feature and are turned off by default. " +
"They do increase performance in many instances, but exceptions on a background thread " +
"may not be caught and logged in Unity, and methods might fail silently. Use with caution!")]
bool m_useBackgroundThread = false;
[SerializeField, Tooltip("Enables encryption for save data. " +
"XOR encryption is basic but extremely fast. Support for AES encryption is planned." +
"Do not change the encryption type once the game has shipped!")]
EncryptionType m_encryptionType = EncryptionType.None;
[SerializeField, Tooltip(
"The password used to encrypt and decrypt save data. This password should be unique to your game. " +
"Do not change the encryption password once the game has shipped!")]
string m_encryptionPassword = "password";
[SerializeField, Tooltip(
"This field can be left blank. SaveAsync allows the FileHandler class to be overridden." +
"This can be useful in scenarios where files should not be saved using local file IO" +
"(such as cloud saves) or when a platform-specific save API must be used. " +
"If you want to use a custom file handler, create a new class that inherits from FileHandler and assign it here.")]
FileHandler m_customFileHandler;
enum FileOperationType
{
Save,
Load,
Delete,
Erase,
LoadDefaults
}
struct FileOperation
{
public FileOperationType Type;
public string[] Filenames;
public FileOperation(FileOperationType operationType, string[] filenames)
{
Type = operationType;
Filenames = filenames;
}
}
struct OperationContext
{
public bool UseBackgroundThread;
public EncryptionType EncryptionType;
public string EncryptionPassword;
public CancellationToken CancellationToken;
}
interface IBoxedSaveable
{
string Key { get; }
string Filename { get; }
Type StateType { get; }
int Version { get; }
object CaptureStateBoxed();
void RestoreStateBoxed(object state);
}
sealed class BoxedSaveable<TState> : IBoxedSaveable
{
readonly ISaveable<TState> m_inner;
public BoxedSaveable(ISaveable<TState> inner) => m_inner = inner;
public string Key => m_inner.Key;
public string Filename => m_inner.Filename;
public Type StateType => typeof(TState);
public int Version => m_inner.Version;
public object CaptureStateBoxed() => m_inner.CaptureState();
public void RestoreStateBoxed(object state)
{
if (state is null)
{
m_inner.RestoreState(default);
return;
}
m_inner.RestoreState((TState)state);
}
}
sealed class LoadedSaveable
{
public string Key;
public int EntryVersion;
public JToken Data;
}
static FileHandler m_fileHandler;
static readonly Dictionary<string, IBoxedSaveable> m_saveables = new();
static readonly List<LoadedSaveable> m_loadedSaveables = new();
static readonly Queue<FileOperation> m_fileOperationQueue = new();
static readonly Dictionary<string, StorageScope> s_fileScopes = new();
static readonly object s_QueueLock = new();
static bool m_initialized;
static int s_MainThreadId;
static readonly JsonSerializerSettings s_jsonNoTypes = new()
{
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
TypeNameHandling = TypeNameHandling.Auto
};
static bool IsMainThread => Environment.CurrentManagedThreadId == s_MainThreadId;
void Awake()
{
s_MainThreadId = Environment.CurrentManagedThreadId;
Initialize();
}
static void Initialize()
{
if (m_initialized)
return;
m_fileHandler = Instance != null && Instance.m_customFileHandler != null
? Instance.m_customFileHandler
: ScriptableObject.CreateInstance<FileHandler>();
m_initialized = true;
}
#region SaveAsync API
/// <summary>
/// Boolean indicating whether a file operation is in progress.
/// </summary>
public static bool IsBusy { get; private set; }
/// <summary>
/// Stores the current save slot index, which can be used to determine which save slot to use for saving and loading files.
/// A value of -1 indicates that no save slot is being used, which can be useful for settings files or other data that does not require a save slot.
/// </summary>
public static int SaveSlotIndex { get; set; } = -1;
/// <summary>
/// Registers an ISaveable and its file for saving and loading.
/// </summary>
/// <typeparam name="TState">The serializable state type for this saveable.</typeparam>
/// <param name="saveable">The ISaveable to register for saving and loading.</param>
public static void RegisterSaveable<TState>(ISaveable<TState> saveable)
{
Initialize();
if (saveable == null)
{
Debug.LogWarning("[Save Async] SaveManager.RegisterSaveable() - Attempted to register a null ISaveable.");
return;
}
var boxed = new BoxedSaveable<TState>(saveable);
if (!m_saveables.TryAdd(boxed.Key, boxed))
Debug.LogWarning($"[Save Async] SaveManager.RegisterSaveable() - Saveable with Key \"{boxed.Key}\" already exists.");
var scope = saveable.Scope;
if (s_fileScopes.TryGetValue(boxed.Filename, out var existing) && existing != scope)
Debug.LogError($"[Save Async] Conflicting scopes for filename \"{boxed.Filename}\": {existing} vs {scope}.");
else
s_fileScopes[boxed.Filename] = scope;
}
public static StorageScope ResolveScopeFor(string filename)
{
if (string.IsNullOrEmpty(filename))
return StorageScope.Slot; // safest default
return s_fileScopes.GetValueOrDefault(filename, StorageScope.Slot); // default Slot unless explicitly registered as Global
}
/// <summary>
/// Checks if a file exists at the given path or filename.
/// <code>
/// File example: "MyFile"
/// Path example: "MyFolder/MyFile"
/// </code>
/// </summary>
/// <param name="filename">The path or filename to check for existence.</param>
public static bool Exists(string filename)
{
Initialize();
return m_fileHandler.Exists(filename);
}
/// <summary>
/// Saves the files at the given paths or filenames.
/// <code>
/// File example: "MyFile"
/// Path example: "MyFolder/MyFile"
/// </code>
/// </summary>
/// <param name="filenames">The array of paths or filenames to save.</param>
public static async Awaitable Save(string[] filenames)
{
Initialize();
var ctx = CreateContext();
if (ctx.CancellationToken.IsCancellationRequested)
return;
await DoFileOperation(FileOperationType.Save, filenames, ctx);
}
/// <summary>
/// Saves the file at the given path or filename.
/// <code>
/// File example: "MyFile"
/// Path example: "MyFolder/MyFile"
/// </code>
/// </summary>
/// <param name="filename">The path or filename to save.</param>
public static async Awaitable Save(string filename)
=> await Save(new[] { filename });
/// <summary>
/// Loads the files at the given paths or filenames.
/// <code>
/// File example: "MyFile"
/// Path example: "MyFolder/MyFile"
/// </code>
/// </summary>
/// <param name="filenames">The array of paths or filenames to load.</param>
public static async Awaitable Load(string[] filenames)
{
Initialize();
var ctx = CreateContext();
if (ctx.CancellationToken.IsCancellationRequested)
return;
await DoFileOperation(FileOperationType.Load, filenames, ctx);
}
/// <summary>
/// Loads the file at the given path or filename.
/// <code>
/// File example: "MyFile"
/// Path example: "MyFolder/MyFile"
/// </code>
/// </summary>
/// <param name="filename">The path or filename to load.</param>
public static async Awaitable Load(string filename)
=> await Load(new[] { filename });
/// <summary>
/// Triggers loading without file I/O. Any saved files will be ignored and RestoreState() will be passed a null value.
/// This can be useful if you want RestoreState() to use default values, such as when working in the Unity Editor
/// where you may want to test default states without loading save data.
/// <code>
/// File example: "MyFile"
/// Path example: "MyFolder/MyFile"
/// </code>
/// </summary>
/// <param name="filenames">The array of paths or filenames whose ISaveables should be reset to defaults.</param>
public static async Awaitable LoadDefaults(string[] filenames)
{
Initialize();
var ctx = CreateContext();
if (ctx.CancellationToken.IsCancellationRequested)
return;
await DoFileOperation(FileOperationType.LoadDefaults, filenames, ctx);
}
/// <summary>
/// Triggers loading without file I/O. Any saved files will be ignored and RestoreState() will be passed a null value.
/// This can be useful if you want RestoreState() to use default values, such as when working in the Unity Editor
/// where you may want to test default states without loading save data.
/// <code>
/// File example: "MyFile"
/// Path example: "MyFolder/MyFile"
/// </code>
/// </summary>
/// <param name="filename">The path or filename whose ISaveables should be reset to defaults.</param>
public static async Awaitable LoadDefaults(string filename)
=> await LoadDefaults(new[] { filename });
/// <summary>
/// Deletes the files at the given paths or filenames. Each file will be removed from disk.
/// Use <see cref="Erase(string[])"/> to fill each file with an empty string without removing it from disk.
/// <code>
/// File example: "MyFile"
/// Path example: "MyFolder/MyFile"
/// </code>
/// </summary>
/// <param name="filenames">The array of paths or filenames to delete.</param>
public static async Awaitable Delete(string[] filenames)
{
Initialize();
var ctx = CreateContext();
if (ctx.CancellationToken.IsCancellationRequested)
return;
await DoFileOperation(FileOperationType.Delete, filenames, ctx);
}
/// <summary>
/// Deletes the file at the given path or filename. The file will be removed from disk.
/// Use <see cref="Erase(string)"/> to fill the file with an empty string without removing it from disk.
/// <code>
/// File example: "MyFile"
/// Path example: "MyFolder/MyFile"
/// </code>
/// </summary>
/// <param name="filename">The path or filename to delete.</param>
public static async Awaitable Delete(string filename)
=> await Delete(new[] { filename });
/// <summary>
/// Erases the files at the given paths or filenames. Each file will still exist on disk, but it will be empty.
/// Use <see cref="Delete(string[])"/> to remove the files from disk.
/// <code>
/// File example: "MyFile"
/// Path example: "MyFolder/MyFile"
/// </code>
/// </summary>
/// <param name="filenames">The array of paths or filenames to erase.</param>
public static async Awaitable Erase(string[] filenames)
{
Initialize();
var ctx = CreateContext();
if (ctx.CancellationToken.IsCancellationRequested)
return;
await DoFileOperation(FileOperationType.Erase, filenames, ctx);
}
/// <summary>
/// Erases the file at the given path or filename. The file will still exist on disk, but it will be empty.
/// Use <see cref="Delete(string)"/> to remove the file from disk.
/// <code>
/// File example: "MyFile"
/// Path example: "MyFolder/MyFile"
/// </code>
/// </summary>
/// <param name="filename">The path or filename to erase.</param>
public static async Awaitable Erase(string filename)
=> await Erase(new[] { filename });
/// <summary>
/// Sets the given Guid byte array to a new Guid byte array if it is null, empty, or an empty Guid.
/// This method can be useful for creating unique keys for ISaveables.
/// </summary>
/// <param name="guidBytes">The byte array (passed by reference) that you would like to fill with a serializable guid.</param>
/// <returns>The same byte array that contains the serializable guid, but returned from the method.</returns>
public static byte[] GetSerializableGuid(ref byte[] guidBytes)
{
if (guidBytes == null)
{
Debug.LogWarning("[Save Async] SaveManager.GetSerializableGuid() - Guid byte array is null. Generating a new Guid.");
guidBytes = Guid.NewGuid().ToByteArray();
}
if (guidBytes.Length == 0)
{
Debug.LogWarning("[Save Async] SaveManager.GetSerializableGuid() - Guid byte array is empty. Generating a new Guid.");
guidBytes = Guid.NewGuid().ToByteArray();
}
if (guidBytes.Length != 16)
throw new ArgumentException("[Save Async] SaveManager.GetSerializableGuid() - Guid byte array must be 16 bytes long.");
Guid guidObj = new Guid(guidBytes);
if (guidObj == Guid.Empty)
{
Debug.LogWarning("[Save Async] SaveManager.GetSerializableGuid() - Guid is empty. Generating a new Guid.");
guidBytes = Guid.NewGuid().ToByteArray();
}
return guidBytes;
}
#endregion
static OperationContext CreateContext()
{
var linked = CancellationTokenSource.CreateLinkedTokenSource(Instance.destroyCancellationToken, Application.exitCancellationToken).Token;
return new OperationContext
{
UseBackgroundThread = Instance && Instance.m_useBackgroundThread,
EncryptionType = Instance ? Instance.m_encryptionType : EncryptionType.None,
EncryptionPassword = Instance ? Instance.m_encryptionPassword : string.Empty,
CancellationToken = linked
};
}
static async Awaitable DoFileOperation(FileOperationType requestedType, string[] requestedFilenames, OperationContext ctx)
{
try
{
if (m_saveables.Count == 0)
{
Debug.LogError("[Save Async] SaveManager.DoFileOperation() - No saveables have been registered. " +
"Register ISaveable<TState> before using save, load, erase, or delete methods.");
return;
}
lock (s_QueueLock)
{
m_fileOperationQueue.Enqueue(new FileOperation(requestedType, requestedFilenames));
if (IsBusy)
return;
IsBusy = true;
}
if (ctx.UseBackgroundThread)
await Awaitable.BackgroundThreadAsync();
bool processedLoad = false;
bool processedLoadDefaults = false;
var affectedFilenames = new HashSet<string>();
while (true)
{
FileOperation fileOperation;
lock (s_QueueLock)
{
if (m_fileOperationQueue.Count == 0)
break;
fileOperation = m_fileOperationQueue.Dequeue();
}
switch (fileOperation.Type)
{
case FileOperationType.Save:
await SaveFileOperationAsync(fileOperation.Filenames, ctx);
break;
case FileOperationType.Load:
await LoadFileOperationAsync(fileOperation.Filenames, ctx);
processedLoad = true;
foreach (var f in fileOperation.Filenames)
affectedFilenames.Add(f);
break;
case FileOperationType.Delete:
await DeleteFileOperationAsync(fileOperation.Filenames, eraseAndKeepFile: false, ctx);
break;
case FileOperationType.Erase:
await DeleteFileOperationAsync(fileOperation.Filenames, eraseAndKeepFile: true, ctx);
break;
case FileOperationType.LoadDefaults:
processedLoadDefaults = true;
foreach (var f in fileOperation.Filenames)
affectedFilenames.Add(f);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
// Always hop back to the main thread before touching Unity objects
// and before returning to the caller so their continuation resumes on main.
await Awaitable.MainThreadAsync();
if (processedLoad || processedLoadDefaults)
RestorePass(affectedFilenames, processedLoad, processedLoadDefaults);
m_loadedSaveables.Clear();
}
catch (Exception e)
{
Debug.LogError($"[Save Async] SaveManager.DoFileOperation() - Exception: {e.Message}\n{e.StackTrace}");
throw;
}
finally
{
lock (s_QueueLock)
{
IsBusy = false;
}
}
}
static void RestorePass(HashSet<string> affectedFilenames, bool didLoad, bool didDefaults)
{
var restoredSaveables = new Dictionary<string, bool>(m_saveables.Count);
foreach (var kvp in m_saveables)
restoredSaveables[kvp.Key] = false;
if (didLoad && m_loadedSaveables.Count > 0)
{
foreach (var loaded in m_loadedSaveables)
{
if (loaded.Key == null)
{
Debug.LogError("[Save Async] SaveManager.DoFileOperation() - The key for an ISaveable was null. JSON data may be malformed.");
continue;
}
if (!m_saveables.TryGetValue(loaded.Key, out var boxed) || boxed == null)
{
Debug.LogError($"[Save Async] SaveManager.DoFileOperation() - The ISaveable with the key \"{loaded.Key}\" was not found or is null. The data will not be restored.");
continue;
}
// Version check: if the on-disk entry's Version doesn't match the registered saveable's Version,
// skip old data and explicitly restore defaults for this saveable.
if (loaded.EntryVersion != boxed.Version)
{
Debug.LogWarning($"[Save Async] SaveManager.DoFileOperation() - Version mismatch for key \"{loaded.Key}\". " +
$"Save data has Version {loaded.EntryVersion}; runtime expects {boxed.Version}. Defaults will be used.");
boxed.RestoreStateBoxed(null);
restoredSaveables[loaded.Key] = true;
continue;
}
try
{
object state = loaded.Data?.ToObject(boxed.StateType, JsonSerializer.CreateDefault(s_jsonNoTypes));
boxed.RestoreStateBoxed(state);
restoredSaveables[loaded.Key] = true;
}
catch (Exception ex)
{
Debug.LogError($"[Save Async] SaveManager.DoFileOperation() - Failed to restore state for key \"{loaded.Key}\": {ex.Message}\n{ex.StackTrace}");
}
}
}
foreach (var kvp in m_saveables)
{
if (restoredSaveables[kvp.Key])
continue;
if (!affectedFilenames.Contains(kvp.Value.Filename))
continue;
kvp.Value.RestoreStateBoxed(null);
if (didLoad)
{
Debug.LogWarning($"[Save Async] SaveManager.DoFileOperation() - The ISaveable with the key \"{kvp.Key}\" " +
"was not restored from save data. This could mean the save data did not contain any data for this ISaveable.");
}
}
if (didDefaults)
Debug.Log("[Save Async] SaveManager.DoFileOperation() - Saveables were loaded with default state because LoadDefaults() was called.");
}
static async Awaitable SaveFileOperationAsync(string[] filenames, OperationContext ctx)
{
var ct = ctx.CancellationToken;
if (ct.IsCancellationRequested)
return;
try
{
foreach (string filename in filenames)
{
var toSave = new List<IBoxedSaveable>();
foreach (var s in m_saveables.Values)
if (s.Filename == filename)
toSave.Add(s);
string json = SaveablesToJson(toSave);
if (string.IsNullOrEmpty(json))
throw new InvalidOperationException($"[Save Async] SaveManager.SaveFileOperationAsync() - JSON serialization returned empty for file \"{filename}\".");
string encrypted = Encryption.Encrypt(json, ctx.EncryptionPassword, ctx.EncryptionType);
await m_fileHandler.WriteFile(filename, encrypted, ct).ConfigureAwait(false);
}
}
catch (Exception e)
{
Debug.LogError($"[Save Async] SaveManager.SaveFileOperationAsync() - Exception: {e.Message}\n{e.StackTrace}");
throw;
}
}
static async Awaitable LoadFileOperationAsync(string[] filenames, OperationContext ctx)
{
var ct = ctx.CancellationToken;
if (ct.IsCancellationRequested)
return;
try
{
foreach (string filename in filenames)
{
string fileContent = await m_fileHandler.ReadFile(filename, ct).ConfigureAwait(false);
if (string.IsNullOrEmpty(fileContent))
continue;
string json = Encryption.Decrypt(fileContent, ctx.EncryptionPassword, ctx.EncryptionType);
try
{
var array = JArray.Parse(json);
foreach (var item in array)
{
var key = item["Key"]?.ToString();
int entryVersion = item["Version"]?.Value<int?>() ?? 0; // legacy entries will be 0
var data = item["Data"];
m_loadedSaveables.Add(new LoadedSaveable
{
Key = key,
EntryVersion = entryVersion,
Data = data
});
}
}
catch (Exception ex)
{
Debug.LogError($"[Save Async] SaveManager.LoadFileOperationAsync() - Error deserializing JSON data: {ex.Message}\n{ex.StackTrace}");
}
}
}
catch (Exception e)
{
Debug.LogError($"[Save Async] SaveManager.LoadFileOperationAsync() - Exception: {e.Message}\n{e.StackTrace}");
throw;
}
}
static async Awaitable DeleteFileOperationAsync(string[] filenames, bool eraseAndKeepFile, OperationContext ctx)
{
var ct = ctx.CancellationToken;
if (ct.IsCancellationRequested)
return;
try
{
foreach (string filename in filenames)
{
if (eraseAndKeepFile)
await m_fileHandler.Erase(filename, ct).ConfigureAwait(false);
else
await m_fileHandler.Delete(filename, ct).ConfigureAwait(false);
}
}
catch (Exception e)
{
Debug.LogError($"[Save Async] SaveManager.DeleteFileOperationAsync() - Exception: {e.Message}\n{e.StackTrace}");
throw;
}
}
static string SaveablesToJson(List<IBoxedSaveable> saveables)
{
if (saveables == null)
throw new ArgumentNullException(nameof(saveables));
var array = new JArray();
foreach (var s in saveables)
{
object data = null;
try
{
data = s.CaptureStateBoxed();
}
catch (Exception e)
{
Debug.LogError($"[Save Async] SaveManager.SaveablesToJson() - Failed to capture state for ISaveable with key \"{s.Key}\": {e.Message}\n{e.StackTrace}");
}
var token = JToken.FromObject(data, JsonSerializer.CreateDefault(s_jsonNoTypes));
var obj = new JObject
{
["Key"] = s.Key,
["Version"] = s.Version,
["Data"] = token
};
array.Add(obj);
}
return array.ToString(Formatting.Indented);
}
}
}