Skip to content

Commit

Permalink
Configuration!
Browse files Browse the repository at this point in the history
  • Loading branch information
cheese3660 committed Feb 25, 2023
1 parent 66c6bbc commit c03d497
Show file tree
Hide file tree
Showing 8 changed files with 162 additions and 46 deletions.
13 changes: 12 additions & 1 deletion ModTemplateGenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# config/
# ModId
# Mod.cs
# Config.cs
# mod_project.csproj
# external_dlls/
# .gitignore
Expand Down Expand Up @@ -141,8 +142,10 @@
readme.write("# Default Readme")
code_folder = project_name + "/" + project_name + "/" + namespace
with open(code_folder + "/" + namespace + "Mod.cs","w") as default_code:
default_code.write("using SpaceWarp.API;\n\nnamespace " + namespace + "\n{\n [MainMod]\n public class " + namespace + "Mod : Mod\n {\n public override void Initialize()\n {\n Logger.Info(\"Mod is initialized\");\n }\n }\n}")
default_code.write("using SpaceWarp.API.Mods;\n\nnamespace " + namespace + "\n{\n [MainMod]\n public class " + namespace + "Mod : Mod\n {\n public override void Initialize()\n {\n Logger.Info(\"Mod is initialized\");\n }\n }\n}")

with open(code_folder + "/" + namespace + "Config.cs","w") as default_config:
default_config.write("using SpaceWarp.API.Configuration;\nusing Newtonsoft.Json;\n\nnamespace " + namespace + "\n{\n [JsonObject(MemberSerialization.OptOut)]\n [ModConfig]\n public class " + namespace + "Config\n {\n [ConfigField(\"pi\")] [ConfigDefaultValue(3.14159)] public double pi;\n }\n}")


def quickCreateProperty(root,name,text):
Expand Down Expand Up @@ -184,5 +187,13 @@ def quickCreateProperty(root,name,text):
ref4.setAttribute("Include","..\\external_dlls\\Assembly-CSharp.dll")
itemGroup.appendChild(ref4)

ref5 = root.createElement('Reference')
ref5.setAttribute("Include","..\\external_dlls\\NewtonSoft.Json.dll")
itemGroup.appendChild(ref5)

ref6 = root.createElement('Reference')
ref6.setAttribute("Include","..\\external_dlls\\NewtonSoft.Json.dll")
itemGroup.appendChild(ref6)

xml_str = root.toprettyxml(indent = ' ')
csproj.write(xml_str)
20 changes: 0 additions & 20 deletions SpaceWarp/API/Configuration/ConfigSliderAttribute.cs

This file was deleted.

24 changes: 21 additions & 3 deletions SpaceWarp/API/Configuration/ConfigurationManager.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,31 @@
using System;
using System.Collections.Generic;
using System.IO;
using SpaceWarp.API.Managers;
using Newtonsoft.Json;

namespace SpaceWarp.API.Configuration
{
public class ConfigurationManager
public class ConfigurationManager : Manager
{
public static readonly Dictionary<string, (Type configType, object configObject)> ModConfigurations = new Dictionary<string, (Type configType, object configObject)>();

private readonly Dictionary<string, (Type configType, object configObject, string path)> ModConfigurations = new Dictionary<string, (Type configType, object configObject, string path)>();
public void Add(string id, (Type configType, object configObject, string path) configuration)
{
if (ModConfigurations.ContainsKey(id)) return;
ModConfigurations[id] = configuration;
}

public bool TryGet(string id, out (Type configType, object configObject, string path) config)
{
return ModConfigurations.TryGetValue(id, out config);
}

public void UpdateConfiguration(string id)
{
if (!ModConfigurations.TryGetValue(id, out (Type, object, string) config))
return;
// Saves the new configuration
File.WriteAllText(config.Item3,JsonConvert.SerializeObject(config.Item2));
}
}
}
6 changes: 4 additions & 2 deletions SpaceWarp/API/Configuration/ModConfigAttribute.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
namespace SpaceWarp.API.Configuration
using System;

