-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPositionEventsModule.cs
451 lines (365 loc) · 15.8 KB
/
PositionEventsModule.cs
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
using Blish_HUD;
using Blish_HUD.Modules;
using Blish_HUD.Modules.Managers;
using Blish_HUD.Settings;
using Flyga.PositionEventsModule.Contexts;
using Flyga.PositionEventsModule.Debug;
using Microsoft.Xna.Framework;
using PositionEvents;
using PositionEvents.Area;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
namespace Flyga.PositionEventsModule
{
[Export(typeof(Module))]
public class PositionEventsModule : Module
{
private static readonly Logger Logger = Logger.GetLogger<PositionEventsModule>();
internal static PositionEventsModule Instance { get; set; }
private readonly BoundingObjectDebug _debugDisplay;
private readonly Dictionary<int, List<IBoundingObject>> _debugAreas;
private readonly Dictionary<Type, Dictionary<int, List<IBoundingObject>>> _areasByModule;
private readonly List<Module> _registeredModules;
private IPositionHandler _positionHandler;
private static SettingEntry<int> _updateCooldown;
private static SettingEntry<bool> _updateCooldownOverrideAllowed;
private static int _actualCooldown = 0;
private Dictionary<Type, int> _cooldownOverridesByModule;
private double _lastUpdate = 0;
private PositionEventsContext _positionEventsContext;
private ContextsService.ContextHandle<PositionEventsContext> _positionEventsContextHandle;
private ContextManager _contextManager;
/// <summary>
/// The value of the UpdateCooldown (refresh rate) setting of this
/// <see cref="PositionEventsModule"/>. Clamped between 0 and 5000 ms.
/// Will return 0, if the setting is null.
/// </summary>
public static int ClampedCooldown
{
get
{
if (_updateCooldown.IsNull)
{
return 0;
}
if (_updateCooldown.Value <= 0)
{
return 0;
}
if (_updateCooldown.Value >= 5000)
{
return 5000;
}
return _updateCooldown.Value;
}
}
/// <summary>
/// The actual update cooldown (refresh rate) determined by the UpdateCooldown
/// setting, the UpdateCooldownOverrideAllowed setting of this
/// <see cref="PositionEventsModule"/> and the registered
/// cooldown overrides by the dependent <see cref="Module">Modules</see>.
/// </summary>
public static int ActualCooldown
{
get
{
return _actualCooldown;
}
}
public static bool UpdateCooldownOverrideAllowed
{
get
{
if (_updateCooldownOverrideAllowed.IsNull)
{
return true;
}
return _updateCooldownOverrideAllowed.Value;
}
}
#region Service Managers
internal SettingsManager SettingsManager => this.ModuleParameters.SettingsManager;
internal ContentsManager ContentsManager => this.ModuleParameters.ContentsManager;
internal DirectoriesManager DirectoriesManager => this.ModuleParameters.DirectoriesManager;
internal Gw2ApiManager Gw2ApiManager => this.ModuleParameters.Gw2ApiManager;
#endregion
[ImportingConstructor]
public PositionEventsModule([Import("ModuleParameters")] ModuleParameters moduleParameters) : base(moduleParameters)
{
Instance = this;
_debugDisplay = new BoundingObjectDebug(this);
_debugAreas = new Dictionary<int, List<IBoundingObject>>();
_registeredModules = new List<Module>();
_areasByModule = new Dictionary<Type, Dictionary<int, List<IBoundingObject>>>();
_cooldownOverridesByModule = new Dictionary<Type, int>();
}
protected override void DefineSettings(SettingCollection settings)
{
_updateCooldown = settings.DefineSetting("UpdateCooldown", 30, () => "Update Cooldown (ms)", () => "The cooldown between checking the player position in miliseconds (1000ms = 1s). Clamped between 0s - 5s.");
_updateCooldown.SetRange(0, 5000);
_updateCooldownOverrideAllowed = settings.DefineSetting("UpdateCooldownOverrideAllowed", true, () => "Allow modules to ignore cooldown", () => "Allows individual modules to update the position data more often than you specified in the \"Update Cooldown\" setting.");
}
protected override void Initialize()
{
GameService.Gw2Mumble.CurrentMap.MapChanged += OnMapChange;
_positionHandler = new PositionHandler(MapChanged);
_updateCooldown.SettingChanged += OnUpdateCooldownSettingChanged;
_updateCooldownOverrideAllowed.SettingChanged += OnUpdateCooldownOverrideAllowedSettingChanged;
UpdateActualCooldown();
}
private void OnUpdateCooldownSettingChanged(object _, ValueChangedEventArgs<int> _1)
{
UpdateActualCooldown();
}
private void OnUpdateCooldownOverrideAllowedSettingChanged(object _, ValueChangedEventArgs<bool> _1)
{
UpdateActualCooldown();
}
private void UpdateActualCooldown()
{
int min = ClampedCooldown;
if (!_updateCooldownOverrideAllowed.IsNull && !_updateCooldownOverrideAllowed.Value)
{
_actualCooldown = min;
return;
}
foreach (int overrideCooldown in _cooldownOverridesByModule.Values)
{
if (overrideCooldown < min)
{
min = overrideCooldown;
}
}
_actualCooldown = min;
}
private event EventHandler<PositionData> MapChanged;
private void OnMapChange(object _, ValueEventArgs<int> mapId)
{
MapChanged?.Invoke(this, GameService.Gw2Mumble.GetPositionData(mapId.Value));
_debugDisplay.RemoveAllBoundingObjects();
LoadCurrentDebugEntities(mapId.Value);
}
private void LoadCurrentDebugEntities(int mapId)
{
if (!_debugAreas.ContainsKey(mapId))
{
return;
}
foreach (IBoundingObject area in _debugAreas[mapId])
{
_debugDisplay.DisplayBoundingObject(area);
}
}
protected override Task LoadAsync()
{
return Task.CompletedTask;
}
private void OnDebugAreaJoinOrLeave(IBoundingObject area, bool joined)
{
if (joined)
{
_debugDisplay.ChangeBoundingObject(area, Debug.DebugColor.Green);
return;
}
_debugDisplay.ChangeBoundingObject(area, Debug.DebugColor.Red);
}
private void OnOtherModuleRunStateChanged(object sender, ModuleRunStateChangedEventArgs runStateChangedEventArgs)
{
ModuleRunState runState = runStateChangedEventArgs.RunState;
if (!(sender is Module module))
{
return;
}
if (!_registeredModules.Contains(module))
{
return;
}
if (runState != ModuleRunState.Unloaded && runState != ModuleRunState.FatalError)
{
return;
}
OnOtherModuleUnloaded(module);
_registeredModules.Remove(module); // unregister module
_areasByModule.Remove(module.GetType()); // remove artifacts of the module
}
private void OnOtherModuleUnloaded(Module module)
{
RemoveAllAreas(module);
}
protected override void OnModuleLoaded(EventArgs e)
{
RegisterContext();
// Base handler must be called
base.OnModuleLoaded(e);
}
private void RegisterContext()
{
_positionEventsContext = new PositionEventsContext();
_contextManager = new ContextManager(_positionEventsContext, this);
_positionEventsContextHandle = GameService.Contexts.RegisterContext(_positionEventsContext);
}
protected override void Update(GameTime gameTime)
{
if (_lastUpdate < ActualCooldown)
{
_lastUpdate += gameTime.ElapsedGameTime.TotalMilliseconds;
return;
}
_lastUpdate = 0;
_positionHandler.Update(GameService.Gw2Mumble.GetPositionData());
}
/// <summary>
/// Registers an <paramref name="area"/> for the map with the given <paramref name="mapId"/>. The
/// <paramref name="callback"/> will be invoked once, when the player joins the <paramref name="area"/>
/// and once, when the player leaves the <paramref name="area"/>.
/// </summary>
/// <param name="module">The <see cref="Module"/> that registers the area.</param>
/// <param name="mapId">The mapId in which the <paramref name="area"/> should be active.</param>
/// <param name="area">The <see cref="IBoundingObject"/> that defines the area.</param>
/// <param name="callback">The <see cref="Action"/> to be called, when the player leaves or
/// joins the <paramref name="area"/>.</param>
/// <param name="debug">A debug flag. If set to true, the <paramref name="area"/> will be
/// rendered visually when in the given map. Should always be set to false when shipping
/// a <see cref="Module"/>.</param>
internal void RegisterArea(Module module, int mapId, IBoundingObject area, Action<PositionData, bool> callback, bool debug = false)
{
Type moduleType = module.GetType();
if (!_areasByModule.ContainsKey(moduleType))
{
_areasByModule[moduleType] = new Dictionary<int, List<IBoundingObject>>();
}
if (!_registeredModules.Contains(module))
{
_registeredModules.Add(module);
module.ModuleRunStateChanged += OnOtherModuleRunStateChanged;
}
if (!_areasByModule[moduleType].ContainsKey(mapId))
{
_areasByModule[moduleType][mapId] = new List<IBoundingObject>();
}
_areasByModule[moduleType][mapId].Add(area);
if (debug == false)
{
_positionHandler.AddArea(mapId, area, callback);
return;
}
_positionHandler.AddArea(mapId, area,
(positionData, isContained) =>
{
OnDebugAreaJoinOrLeave(area, isContained);
callback(positionData, isContained);
});
if (!_debugAreas.ContainsKey(mapId))
{
_debugAreas[mapId] = new List<IBoundingObject>();
}
_debugAreas[mapId].Add(area);
if (mapId == GameService.Gw2Mumble.CurrentMap.Id)
{
_debugDisplay.DisplayBoundingObject(area);
}
}
private bool RemoveArea(Type moduleType, int mapId, IBoundingObject area)
{
if (_debugAreas.ContainsKey(mapId) && _debugAreas[mapId].Contains(area))
{
_debugAreas[mapId].Remove(area);
_debugDisplay.RemoveBoundingObject(area);
}
if (_areasByModule.ContainsKey(moduleType)
&& _areasByModule[moduleType].ContainsKey(mapId)
&& _areasByModule[moduleType][mapId].Contains(area))
{
_areasByModule[moduleType][mapId].Remove(area);
}
return _positionHandler.RemoveArea(mapId, area);
}
/// <summary>
/// Removes an <paramref name="area"/> for the map with the given <paramref name="mapId"/>,
/// that was registered via
/// <see cref="RegisterArea(Module, int, IBoundingObject, Action{PositionData, bool}, bool)"/>.
/// </summary>
/// <param name="module">The <see cref="Module"/> that registered the area.</param>
/// <param name="mapId">The mapId for which the <paramref name="area"/> was registered.</param>
/// <param name="area">The <see cref="IBoundingObject"/> that defined the area.</param>
/// <returns>True, if the <paramref name="area"/> was registered for the given <paramref name="mapId"/>
/// and successfully removed. Otherwise false.</returns>
internal bool RemoveArea(Module module, int mapId, IBoundingObject area)
{
return RemoveArea(module.GetType(), mapId, area);
}
/// <summary>
/// Removes all <see cref="IBoundingObject">areas</see> that were registered for the given
/// <paramref name="module"/>.
/// </summary>
/// <param name="module">The <see cref="Module"/> that registered the areas.</param>
internal void RemoveAllAreas(Module module)
{
Type moduleType = module.GetType();
if (!_areasByModule.ContainsKey(moduleType))
{
return;
}
Dictionary<int, List<IBoundingObject>> areasForModule = _areasByModule[moduleType];
foreach (KeyValuePair<int, List<IBoundingObject>> areasByMapId in areasForModule)
{
int mapId = areasByMapId.Key;
IBoundingObject[] areas = areasByMapId.Value.ToArray(); // copy values, so we can remove them while iterating
foreach (IBoundingObject area in areas)
{
RemoveArea(moduleType, mapId, area);
}
}
}
/// <summary>
/// Registers the cooldown (refresh rate) override <paramref name="value"/> for
/// the given <paramref name="module"/>.
/// </summary>
/// <param name="module"></param>
/// <param name="value"></param>
/// <returns>The current <see cref="PositionEventsModule.ActualCooldown"/>
/// value.</returns>
/// <exception cref="ArgumentException">If the set value is less than 0.</exception>
internal int OverrideCooldown(Module module, int value)
{
if (value < 0)
{
throw new ArgumentException("value can't be less than 0.", nameof(value));
}
_cooldownOverridesByModule[module.GetType()] = value;
UpdateActualCooldown();
return ActualCooldown;
}
private void UnloadContext()
{
_positionEventsContextHandle?.Expire();
if (this._contextManager != null)
{
this._contextManager.Dispose();
this._contextManager = null;
}
this._positionEventsContext = null;
this._positionEventsContextHandle = null;
}
/// <inheritdoc />
protected override void Unload()
{
GameService.Gw2Mumble.CurrentMap.MapChanged -= OnMapChange;
foreach (Module module in _registeredModules)
{
module.ModuleRunStateChanged -= OnOtherModuleRunStateChanged;
}
UnloadContext();
_registeredModules.Clear();
_areasByModule.Clear();
_cooldownOverridesByModule.Clear();
_positionHandler.Clear();
_positionHandler.Dispose();
_updateCooldown.SettingChanged -= OnUpdateCooldownSettingChanged;
_updateCooldownOverrideAllowed.SettingChanged -= OnUpdateCooldownOverrideAllowedSettingChanged;
_debugDisplay.Dispose();
}
}
}