using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using GraveyardOrbit;
using GraveyardOrbit.UI;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.UIElements;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
internal sealed class RefSafetyRulesAttribute : Attribute
{
public readonly int Version;
public RefSafetyRulesAttribute(int P_0)
{
Version = P_0;
}
}
}
namespace GraveFramework
{
[HarmonyPatch(typeof(AnomalyCatalog), "EnsureLoaded")]
internal static class AnomaliesInjectPatch
{
private static readonly FieldInfo AllField = AccessTools.Field(typeof(AnomalyCatalog), "_all");
private static readonly FieldInfo ByIdField = AccessTools.Field(typeof(AnomalyCatalog), "_byId");
internal static readonly InjectedTracker Tracker = new InjectedTracker();
private static void Postfix()
{
Tracker.RunOnce(Apply);
}
public static void Reload()
{
Tracker.Reload(delegate(IReadOnlyCollection<string> ids)
{
List<AnomalyDef> obj = (List<AnomalyDef>)AllField.GetValue(null);
Dictionary<string, AnomalyDef> dictionary = (Dictionary<string, AnomalyDef>)ByIdField.GetValue(null);
obj.RemoveAll((AnomalyDef a) => ids.Contains(a.id));
foreach (string id in ids)
{
dictionary.Remove(id);
AnomalyCatalog.Implemented.Remove(id);
}
}, Apply);
}
private static void Apply()
{
List<AnomalyDef> all = (List<AnomalyDef>)AllField.GetValue(null);
Dictionary<string, AnomalyDef> byId = (Dictionary<string, AnomalyDef>)ByIdField.GetValue(null);
ContentInjector.ScanFolder("NewAnomalies", ModDiscovery.Current, "anomalies", byId.ContainsKey, BuildFromJson, delegate(AnomalyDef def, string id)
{
all.Add(def);
byId[id] = def;
Tracker.Add(id);
AnomalyCatalog.Implemented.Add(id);
Plugin.Log.LogInfo((object)$"NewAnomalies: injected '{id}' (band={def.band}, charge={def.chargeSecs}s, effect={def.effectSecs}s).");
});
}
private static AnomalyDef BuildFromJson(JObject o, string file)
{
//IL_0000: Unknown result type (might be due to invalid IL or missing references)
//IL_0005: Unknown result type (might be due to invalid IL or missing references)
//IL_001b: Unknown result type (might be due to invalid IL or missing references)
//IL_0031: Unknown result type (might be due to invalid IL or missing references)
//IL_0047: Unknown result type (might be due to invalid IL or missing references)
//IL_005d: Unknown result type (might be due to invalid IL or missing references)
//IL_0080: Unknown result type (might be due to invalid IL or missing references)
//IL_009e: Unknown result type (might be due to invalid IL or missing references)
//IL_00b5: Expected O, but got Unknown
return new AnomalyDef
{
id = (string)o["id"],
name = (string)o["name"],
band = (string)o["band"],
blurb = (string)o["blurb"],
chargeSecs = (((float?)o["chargeSecs"]) ?? 75f),
effectSecs = ((float?)o["effectSecs"]).GetValueOrDefault(),
p = (JObject)/*isinst with value type is only supported in some contexts*/
};
}
}
[HarmonyPatch(typeof(MiningSortie), "FireAnomaly")]
internal static class FireAnomalyAliasPatch
{
private static bool Prefix(string id, ref bool __result)
{
if (!AnomaliesInjectPatch.Tracker.Contains(id))
{
return true;
}
GameState i = GameState.I;
AnomalyDef val = AnomalyCatalog.Get(id);
if (i == null || val == null)
{
__result = false;
return false;
}
i.TriggerWarCry(val.effectSecs, val.P("damage", 5f), val.P("rate", 2f));
Plugin.Log.LogInfo((object)string.Format("NewAnomalies: fired custom anomaly '{0}' via TriggerWarCry alias (effect={1}s, damage={2}, rate={3}).", id, val.effectSecs, val.P("damage", 5f), val.P("rate", 2f)));
__result = true;
return false;
}
}
[HarmonyPatch(typeof(BoosterCatalog), "EnsureLoaded")]
internal static class BoostersInjectPatch
{
private static readonly FieldInfo AllField = AccessTools.Field(typeof(BoosterCatalog), "_all");
private static readonly InjectedTracker Tracker = new InjectedTracker();
private static void Postfix()
{
Tracker.RunOnce(Apply);
}
public static void Reload()
{
Tracker.Reload(delegate(IReadOnlyCollection<string> ids)
{
((List<BoosterDef>)AllField.GetValue(null)).RemoveAll((BoosterDef b) => ids.Contains(b.id));
}, Apply);
}
private static void Apply()
{
List<BoosterDef> all = (List<BoosterDef>)AllField.GetValue(null);
ContentInjector.ScanFolder("NewBoosters", ModDiscovery.Current, "boosters", (string id) => all.Any((BoosterDef b) => b.id == id), BuildFromJson, delegate(BoosterDef def, string id)
{
//IL_0023: Unknown result type (might be due to invalid IL or missing references)
all.Add(def);
Tracker.Add(id);
Plugin.Log.LogInfo((object)string.Format("NewBoosters: injected '{0}' (rarity={1}, stats={2}).", id, def.rarity, string.Join(",", def.stats.Keys)));
});
}
private static BoosterDef BuildFromJson(JObject o, string file)
{
//IL_0032: Unknown result type (might be due to invalid IL or missing references)
//IL_0033: Unknown result type (might be due to invalid IL or missing references)
//IL_0038: Unknown result type (might be due to invalid IL or missing references)
//IL_004e: Unknown result type (might be due to invalid IL or missing references)
//IL_0064: Unknown result type (might be due to invalid IL or missing references)
//IL_007a: Unknown result type (might be due to invalid IL or missing references)
//IL_007b: Unknown result type (might be due to invalid IL or missing references)
//IL_007c: Unknown result type (might be due to invalid IL or missing references)
//IL_0082: Expected O, but got Unknown
string text = (string)o["rarity"];
BoosterRarity rarity = (BoosterRarity)((text == "gold") ? 2 : ((text == "rare") ? 1 : 0));
BoosterDef val = new BoosterDef
{
id = (string)o["id"],
name = (string)o["name"],
group = (string)o["group"],
rarity = rarity
};
JToken obj = o["stats"];
JObject val2 = (JObject)(object)((obj is JObject) ? obj : null);
if (val2 != null)
{
foreach (JProperty item in val2.Properties())
{
val.stats[item.Name] = (float)item.Value;
}
}
return val;
}
}
internal static class ContentInjector
{
public static void ScanFolder<TDef>(string tag, IEnumerable<DiscoveredMod> mods, string folderName, Func<string, bool> alreadyExists, Func<JObject, string, TDef> build, Action<TDef, string> onAdd, string skipSuffix = null) where TDef : class
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (DiscoveredMod mod in mods)
{
string path = Path.Combine(mod.RootDir, "content", folderName);
if (!Directory.Exists(path))
{
continue;
}
string[] files = Directory.GetFiles(path, "*.json");
foreach (string text in files)
{
if (skipSuffix != null && text.EndsWith(skipSuffix, StringComparison.OrdinalIgnoreCase))
{
continue;
}
string text2 = null;
try
{
JObject val = JObject.Parse(File.ReadAllText(text));
text2 = (string)val["id"];
string value;
if (string.IsNullOrEmpty(text2))
{
Plugin.Log.LogError((object)(tag + ": '" + text + "' has no 'id', skipping."));
LoadReport.Record(mod.Id, folderName, LoadOutcome.Rejected, Path.GetFileName(text), "no 'id'");
}
else if (dictionary.TryGetValue(text2, out value) && value != mod.Id)
{
string text3 = "id collision: mod '" + mod.Id + "' declares '" + text2 + "', already claimed by mod '" + value + "'";
Plugin.Log.LogError((object)(tag + ": " + text3 + ", skipping (" + text + ")."));
LoadReport.Record(mod.Id, folderName, LoadOutcome.Rejected, text2, text3);
}
else if (alreadyExists(text2))
{
Plugin.Log.LogError((object)(tag + ": '" + text2 + "' already exists, skipping (" + text + ")."));
LoadReport.Record(mod.Id, folderName, LoadOutcome.Skipped, text2, "already exists in the game catalog");
}
else
{
TDef val2 = build(val, text);
if (val2 == null)
{
LoadReport.Record(mod.Id, folderName, LoadOutcome.Rejected, text2, "failed validation (see log above)");
continue;
}
onAdd(val2, text2);
dictionary[text2] = mod.Id;
LoadReport.Record(mod.Id, folderName, LoadOutcome.Injected, text2);
}
}
catch (Exception ex)
{
Plugin.Log.LogError((object)$"{tag}: failed to load '{text}': {ex}");
LoadReport.Record(mod.Id, folderName, LoadOutcome.Rejected, text2 ?? Path.GetFileName(text), "load error: " + ex.Message);
}
}
}
}
}
internal sealed class InjectedTracker
{
private readonly HashSet<string> _ids = new HashSet<string>();
private bool _done;
public void Add(string id)
{
_ids.Add(id);
}
public bool Contains(string id)
{
return _ids.Contains(id);
}
public void RunOnce(Action apply)
{
if (!_done)
{
_done = true;
apply();
}
}
public void Reload(Action<IReadOnlyCollection<string>> remove, Action apply)
{
if (_ids.Count > 0)
{
remove(_ids);
_ids.Clear();
}
apply();
}
}
internal enum LoadOutcome
{
Injected,
Skipped,
Rejected
}
internal static class LoadReport
{
private sealed class Entry
{
public string ModId;
public string ContentType;
public LoadOutcome Outcome;
public string Id;
public string Reason;
}
private static readonly List<Entry> Entries = new List<Entry>();
public static void Reset()
{
Entries.Clear();
}
public static void Record(string modId, string contentType, LoadOutcome outcome, string id, string reason = null)
{
Entries.Add(new Entry
{
ModId = modId,
ContentType = contentType,
Outcome = outcome,
Id = id,
Reason = reason
});
}
public static string BuildReportText()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("=== Content load report ===");
IReadOnlyList<DiscoveredMod> current = ModDiscovery.Current;
stringBuilder.AppendLine($"Discovered mods ({current.Count}):");
foreach (DiscoveredMod item in current)
{
string s = ((item.Dependencies != null && item.Dependencies.Length != 0) ? string.Join(", ", item.Dependencies) : null);
stringBuilder.AppendLine(" " + Dash(item.Id) + " name=" + Dash(item.Name) + " version=" + Dash(item.Version) + " dependencies=" + Dash(s) + " (" + item.RootDir + ")");
}
if (Entries.Count == 0)
{
stringBuilder.Append("No content files processed yet.");
return stringBuilder.ToString();
}
IEnumerable<string> enumerable = ModDiscovery.ContentTypes.Where((string t) => Entries.Any((Entry e) => e.ContentType == t)).Concat((from t in Entries.Select((Entry e) => e.ContentType).Distinct()
where !ModDiscovery.ContentTypes.Contains(t)
select t).OrderBy<string, string>((string t) => t, StringComparer.Ordinal));
stringBuilder.AppendLine("Content:");
foreach (string type in enumerable)
{
foreach (IGrouping<string, Entry> item2 in (from e in Entries
where e.ContentType == type
group e by e.ModId).OrderBy<IGrouping<string, Entry>, string>((IGrouping<string, Entry> g) => g.Key, StringComparer.OrdinalIgnoreCase))
{
stringBuilder.AppendLine($" {type}: {item2.Key} injected={item2.Count((Entry e) => e.Outcome == LoadOutcome.Injected)} skipped={item2.Count((Entry e) => e.Outcome == LoadOutcome.Skipped)} rejected={item2.Count((Entry e) => e.Outcome == LoadOutcome.Rejected)}");
}
}
List<Entry> list = Entries.Where((Entry e) => e.Outcome != LoadOutcome.Injected).ToList();
if (list.Count > 0)
{
stringBuilder.AppendLine("Not loaded:");
foreach (Entry item3 in list)
{
stringBuilder.AppendLine(" " + item3.ContentType + ": " + item3.ModId + " '" + item3.Id + "' " + item3.Outcome.ToString().ToLowerInvariant() + ": " + Dash(item3.Reason));
}
}
return stringBuilder.ToString().TrimEnd();
}
private static string Dash(string s)
{
if (!string.IsNullOrWhiteSpace(s))
{
return s;
}
return "-";
}
}
internal sealed class DiscoveredMod
{
public string Id;
public string Name;
public string Version;
public string WebsiteUrl;
public string Description;
public string[] Dependencies;
public string RootDir;
}
internal static class ModDiscovery
{
public static readonly string[] ContentTypes = new string[5] { "structures", "mods", "boosters", "anomalies", "quotas" };
private static List<DiscoveredMod> _current;
public static IReadOnlyList<DiscoveredMod> Current
{
get
{
IReadOnlyList<DiscoveredMod> current = _current;
return current ?? Refresh();
}
}
public static IReadOnlyList<DiscoveredMod> Refresh()
{
_current = Scan();
return _current;
}
public static List<DiscoveredMod> Scan()
{
List<DiscoveredMod> list = new List<DiscoveredMod>();
string text = FindPluginsDir();
if (text == null || !Directory.Exists(text))
{
Plugin.Log.LogError((object)("ModDiscovery: could not locate the BepInEx plugins folder (from '" + Assembly.GetExecutingAssembly().Location + "')."));
return list;
}
string[] directories = Directory.GetDirectories(text);
foreach (string text2 in directories)
{
try
{
DiscoveredMod discoveredMod = TryRead(text2);
if (discoveredMod != null)
{
list.Add(discoveredMod);
}
}
catch (Exception arg)
{
Plugin.Log.LogError((object)$"ModDiscovery: failed to read mod folder '{text2}': {arg}");
}
}
list.Sort(delegate(DiscoveredMod a, DiscoveredMod b)
{
int num = string.Compare(a.Id, b.Id, StringComparison.OrdinalIgnoreCase);
return (num == 0) ? string.Compare(a.RootDir, b.RootDir, StringComparison.OrdinalIgnoreCase) : num;
});
foreach (IGrouping<string, DiscoveredMod> item in from g in list.GroupBy<DiscoveredMod, string>((DiscoveredMod m) => m.Id, StringComparer.OrdinalIgnoreCase)
where g.Count() > 1
select g)
{
Plugin.Log.LogWarning((object)("ModDiscovery: mod id '" + item.Key + "' is used by more than one folder (" + string.Join(", ", item.Select((DiscoveredMod m) => m.RootDir)) + "); their content will collide."));
}
return list;
}
private static DiscoveredMod TryRead(string dir)
{
string fileName = Path.GetFileName(dir);
string text = Path.Combine(dir, "manifest.json");
ModManifest modManifest = null;
if (File.Exists(text))
{
try
{
modManifest = ModManifest.Load(text);
}
catch (Exception ex)
{
Plugin.Log.LogError((object)("ModDiscovery: bad manifest '" + text + "' for mod '" + fileName + "', ignoring its fields: " + ex.Message));
modManifest = new ModManifest();
}
}
else if (!ContentTypes.Any((string t) => Directory.Exists(Path.Combine(dir, "content", t))))
{
return null;
}
return new DiscoveredMod
{
Id = fileName,
Name = (modManifest?.Name ?? ""),
Version = (modManifest?.VersionNumber ?? ""),
WebsiteUrl = (modManifest?.WebsiteUrl ?? ""),
Description = (modManifest?.Description ?? ""),
Dependencies = (modManifest?.Dependencies ?? new string[0]),
RootDir = Path.GetFullPath(dir)
};
}
private static string FindPluginsDir()
{
string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
for (DirectoryInfo directoryInfo = new DirectoryInfo(directoryName); directoryInfo != null; directoryInfo = directoryInfo.Parent)
{
if (string.Equals(directoryInfo.Name, "plugins", StringComparison.OrdinalIgnoreCase))
{
return directoryInfo.FullName;
}
}
return Directory.GetParent(directoryName)?.FullName;
}
}
internal sealed class ModManifest
{
public string Name;
public string VersionNumber;
public string WebsiteUrl;
public string Description;
public string[] Dependencies = new string[0];
public static ModManifest Load(string manifestPath)
{
if (!File.Exists(manifestPath))
{
return null;
}
JObject val = JObject.Parse(File.ReadAllText(manifestPath));
ModManifest obj = new ModManifest
{
Name = (string)val["name"],
VersionNumber = (string)val["version_number"],
WebsiteUrl = (string)val["website_url"],
Description = (string)val["description"]
};
JToken obj2 = val["dependencies"];
JArray val2 = (JArray)(object)((obj2 is JArray) ? obj2 : null);
obj.Dependencies = ((val2 != null) ? (from d in (IEnumerable<JToken>)val2
select (string)d into d
where !string.IsNullOrWhiteSpace(d)
select d).ToArray() : new string[0]);
return obj;
}
}
[HarmonyPatch(typeof(ModCatalog), "EnsureLoaded")]
internal static class ModsInjectPatch
{
private static readonly FieldInfo AllField = AccessTools.Field(typeof(ModCatalog), "_all");
private static readonly FieldInfo ByIdField = AccessTools.Field(typeof(ModCatalog), "_byId");
private static readonly MethodInfo ValidateMethod = AccessTools.Method(typeof(ModCatalog), "Validate", (Type[])null, (Type[])null);
private static readonly MethodInfo ValidateGraphMethod = AccessTools.Method(typeof(ModCatalog), "ValidateGraph", (Type[])null, (Type[])null);
private static readonly InjectedTracker Tracker = new InjectedTracker();
private static void Postfix()
{
Tracker.RunOnce(Apply);
}
public static void Reload()
{
Tracker.Reload(delegate(IReadOnlyCollection<string> ids)
{
List<ModDef> obj = (List<ModDef>)AllField.GetValue(null);
Dictionary<string, ModDef> dictionary = (Dictionary<string, ModDef>)ByIdField.GetValue(null);
obj.RemoveAll((ModDef d) => ids.Contains(d.id));
foreach (string id in ids)
{
dictionary.Remove(id);
}
}, Apply);
}
private static void Apply()
{
List<ModDef> all = (List<ModDef>)AllField.GetValue(null);
Dictionary<string, ModDef> byId = (Dictionary<string, ModDef>)ByIdField.GetValue(null);
bool added = false;
ContentInjector.ScanFolder("NewMods", ModDiscovery.Current, "mods", byId.ContainsKey, BuildFromJson, delegate(ModDef def, string id)
{
all.Add(def);
byId[id] = def;
Tracker.Add(id);
added = true;
Plugin.Log.LogInfo((object)$"NewMods: injected '{id}' (arm={def.arm}, kind={def.kind}, row={def.row}, col={def.col}).");
});
if (added)
{
ValidateGraphMethod.Invoke(null, null);
}
}
private static ModDef BuildFromJson(JObject o, string file)
{
//IL_0000: Unknown result type (might be due to invalid IL or missing references)
//IL_0005: Unknown result type (might be due to invalid IL or missing references)
//IL_001b: Unknown result type (might be due to invalid IL or missing references)
//IL_0031: Unknown result type (might be due to invalid IL or missing references)
//IL_0047: Unknown result type (might be due to invalid IL or missing references)
//IL_005d: Unknown result type (might be due to invalid IL or missing references)
//IL_0073: Unknown result type (might be due to invalid IL or missing references)
//IL_0092: Unknown result type (might be due to invalid IL or missing references)
//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
//IL_0108: Expected O, but got Unknown
//IL_0253: Unknown result type (might be due to invalid IL or missing references)
//IL_0259: Invalid comparison between Unknown and I4
//IL_0282: Unknown result type (might be due to invalid IL or missing references)
//IL_0288: Invalid comparison between Unknown and I4
//IL_0291: Unknown result type (might be due to invalid IL or missing references)
//IL_0297: Invalid comparison between Unknown and I4
ModDef val = new ModDef
{
id = (string)o["id"],
name = (string)o["name"],
arm = (string)o["arm"],
kind = (string)o["kind"],
legacy = (string)o["legacy"],
blurb = (((string)o["blurb"]) ?? ""),
perCopy = (((string)o["perCopy"]) ?? ""),
glyph = (string)o["glyph"],
col = (((int?)o["col"]) ?? (-1)),
row = (((int?)o["row"]) ?? (-1))
};
val.tier = ModCatalog.TierOfRow(val.row);
JToken obj = o["fits"];
JArray val2 = (JArray)(object)((obj is JArray) ? obj : null);
if (val2 != null)
{
val.fits = new string[((JContainer)val2).Count];
for (int i = 0; i < ((JContainer)val2).Count; i++)
{
val.fits[i] = (string)val2[i];
}
}
JToken obj2 = o["parents"];
JArray val3 = (JArray)(object)((obj2 is JArray) ? obj2 : null);
if (val3 != null)
{
val.parents = new string[((JContainer)val3).Count];
for (int j = 0; j < ((JContainer)val3).Count; j++)
{
val.parents[j] = (string)val3[j];
}
}
JToken obj3 = o["price"];
JObject val4 = (JObject)(object)((obj3 is JObject) ? obj3 : null);
if (val4 != null)
{
foreach (JProperty item in val4.Properties())
{
val.price[item.Name] = (int)item.Value;
}
}
JToken obj4 = o["params"];
JObject val5 = (JObject)(object)((obj4 is JObject) ? obj4 : null);
if (val5 != null)
{
foreach (JProperty item2 in val5.Properties())
{
if ((int)item2.Value.Type == 8)
{
val.sparam[item2.Name] = (string)item2.Value;
}
else if ((int)item2.Value.Type == 6 || (int)item2.Value.Type == 7)
{
val.param[item2.Name] = (float)item2.Value;
}
}
}
string text = (string)ValidateMethod.Invoke(null, new object[1] { val });
if (text != null)
{
Plugin.Log.LogError((object)("NewMods: '" + val.id + "' invalid (" + text + "), skipping (" + file + ")."));
return null;
}
return val;
}
}
[HarmonyPatch(typeof(MainMenuController), "Show")]
internal static class ModsMenuPatch
{
private const string ButtonName = "GraveFramework_ModsBtn";
private const string ModalName = "GraveFramework_ModsModal";
private static string ReloadedLabel => Loc.T("graveframework.mods_menu.reloaded", "RELOADED");
private static string ReloadLabel => Loc.T("graveframework.mods_menu.reload_button", "RELOAD MODS");
private static void Postfix(MainMenuController __instance)
{
//IL_007d: Unknown result type (might be due to invalid IL or missing references)
//IL_009f: Unknown result type (might be due to invalid IL or missing references)
//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
VisualElement root = __instance.Root;
if (root != null)
{
VisualElement val = UQueryExtensions.Q<VisualElement>(root, "MenuRoot", (string)null) ?? root;
VisualElement val2 = MetaUi.Key(Loc.F("graveframework.mods_menu.button", "MODS ({count})", new(string, object)[1] { ("count", ModDiscovery.Current.Count) }), (Action)delegate
{
OpenPanel(root);
}, 170f, (Color?)MetaUi.Blue);
val2.name = "GraveFramework_ModsBtn";
val2.style.position = StyleEnum<Position>.op_Implicit((Position)1);
val2.style.top = StyleLength.op_Implicit(40f);
val2.style.right = StyleLength.op_Implicit(40f);
val.Add(val2);
}
}
private static void OpenPanel(VisualElement root)
{
//IL_0022: Unknown result type (might be due to invalid IL or missing references)
//IL_0027: Unknown result type (might be due to invalid IL or missing references)
//IL_002c: Unknown result type (might be due to invalid IL or missing references)
//IL_0032: Unknown result type (might be due to invalid IL or missing references)
//IL_0037: Unknown result type (might be due to invalid IL or missing references)
//IL_0047: Expected O, but got Unknown
//IL_0053: Unknown result type (might be due to invalid IL or missing references)
//IL_006d: Unknown result type (might be due to invalid IL or missing references)
//IL_0087: Unknown result type (might be due to invalid IL or missing references)
//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
//IL_0110: Unknown result type (might be due to invalid IL or missing references)
//IL_0115: Unknown result type (might be due to invalid IL or missing references)
//IL_0125: Unknown result type (might be due to invalid IL or missing references)
//IL_014a: Unknown result type (might be due to invalid IL or missing references)
//IL_0154: Expected O, but got Unknown
//IL_0164: Unknown result type (might be due to invalid IL or missing references)
//IL_019a: Unknown result type (might be due to invalid IL or missing references)
//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
//IL_01af: Unknown result type (might be due to invalid IL or missing references)
//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
//IL_021e: Unknown result type (might be due to invalid IL or missing references)
//IL_0251: Unknown result type (might be due to invalid IL or missing references)
Palette palette;
ScrollView scroll;
VisualElement reloadKey;
if (UQueryExtensions.Q<VisualElement>(root, "GraveFramework_ModsModal", (string)null) == null)
{
palette = new Palette(MetaUi.Blue);
VisualElement dim = new VisualElement
{
name = "GraveFramework_ModsModal"
};
dim.style.position = StyleEnum<Position>.op_Implicit((Position)1);
dim.style.left = StyleLength.op_Implicit(0f);
dim.style.top = StyleLength.op_Implicit(0f);
dim.style.right = StyleLength.op_Implicit(0f);
dim.style.bottom = StyleLength.op_Implicit(0f);
dim.style.alignItems = StyleEnum<Align>.op_Implicit((Align)2);
dim.style.justifyContent = StyleEnum<Justify>.op_Implicit((Justify)1);
dim.style.backgroundColor = StyleColor.op_Implicit(new Color(0f, 0f, 0f, 0.7f));
VisualElement val2 = default(VisualElement);
VisualElement val3 = default(VisualElement);
VisualElement val = ModalKit.DoorCard(820f, palette, Loc.T("graveframework.mods_menu.title", "Installed Mods"), 34f, ref val2, ref val3);
scroll = new ScrollView((ScrollViewMode)0);
((VisualElement)scroll).style.maxHeight = StyleLength.op_Implicit(560f);
val2.Add((VisualElement)(object)scroll);
PopulateList();
MetaUi.AccentScroll(scroll, new Color(1f, 1f, 1f, 0.06f), ModalKit.Over(palette.accent, 0.45f), ModalKit.Over(palette.accent, 0.75f), (Func<string>)null, 6f, (Color?)null);
reloadKey = null;
reloadKey = ModalKit.DoorKey(ReloadLabel, (Action)OnReloadClicked, palette, false, (string)null);
reloadKey.style.marginRight = StyleLength.op_Implicit(ModalKit.S(16f));
val3.Add(reloadKey);
val3.Add(ModalKit.DoorKey(Loc.T("common.words.close", "CLOSE"), (Action)delegate
{
dim.RemoveFromHierarchy();
}, palette, true, (string)null));
dim.Add(val);
dim.AddToClassList("pad-modal");
PadNav.SetModalBack(dim, (Action)delegate
{
dim.RemoveFromHierarchy();
});
root.Add(dim);
UiSfx.Wire(dim);
}
void OnReloadClicked()
{
Plugin.ReloadAll();
PopulateList();
VisualElement obj = UQueryExtensions.Q<VisualElement>(root, "GraveFramework_ModsBtn", (string)null);
Button val4 = ((obj != null) ? UQueryExtensions.Q<Button>(obj, (string)null, (string)null) : null);
if (val4 != null)
{
((TextElement)val4).text = Loc.F("graveframework.mods_menu.button", "MODS ({count})", new(string, object)[1] { ("count", ModDiscovery.Current.Count) });
}
VisualElement obj2 = reloadKey;
Label label = ((obj2 != null) ? UQueryExtensions.Q<Label>(obj2, "modal-key-label", (string)null) : null);
if (label != null)
{
((TextElement)label).text = ReloadedLabel;
reloadKey.schedule.Execute((Action)delegate
{
((TextElement)label).text = ReloadLabel;
}).ExecuteLater(1200L);
}
}
void PopulateList()
{
//IL_0061: Unknown result type (might be due to invalid IL or missing references)
((VisualElement)scroll).Clear();
IReadOnlyList<DiscoveredMod> current = ModDiscovery.Current;
if (current.Count == 0)
{
((VisualElement)scroll).Add((VisualElement)(object)ModalKit.Copy(Loc.T("graveframework.mods_menu.empty", "No mods found in BepInEx/plugins."), 18f, false, 0.88f));
return;
}
foreach (DiscoveredMod item in current)
{
((VisualElement)scroll).Add(ModRow(item, palette.accent));
}
}
}
private static VisualElement ModRow(DiscoveredMod mod, Color accent)
{
//IL_0007: Unknown result type (might be due to invalid IL or missing references)
//IL_0008: Unknown result type (might be due to invalid IL or missing references)
//IL_000d: Unknown result type (might be due to invalid IL or missing references)
//IL_0012: Unknown result type (might be due to invalid IL or missing references)
//IL_001a: Expected O, but got Unknown
//IL_0025: Unknown result type (might be due to invalid IL or missing references)
//IL_003a: Unknown result type (might be due to invalid IL or missing references)
//IL_004f: Unknown result type (might be due to invalid IL or missing references)
//IL_0064: Unknown result type (might be due to invalid IL or missing references)
//IL_0079: Unknown result type (might be due to invalid IL or missing references)
//IL_0086: Unknown result type (might be due to invalid IL or missing references)
//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
//IL_00f1: Expected O, but got Unknown
//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
//IL_0109: Unknown result type (might be due to invalid IL or missing references)
//IL_013d: Unknown result type (might be due to invalid IL or missing references)
//IL_0142: Unknown result type (might be due to invalid IL or missing references)
//IL_0197: Unknown result type (might be due to invalid IL or missing references)
//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
//IL_0234: Unknown result type (might be due to invalid IL or missing references)
//IL_023e: Unknown result type (might be due to invalid IL or missing references)
VisualElement val = new VisualElement
{
pickingMode = (PickingMode)0
};
val.style.marginBottom = StyleLength.op_Implicit(10f);
val.style.paddingLeft = StyleLength.op_Implicit(22f);
val.style.paddingRight = StyleLength.op_Implicit(22f);
val.style.paddingTop = StyleLength.op_Implicit(14f);
val.style.paddingBottom = StyleLength.op_Implicit(14f);
SlabFrame frame = MetaUi.Slab(val, accent, false, 13f, 2f);
MetaUi.PaintSlab(frame, accent, false, 0.45f);
((CallbackEventHandler)val).RegisterCallback<PointerEnterEvent>((EventCallback<PointerEnterEvent>)delegate
{
//IL_0007: Unknown result type (might be due to invalid IL or missing references)
MetaUi.PaintSlab(frame, accent, false, 0.85f);
}, (TrickleDown)0);
((CallbackEventHandler)val).RegisterCallback<PointerLeaveEvent>((EventCallback<PointerLeaveEvent>)delegate
{
//IL_0007: Unknown result type (might be due to invalid IL or missing references)
MetaUi.PaintSlab(frame, accent, false, 0.45f);
}, (TrickleDown)0);
MetaUi.Lift(val, true);
VisualElement val2 = new VisualElement
{
pickingMode = (PickingMode)1
};
val2.style.flexDirection = StyleEnum<FlexDirection>.op_Implicit((FlexDirection)2);
val2.style.justifyContent = StyleEnum<Justify>.op_Implicit((Justify)3);
string text = (string.IsNullOrWhiteSpace(mod.Name) ? mod.Id : mod.Name);
val2.Add((VisualElement)(object)MetaUi.Text(text.ToUpperInvariant(), (Face)1, 22f, MetaUi.TextTone(accent), 2f, false));
if (!string.IsNullOrWhiteSpace(mod.Version))
{
val2.Add((VisualElement)(object)MetaUi.Text(Loc.F("graveframework.mods_menu.version", "v{version}", new(string, object)[1] { ("version", mod.Version) }), (Face)2, 16f, MetaUi.Fade(MetaUi.Ink, 0.6f), 0f, false));
}
val.Add(val2);
if (!string.IsNullOrWhiteSpace(mod.Description))
{
val.Add((VisualElement)(object)ModalKit.Copy(mod.Description, 16f, false, 0.8f));
}
if (mod.Dependencies != null && mod.Dependencies.Length != 0)
{
val.Add((VisualElement)(object)MetaUi.Text(Loc.F("graveframework.mods_menu.requires", "Requires: {deps}", new(string, object)[1] { ("deps", string.Join(", ", mod.Dependencies)) }), (Face)2, 14f, MetaUi.Fade(MetaUi.Ink, 0.5f), 0f, true));
}
return val;
}
}
[BepInPlugin("com.luminaex.graveframework", "GraveFramework", "1.1.0")]
public class Plugin : BaseUnityPlugin
{
public const string PluginGuid = "com.luminaex.graveframework";
public const string PluginName = "GraveFramework";
public const string PluginVersion = "1.1.0";
private const float BootReportDelaySecs = 2f;
private static readonly string[] ReloadScanSkipPrefixes = new string[9] { "System", "Mono", "Unity", "mscorlib", "netstandard", "BepInEx", "0Harmony", "Newtonsoft", "Assembly-CSharp" };
internal static ManualLogSource Log;
private float _awakeTime;
private bool _awakeTimeSet;
private bool _bootReportPrinted;
private static List<(string Name, MethodInfo Method)> _reloadMethods;
private static List<(string Name, MethodInfo Method)> ReloadMethods
{
get
{
if (_reloadMethods != null)
{
return _reloadMethods;
}
List<(string, string, MethodInfo)> list = new List<(string, string, MethodInfo)>();
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
string asmName = assembly.GetName().Name ?? "";
if (assembly.IsDynamic || ReloadScanSkipPrefixes.Any((string p) => asmName.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
{
continue;
}
Type[] source;
try
{
source = assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
source = ex.Types.Where((Type t) => t != null).ToArray();
}
catch (Exception ex2)
{
Log.LogWarning((object)("Hot-reload scan: skipping assembly '" + asmName + "', could not list its types: " + ex2.Message));
continue;
}
foreach (Type item in source.Where((Type t) => !t.ContainsGenericParameters))
{
MethodInfo method = item.GetMethod("Reload", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
if (method != null)
{
list.Add((item.Name, item.AssemblyQualifiedName ?? item.FullName ?? item.Name, method));
}
}
}
_reloadMethods = (from x in list.OrderBy<(string, string, MethodInfo), string>(((string Name, string FullName, MethodInfo Method) x) => x.Name, StringComparer.Ordinal).ThenBy<(string, string, MethodInfo), string>(((string Name, string FullName, MethodInfo Method) x) => x.FullName, StringComparer.Ordinal)
select (Name: x.Name, Method: x.Method)).ToList();
Log.LogInfo((object)("Hot-reload targets: " + string.Join(", ", _reloadMethods.Select(((string Name, MethodInfo Method) x) => x.Method.DeclaringType?.Assembly.GetName().Name + ":" + x.Name))));
return _reloadMethods;
}
}
private void Awake()
{
//IL_0010: Unknown result type (might be due to invalid IL or missing references)
Log = ((BaseUnityPlugin)this).Logger;
new Harmony("com.luminaex.graveframework").PatchAll();
Log.LogInfo((object)"Harmony patches applied — content injectors (structures/mods/boosters/anomalies/quotas) active.");
Log.LogInfo((object)"Press RELOAD MODS on the main menu's Mods page to hot-reload mod content (structures/mods/boosters/anomalies/quotas/parts) without restarting.");
}
private void Update()
{
if (!_awakeTimeSet)
{
_awakeTimeSet = true;
_awakeTime = Time.realtimeSinceStartup;
}
if (!_bootReportPrinted && Time.realtimeSinceStartup - _awakeTime >= 2f)
{
_bootReportPrinted = true;
Log.LogInfo((object)LoadReport.BuildReportText());
}
}
public static void ReloadAll()
{
Log.LogInfo((object)"=== Hot-reload requested ===");
ModDiscovery.Refresh();
LoadReport.Reset();
foreach (var reloadMethod in ReloadMethods)
{
var (name, method) = reloadMethod;
TryReload(name, delegate
{
try
{
method.Invoke(null, null);
}
catch (TargetInvocationException ex) when (ex.InnerException != null)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
});
}
Log.LogInfo((object)"=== Hot-reload complete === (note: new languages/weapon-mechanic handlers need a restart, not hot-reloadable)");
Log.LogInfo((object)LoadReport.BuildReportText());
}
private static void TryReload(string name, Action reload)
{
try
{
reload();
}
catch (Exception arg)
{
Log.LogError((object)$"Hot-reload of '{name}' failed: {arg}");
}
}
}
[HarmonyPatch(typeof(GameConfig), "Load")]
internal static class QuotasInjectPatch
{
private static readonly InjectedTracker Tracker = new InjectedTracker();
private static void Postfix()
{
Tracker.RunOnce(Apply);
}
public static void Reload()
{
Tracker.Reload(delegate(IReadOnlyCollection<string> ids)
{
QuotaCatalog.All.RemoveAll((QuotaDef q) => ids.Contains(q.id));
}, Apply);
}
private static void Apply()
{
ContentInjector.ScanFolder("NewQuotas", ModDiscovery.Current, "quotas", (string id) => QuotaCatalog.All.Any((QuotaDef q) => q.id == id), BuildFromJson, delegate(QuotaDef def, string id)
{
//IL_002d: Unknown result type (might be due to invalid IL or missing references)
QuotaCatalog.All.Add(def);
Tracker.Add(id);
Plugin.Log.LogInfo((object)$"NewQuotas: injected '{id}' (goal={def.goal}, target={def.target}, reward={def.reward}).");
});
}
private static QuotaDef BuildFromJson(JObject o, string file)
{
//IL_0063: Unknown result type (might be due to invalid IL or missing references)
//IL_0068: Unknown result type (might be due to invalid IL or missing references)
//IL_006f: Unknown result type (might be due to invalid IL or missing references)
//IL_0070: Unknown result type (might be due to invalid IL or missing references)
//IL_0071: Unknown result type (might be due to invalid IL or missing references)
//IL_0076: Unknown result type (might be due to invalid IL or missing references)
//IL_0094: Unknown result type (might be due to invalid IL or missing references)
//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
//IL_010f: Unknown result type (might be due to invalid IL or missing references)
//IL_012d: Unknown result type (might be due to invalid IL or missing references)
//IL_014d: Expected O, but got Unknown
string text = (string)o["id"];
string text2 = (string)o["goal"];
if (!Enum.TryParse<QuotaGoal>(text2, out QuotaGoal result))
{
Plugin.Log.LogError((object)("NewQuotas: '" + text + "' has unknown goal '" + text2 + "', skipping."));
return null;
}
return new QuotaDef
{
id = text,
goal = result,
target = ((int?)o["target"]).GetValueOrDefault(),
reward = ((int?)o["reward"]).GetValueOrDefault(),
text = (((string)o["text"]) ?? text),
materialId = (string)o["material_id"],
family = (string)o["family"],
rewardMeta = (string)o["reward_meta"],
rewardMetaCount = ((int?)o["reward_meta_count"]).GetValueOrDefault(),
rewardRoll = ((bool?)o["reward_roll"] == true)
};
}
}
[HarmonyPatch(typeof(StructureCatalog), "get_I")]
public static class StructuresInjectPatch
{
private static readonly FieldInfo CacheField = AccessTools.Field(typeof(StructureCatalog), "_cache");
private static readonly InjectedTracker Tracker = new InjectedTracker();
public static bool IsInjected(string id)
{
if (id != null)
{
return Tracker.Contains(id);
}
return false;
}
private static void Postfix(ref StructureCatalog __result)
{
if (!((Object)(object)__result == (Object)null))
{
StructureCatalog cat = __result;
Tracker.RunOnce(delegate
{
Apply(cat);
});
}
}
public static void Reload()
{
StructureCatalog cat = StructureCatalog.I;
if ((Object)(object)cat == (Object)null)
{
Plugin.Log.LogError((object)"NewStructures: StructureCatalog.I is null, cannot reload.");
return;
}
Tracker.Reload(delegate(IReadOnlyCollection<string> ids)
{
if (cat.campaign != null)
{
cat.campaign = cat.campaign.Where((StructureDef d) => (Object)(object)d == (Object)null || !ids.Contains(d.id)).ToArray();
}
Dictionary<string, StructureDef> dictionary = (Dictionary<string, StructureDef>)CacheField.GetValue(null);
foreach (string id in ids)
{
dictionary.Remove(id);
}
}, delegate
{
Apply(cat);
});
}
private static void Apply(StructureCatalog cat)
{
ContentInjector.ScanFolder("NewStructures", ModDiscovery.Current, "structures", (string id) => cat.campaign != null && cat.campaign.Any((StructureDef d) => (Object)(object)d != (Object)null && d.id == id), (JObject o, string file) => BuildFromJson(o, Path.GetDirectoryName(file)), delegate(StructureDef def, string id)
{
StructureDef[] campaign = cat.campaign;
int num = ((campaign != null) ? campaign.Length : 0);
Array.Resize(ref cat.campaign, num + 1);
cat.campaign[num] = def;
Tracker.Add(id);
Plugin.Log.LogInfo((object)$"NewStructures: injected '{id}' into StructureCatalog.campaign (now {cat.campaign.Length} entries).");
}, "_cells.json");
}
private static StructureDef BuildFromJson(JObject o, string dir)
{
//IL_0142: Unknown result type (might be due to invalid IL or missing references)
//IL_0147: Unknown result type (might be due to invalid IL or missing references)
//IL_015d: Expected O, but got Unknown
//IL_019a: Unknown result type (might be due to invalid IL or missing references)
//IL_01a1: Expected O, but got Unknown
//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
//IL_01af: Unknown result type (might be due to invalid IL or missing references)
//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
//IL_0218: Expected O, but got Unknown
string text = (string)o["id"];
string text2 = (string)o["cells_file"];
string text3 = null;
int cellCount = 0;
if (!string.IsNullOrEmpty(text2))
{
string path = Path.Combine(dir, text2);
if (File.Exists(path))
{
text3 = File.ReadAllText(path);
cellCount = ((int?)JObject.Parse(text3)["count"]).GetValueOrDefault();
}
}
StructureDef val = ScriptableObject.CreateInstance<StructureDef>();
val.id = text;
val.displayName = ((string)o["display_name"]) ?? text;
val.description = ((string)o["description"]) ?? "";
val.cellCount = cellCount;
val.sealedLayers = ((bool?)o["sealed_layers"]) ?? true;
val.startingMoney = ((int?)o["starting_money"]).GetValueOrDefault();
val.glyphCount = ((int?)o["glyph_count"]).GetValueOrDefault();
val.greenCount = ((int?)o["green_count"]) ?? (-1);
if (text3 != null)
{
val.cells = new TextAsset(text3)
{
name = text + "_cells"
};
}
JToken obj = o["bands"];
JArray val2 = (JArray)(object)((obj is JArray) ? obj : null);
if (val2 != null)
{
val.bands = (BandDef[])(object)new BandDef[((JContainer)val2).Count];
for (int i = 0; i < ((JContainer)val2).Count; i++)
{
JObject val3 = (JObject)val2[i];
val.bands[i] = new BandDef
{
layer = (((int?)val3["layer"]) ?? 1),
outerFrac = (((float?)val3["outer_frac"]) ?? 1f),
hpSealed = (((int?)val3["hp_sealed"]) ?? 75)
};
}
}
return val;
}
}
internal static class PluginVersionInfo
{
public const string Version = "1.1.0";
}
}