namespace SpaceWarp.API.Configuration
{
public class ModConfigAttribute
public class ModConfigAttribute : Attribute
{

}
Expand Down
86 changes: 83 additions & 3 deletions SpaceWarp/API/SpaceWarpManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,26 @@ protected override void Start()
/// </summary>
private void Initialize()
{
InitializeConfigManager();
InitializeSpaceWarpConfig();

InitializeModLogger();

InitializePatches();
}

///<summary>
///Initializes the configuration manager
///</summary>
public void InitializeConfigManager()
{
var confManagerObject = new GameObject("Configuration Manager");
DontDestroyOnLoad(confManagerObject);
confManagerObject.AddComponent<ConfigurationManager>();
confManagerObject.SetActive(true);
}


/// <summary>
/// Initializes Harmony
/// </summary>
Expand Down Expand Up @@ -250,7 +263,7 @@ private bool TryLoadMod(string codePath, string modName, out Type mainModType)
}
catch
{
_modLogger.Error("Could not load mod: {modName}, unable to read directory");
_modLogger.Error($"Could not load mod: {modName}, unable to read directory");
mainModType = null;
return false;
}
Expand Down Expand Up @@ -294,6 +307,21 @@ private bool TryLoadMod(string codePath, string modName, out Type mainModType)
return false;
}


// We want to load the configuration for the mod as well
Type configurationModType = null;
foreach (Assembly asm in modAssemblies)
{
configurationModType = asm.GetTypes()
.FirstOrDefault(type => type.GetCustomAttribute <ModConfigAttribute>() != null);
if (configurationModType != null) break;
}

if (configurationModType != null)
{
InitializeModConfig(configurationModType, modName);
}

if (!typeof(Mod).IsAssignableFrom(mainModType))
{
_modLogger.Error($"Could not load mod: {modName}, the found class ({mainModType.FullName}) with [MainMod] doesn't inherit from {nameof(Mod)}");
Expand All @@ -307,7 +335,59 @@ private bool TryLoadMod(string codePath, string modName, out Type mainModType)
}

/// <summary>
/// Tried to find the SpaceWarp config file in the game, if none is round one is created.
/// Tries to find a specific mods config file, if none is found, one is created
/// </summary>
private void InitializeModConfig(Type config_type, string mod_id)
{
object modConfiguration = null;
var config_path = MODS_FULL_PATH + "\\" + mod_id + "\\config\\config.json";
if (!File.Exists(config_path))
{
modConfiguration = Activator.CreateInstance(config_type);
foreach (var fieldInfo in config_type.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
var def = fieldInfo.GetCustomAttribute<ConfigDefaultValueAttribute>();
if (def != null)
{
fieldInfo.SetValue(modConfiguration, def.DefaultValue);
}
}
}
else
{
try
{
string json = File.ReadAllText(config_path);
modConfiguration = JsonConvert.DeserializeObject(json,config_type);

}
catch (Exception exception)
{
_modLogger.Error($"Loading mod config failed\nException: {exception}");

File.Delete(config_path);
InitializeSpaceWarpConfig();
return;
}
}

try
{
File.WriteAllLines(config_path, new[] { JsonConvert.SerializeObject(modConfiguration) });
}
catch (Exception exception)
{
_modLogger.Error($"Saving mod config failed\nException: {exception}");
}

if (ManagerLocator.TryGet(out ConfigurationManager configurationManager))
{
configurationManager.Add(mod_id,(config_type,modConfiguration,config_path));
}
}

/// <summary>
/// Tried to find the SpaceWarp config file in the game, if none is found one is created.
/// </summary>
/// <param name="spaceWarpGlobalConfiguration"></param>
private void InitializeSpaceWarpConfig()
Expand Down
1 change: 0 additions & 1 deletion SpaceWarp/SpaceWarp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@
<ItemGroup>
<Compile Include="API\Configuration\ConfigDefaultValueAttribute.cs" />
<Compile Include="API\Configuration\ConfigFieldAttribute.cs" />
<Compile Include="API\Configuration\ConfigSliderAttribute.cs" />
<Compile Include="API\Configuration\ConfigurationManager.cs" />
<Compile Include="API\Configuration\DependencyInfo.cs" />
<Compile Include="API\Configuration\ModConfigAttribute.cs" />
Expand Down
37 changes: 22 additions & 15 deletions SpaceWarp/UI/ModConfigurationUI.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using KSP.Game;
using SpaceWarp.API.Configuration;
using SpaceWarp.API.Managers;
using UnityEngine;

