-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMagicPowerPlantPanel.cs
More file actions
339 lines (284 loc) · 8.93 KB
/
Copy pathMagicPowerPlantPanel.cs
File metadata and controls
339 lines (284 loc) · 8.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
using HarmonyLib;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Oxide.Core.Configuration;
using Oxide.Core.Plugins;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Reflection;
using UnityEngine;
namespace Oxide.Plugins;
[Info("Magic Power Plant Panel", "HunterZ", "1.0.0")]
[Description("Provides a Magic Panel that displays Power Plant grid power status")]
public class MagicPowerPlantPanel : RustPlugin
{
#region Class Fields
// ReSharper disable once InconsistentNaming
[PluginReference] private Plugin MagicPanel;
private DynamicConfigFile _configFile;
private PluginConfig _pluginConfig;
private int _phase = -1;
private readonly string[] _defaultColors =
{
"#FFFFFF0F",
"#FFFFFF7F",
"#FFFFFF7F",
"#FFFFFF7F",
"#FFFFFF7F"
};
// private readonly string[] _defaultUrls =
// {
// "https://i.postimg.cc/sD0cJRDv/powerplant0.png",
// "https://i.postimg.cc/dtSB9KtZ/powerplant1.png",
// "https://i.postimg.cc/J4dqQW4B/powerplant2.png",
// "https://i.postimg.cc/wTbVkdTJ/powerplant3.png",
// "https://i.postimg.cc/zXPjk1XK/powerplant4.png"
// };
private readonly string[] _defaultUrls =
{
"https://i.postimg.cc/pd1PBZ1w/powerplant0.png",
"https://i.postimg.cc/xdF9PR4V/powerplant1.png",
"https://i.postimg.cc/mr6TSw5G/powerplant2.png",
"https://i.postimg.cc/QMnjqbyD/powerplant3.png",
"https://i.postimg.cc/W3FTYkQf/powerplant4.png"
};
private enum UpdateType
{
// All = 1,
// Panel = 2,
Image = 3
// Text = 4
}
#endregion
#region Helper Methods
private void HZ_OnPhaseChange() => NextTick(CheckUpdate);
private bool CheckPhase()
{
var oldPhase = _phase;
var newPhase =
Powergrid.enabled ? PowergridManager.GetCurrentStage(true) : 0;
_phase = newPhase;
return _phase >= 0 && newPhase != oldPhase;
}
private void CheckUpdate()
{
if (!CheckPhase()) return;
MagicPanel?.Call("UpdatePanel", Name, (int)UpdateType.Image);
}
#endregion
#region Harmony Patches
[AutoPatch, HarmonyPatch(
typeof(PowergridManager), nameof(PowergridManager.ServerTick))]
internal static class PowerGridManagerServerTickPatch
{
[HarmonyTranspiler, UsedImplicitly]
internal static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
var list = new List<CodeInstruction>(instructions);
var index = list.FindIndex(static i =>
i.opcode == OpCodes.Stfld &&
((FieldInfo)i.operand)?.Name.Contains("hasTickedOnce") is true);
index -= 2;
if (index < 0)
{
Debug.LogError("MagicPowerPlantPanel: Failed to patch PowergridManager.ServerTick()");
return list;
}
list.Insert(
index, new CodeInstruction(OpCodes.Ldstr, nameof(HZ_OnPhaseChange)));
list.Insert(
index + 1, new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(
typeof(Core.Interface), nameof(CallHook), new[] { typeof(string) })));
return list;
}
}
#endregion
#region Oxide API
protected override void LoadDefaultConfig()
{
Puts("Creating new config data");
_pluginConfig = new PluginConfig();
}
protected override void LoadConfig()
{
var path = $"{Manager.ConfigPath}/MagicPanel/{Name}.json";
_configFile = new DynamicConfigFile(path);
if (_configFile?.Exists() is not true)
{
LoadDefaultConfig();
return;
}
try
{
_pluginConfig = _configFile.ReadObject<PluginConfig>();
}
catch (System.Exception ex)
{
PrintWarning($"Exception reading config file {path}: " + ex.Message);
LoadDefaultConfig();
}
}
private void Init()
{
Unsubscribe(nameof(HZ_OnPhaseChange));
if (null == _configFile)
{
PrintError("Config file handle is null; aborting");
return;
}
if (null == _pluginConfig)
{
PrintError("Config object is null; aborting");
return;
}
// need 5 panel layouts (one for each power grid phase)
// if config file contains something different, pad out with defaults or
// truncate as necessary
// TODO: is there a less stupid way to do enforce a fixed-size array in a
// config file?
var oldLength = _pluginConfig.PanelLayouts?.Length ?? -1;
if (oldLength is not 5)
{
switch (oldLength)
{
case -1:
Puts("LoadConfig(): New/reset config - populating with default layout values");
break;
case <= 5:
PrintWarning($"LoadConfig(): Loaded config has {oldLength} layout(s) but expected 5 - populating missing entries with default values");
break;
default:
PrintWarning($"LoadConfig(): Loaded config has {oldLength} layout(s) but expected 5 - truncating list to expected size");
break;
}
var newLayout = new PanelLayout[5];
for (var i = 0; i < 5 && i < oldLength; ++i)
{
Puts($"LoadConfig(): Populating layout index {i} with config values");
newLayout[i] = _pluginConfig.PanelLayouts![i];
}
if (oldLength < 0) oldLength = 0;
for (var j = oldLength; j < 5; ++j)
{
Puts($"LoadConfig(): Populating layout index {j} with default URL {_defaultUrls[j]}");
newLayout[j] = new PanelLayout
{
Image = new PanelImage
{
Color = _defaultColors[j],
Url = _defaultUrls[j]
}
};
}
_pluginConfig.PanelLayouts = newLayout;
}
Puts($"Writing config file {_configFile.Filename}");
_configFile.WriteObject(_pluginConfig);
}
private void OnServerInitialized()
{
MagicPanelRegisterPanels();
}
private void Unload()
{
_configFile = null;
_pluginConfig = null;
_phase = -1;
}
#endregion
#region MagicPanel API
private void MagicPanelRegisterPanels()
{
Unsubscribe(nameof(HZ_OnPhaseChange));
if (MagicPanel?.IsLoaded is not true)
{
PrintError("Missing plugin dependency MagicPanel: https://umod.org/plugins/magic-panel");
return;
}
// set _phase to current server state
CheckPhase();
// NOTE: this will trigger an initial call to GetPanel()
MagicPanel.Call("RegisterGlobalPanel",
this, Name, JsonConvert.SerializeObject(_pluginConfig.PanelSettings),
nameof(GetPanel));
Subscribe(nameof(HZ_OnPhaseChange));
}
private Hash<string, object> GetPanel() =>
_pluginConfig?.PanelLayouts?.Length is >= 0 &&
_phase >= 0 && _phase < _pluginConfig.PanelLayouts.Length ?
_pluginConfig.PanelLayouts[_phase].ToHash() :
null;
#endregion
#region Classes
private sealed class PluginConfig
{
[JsonProperty(PropertyName = "Panel Settings")]
public PanelRegistration PanelSettings { get; set; } = new();
[JsonProperty(PropertyName = "Panel Layout By Power Grid Phase")]
public PanelLayout[] PanelLayouts { get; set; }
}
private sealed class PanelRegistration
{
[UsedImplicitly] public string Dock { get; set; } = "center";
[UsedImplicitly] public float Width { get; set; } = 0.02f;
[UsedImplicitly] public int Order { get; set; } = 1;
[UsedImplicitly] public string BackgroundColor { get; set; } = "#FFFFFF08";
}
private sealed class PanelLayout
{
[UsedImplicitly] public PanelImage Image { get; set; } = new();
// cache hash instead of regenerating it on every call/change
[JsonIgnore]
private Hash<string, object> _hash;
public Hash<string, object> ToHash()
{
// only create new hash if none exists yet
_hash ??= new Hash<string, object>
{
[nameof(Image)] = Image.ToHash()
};
return _hash;
}
}
private abstract class PanelBase
{
[UsedImplicitly] public bool Enabled { get; set; } = true;
[UsedImplicitly] public string Color { get; set; } = "#FFFFFF0F";
[UsedImplicitly] public int Order { get; set; } = 0;
[UsedImplicitly] public float Width { get; set; } = 1.0f;
[UsedImplicitly] public TypePadding Padding { get; set; } = new();
public virtual Hash<string, object> ToHash() => new()
{
[nameof(Enabled)] = Enabled,
[nameof(Color)] = Color,
[nameof(Order)] = Order,
[nameof(Width)] = Width,
[nameof(Padding)] = Padding.ToHash()
};
}
private sealed class PanelImage : PanelBase
{
[UsedImplicitly] public string Url { get; set; }
public override Hash<string, object> ToHash()
{
var hash = base.ToHash();
hash[nameof(Url)] = Url;
return hash;
}
}
private sealed class TypePadding
{
[UsedImplicitly] public float Left { get; set; } = 0.05f;
[UsedImplicitly] public float Right { get; set; } = 0.05f;
[UsedImplicitly] public float Top { get; set; } = 0.05f;
[UsedImplicitly] public float Bottom { get; set; } = 0.05f;
public Hash<string, object> ToHash() => new()
{
[nameof(Left)] = Left,
[nameof(Right)] = Right,
[nameof(Top)] = Top,
[nameof(Bottom)] = Bottom
};
}
#endregion
}