casualexpiesource

cu-trainer/Ultra Paradise Application/src/MyMods.cs

311 lines · 13.8 KB · plain text · download

1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Globalization;
5using System.Reflection;
6using System.Text;
7using HarmonyLib;
8using UnityEngine;
9using Object = UnityEngine.Object;
10
11namespace UltraParadise
12{
13 internal static class ModBridge
14 {
15 private const char REC = '\u001d', SEP = '\u001c';
16
17 private sealed class Def
18 {
19 public string Guid, Type;
20 public string[] Methods;
21 public string[] Actions;
22 public Def(string guid, string type, string[] methods, params string[] actions) { Guid = guid; Type = type; Methods = methods; Actions = actions; }
23 }
24
25 private static readonly Def[] Defs =
26 {
27 new Def("getstinky", "GetStinky.StinkMenu", new[] { "Update", "OnGUI" }, "max=Max Stink", "plus=+25% Stink", "clean=Clean Me"),
28 new Def("nodurability", "NoDurability.Runner", new[] { "Update", "OnGUI" }, "toggle=Turn On / Off"),
29 new Def("saveanywhere", null, null, "save=Save Now"),
30 new Def("controllersupport", null, null),
31 new Def("hatshatshats", null, null),
32 new Def("thighhighsrevamped", null, null),
33 new Def("pickyournumber", null, null),
34 new Def("alwaysgivenachance", null, null),
35 new Def("nomoresoundcannons", null, null),
36 new Def("bossmusic", null, null),
37 };
38
39 private static readonly Dictionary<string, bool> taken = new Dictionary<string, bool>();
40 private static readonly Dictionary<MethodBase, string> patched = new Dictionary<MethodBase, string>();
41 private static Harmony harmony;
42 private static float nextStat;
43
44 private static Def Find(string guid)
45 {
46 foreach (Def d in Defs) if (d.Guid == guid) return d;
47 return null;
48 }
49
50 private static object Prop(object o, string name)
51 {
52 if (o == null) return null;
53 try
54 {
55 PropertyInfo p = o.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
56 if (p != null) return p.GetValue(o, null);
57 FieldInfo f = o.GetType().GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
58 return f != null ? f.GetValue(o) : null;
59 }
60 catch (Exception) { return null; }
61 }
62
63 private static object Plugin(string guid)
64 {
65 IDictionary d = DebugFeed.BepPlugins();
66 if (d == null || !d.Contains(guid)) return null;
67 return d[guid];
68 }
69
70 private static IEnumerable<object> Entries(object info)
71 {
72 List<object> list = new List<object>();
73 IEnumerable cfg = Prop(Prop(info, "Instance"), "Config") as IEnumerable;
74 if (cfg == null) return list;
75 foreach (object kv in cfg)
76 {
77 object e = Prop(kv, "Value");
78 if (e != null) list.Add(e);
79 }
80 return list;
81 }
82
83 private static string Clean(object o)
84 {
85 string s = o == null ? "" : o.ToString();
86 return s.Replace('\r', ' ').Replace('\n', ' ').Replace(REC, ' ').Replace(SEP, ' ');
87 }
88
89 private static string Serialized(object entry)
90 {
91 try
92 {
93 MethodInfo m = entry.GetType().GetMethod("GetSerializedValue", BindingFlags.Public | BindingFlags.Instance);
94 if (m != null) return m.Invoke(entry, null) as string;
95 }
96 catch (Exception) { }
97 return Clean(Prop(entry, "BoxedValue"));
98 }
99
100 public static string List()
101 {
102 StringBuilder sb = new StringBuilder("MODS ");
103 bool first = true;
104 foreach (Def d in Defs)
105 {
106 object info = Plugin(d.Guid);
107 if (info == null) continue;
108 object meta = Prop(info, "Metadata");
109 if (!first) sb.Append(REC);
110 first = false;
111 bool can = d.Type != null && AccessTools.TypeByName(d.Type) != null;
112 bool on;
113 taken.TryGetValue(d.Guid, out on);
114 sb.Append('M').Append(SEP).Append(d.Guid).Append(SEP).Append(Clean(Prop(meta, "Name"))).Append(SEP).Append(Clean(Prop(meta, "Version")))
115 .Append(SEP).Append(can ? '1' : '0').Append(SEP).Append(on ? '1' : '0').Append(SEP).Append(Clean(string.Join(";", d.Actions)));
116 foreach (object e in Entries(info))
117 {
118 object def = Prop(e, "Definition");
119 object desc = Prop(e, "Description");
120 Type t = Prop(e, "SettingType") as Type;
121 object acc = Prop(desc, "AcceptableValues");
122 string min = "", max = "", opts = "";
123 if (acc != null)
124 {
125 object lo = Prop(acc, "MinValue"), hi = Prop(acc, "MaxValue");
126 if (lo != null && hi != null)
127 {
128 min = Convert.ToString(lo, CultureInfo.InvariantCulture);
129 max = Convert.ToString(hi, CultureInfo.InvariantCulture);
130 }
131 IEnumerable vals = Prop(acc, "AcceptableValues") as IEnumerable;
132 if (vals != null)
133 {
134 List<string> l = new List<string>();
135 foreach (object v in vals) l.Add(Clean(v));
136 opts = string.Join("|", l.ToArray());
137 }
138 }
139 if (t != null && t.IsEnum && opts.Length == 0) opts = string.Join("|", Enum.GetNames(t));
140 string kind = t == null ? "text" : t == typeof(bool) ? "bool" : t == typeof(int) ? "int" : t == typeof(float) || t == typeof(double) ? "float" : t == typeof(KeyCode) || t.Name == "KeyboardShortcut" ? "key" : t.IsEnum ? "enum" : "text";
141 sb.Append(REC).Append('E').Append(SEP).Append(d.Guid).Append(SEP).Append(Clean(Prop(def, "Section"))).Append(SEP).Append(Clean(Prop(def, "Key")))
142 .Append(SEP).Append(kind).Append(SEP).Append(Clean(Serialized(e))).Append(SEP).Append(Clean(Prop(desc, "Description")))
143 .Append(SEP).Append(min).Append(SEP).Append(max).Append(SEP).Append(opts);
144 }
145 }
146 return sb.ToString();
147 }
148
149 private static string SetConfig(string guid, string section, string key, string value)
150 {
151 if (Find(guid) == null) return "That mod isn't supported.";
152 object info = Plugin(guid);
153 if (info == null) return "That mod isn't loaded.";
154 foreach (object e in Entries(info))
155 {
156 object def = Prop(e, "Definition");
157 if (Clean(Prop(def, "Section")) != section || Clean(Prop(def, "Key")) != key) continue;
158 try
159 {
160 MethodInfo m = e.GetType().GetMethod("SetSerializedValue", BindingFlags.Public | BindingFlags.Instance);
161 if (m == null) return "Couldn't change that setting.";
162 m.Invoke(e, new object[] { value });
163 return null;
164 }
165 catch (Exception ex) { return "Couldn't change it: " + (ex.InnerException ?? ex).Message; }
166 }
167 return "That setting wasn't found.";
168 }
169
170 public static bool Skip(MethodBase __originalMethod)
171 {
172 string g;
173 bool on;
174 return !(__originalMethod != null && patched.TryGetValue(__originalMethod, out g) && taken.TryGetValue(g, out on) && on);
175 }
176
177 private static string Take(string guid, bool on)
178 {
179 Def d = Find(guid);
180 if (d == null || d.Type == null) return "That mod has no in-game window to take over.";
181 Type t = AccessTools.TypeByName(d.Type);
182 if (t == null || Plugin(guid) == null) return "That mod isn't loaded.";
183 if (on)
184 {
185 if (harmony == null) harmony = new Harmony("casualexpie.ultraparadise.mymods");
186 MethodInfo skip = typeof(ModBridge).GetMethod("Skip", BindingFlags.Public | BindingFlags.Static);
187 foreach (string name in d.Methods)
188 {
189 MethodInfo m = AccessTools.Method(t, name);
190 if (m == null || patched.ContainsKey(m)) continue;
191 try { harmony.Patch(m, new HarmonyMethod(skip)); patched[m] = guid; }
192 catch (Exception e) { return "Couldn't take over " + name + ": " + e.Message; }
193 }
194 foreach (Object o in Resources.FindObjectsOfTypeAll(t))
195 {
196 FieldInfo open = AccessTools.Field(t, "open");
197 if (open != null && open.FieldType == typeof(bool)) open.SetValue(o, false);
198 FieldInfo blocker = AccessTools.Field(t, "blocker");
199 GameObject b = blocker != null ? blocker.GetValue(o) as GameObject : null;
200 if (b != null) { Object.Destroy(b); blocker.SetValue(o, null); }
201 }
202 }
203 taken[guid] = on;
204 return null;
205 }
206
207 public static void ReleaseAll()
208 {
209 taken.Clear();
210 }
211
212 private static Body Player()
213 {
214 try
215 {
216 if (PlayerCamera.main != null && PlayerCamera.main.body != null && WorldGeneration.world != null) return PlayerCamera.main.body;
217 }
218 catch (Exception) { }
219 return null;
220 }
221
222 private static object Instance(string type)
223 {
224 Type t = AccessTools.TypeByName(type);
225 if (t == null) return null;
226 Object[] all = Resources.FindObjectsOfTypeAll(t);
227 return all.Length > 0 ? all[0] : null;
228 }
229
230 private static bool ConfigBool(string guid, string key)
231 {
232 object info = Plugin(guid);
233 if (info == null) return false;
234 foreach (object e in Entries(info))
235 if (Clean(Prop(Prop(e, "Definition"), "Key")) == key) return Prop(e, "BoxedValue") is bool && (bool)Prop(e, "BoxedValue");
236 return false;
237 }
238
239 private static string Act(string guid, string id)
240 {
241 if (guid == "getstinky")
242 {
243 Body b = Player();
244 if (b == null) return "Start a run first.";
245 object menu = Instance("GetStinky.StinkMenu");
246 MethodInfo set = menu != null ? AccessTools.Method(menu.GetType(), "SetDirt") : null;
247 float v = id == "max" ? 100f : id == "plus" ? b.dirtyness + 25f : 0f;
248 if (set != null) set.Invoke(menu, new object[] { b, v });
249 else b.dirtyness = Mathf.Clamp(v, 0f, 100f);
250 return null;
251 }
252 if (guid == "nodurability" && id == "toggle")
253 return SetConfig(guid, "General", "Enabled", ConfigBool(guid, "Enabled") ? "false" : "true");
254 if (guid == "saveanywhere" && id == "save")
255 {
256 Type r = AccessTools.TypeByName("SaveAnywhere.Runner");
257 Type s = AccessTools.TypeByName("SaveAnywhere.Slots");
258 if (r == null || s == null) return "Save Anywhere isn't loaded.";
259 MethodInfo inRun = AccessTools.Method(r, "InRun");
260 if (inRun != null && !(bool)inRun.Invoke(null, null)) return "Start a run first.";
261 MethodInfo pick = AccessTools.Method(s, "PickManualSlot");
262 if (pick != null && (int)pick.Invoke(null, null) <= 0) return "Pick a slot first: pause the game and click Save once.";
263 MethodInfo save = AccessTools.Method(r, "SaveAsync");
264 if (save == null) return "This version of Save Anywhere can't be saved from the trainer.";
265 save.Invoke(null, new object[] { false, 0, null });
266 return null;
267 }
268 return "Unknown action.";
269 }
270
271 public static bool Handle(string cmd, string[] p)
272 {
273 if (cmd == "MODS") { Link.Post(List()); return true; }
274 if (cmd != "MODCFG" && cmd != "MODTAKE" && cmd != "MODACT") return false;
275 if (p.Length < 3) return true;
276 string err;
277 try
278 {
279 if (cmd == "MODTAKE") err = Take(p[1], p[2] == "1");
280 else if (cmd == "MODACT") err = Act(p[1], p[2]);
281 else
282 {
283 string[] f = p[2].Split(SEP);
284 err = f.Length < 3 ? "Bad setting." : SetConfig(p[1], f[0], f[1], f[2]);
285 }
286 }
287 catch (Exception e) { err = (e.InnerException ?? e).Message; }
288 if (err != null) Link.Send("MODERR " + p[1] + " " + Clean(err));
289 Link.Post(List());
290 return true;
291 }
292
293 public static void Tick()
294 {
295 if (!Link.Connected || Time.unscaledTime < nextStat) return;
296 nextStat = Time.unscaledTime + 1f;
297 StringBuilder sb = new StringBuilder();
298 if (Plugin("getstinky") != null)
299 {
300 Body b = Player();
301 sb.Append("getstinky").Append(SEP).Append(b == null ? "Not in a run." : "Dirtiness " + Mathf.RoundToInt(b.dirtyness) + "%" + (ConfigBool("getstinky", "StayStinkyForever") ? " (locked)" : ""));
302 }
303 if (Plugin("nodurability") != null)
304 {
305 if (sb.Length > 0) sb.Append(REC);
306 sb.Append("nodurability").Append(SEP).Append(ConfigBool("nodurability", "Enabled") ? "No Durability is ON" : "No Durability is OFF");
307 }
308 if (sb.Length > 0) Link.Post("MODSTAT " + sb);
309 }
310 }
311}