forked from Hazardu/ChampionsOfForest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSerializer.cs
417 lines (367 loc) · 10.6 KB
/
Serializer.cs
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
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using ChampionsOfForest.Player;
using TheForest.Save;
using TheForest.Utils;
using UnityEngine;
namespace ChampionsOfForest
{
public class Serializer : MonoBehaviour
{
private static bool Saving = false;
private static Serializer Instance
{
get;
set;
}
private static void CreateInstance()
{
if (Instance == null)
{
Instance = new GameObject().AddComponent<Serializer>();
}
}
private void OnApplicationQuit()
{
EmergencySave();
}
private void DoLoad(string path, out float HealthPercentage, out Dictionary<int, int> ExtraCarriedItems)
{
ExtraCarriedItems = new Dictionary<int, int>();
HealthPercentage = 1;
try
{
byte[] bytes = File.ReadAllBytes(path);
BinaryReader buf = new BinaryReader(new MemoryStream(bytes));
//reading in the same order to saving
string version = buf.ReadString();
if (ModSettings.RequiresNewSave)
{
var ver = Res.ResourceLoader.CompareVersion(version, ModSettings.RequiresNewSaveVersion);
if (ver == Res.ResourceLoader.Status.Newer)
{
CotfUtils.Log("last time cotf was played on this save was on version: " + version + " \ndue to issues with this and following updates, new save will be used. Sorry for inconvenience");
return;
}
}
ModdedPlayer.instance.ExpCurrent = buf.ReadInt64(); //buf.Write(ModdedPlayer.instance.ExpCurrent);
HealthPercentage = buf.ReadSingle(); //buf.Write(LocalPlayer.Stats.Health / ModdedPlayer.Stats.TotalMaxHealth);
ModdedPlayer.instance.MutationPoints = buf.ReadInt32(); //buf.Write(ModdedPlayer.instance.MutationPoints);
ModdedPlayer.instance.level = buf.ReadInt32(); //buf.Write(ModdedPlayer.instance.Level);
ModdedPlayer.instance.AssignLevelAttributes();
ModdedPlayer.instance.PermanentBonusPerkPoints = buf.ReadInt32(); //buf.Write(ModdedPlayer.instance.PermanentBonusPerkPoints);
ModdedPlayer.instance.LastDayOfGeneration = buf.ReadInt32(); //buf.Write(ModdedPlayer.instance.LastDayOfGeneration);
ModdedPlayer.instance.ExpGoal = ModdedPlayer.instance.GetGoalExp();
//extra carried item amounts
//key - ID of an item
//value - amount at the moment of saving
int ExtraItemCount = buf.ReadInt32(); //buf.Write(ModdedPlayer.instance.ExtraCarryingCapactity.Count);
for (int i = 0; i < ExtraItemCount; i++)
{
int ID = buf.ReadInt32();
int AMOUNT = buf.ReadInt32();
ExtraCarriedItems.Add(ID, AMOUNT);
}
//loading inventory
int ItemSlotCount = buf.ReadInt32();
for (int i = 0; i < ItemSlotCount; i++)
{
int Slot = buf.ReadInt32();
int ID = buf.ReadInt32();
if (ID != -1)
{
int LVL = buf.ReadInt32();
int AMO = buf.ReadInt32();
int StatCount = buf.ReadInt32();
Item LoadedItem = new Item(ItemDataBase.ItemBases[ID], AMO, 0, false)
{
level = LVL
};
for (int a = 0; a < StatCount; a++)
{
int statID = buf.ReadInt32();
int statgroupID = buf.ReadInt32();
float statAMO = buf.ReadSingle();
ItemStat stat = new ItemStat(ItemDataBase.Stats[statID],1,statgroupID)
{
Amount = statAMO
};
LoadedItem.Stats.Add(stat);
LoadedItem.SortStats();
}
Inventory.Instance.ItemSlots[Slot] = LoadedItem;
}
else
{
Inventory.Instance.ItemSlots[Slot] = null;
}
}
//loading perks
int perkCount = buf.ReadInt32();
for (int i = 0; i < perkCount; i++)
{
int id = buf.ReadInt32();
bool isBought = buf.ReadBoolean();
int applyCount = buf.ReadInt32();
PerkDatabase.perks[id].isBought = isBought;
try
{
if (isBought)
{
PerkDatabase.perks[id].boughtTimes = applyCount;
if (applyCount == 0)
{
PerkDatabase.perks[id].isApplied = true;
PerkDatabase.perks[id].onApply();
}
else
{
for (int a = 0; a < applyCount; a++)
{
PerkDatabase.perks[id].onApply();
}
PerkDatabase.perks[id].isApplied = true;
}
PerkDatabase.perks[id].OnBuy();
}
}
catch (System.Exception ex)
{
ModAPI.Log.Write($"Loading perks exception: id = {id}, isBought = {isBought}, applycount ={applyCount}\n" + ex);
}
}
//loading bought spells
int spellCount = buf.ReadInt32();
for (int i = 0; i < spellCount; i++)
{
int ID = buf.ReadInt32();
bool isBought = buf.ReadBoolean();
SpellDataBase.spellDictionary[ID].Bought = isBought;
}
//loading spell loadout
int spellLoadoutCount = buf.ReadInt32();
for (int i = 0; i < spellLoadoutCount; i++)
{
int ID = buf.ReadInt32();
if (ID == -1)
{
SpellCaster.instance.infos[i].spell = null;
}
else
{
SpellCaster.instance.infos[i].spell = SpellDataBase.spellDictionary[ID];
SpellCaster.instance.infos[i].spell.EquippedSlot = i;
}
}
ModdedPlayer.ReapplyAllSpell();
}
catch (System.Exception ex)
{
ModAPI.Log.Write(ex.ToString());
}
}
private static void DoSave()
{
Saving = true;
while (Path() == string.Empty)
{
Thread.Sleep(20);
}
//Thread.Sleep(1000);
MemoryStream stream = new MemoryStream();
BinaryWriter buf = new BinaryWriter(stream);
//saving modded player variables
buf.Write(ModSettings.Version);
buf.Write(ModdedPlayer.instance.ExpCurrent);
buf.Write(LocalPlayer.Stats.Health / ModdedPlayer.Stats.TotalMaxHealth);
buf.Write(ModdedPlayer.instance.MutationPoints);
buf.Write(ModdedPlayer.instance.level);
buf.Write(ModdedPlayer.instance.PermanentBonusPerkPoints);
buf.Write(ModdedPlayer.instance.LastDayOfGeneration);
//saving extra item amounts to not loose any extra
//im doing that because the game trims the excess on load
buf.Write(ModdedPlayer.instance.ExtraCarryingCapactity.Count);
foreach (KeyValuePair<int, ModdedPlayer.ExtraItemCapacity> item in ModdedPlayer.instance.ExtraCarryingCapactity)
{
buf.Write(item.Value.ID);
buf.Write(LocalPlayer.Inventory.AmountOf(item.Value.ID));
}
//saving inventory
buf.Write(Inventory.Instance.ItemSlots.Count);
foreach (KeyValuePair<int, Item> item in Inventory.Instance.ItemSlots)
{
buf.Write(item.Key);
if (item.Value != null)
{
//save the slot id
//save individual item
buf.Write(item.Value.ID);
buf.Write(item.Value.level);
buf.Write(item.Value.Amount);
buf.Write(item.Value.Stats.Count);
//save every stat
for (int i = 0; i < item.Value.Stats.Count; i++)
{
buf.Write(item.Value.Stats[i].StatID);
buf.Write(item.Value.Stats[i].possibleStatsIndex);
buf.Write(item.Value.Stats[i].Amount);
}
}
else
{
buf.Write(-1);
}
}
//saving perks
buf.Write(PerkDatabase.perks.Count);
foreach (Perk item in PerkDatabase.perks)
{
buf.Write(item.id);
buf.Write(item.isBought);
buf.Write(item.boughtTimes);
}
//saving bought spells
buf.Write(SpellDataBase.spellDictionary.Count);
foreach (KeyValuePair<int, Spell> pair in SpellDataBase.spellDictionary)
{
buf.Write(pair.Value.ID);
buf.Write(pair.Value.Bought);
}
//saving spell loadout
buf.Write(SpellCaster.instance.infos.Length);
foreach (SpellCaster.SpellInfo info in SpellCaster.instance.infos)
{
if (info.spell == null)
{
buf.Write(-1);
}
else
{
buf.Write(info.spell.ID);
}
}
//finally
//saving to a file
//checking if dir exists
if (!Directory.Exists(Path()))
{
Directory.CreateDirectory(Path());
}
string path = Path() + "/COTF.save";
File.WriteAllBytes(path, stream.ToArray());
Saving = false;
}
private IEnumerator DoLoadCoroutine()
{
while (LocalPlayer.Stats == null || LocalPlayer.Inventory == null)
{
yield return null;
}
yield return null;
yield return null;
yield return null;
yield return null;
yield return null;
//waits some frames
string path = Path();
if (path == string.Empty)
{
yield break;
}
//checking and cancelling loading routine if there is no directory of the save
if (!Directory.Exists(path))
{
yield break;
}
path += "/COTF.save";
if (!File.Exists(path))
{
yield break;
}
yield return new WaitForSeconds(1f);
DoLoad(path, out float HealthPercentage, out Dictionary<int, int> ExtraCarriedItems);
//waiting for buffs and perks to apply
yield return new WaitForSeconds(5f);
ModdedPlayer.ResetAllStats();
//bringing health back to correct amount
yield return null;
LocalPlayer.Stats.Health = ModdedPlayer.Stats.TotalMaxHealth * HealthPercentage;
//waiting for buffs and perks to apply
yield return new WaitForSeconds(6f);
//fixing missing items
foreach (KeyValuePair<int, int> item in ExtraCarriedItems)
{
int amount = LocalPlayer.Inventory.AmountOf(item.Key);
if (amount < item.Value)
{
int toAdd = item.Value - amount;
LocalPlayer.Inventory.AddItem(item.Key, toAdd);
}
}
}
public static void EmergencySave() //previousely, clients would disconnect for no reason. Now obsolete
{
if (GameSetup.IsMpClient)
{
ModAPI.Console.Write("Saving");
CreateInstance();
if (!Saving)
{
DoSave();
}
}
}
public static void Save()
{
if (ModSettings.IsDedicated)
return;
CreateInstance();
if (!Saving)
{
Thread saveThread = new Thread(DoSave);
saveThread.Start();
}
}
public static void Load()
{
if (ModSettings.IsDedicated)
return;
CreateInstance();
Instance.StartCoroutine(Instance.DoLoadCoroutine());
}
public static string Path()
{
if (GameSetup.IsMultiplayer)
{
if (GameSetup.IsMpClient)
return "Mods/Champions of the Forest/Multiplayer/" + PlayerSpawn.GetClientSaveFileName();
else if (GameSetup.IsMpServer)
return GameSetup.Slot.ToString() == "0" ? string.Empty : "Mods/Champions of the Forest/Multiplayer/" + GameSetup.Slot.ToString();
}
if (GameSetup.Slot.ToString() == "0")
return string.Empty;
return "Mods/Champions of the Forest/Singleplayer/" + GameSetup.Slot.ToString();
}
}
public class SaveOverride : PlayerStats
{
public override void OnSaveSlotSelected()
{
if (!this.Dead)
{
Serializer.Save();
}
base.OnSaveSlotSelected();
}
public override void JustSave()
{
if (!this.Dead && GameSetup.IsMpClient)
{
Serializer.Save();
}
base.JustSave();
}
}
}