Use JSON serialization settings

This commit is contained in:
Nick 2022-05-22 00:47:01 -04:00
parent 134ba469d3
commit 0e545850cc

View File

@ -1,10 +1,12 @@
using NewHorizons.External; using NewHorizons.External;
using NewHorizons.External.Configs; using NewHorizons.External.Configs;
using NewHorizons.External.Modules; using NewHorizons.External.Modules;
using Newtonsoft.Json;
using OWML.Common; using OWML.Common;
using OWML.Common.Menus; using OWML.Common.Menus;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -47,15 +49,22 @@ namespace NewHorizons.Utility.DebugUtilities
private bool saveButtonUnlocked = false; private bool saveButtonUnlocked = false;
private Vector2 recentModListScrollPosition = Vector2.zero; private Vector2 recentModListScrollPosition = Vector2.zero;
private static JsonSerializerSettings jsonSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
Formatting = Formatting.Indented,
};
private void Awake() private void Awake()
{ {
_dpp = this.GetRequiredComponent<DebugPropPlacer>(); _dpp = this.GetRequiredComponent<DebugPropPlacer>();
_drc = this.GetRequiredComponent<DebugRaycaster>(); _drc = this.GetRequiredComponent<DebugRaycaster>();
LoadFavoriteProps(); LoadFavoriteProps();
} }
private void Start()
{ private void Start()
{
if (!Main.Debug) return; if (!Main.Debug) return;
if (!staticInitialized) if (!staticInitialized)
{ {
@ -64,11 +73,11 @@ namespace NewHorizons.Utility.DebugUtilities
Main.Instance.ModHelper.Menus.PauseMenu.OnInit += PauseMenuInitHook; Main.Instance.ModHelper.Menus.PauseMenu.OnInit += PauseMenuInitHook;
Main.Instance.ModHelper.Menus.PauseMenu.OnClosed += CloseMenu; Main.Instance.ModHelper.Menus.PauseMenu.OnClosed += CloseMenu;
Main.Instance.ModHelper.Menus.PauseMenu.OnOpened += RestoreMenuOpennessState; Main.Instance.ModHelper.Menus.PauseMenu.OnOpened += RestoreMenuOpennessState;
PauseMenuInitHook(); PauseMenuInitHook();
Main.Instance.OnChangeStarSystem.AddListener((string s) => SaveLoadedConfigsForRecentSystem()); Main.Instance.OnChangeStarSystem.AddListener((string s) => SaveLoadedConfigsForRecentSystem());
} }
else else
{ {
InitMenu(); InitMenu();
@ -85,6 +94,7 @@ namespace NewHorizons.Utility.DebugUtilities
pauseMenuButton = Main.Instance.ModHelper.Menus.PauseMenu.OptionsButton.Duplicate("Toggle Prop Placer Menu".ToUpper()); pauseMenuButton = Main.Instance.ModHelper.Menus.PauseMenu.OptionsButton.Duplicate("Toggle Prop Placer Menu".ToUpper());
InitMenu(); InitMenu();
} }
private void RestoreMenuOpennessState() { menuOpen = openMenuOnPause; } private void RestoreMenuOpennessState() { menuOpen = openMenuOnPause; }
private void ToggleMenu() { menuOpen = !menuOpen; openMenuOnPause = !openMenuOnPause; } private void ToggleMenu() { menuOpen = !menuOpen; openMenuOnPause = !openMenuOnPause; }
@ -103,13 +113,13 @@ namespace NewHorizons.Utility.DebugUtilities
this.favoriteProps.Add(favoriteProp); this.favoriteProps.Add(favoriteProp);
} }
} }
private void OnGUI() private void OnGUI()
{ {
if (!menuOpen) return; if (!menuOpen) return;
if (!Main.Debug) return; if (!Main.Debug) return;
Vector2 menuPosition = new Vector2(10, 40); Vector2 menuPosition = new Vector2(10, 40);
GUILayout.BeginArea(new Rect(menuPosition.x, menuPosition.y, EditorMenuSize.x, EditorMenuSize.y), _editorMenuStyle); GUILayout.BeginArea(new Rect(menuPosition.x, menuPosition.y, EditorMenuSize.x, EditorMenuSize.y), _editorMenuStyle);
@ -118,18 +128,18 @@ namespace NewHorizons.Utility.DebugUtilities
// //
GUILayout.Label("Recently placed objects"); GUILayout.Label("Recently placed objects");
_dpp.SetCurrentObject(GUILayout.TextArea(_dpp.currentObject)); _dpp.SetCurrentObject(GUILayout.TextArea(_dpp.currentObject));
GUILayout.Space(5); GUILayout.Space(5);
// List of recently placed objects // List of recently placed objects
GUILayout.Label("Recently placed objects"); GUILayout.Label("Recently placed objects");
recentPropsScrollPosition = GUILayout.BeginScrollView(recentPropsScrollPosition, GUILayout.Width(EditorMenuSize.x), GUILayout.Height(100)); recentPropsScrollPosition = GUILayout.BeginScrollView(recentPropsScrollPosition, GUILayout.Width(EditorMenuSize.x), GUILayout.Height(100));
foreach (string propPath in DebugPropPlacer.RecentlyPlacedProps) foreach (string propPath in DebugPropPlacer.RecentlyPlacedProps)
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
var propPathElements = propPath.Split('/'); var propPathElements = propPath.Split('/');
string propName = propPathElements[propPathElements.Length-1]; string propName = propPathElements[propPathElements.Length - 1];
string favoriteButtonIcon = favoriteProps.Contains(propPath) ? "★" : "☆"; string favoriteButtonIcon = favoriteProps.Contains(propPath) ? "★" : "☆";
if (GUILayout.Button(favoriteButtonIcon, GUILayout.ExpandWidth(false))) if (GUILayout.Button(favoriteButtonIcon, GUILayout.ExpandWidth(false)))
@ -144,9 +154,9 @@ namespace NewHorizons.Utility.DebugUtilities
} }
string[] favoritePropsArray = favoriteProps.ToArray<string>(); string[] favoritePropsArray = favoriteProps.ToArray<string>();
PlayerPrefs.SetString(favoritePropsPlayerPrefKey, string.Join(separatorCharacter+"", favoritePropsArray)); PlayerPrefs.SetString(favoritePropsPlayerPrefKey, string.Join(separatorCharacter + "", favoritePropsArray));
} }
if (GUILayout.Button(propName)) if (GUILayout.Button(propName))
{ {
_dpp.SetCurrentObject(propPath); _dpp.SetCurrentObject(propPath);
@ -155,7 +165,7 @@ namespace NewHorizons.Utility.DebugUtilities
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
GUILayout.EndScrollView(); GUILayout.EndScrollView();
GUILayout.Space(5); GUILayout.Space(5);
// continue working on existing mod // continue working on existing mod
@ -163,7 +173,7 @@ namespace NewHorizons.Utility.DebugUtilities
GUILayout.Label("Name of your mod"); GUILayout.Label("Name of your mod");
if (loadedMod == null) if (loadedMod == null)
{ {
recentModListScrollPosition = GUILayout.BeginScrollView(recentModListScrollPosition, GUILayout.Width(EditorMenuSize.x), GUILayout.Height(100)); recentModListScrollPosition = GUILayout.BeginScrollView(recentModListScrollPosition, GUILayout.Width(EditorMenuSize.x), GUILayout.Height(100));
foreach (var mod in Main.MountedAddons) foreach (var mod in Main.MountedAddons)
{ {
@ -174,7 +184,7 @@ namespace NewHorizons.Utility.DebugUtilities
} }
GUILayout.EndScrollView(); GUILayout.EndScrollView();
} }
else else
{ {
GUILayout.Label(loadedMod.ModHelper.Manifest.UniqueName); GUILayout.Label(loadedMod.ModHelper.Manifest.UniqueName);
@ -184,7 +194,7 @@ namespace NewHorizons.Utility.DebugUtilities
// save your work // save your work
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
if (GUILayout.Button(saveButtonUnlocked ? " O " : " | ", GUILayout.ExpandWidth(false))) if (GUILayout.Button(saveButtonUnlocked ? " O " : " | ", GUILayout.ExpandWidth(false)))
{ {
@ -209,7 +219,7 @@ namespace NewHorizons.Utility.DebugUtilities
DebugPropPlacer.active = true; DebugPropPlacer.active = true;
var folder = loadedMod.ModHelper.Manifest.ModFolderPath; var folder = loadedMod.ModHelper.Manifest.ModFolderPath;
List<NewHorizonsBody> bodiesForThisMod = Main.BodyDict.Values.SelectMany(x => x).Where(x => x.Mod == loadedMod).ToList(); List<NewHorizonsBody> bodiesForThisMod = Main.BodyDict.Values.SelectMany(x => x).Where(x => x.Mod == loadedMod).ToList();
foreach (NewHorizonsBody body in bodiesForThisMod) foreach (NewHorizonsBody body in bodiesForThisMod)
{ {
@ -226,7 +236,7 @@ namespace NewHorizons.Utility.DebugUtilities
private void SaveLoadedConfigsForRecentSystem() private void SaveLoadedConfigsForRecentSystem()
{ {
UpdateLoadedConfigsForRecentSystem(); UpdateLoadedConfigsForRecentSystem();
string backupFolderName = "configBackups\\" + DateTime.Now.ToString("yyyyMMddTHHmmss") + "\\"; string backupFolderName = "configBackups\\" + DateTime.Now.ToString("yyyyMMddTHHmmss") + "\\";
Logger.Log($"Potentially saving {loadedConfigFiles.Keys.Count} files"); Logger.Log($"Potentially saving {loadedConfigFiles.Keys.Count} files");
@ -236,32 +246,38 @@ namespace NewHorizons.Utility.DebugUtilities
if (loadedConfigFiles[filePath].StarSystem != Main.Instance.CurrentStarSystem) continue; if (loadedConfigFiles[filePath].StarSystem != Main.Instance.CurrentStarSystem) continue;
var relativePath = filePath.Replace(loadedMod.ModHelper.Manifest.ModFolderPath, ""); var relativePath = filePath.Replace(loadedMod.ModHelper.Manifest.ModFolderPath, "");
try
{
Logger.Log("Saving... " + relativePath + " to " + filePath);
var directoryName = System.IO.Path.GetDirectoryName(loadedMod.ModHelper.Manifest.ModFolderPath + relativePath);
System.IO.Directory.CreateDirectory(directoryName);
loadedMod.ModHelper.Storage.Save(loadedConfigFiles[filePath], relativePath);
}
catch (Exception e) { Logger.LogError("Failed to save file " + backupFolderName+relativePath); Logger.LogError(e.Message + "\n" + e.StackTrace); }
try var json = JsonConvert.SerializeObject(loadedConfigFiles[filePath], jsonSettings);
{ // Add the schema line
var directoryName = System.IO.Path.GetDirectoryName(Main.Instance.ModHelper.Manifest.ModFolderPath + backupFolderName + relativePath); json = "{\n\t\"$schema\": \"https://raw.githubusercontent.com/xen-42/outer-wilds-new-horizons/main/NewHorizons/Schemas/body_schema.json\"," + json.Substring(1);
System.IO.Directory.CreateDirectory(directoryName);
try
Main.Instance.ModHelper.Storage.Save(loadedConfigFiles[filePath], backupFolderName+relativePath); {
} Logger.Log("Saving... " + relativePath + " to " + filePath);
catch (Exception e) { Logger.LogError("Failed to save backup file " + backupFolderName+relativePath); Logger.LogError(e.Message + "\n" + e.StackTrace); } var path = loadedMod.ModHelper.Manifest.ModFolderPath + relativePath;
var directoryName = Path.GetDirectoryName(path);
Directory.CreateDirectory(directoryName);
File.WriteAllText(path, json);
}
catch (Exception e) { Logger.LogError("Failed to save file " + backupFolderName + relativePath); Logger.LogError(e.Message + "\n" + e.StackTrace); }
try
{
var path = Main.Instance.ModHelper.Manifest.ModFolderPath + backupFolderName + relativePath;
var directoryName = Path.GetDirectoryName(path);
Directory.CreateDirectory(directoryName);
File.WriteAllText(path, json);
}
catch (Exception e) { Logger.LogError("Failed to save backup file " + backupFolderName + relativePath); Logger.LogError(e.Message + "\n" + e.StackTrace); }
} }
} }
private void UpdateLoadedConfigsForRecentSystem() private void UpdateLoadedConfigsForRecentSystem()
{ {
var newDetails = _dpp.GetPropsConfigByBody(); var newDetails = _dpp.GetPropsConfigByBody();
Logger.Log("Updating config files. New Details Counts by planet: " + string.Join(", ", newDetails.Keys.Select(x => x + $" ({newDetails[x].Length})"))); Logger.Log("Updating config files. New Details Counts by planet: " + string.Join(", ", newDetails.Keys.Select(x => x + $" ({newDetails[x].Length})")));
Dictionary<string, string> planetToConfigPath = new Dictionary<string, string>(); Dictionary<string, string> planetToConfigPath = new Dictionary<string, string>();
@ -272,7 +288,7 @@ namespace NewHorizons.Utility.DebugUtilities
Logger.Log("potentially updating copy of config at " + filePath); Logger.Log("potentially updating copy of config at " + filePath);
if (loadedConfigFiles[filePath].StarSystem != Main.Instance.CurrentStarSystem) return; if (loadedConfigFiles[filePath].StarSystem != Main.Instance.CurrentStarSystem) return;
if (loadedConfigFiles[filePath].Name == null || AstroObjectLocator.GetAstroObject(loadedConfigFiles[filePath].Name) == null) { Logger.Log("Failed to update copy of config at " + filePath); continue; } if (loadedConfigFiles[filePath].Name == null || AstroObjectLocator.GetAstroObject(loadedConfigFiles[filePath].Name) == null) { Logger.Log("Failed to update copy of config at " + filePath); continue; }
var astroObjectName = DebugPropPlacer.GetAstroObjectName(loadedConfigFiles[filePath].Name); var astroObjectName = DebugPropPlacer.GetAstroObjectName(loadedConfigFiles[filePath].Name);
planetToConfigPath[astroObjectName] = filePath; planetToConfigPath[astroObjectName] = filePath;
@ -290,7 +306,7 @@ namespace NewHorizons.Utility.DebugUtilities
foreach (var astroObjectName in planetsThatDoNotHaveConfigFiles) foreach (var astroObjectName in planetsThatDoNotHaveConfigFiles)
{ {
Logger.Log("Fabricating new config file for " + astroObjectName); Logger.Log("Fabricating new config file for " + astroObjectName);
var filepath = "planets/" + Main.Instance.CurrentStarSystem + "/" + astroObjectName + ".json"; var filepath = "planets/" + Main.Instance.CurrentStarSystem + "/" + astroObjectName + ".json";
PlanetConfig c = new PlanetConfig(); PlanetConfig c = new PlanetConfig();
c.StarSystem = Main.Instance.CurrentStarSystem; c.StarSystem = Main.Instance.CurrentStarSystem;
@ -305,14 +321,13 @@ namespace NewHorizons.Utility.DebugUtilities
private void InitMenu() private void InitMenu()
{ {
if (_editorMenuStyle != null) return; if (_editorMenuStyle != null) return;
// TODO: figure out how to clear this event list so that we don't pile up useless instances of the DebugMenu that can't get garbage collected // TODO: figure out how to clear this event list so that we don't pile up useless instances of the DebugMenu that can't get garbage collected
pauseMenuButton.OnClick += ToggleMenu; pauseMenuButton.OnClick += ToggleMenu;
_dpp = this.GetRequiredComponent<DebugPropPlacer>(); _dpp = this.GetRequiredComponent<DebugPropPlacer>();
_drc = this.GetRequiredComponent<DebugRaycaster>(); _drc = this.GetRequiredComponent<DebugRaycaster>();
Texture2D bgTexture = ImageUtilities.MakeSolidColorTexture((int)EditorMenuSize.x, (int)EditorMenuSize.y, Color.black); Texture2D bgTexture = ImageUtilities.MakeSolidColorTexture((int)EditorMenuSize.x, (int)EditorMenuSize.y, Color.black);
_editorMenuStyle = new GUIStyle _editorMenuStyle = new GUIStyle