namespace SpaceWarp.UI
Expand All @@ -19,7 +21,6 @@ public class ModConfigurationUI : KerbalMonoBehaviour
private int windowWidth = 350;
private int windowHeight = 700;
private Rect windowRect;
public ConfigurationManager manager;


private List<(string name, FieldInfo info, object confAttribute)> fieldsToConfigure =
Expand All @@ -33,7 +34,7 @@ void Awake()

public void Start()
{
foreach (var field in configurationType.GetFields())
foreach (var field in configurationType.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
object attribute = null;
string attributeName = "";
Expand All @@ -45,16 +46,6 @@ public void Start()
fieldsToConfigure.Add((attributeName, field, attribute));

}
else
{
var sliderAttribute = field.GetCustomAttribute<ConfigSliderAttribute>();
if (sliderAttribute != null)
{
attribute = sliderAttribute;
attributeName = sliderAttribute.Name;
fieldsToConfigure.Add((attributeName, field, attribute));
}
}
}
windowRect = new Rect((Screen.width * 0.15f), (Screen.height * 0.15f),
0, 0);
Expand All @@ -65,16 +56,28 @@ public void OnGUI()
GUIUtility.GetControlID(FocusType.Passive),
windowRect,
FillWindow,
$"{modName} configuration",
$"{modID} configuration",
GUILayout.Width((float)(windowWidth * 0.5)),
GUILayout.Height((float)(windowHeight * 0.5))
);
}



public void EditorInputField(string fieldName, FieldInfo info, ConfigFieldAttribute fieldAttribute)
{
GUILayout.BeginHorizontal();
GUILayout.Label(fieldName);
var val = GUILayout.TextField(info.GetValue(configurationObject).ToString());
info.SetValue(configurationObject, TypeDescriptor.GetConverter(info.FieldType).ConvertFromInvariantString(val));
GUILayout.EndHorizontal();
}

public void EditorForField((string name, FieldInfo info, object confAttribute) field)
{

if (field.confAttribute is ConfigFieldAttribute fieldAttribute)
{
EditorInputField(field.name,field.info,fieldAttribute);
}
}
private static GUIStyle boxStyle;

Expand All @@ -90,6 +93,10 @@ private void FillWindow(int windowID)
if (GUILayout.Button("Save and close"))
{
//Run saving code from the configuration manager
if (ManagerLocator.TryGet(out ConfigurationManager configurationManager))
{
configurationManager.UpdateConfiguration(modID);
}
Destroy(this);
}
GUILayout.EndVertical();
Expand Down
21 changes: 20 additions & 1 deletion SpaceWarp/UI/ModListUI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using KSP.Game;
using SpaceWarp.API;
using SpaceWarp.API.Configuration;
using SpaceWarp.API.Managers;
using UnityEngine;

namespace SpaceWarp.UI
Expand Down Expand Up @@ -68,7 +69,7 @@ private void FillWindow(int windowID)
GUILayout.BeginVertical();
scrollPositionMods = GUILayout.BeginScrollView(scrollPositionMods, false, true,
GUILayout.Height((float)(windowHeight * 0.8)), GUILayout.Width(300));
foreach ((string modID, ModInfo modInfo) in manager.loadedMods)
foreach ((string modID, ModInfo modInfo) in manager.LoadedMods)
{
if (GUILayout.Button(modID))
{
Expand All @@ -91,6 +92,24 @@ private void FillWindow(int windowID)
{
GUILayout.Label($"{dependency.id}: {dependency.version.min} - {dependency.version.max}");
}

if (ManagerLocator.TryGet(out ConfigurationManager configManager))
{
if (configManager.TryGet(selectedModInfo.mod_id, out var config))
{
if (GUILayout.Button("Configure"))
{
GameObject go = new GameObject(selectedModInfo.mod_id);
go.transform.SetParent(transform);
ModConfigurationUI configUI = go.AddComponent<ModConfigurationUI>();
configUI.configurationType = config.configType;
configUI.configurationObject = config.configObject;
configUI.name = selectedModInfo.name;
configUI.modID = selectedModInfo.mod_id;
go.SetActive(true);
}
}
}
}
else
{
Expand Down

0 comments on commit c03d497

Please sign in to comment.