private static Dictionary <uint, ISaveable> buildObjectTable(ISaveable root, SaveType saveType) { Dictionary <uint, ISaveable> objects = new Dictionary <uint, ISaveable>(); objects.Add(root.GetId(), root); Stack <ISaveable> toVisit = new Stack <ISaveable>(); addUnvisitedSaveablesToStack(objects, root.GetSaveableRefs(saveType), toVisit); while (toVisit.Count != 0) { ISaveable next = toVisit.Pop(); if (objects.ContainsKey(next.GetId())) { throw new InvalidOperationException("Cannot add same object again"); } if (next.GetId() != VALUE_TYPE_ID) { objects.Add(next.GetId(), next); } List <ISaveable> refs = next.GetSaveableRefs(saveType); addUnvisitedSaveablesToStack(objects, refs, toVisit); } return(objects); }
private void OnSaveableLoaded(ISaveable saveable) { if (saveable.saveId == "player") { Setup(); } }
/// <summary> /// Links the logs to a settings field performing a save every time log is inserted. /// </summary> /// <param name="settings">The AppSettings</param> /// <param name="target">The field that holds the logs</param> public void LinkToSettings(ISaveable settings, ref List <string> target) { _settingsSaver = settings; _settingsHolder = target; Items.Clear(); Items.AddRange(target.Cast <object>().ToArray()); }
private IEnumerator LoadSequence(List <SaveData> saveData) { Processing = true; yield return(new WaitForSecondsRealtime(0.5f)); yield return(new WaitForSecondsRealtime(loadDelay)); for (int i = 0; i < saveData.Count; i++) { SaveData data = saveData[i]; ISaveable saveable = saveables.SingleOrDefault(x => x.Id == data.id); if (saveable != null && saveable.ToString() != "null") { saveable.Load(data); } } Processing = false; ClearTrash(); List <ISaveable> redundant = saveables.Where(x => !saveData.Any(y => y.id == x.Id)).ToList(); for (int i = redundant.Count - 1; i >= 0; i--) { Destroy(redundant[i].GO); } DevTools.Instance().DisableAll(); yield return(new WaitForEndOfFrame()); onLoad?.Invoke(); }
public static string Save(ISaveable saveable) { Saver saver = new Saver(); var object_data = saver.CreateAndSerialize(saveable); return(JSON.Print(object_data)); }
public void RegisterObject(ISaveable saveable, string value) { string key = saveable.Register(Unregister, UpdateEntry); save[key] = value; saveables.Add(saveable); }
public void Export(ItemsBase itemBase, PixelSet[,] pixelArray) { if (pixelArray == null) { return; } ISaveable saveable = itemBase as ISaveable; ProjectHolder ph = ServiceLocator.Instance.GetService <ProjectHolder>(); string outputFileName = Path.Combine(ph.ProjectPath, saveable.GetFileName); string extension = Path.GetExtension(outputFileName); outputFileName = outputFileName.Replace(extension, string.Empty); int directions = 8; int frames = 4; for (int i = 0; i < directions; i++) { for (int j = 0; j < frames; j++) { Bitmap image = CreateImage(pixelArray[i, j]); string filename = $"{outputFileName}_{i}_{j}.png"; image.Save(filename); } } }
public virtual void Unregister(ISaveable saveable) { if (m_Saveables.ContainsKey(saveable.saveId)) { m_Saveables.Remove(saveable.saveId); } }
public async static void WriteSaveGame(ISaveable _saveable, string _path) { MemoryStream memStream = new MemoryStream(); AddValue("Dataversion", version, memStream); _saveable.WriteTo(memStream, version); FileStream fileStream = new FileStream(_path, FileMode.Create, FileAccess.Write); memStream.WriteTo(fileStream); //memStream.GetBuffer(); //write buffer to disc async! memStream.Flush(); memStream.Dispose(); await fileStream.FlushAsync(); fileStream.Dispose(); //ISaveable }
private void LoadSaveable(ISaveable saveable) { string fileName = GetSaveableFilePath(saveable); if (System.IO.File.Exists(fileName)) { using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open))) { string saveString = reader.ReadString(); if (!string.IsNullOrEmpty(saveString)) { saveable.Load(saveString); saveable.OnLoaded(); RavenhillEvents.OnSaveableLoaded(saveable); } else { saveable.InitSave(); saveable.OnLoaded(); RavenhillEvents.OnSaveableLoaded(saveable); } } } else { saveable.InitSave(); saveable.OnLoaded(); RavenhillEvents.OnSaveableLoaded(saveable); } }
public void Save(ISaveable data) { try { string json = jsonTraslator.TranslateToJson(data); string destination = Application.persistentDataPath + String.Format("/{0}.dat", data.PathName()); FileStream file; if (File.Exists(destination)) { file = File.OpenWrite(destination); } else { file = File.Create(destination); } BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(file, json); file.Close(); #if UNITY_WEBGL WebUtil.SyncFs(); #endif } catch (Exception e) { Debug.Log(e.Message); } }
public void Load(ISaveable saveable) { if (IsRegistered(saveable)) { string saveString = storage?.GetString(saveable.SaveKey, string.Empty); if (string.IsNullOrEmpty(saveString)) { saveable.LoadDefaults(); } else { try { object save = JsonConvert.DeserializeObject(saveString, saveable.SaveType); saveable.LoadSave(save); } catch (System.Exception exception) { UDebug.LogError(exception.Message); saveable.LoadDefaults(); } } } else { throw new UnityException($"Load: saveable of type => {saveable.GetType().Name} is not registered on ISaveService"); } }
public static void SaveJsonData(ISaveable saveable) { if (FileManager.WriteToFile(saveable.FileNameToUseForData(), saveable.ToJson())) { // Debug.Log("Save successful"); } }
private void Unregister(ISaveable saveable) { string saveName = saveable.GetSaveName(); save.Remove(saveName); saveables.Remove(saveable); }
/// <summary> /// Adds an object to be tracked by this objecttype. /// </summary> /// <param name="existingObject">Object to track.</param> /// <param name="assumeNew">If false, ignores objects not ready to be saved (with id=-1). /// Else assign a new ID if the object has not been saved yet.</param> /// <returns>True on success. False if somehow the add failed.</returns> public virtual bool Add(ISaveable existingObject, bool assumeNew = true) { int id = existingObject.GetSaveID(); if (assumeNew && id == -1) { // SetSaveID is only called by two things: Loading, and this method. By locking here, this should be threadsafe. lock (this) { id = existingObject.GetSaveID(); if (id == -1) { id = NextFreeNumber(); //Note that this may get a lock on ItemDictionary also, and then the file stream. existingObject.SetSaveID(id); existingObject.Save(); } } } if (id >= 0) { Add(existingObject, id, false); return(true); } return(false); }
/// <summary> /// Requests the object for the given ID. /// </summary> /// <param name="id">ID of object to get</param> /// <param name="loadIfNotFound">If the object is not currently loaded, try to load it.</param> /// <param name="waitForLoaded">If the object is currently loading, wait for it to finish loading first.</param> /// <returns>The object, or null if not found.</returns> public ISaveable Get(int id, bool loadIfNotFound, bool waitForLoaded) { ISaveable foundObject = null; if (id >= ItemDictionary.Count || (foundObject = ItemDictionary[id]) == null) { if (loadIfNotFound) { DatabaseManager.LoadSaveable(this, id); //Check now for results. // If null, mark as unloaded. // If set, can check if loaded and wait if requested. // Else do nothing. foundObject = ItemDictionary.Count <= id ? null : ItemDictionary[id]; if (foundObject == null) { //TODO: Mark as unloaded? } else if (waitForLoaded) { ManualResetEvent waitEvent = foundObject.SaveValues.LoadingIndicator; if (waitEvent != null) { waitEvent.WaitOne(); } } } } if (foundObject == UnreadableSlot) { //Handle case of data being unreadable on the database. Not much that can be done. Log.LogText("Reference to unreadable data (" + this.BaseClass.Name + "[" + id + "]" + "): " + new Exception().ToString()); return(null); } return(foundObject); }
public static void SubscribeSV(GameObject gm) { ISaveable isave = gm.GetComponent <ISaveable>(); SaveAll += isave.Save; LoadAll += isave.Load; }
public void RegisterSaveableInstance(ISaveable instance) { if (!m_saveablesInstances.Contains(instance)) { m_saveablesInstances.Add(instance); } }
public bool Save(ISaveable aSauver) { string docId = $"{aSauver.Table}_{Guid.NewGuid()}"; ITechnicalKey technicalKey = aSauver as ITechnicalKey; if (technicalKey == null) { return(false); } MutableDocument document = null; if (string.IsNullOrEmpty(technicalKey.Id)) { technicalKey.Id = docId; } else { document = _dbConfigurationGetter.Get().GetDocument(technicalKey.Id).ToMutable(); } MutableDictionaryObject dico = aSauver.DocumentInitialize(); document = dico.ToDocument(docId, document); _dbConfigurationGetter.Get().Save(document); return(true); }
// ----------------------------------------------------------------------------------- /// <summary> /// Unregisters an object for saving / loading /// </summary> /// <param name="target">target to save laod</param> public void Remove(ISaveable target) { if (_list.ContainsKey(target.id)) { _list.Remove(target.id); } }
/// <inheritdoc/> public void LoadSaveable(ISaveable saveable) { if (GameState.TryGetValue(saveable.Id, out var value)) { saveable.Load((JObject)value); } }
public void ConvertFromDBObject(IDBObject obj) { if (!(obj is DB_Category)) { return; } DB_Category dbCat = obj as DB_Category; this.ID = Guid.Parse(dbCat.ID); this.IsMasterCategory = dbCat.IsMasterCategory; this.Name = dbCat.Name; DataHelper.AddItem(this); if (!string.IsNullOrEmpty(dbCat.ParentCategory)) { DB_Category parentDBCat = new DB_Category(); parentDBCat.Load(dbCat.ParentCategory); ISaveable saveable = DataHelper.LoadedObjects.FirstOrDefault(lo => lo.ID.ToString() == parentDBCat.ID); if (saveable != null) { Category parentCat = DataHelper.LoadedObjects.Where(lo => lo is Category).Cast <Category>().FirstOrDefault(lo => lo.ID.ToString() == parentDBCat.ID); this.ParentCategory = parentCat; } else { Category parentCat = new Category(); parentCat.ConvertFromDBObject(parentDBCat); this.ParentCategory = parentCat; } } }
public bool SaveDataSingle(ISaveable saveable) { string outputFileName = Path.Combine(_outputFolder, saveable.GetFileName); IFormatter formatter = new BinaryFormatter(); Stream stream = null; try { stream = StreamFactory.GetStream(outputFileName); if (SaveToStream(stream, formatter, saveable)) { stream.Close(); } else { return(false); } } catch { if (stream != null) { stream.Close(); } return(false); } return(true); }
public static string SaveSingle(ISaveable saveable) { Saver saver = new Saver(); var object_data = saver.EncodeObject(saveable); return(saver.Flush() + "\n" + JSON.Print(object_data)); }
public void Inflate(Dictionary <uint, ISaveable> objectTable) { foreach (uint id in inflatables.objects) { ISaveable reference = objectTable[id]; this.Add((T)reference); } }
public static void SaveData <T>(string path, ISaveable <T> data) { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Create(path); bf.Serialize(file, data); file.Close(); }
public void Register(ISaveable saveable) { registeredSaveables[saveable.GetType()] = saveable; if (!saveable.IsLoaded) { Load(saveable); } }
public static void LoadJsonData(ISaveable saveable) { if (FileManager.LoadFromFile(saveable.FileNameToUseForData(), out var json)) { saveable.LoadFromJson(json); // Debug.Log("Load complete"); } }
/// <inheritdoc/> public void SaveSaveable(ISaveable saveable) { if (IsIgnoringStateSynchronization) { return; } GameState.Set(saveable.Id, saveable.Save(), saveable.Context); }
public ISaveable FromData(Godot.Collections.Dictionary data) { Type type = Type.GetType((string)data["type"]); ISaveable saveable = (ISaveable)Activator.CreateInstance(type); DecodeObject(saveable, data); return(saveable); }
private string ExistingEntityGuard(ISaveable entity, object id) { if (entity == null) { return "the record with key " + id + " was not found."; } var userSessionId = entity.UserSessionId; if (userSessionId == null || userSessionId == Guid.Empty) { return "changes to an original record may not be saved."; } if (userSessionId != UserSessionId) { return "you may only change records created within your own user session."; } return null; // ok so far }
/// <summary> /// Links the logs to a settings field performing a save every time log is inserted. /// </summary> /// <param name="settings">The AppSettings</param> /// <param name="target">The field that holds the logs</param> public void LinkToSettings(ISaveable settings, ref List<string> target) { _settingsSaver = settings; _settingsHolder = target; Items.Clear(); Items.AddRange(target.Cast<object>().ToArray()); }