forked from arturino009/ExpeditionIcons
-
Notifications
You must be signed in to change notification settings - Fork 5
/
ExpeditionIcons.cs
956 lines (850 loc) · 41.2 KB
/
ExpeditionIcons.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using ExileCore;
using ExileCore.PoEMemory.Components;
using ExileCore.PoEMemory.Elements;
using ExileCore.PoEMemory.MemoryObjects;
using ExileCore.Shared.Enums;
using ExileCore.Shared.Helpers;
using ExileCore.Shared.Nodes;
using ExpeditionIcons.PathPlannerData;
using GameOffsets.Native;
using ImGuiNET;
using SharpDX;
using Vector2 = System.Numerics.Vector2;
using Vector3 = System.Numerics.Vector3;
using Vector4 = System.Numerics.Vector4;
namespace ExpeditionIcons;
public class ExpeditionIcons : BaseSettingsPlugin<ExpeditionIconsSettings>
{
private const string MarkerPath = "Metadata/MiscellaneousObjects/Expedition/ExpeditionMarker";
private const string ExplosivePath = "Metadata/MiscellaneousObjects/Expedition/ExpeditionExplosive";
private const string RelicPath = "Metadata/MiscellaneousObjects/Expedition/ExpeditionRelic";
private const string TextureName = "Icons.png";
private const double CameraAngle = 38.7 * Math.PI / 180;
private static readonly float CameraAngleCos = (float)Math.Cos(CameraAngle);
private static readonly float CameraAngleSin = (float)Math.Sin(CameraAngle);
private const float GridToWorldMultiplier = 250 / 23f;
//TODO
private const int ExplosiveBaseRange = 87;
private const int ExplosiveBaseRadius = 30;
private readonly ConcurrentDictionary<string, List<ExpeditionMarkerIconDescription>> _relicModIconMapping = new();
private readonly ConcurrentDictionary<string, ExpeditionMarkerIconDescription> _metadataIconMapping = new();
private readonly Dictionary<uint, EntityCacheItem> _cachedEntities = new Dictionary<uint, EntityCacheItem>();
private readonly ConcurrentDictionary<string, ExpeditionEntityType> _entityTypeCache = new();
private double _mapScale;
private Vector2 _mapCenter;
private bool _largeMapOpen;
private Vector2 _playerGridPos;
private float _playerZ;
private List<Vector2> _explosives2DPositions;
private float _explosiveRadius;
private float _explosiveRange;
private PathPlannerRunner _plannerRunner;
private (Vector2, float)? _detonatorPos;
private bool _zoneCleared;
private int[][] _pathfindingData;
private Vector2i _areaDimensions;
private List<float> _scoreHistory = [];
private List<Vector2> _editedPath;
private int? _editedIndex = null;
private PathPlanner.DetailedLootScore _editedPathEval;
private PathPlanner.DetailedLootScore EditedOrNativeScore => _editedPathEval ?? _plannerRunner?.CurrentBestPath;
private Camera Camera => GameController.Game.IngameState.Camera;
private (Vector2 Pos, float Rotation)? DetonatorPos => _detonatorPos ??= RealDetonatorPos;
private (Vector2, float)? RealDetonatorPos => DetonatorEntity is { } e
? (e.GridPosNum, e.GetComponent<Positioned>().Rotation)
: null;
private Entity DetonatorEntity =>
GameController.EntityListWrapper.ValidEntitiesByType[EntityType.IngameIcon]
.FirstOrDefault(x => x.Path == "Metadata/MiscellaneousObjects/Expedition/ExpeditionDetonator");
private int PlacedExplosiveCount => ExpeditionInfo.PlacedExplosiveCount;
private Vector2i[] PlacedExplosives => ExpeditionInfo.PlacedExplosiveGridPositions;
private Vector2i? PlacementIndicatorPos =>
ExpeditionInfo.IsExplosivePlacementActive
? GameController.EntityListWrapper.ValidEntitiesByType[EntityType.MiscellaneousObjects]
.FirstOrDefault(x => x.Path == "Metadata/MiscellaneousObjects/Expedition/ExpeditionPlacementIndicator")?.GridPosNum.RoundToVector2I() ??
ExpeditionInfo.PlacementIndicatorGridPosition
: null;
private ExpeditionDetonatorInfo ExpeditionInfo => GameController.IngameState.IngameUi.ExpeditionDetonatorElement.Info;
private RectangleF LocalWindowRect => GameController.Window.GetWindowRectangleTimeCache with { Location = SharpDX.Vector2.Zero };
public override bool Initialise()
{
Graphics.InitImage(TextureName);
Settings._iconsImageId = Graphics.GetTextureId(TextureName);
Settings.PlannerSettings.StartSearch.OnPressed += StartSearch;
Settings.PlannerSettings.StopSearch.OnPressed += StopSearch;
Settings.PlannerSettings.ClearSearch.OnPressed += ClearSearch;
RegisterHotkey(Settings.PlannerSettings.StartSearchHotkey);
RegisterHotkey(Settings.PlannerSettings.StopSearchHotkey);
RegisterHotkey(Settings.PlannerSettings.ClearSearchHotkey);
return base.Initialise();
}
private static void RegisterHotkey(HotkeyNode hotkey)
{
Input.RegisterKey(hotkey);
hotkey.OnValueChanged += () => { Input.RegisterKey(hotkey); };
}
private void StopSearch()
{
if (_plannerRunner is { } run)
{
run.Stop();
Settings.PlannerSettings.SearchState = SearchState.Stopped;
}
else
{
Settings.PlannerSettings.SearchState = SearchState.Empty;
}
}
private void StartSearch()
{
_scoreHistory = [];
_plannerRunner?.Stop();
var plannerRunner = new PathPlannerRunner();
plannerRunner.Start(Settings.PlannerSettings, PlannerEnvironment, GameController.SoundController);
_plannerRunner = plannerRunner;
Settings.PlannerSettings.SearchState = SearchState.Searching;
}
private void ClearSearch()
{
if (_plannerRunner is { } run)
{
run.Stop();
_plannerRunner = null;
_scoreHistory = [];
_editedPath = null;
_editedIndex = null;
_editedPathEval = null;
}
}
public override void AreaChange(AreaInstance area)
{
_plannerRunner?.Stop();
_plannerRunner = null;
_scoreHistory = [];
_editedPath = null;
_editedIndex = null;
_editedPathEval = null;
_detonatorPos = null;
_cachedEntities.Clear();
_zoneCleared = false;
_pathfindingData = GameController.IngameState.Data.RawPathfindingData;
_areaDimensions = GameController.IngameState.Data.AreaDimensions;
}
private ExpeditionEntityType GetEntityType(string path)
{
return _entityTypeCache.GetOrAdd(path, p => p switch
{
RelicPath => ExpeditionEntityType.Relic,
MarkerPath => ExpeditionEntityType.Marker,
_ when p.StartsWith("Metadata/Terrain/Leagues/Expedition/Tiles/ExpeditionChamber") => ExpeditionEntityType.Cave,
_ when p.StartsWith("Metadata/Terrain/Leagues/Expedition/Tiles/ExpeditionBossDispenser") => ExpeditionEntityType.Boss,
_ => ExpeditionEntityType.None,
});
}
private Vector3 ExpandWithTerrainHeight(Vector2 gridPosition)
{
return new Vector3(gridPosition.GridToWorld(), GameController.IngameState.Data.GetTerrainHeightAt(gridPosition));
}
private void DrawCirclesInWorld(List<Vector3> positions, float radius, Color color)
{
const int segments = 90;
const int segmentSpan = 360 / segments;
var playerPos = GameController.Player?.GetComponent<Positioned>()?.WorldPosNum;
if (playerPos == null)
{
return;
}
foreach (var position in positions
.Where(x => playerPos.Value.Distance(new Vector2(x.X, x.Y)) < 80 * GridToWorldMultiplier + radius))
{
foreach (var segmentId in Enumerable.Range(0, segments))
{
(Vector2, Vector2) GetVector(int i)
{
var (sin, cos) = MathF.SinCos(MathF.PI / 180 * i);
var offset = new Vector2(cos, sin) * radius;
var xy = position.Xy() + offset;
var screen = Camera.WorldToScreen(ExpandWithTerrainHeight(xy.WorldToGrid()));
return (xy, screen);
}
var segmentOrigin = segmentId * segmentSpan;
var (w1, c1) = GetVector(segmentOrigin);
var (w2, c2) = GetVector(segmentOrigin + segmentSpan);
if (Settings.ExplosivesSettings.EnableExplosiveRadiusMerging)
{
if (positions
.Where(x => x != position)
.Select(x => new Vector2(x.X, x.Y))
.Any(x => Vector2.Distance(w1, x) < radius &&
Vector2.Distance(w2, x) < radius))
{
continue;
}
}
Graphics.DrawLine(c1, c2, 1, color);
}
}
}
public override Job Tick()
{
Settings._iconsImageId = Graphics.GetTextureId(TextureName);
Settings.PlannerSettings.SearchState = _plannerRunner switch
{
{ IsRunning: true } => SearchState.Searching,
{ IsRunning: false, CurrentBestPath.PerPointScore.Count: > 0 } => SearchState.Stopped,
_ => SearchState.Empty
};
var detonatorPos = DetonatorPos;
var playerGridPos = GameController.Player?.GetComponent<Positioned>()?.WorldPosNum.WorldToGrid();
if (playerGridPos == null)
{
return null;
}
_playerGridPos = playerGridPos.Value;
if (detonatorPos is { Pos: var dp } && _playerGridPos.Distance(dp) < 90)
{
_zoneCleared = DetonatorEntity?.IsTargetable != true;
if (_zoneCleared)
{
ClearSearch();
return null;
}
}
var ingameUi = GameController.Game.IngameState.IngameUi;
var map = ingameUi.Map;
var largeMap = map.LargeMap.AsObject<SubMap>();
_largeMapOpen = largeMap.IsVisible;
_mapScale = GameController.IngameState.Camera.Height / 677f * largeMap.Zoom;
_mapCenter = largeMap.GetClientRect().TopLeft.ToVector2Num() + largeMap.ShiftNum + largeMap.DefaultShiftNum;
_playerZ = GameController.Player.GetComponent<Render>().Z;
_explosiveRadius = Settings.ExplosivesSettings.CalculateRadiusAutomatically
//ReSharper disable once PossibleLossOfFraction
//rounding here is extremely important to get right, this is taken from the game's code
? ExplosiveBaseRadius * (100 + GameController.IngameState.Data.MapStats?.GetValueOrDefault(GameStat.MapExpeditionExplosionRadiusPct) ?? 0) / 100 * GridToWorldMultiplier
: Settings.ExplosivesSettings.ExplosiveRadius.Value;
//ReSharper disable once PossibleLossOfFraction
//rounding here is extremely important to get right, this is taken from the game's code
_explosiveRange = ExplosiveBaseRange * (100 + GameController.IngameState.Data.MapStats?.GetValueOrDefault(GameStat.MapExpeditionMaximumPlacementDistancePct) ?? 0) / 100 *
GridToWorldMultiplier;
foreach (var entity in new[] { EntityType.IngameIcon, EntityType.Terrain }
.SelectMany(x => GameController.EntityListWrapper.ValidEntitiesByType[x]))
{
if (GetEntityType(entity.Path) != ExpeditionEntityType.None)
{
var newValue = BuildCacheItem(entity);
_cachedEntities[entity.Id] = _cachedEntities.TryGetValue(entity.Id, out var oldValue)
? oldValue.Merge(newValue)
: newValue;
}
}
return null;
}
private (Vector2 Min, Vector2 Max)? GetExclusionRect()
{
if (DetonatorPos is not { } detonatorPos)
{
return null;
}
var negVec = new Vector2(-11.5f, -8.5f);
var posVec = new Vector2(10.5f, 23.5f);
var rotations = (int)Math.Round(detonatorPos.Rotation / (MathF.PI / 2));
for (int i = 0; i < rotations; i++)
{
(negVec.X, negVec.Y, posVec.X, posVec.Y) = (-posVec.Y, negVec.X, -negVec.Y, posVec.X);
}
return (detonatorPos.Pos + negVec, detonatorPos.Pos + posVec);
}
private ExpeditionEnvironment PlannerEnvironment => BuildEnvironment();
private ExpeditionEnvironment BuildEnvironment()
{
if (DetonatorPos is not { Pos: var detonatorPos })
{
throw new Exception("Unable to plan a path: detonator position is unknown");
}
var loot = new List<(Vector2, IExpeditionLoot)>();
var relics = new List<(Vector2, IExpeditionRelic)>();
foreach (var e in _cachedEntities.Values)
{
switch (GetEntityType(e.Path))
{
case ExpeditionEntityType.Marker:
{
var animatedMetaData = e.BaseAnimatedEntityMetadata;
if (animatedMetaData != null)
{
if (animatedMetaData.Contains("elitemarker"))
{
loot.Add((e.GridPos, new RunicMonster()));
}
else
{
var iconDescription = _metadataIconMapping.GetOrAdd(animatedMetaData,
a => Icons.LogbookChestIcons.FirstOrDefault(icon =>
icon.BaseEntityMetadataSubstrings.Any(a.Contains)));
if (iconDescription != null)
{
loot.Add((e.GridPos, new PathPlannerData.Chest(iconDescription.IconPickerIndex)));
}
}
}
continue;
}
case ExpeditionEntityType.Relic:
{
var mods = e.Mods;
if (mods == null)
{
continue;
}
if (e.MinimapIconHide != false) continue;
if (!mods.Any(x => x.Contains("ExpeditionRelicModifier"))) continue;
if (ContainsWarnMods(mods))
{
relics.Add((e.GridPos, new WarningRelic()));
continue;
}
var iconDescriptions = mods.SelectMany(mod =>
_relicModIconMapping.GetOrAdd(mod, s =>
Icons.ExpeditionRelicIcons.Where(icon =>
icon.BaseEntityMetadataSubstrings.Any(s.Contains)).ToList())).Distinct();
var allSubStrings = iconDescriptions.SelectMany(d => d.BaseEntityMetadataSubstrings).ToList();
var fittingMods = mods
.SelectMany(mod => allSubStrings.Where(mod.Contains))
.Distinct()
.Select(x => Icons.GetRelicType(x, Settings.PlannerSettings));
relics.AddRange(fittingMods.Select(expeditionRelic => (e.GridPos, expeditionRelic)));
break;
}
case ExpeditionEntityType.Cave:
{
//Shits given about performance: some? a few?
for (int i = 0; i < Settings.PlannerSettings.LogbookCaveRunicMonsterMultiplier; i++)
{
loot.Add((e.GridPos, new RunicMonster()));
}
for (int i = 0; i < Settings.PlannerSettings.LogbookCaveArtifactChestMultiplier; i++)
{
loot.Add((e.GridPos, new PathPlannerData.Chest(IconPickerIndex.LeagueChest)));
}
break;
}
case ExpeditionEntityType.Boss:
{
//Shits given about performance: some? a few?
for (int i = 0; i < Settings.PlannerSettings.LogbookBossRunicMonsterMultiplier; i++)
{
loot.Add((e.GridPos, new RunicMonster()));
}
break;
}
}
}
return new ExpeditionEnvironment(
relics.FindAll(x => x.Item2 != null),
loot.FindAll(x => x.Item2 != null),
_explosiveRange / GridToWorldMultiplier,
_explosiveRadius / GridToWorldMultiplier,
ExpeditionInfo.TotalExplosiveCount,
detonatorPos,
IsValidPlacement,
GetExclusionRect() ?? default,
(GameController.IngameState.Data.MapStats?.GetValueOrDefault(GameStat.MapMinimapMainAreaRevealed) ?? 0) != 0);
}
private bool IsValidPlacement(Vector2 x)
{
return x.X >= 0 && x.Y >= 0 &&
x.X < _areaDimensions.X &&
x.Y < _areaDimensions.Y &&
_pathfindingData[(int)x.Y][(int)x.X] > 3;
}
public override void Render()
{
if (Settings.PlannerSettings.ClearSearchHotkey.PressedOnce())
{
ClearSearch();
}
if (Settings.PlannerSettings.StopSearchHotkey.PressedOnce())
{
StopSearch();
}
if (_zoneCleared)
{
return;
}
if (Settings.PlannerSettings.StartSearchHotkey.PressedOnce())
{
StartSearch();
}
var explosives3D = GameController.EntityListWrapper.ValidEntitiesByType[EntityType.IngameIcon]
.Where(x => x.Path == ExplosivePath)
.Select(x => x.PosNum)
.ToList();
_explosives2DPositions = explosives3D.Select(x => new Vector2(x.X, x.Y)).ToList();
if (Settings.ExplosivesSettings.ShowExplosives)
{
DrawCirclesInWorld(
positions: explosives3D,
radius: _explosiveRadius,
color: Settings.ExplosivesSettings.ExplosiveColor.Value);
}
foreach (var e in _cachedEntities.Values)
{
switch (GetEntityType(e.Path))
{
case ExpeditionEntityType.Marker:
{
var animatedMetaData = e.BaseAnimatedEntityMetadata;
if (animatedMetaData != null)
{
if (animatedMetaData.Contains("elitemarker"))
{
var mapSettings = Settings.IconMapping.GetValueOrDefault(IconPickerIndex.EliteMonstersIndicator, new IconDisplaySettings());
if (mapSettings.ShowOnMap)
{
DrawIconOnMap(e, mapSettings.Icon ?? ExpeditionIconsSettings.DefaultEliteMonsterIcon, mapSettings.Tint, Vector2.Zero);
}
if (mapSettings.ShowInWorld)
{
DrawIconInWorld(e, mapSettings.Icon ?? ExpeditionIconsSettings.DefaultEliteMonsterIcon, mapSettings.Tint, Vector2.Zero);
}
}
else
{
var iconDescription = _metadataIconMapping.GetOrAdd(animatedMetaData,
a => Icons.LogbookChestIcons.FirstOrDefault(icon =>
icon.BaseEntityMetadataSubstrings.Any(a.Contains)));
if (iconDescription != null)
{
var settings = Settings.IconMapping.GetValueOrDefault(iconDescription.IconPickerIndex, new IconDisplaySettings());
var icon = settings.Icon ?? iconDescription.DefaultIcon;
if (settings.ShowOnMap)
{
DrawIconOnMap(e, icon, settings.Tint, Vector2.Zero);
}
if (settings.ShowInWorld)
{
DrawIconInWorld(e, icon, settings.Tint, Vector2.Zero);
}
}
}
}
continue;
}
case ExpeditionEntityType.Relic:
{
var mods = e.Mods;
if (e.Mods == null) continue;
if (e.MinimapIconHide != false) continue;
if (!mods.Any(x => x.Contains("ExpeditionRelicModifier"))) continue;
if (ContainsWarnMods(mods))
{
var mapSettings = Settings.IconMapping.GetValueOrDefault(IconPickerIndex.BadModsIndicator, new IconDisplaySettings());
if (mapSettings.ShowOnMap)
{
DrawIconOnMap(e, mapSettings.Icon ?? ExpeditionIconsSettings.DefaultBadModsIcon, mapSettings.Tint, Vector2.Zero);
}
if (mapSettings.ShowInWorld)
{
DrawIconInWorld(e, mapSettings.Icon ?? ExpeditionIconsSettings.DefaultBadModsIcon, mapSettings.Tint, -Vector2.UnitY);
}
continue;
}
if (Settings.DrawGoodModsInWorld || Settings.DrawGoodModsOnMap)
{
var worldIcons = new HashSet<(MapIconsIndex, Color?)>();
var mapIcons = new HashSet<(MapIconsIndex, Color?)>();
var iconDescriptions = mods.SelectMany(mod =>
_relicModIconMapping.GetOrAdd(mod, s =>
Icons.ExpeditionRelicIcons.Where(icon =>
icon.BaseEntityMetadataSubstrings.Any(s.Contains)).ToList())).Distinct();
foreach (var iconDescription in iconDescriptions)
{
var settings = Settings.IconMapping.GetValueOrDefault(iconDescription.IconPickerIndex, new IconDisplaySettings());
var icon = settings.Icon ?? iconDescription.DefaultIcon;
if (settings.ShowOnMap)
{
mapIcons.Add((icon, settings.Tint));
}
if (settings.ShowInWorld)
{
worldIcons.Add((icon, settings.Tint));
}
}
var offset = new Vector2(-worldIcons.Count * 0.5f + 0.5f, 0);
foreach (var (icon, tint) in worldIcons)
{
if (Settings.DrawGoodModsInWorld)
{
DrawIconInWorld(e, icon, tint, offset);
}
offset += Vector2.UnitX;
}
offset = new Vector2(-mapIcons.Count * 0.5f + 0.5f, 0);
foreach (var (icon, tint) in mapIcons)
{
if (Settings.DrawGoodModsOnMap)
{
DrawIconOnMap(e, icon, tint, offset);
}
offset += Vector2.UnitX;
}
}
break;
}
}
}
if (EditedOrNativeScore is { PerPointScore.Count: > 0 } score)
{
var path = score.PerPointScore;
var firstPoint = DetonatorPos?.Pos ?? _playerGridPos;
var prevPoint = firstPoint;
for (var i = 0; i < path.Count; i++)
{
var point = path[i].Point;
if (_largeMapOpen)
{
Graphics.DrawLine(GetMapScreenPosition(prevPoint), GetMapScreenPosition(point), 1, Settings.PlannerSettings.MapLineColor);
}
var worldPos = GetWorldScreenPosition(point);
Graphics.DrawLine(GetWorldScreenPosition(prevPoint), worldPos, 1, Settings.PlannerSettings.WorldLineColor);
var text = $"#{i}";
using (Graphics.SetTextScale(Settings.PlannerSettings.TextMarkerScale))
{
Graphics.DrawBox(worldPos, worldPos + Graphics.MeasureText(text), Color.Black);
Graphics.DrawText(text, worldPos, Color.White);
prevPoint = point;
}
}
if (Settings.PlannerSettings.IsSearchRunning)
{
_scoreHistory.Add((float)score.TotalScore);
}
ShowSearchWindow(score);
DrawCirclesInWorld(
positions: path.Select(x => ExpandWithTerrainHeight(x.Point)).ToList(),
radius: _explosiveRadius,
color: Settings.PlannerSettings.ExplosiveColor.Value);
}
}
private void ShowSearchWindow(PathPlanner.DetailedLootScore score)
{
if (Settings.PlannerSettings.ShowScoreHistory &&
(Settings.PlannerSettings.IsSearchRunning || Settings.PlannerSettings.ShowScoreHistoryAfterSearchEnds) &&
ImGui.Begin("Expedition planning result"))
{
if (ImGui.TreeNode("Detailed view"))
{
PathPlanner.DetailedLootScore scoreDiff = null;
if (_editedPath != null && _editedIndex is { } editedIndex)
{
var pos = GameController.IngameState.ServerData.WorldMousePositionNum.WorldToGrid();
var pp = new PathPlanner(Settings.PlannerSettings);
pp.Init(score.Environment);
var path = _editedPath.ToList();
path[editedIndex] = pos;
scoreDiff = pp.GetDetailedScore(path, score.Environment);
DrawCirclesInWorld([ExpandWithTerrainHeight(pos)], _explosiveRadius, Color.LightBlue);
Graphics.DrawLine(GetWorldScreenPosition(_editedPath[editedIndex]), GetWorldScreenPosition(pos), 1, Settings.PlannerSettings.WorldLineColor);
if (Input.IsKeyDown(Settings.PlannerSettings.ConfirmEditorPlacementHotkey))
{
_editedPath[editedIndex] = pos;
_editedPathEval = pp.GetDetailedScore(_editedPath, score.Environment);
_editedIndex = null;
}
if (Input.IsKeyDown(Keys.Escape))
{
_editedIndex = null;
}
}
if (ImGui.BeginTable("Change per explosive", 6, ImGuiTableFlags.Hideable | ImGuiTableFlags.Borders | ImGuiTableFlags.SizingStretchProp))
{
ImGui.TableSetupColumn("Id");
ImGui.TableSetupColumn("Running score");
ImGui.TableSetupColumn("Score diff");
ImGui.TableSetupColumn("New relic mods");
ImGui.TableSetupColumn("New loot");
ImGui.TableSetupColumn("Edit");
ImGui.TableHeadersRow();
var runningScore = 0.0;
var runningScoreAfterDiff = 0.0;
for (var i = 0; i < score.PerPointScore.Count; i++)
{
var perPointLootScore = score.PerPointScore[i];
var diffOrOld = scoreDiff?.PerPointScore[i] ?? perPointLootScore;
ImGui.TableNextRow();
ImGui.PushID(i);
ImGui.TableNextColumn();
ImGui.Text($"{i,2}");
ImGui.TableNextColumn();
runningScore += perPointLootScore.ScoreDiff;
if (scoreDiff != null)
{
runningScoreAfterDiff += scoreDiff.PerPointScore[i].ScoreDiff;
ImGui.Text($"{runningScoreAfterDiff,7:F2}");
var valueDiff = runningScoreAfterDiff - runningScore;
if (valueDiff != 0)
{
ImGui.SameLine();
ImGui.TextColored(GetCompareColor(runningScoreAfterDiff, runningScore), $"{valueDiff:(+0.00);(-0.00);''}");
}
}
else
{
ImGui.Text($"{runningScore,7:F2}");
}
ImGui.TableNextColumn();
ImGui.Text($"{diffOrOld.ScoreDiff,7:F2}");
if (scoreDiff != null)
{
var valueDiff = scoreDiff.PerPointScore[i].ScoreDiff - perPointLootScore.ScoreDiff;
if (valueDiff != 0)
{
ImGui.SameLine();
ImGui.TextColored(
GetCompareColor(scoreDiff.PerPointScore[i].ScoreDiff, perPointLootScore.ScoreDiff),
$"{valueDiff:(+0.00);(-0.00);''}");
}
}
ImGui.TableNextColumn();
ImGui.Text($"{diffOrOld.NewRelics}");
if (scoreDiff != null)
{
var valueDiff = scoreDiff.PerPointScore[i].NewRelics - perPointLootScore.NewRelics;
if (valueDiff != 0)
{
ImGui.SameLine();
ImGui.TextColored(
GetCompareColor(scoreDiff.PerPointScore[i].NewRelics, perPointLootScore.NewRelics),
$"{valueDiff:(+0);(-0);''}");
}
}
ImGui.TableNextColumn();
ImGui.Text($"{diffOrOld.Loot}");
if (scoreDiff != null)
{
var valueDiff = scoreDiff.PerPointScore[i].Loot - perPointLootScore.Loot;
if (valueDiff != 0)
{
ImGui.SameLine();
ImGui.TextColored(
GetCompareColor(scoreDiff.PerPointScore[i].Loot, perPointLootScore.Loot),
$"{valueDiff:(+0);(-0);''}");
}
}
ImGui.TableNextColumn();
if (i == _editedIndex)
{
ImGui.PushStyleColor(ImGuiCol.Button, Color.Green.ToImguiVec4());
if (ImGui.Button("Cancel"))
{
_editedIndex = null;
}
ImGui.PopStyleColor();
}
else if (ImGui.Button(" Edit "))
{
_editedPath ??= score.PerPointScore.Select(x => x.Point).ToList();
var pp = new PathPlanner(Settings.PlannerSettings);
pp.Init(score.Environment);
_editedPathEval = pp.GetDetailedScore(_editedPath, score.Environment);
_editedIndex = i;
}
ImGui.PopID();
}
ImGui.EndTable();
}
if (_editedPath != null && ImGui.Button("Reset edited path"))
{
_editedIndex = null;
_editedPath = null;
_editedPathEval = null;
}
}
ImGui.PlotLines("Score over time", ref CollectionsMarshal.AsSpan(_scoreHistory)[0],
_scoreHistory.Count, 0, "", 0, _scoreHistory.Max(),
new Vector2(0, ImGui.GetContentRegionAvail().Y));
ImGui.End();
}
}
private static Vector4 GetCompareColor(double @new, double old)
{
return @new.CompareTo(old) switch
{
> 0 => Color.Green.ToImguiVec4(), 0 => Color.White.ToImguiVec4(), < 0 => Color.Red.ToImguiVec4()
};
}
private bool ContainsWarnMods(List<string> mods)
{
return Settings.WarnPhysImmune && mods.Any(x => x.Contains("ExpeditionRelicModifierImmunePhysicalDamage")) ||
Settings.WarnFireImmune && mods.Any(x => x.Contains("ExpeditionRelicModifierImmuneFireDamage")) ||
Settings.WarnColdImmune && mods.Any(x => x.Contains("ExpeditionRelicModifierImmuneColdDamage")) ||
Settings.WarnLightningImmune && mods.Any(x => x.Contains("ExpeditionRelicModifierImmuneLightningDamage")) ||
Settings.WarnChaosImmune && mods.Any(x => x.Contains("ExpeditionRelicModifierImmuneChaosDamage")) ||
Settings.WarnCritImmune && mods.Any(x => x.Contains("ExpeditionRelicModifierCannotBeCrit")) ||
Settings.WarnIgniteImmune && mods.Any(x => x.Contains("ExpeditionRelicModifierImmuneStatusAilments")) ||
Settings.WarnArmorPen && mods.Any(x => x.Contains("ExpeditionRelicModifierIgnoreArmour")) ||
Settings.WarnNoEvade && mods.Any(x => x.Contains("ExpeditionRelicModifierHitsCannotBeEvaded")) ||
Settings.WarnNoLeech && mods.Any(x => x.Contains("ExpeditionRelicModifierCannotBeLeechedFrom")) ||
Settings.WarnNoFlask && mods.Any(x => x.Contains("ExpeditionRelicModifierGrantNoFlaskCharges")) ||
Settings.WarnPetrify && mods.Any(x => x.Contains("ExpeditionRelicModifierElitesPetrifyOnHit")) ||
Settings.WarnCurseImmune && mods.Any(x => x.Contains("ExpeditionRelicModifierImmuneToCurses")) ||
Settings.WarnCull && mods.Any(x => x.Contains("ExpeditionRelicModifierCullingStrikeTwentyPercent")) ||
Settings.WarnMonsterBlock && mods.Any(x => x.Contains("ExpeditionRelicModifierAttackBlockSpellBlockMaxBlockChance")) ||
Settings.WarnMonsterResist && mods.Any(x => x.Contains("ExpeditionRelicModifierResistancesAndMaxResistances")) ||
Settings.WarnMonsterRegen && mods.Any(x => x.Contains("ExpeditionRelicModifierElitesRegenerateLifeEveryFourSeconds")) ||
Settings.WarnAlwaysCrit && mods.Any(x => x.Contains("ExpeditionRelicModifierAlwaysCrit")) ||
Settings.WarnReducedDamageTaken && mods.Any(x => x.Contains("ExpeditionRelicModifierReducedDamageTaken")) ||
Settings.WarnBleed && mods.Any(x => x.Contains("ExpeditionRelicModifierBleedOnHitBleedDuration")) ||
Settings.WarnCorrupted && mods.Any(x => x.Contains("ExpeditionRelicModifierExpeditionCorruptedItemsElite")) ||
Settings.WarnPoison && mods.Any(x => x.Contains("ExpeditionRelicModifierAllDamagePoisonsPoisonDuration")) ||
Settings.WarnPhysicalAsExtraChaos && mods.Any(x => x.Contains("ExpeditionRelicModifierDamageAddedAsChaos")) ||
false;
}
private void DrawIconOnMap(EntityCacheItem entity, MapIconsIndex icon, Color? color, Vector2 offset)
{
if (_largeMapOpen)
{
var halfsize = Settings.MapIconSize / 2.0f;
var point = GetEntityPosOnMapScreen(entity) + offset * halfsize * 2;
var entityPos = entity.Pos;
var entityPos2 = new Vector2(entityPos.X, entityPos.Y);
DrawIcon(icon, color, point, entityPos2,
Settings.ExplosivesSettings.HideCapturedEntitiesOnMap,
Settings.ExplosivesSettings.MarkCapturedEntitiesOnMap,
Settings.ExplosivesSettings.CapturedEntityMapFrameColor,
Settings.PlannerSettings.CapturedEntityMapFrameColor,
Settings.ExplosivesSettings.CapturedEntityMapFrameThickness,
Settings.MapIconSize);
}
}
private void DrawIconInWorld(EntityCacheItem entity, MapIconsIndex icon, Color? color, Vector2 offset)
{
var halfsize = Settings.WorldIconSize / 2.0f;
var entityPos = entity.Pos;
var entityPos2 = new Vector2(entityPos.X, entityPos.Y);
var point = Camera.WorldToScreen(entityPos) + offset * halfsize * 2;
DrawIcon(icon, color, point, entityPos2,
Settings.ExplosivesSettings.HideCapturedEntitiesInWorld,
Settings.ExplosivesSettings.MarkCapturedEntitiesInWorld,
Settings.ExplosivesSettings.CapturedEntityWorldFrameColor,
Settings.PlannerSettings.CapturedEntityWorldFrameColor,
Settings.ExplosivesSettings.CapturedEntityWorldFrameThickness,
Settings.WorldIconSize);
}
private void DrawIcon(
MapIconsIndex icon,
Color? color,
Vector2 displayPosition,
Vector2 worldPosition,
bool hideCaptured,
bool markCaptured,
Color capturedFrameColor,
Color plannerCapturedFrameColor,
int frameThickness,
float iconSize)
{
var halfsize = iconSize / 2.0f;
var rect = new RectangleF(displayPosition.X, displayPosition.Y, 0, 0);
rect.Inflate(halfsize, halfsize);
var calculateExplosiveFrameDisplay = hideCaptured || markCaptured;
var isInExplosiveRadius = calculateExplosiveFrameDisplay &&
_explosives2DPositions.Any(x => Vector2.Distance(x, worldPosition) < _explosiveRadius);
var gridPosition = worldPosition.WorldToGrid();
var isInPlannedExplosiveRadius = calculateExplosiveFrameDisplay &&
EditedOrNativeScore is { PerPointScore.Count: > 0 } path &&
path.PerPointScore.Any(x => Vector2.Distance(x.Point, gridPosition) < _explosiveRadius / GridToWorldMultiplier);
if (markCaptured)
{
var plannedRect = rect;
if (isInExplosiveRadius)
{
Graphics.DrawFrame(rect, capturedFrameColor, frameThickness);
plannedRect.Inflate(frameThickness, frameThickness);
}
if (isInPlannedExplosiveRadius)
{
Graphics.DrawFrame(plannedRect, plannerCapturedFrameColor, frameThickness);
}
}
if (!isInExplosiveRadius || !hideCaptured)
{
Graphics.DrawImage(TextureName, rect, SpriteHelper.GetUV(icon), color ?? Color.White);
}
}
private Vector2 GetMapScreenPosition(Vector2 gridPos)
{
return _mapCenter + TranslateGridDeltaToMapDelta(gridPos - _playerGridPos, GameController.IngameState.Data.GetTerrainHeightAt(gridPos) - _playerZ);
}
private Vector2 GetWorldScreenPosition(Vector2 gridPos)
{
return Camera.WorldToScreen(ExpandWithTerrainHeight(gridPos));
}
private Vector2 GetEntityPosOnMapScreen(EntityCacheItem entity)
{
var point = _mapCenter + TranslateGridDeltaToMapDelta(entity.GridPos - _playerGridPos, (entity.RenderZ ?? 0) - _playerZ);
return point;
}
private Vector2 TranslateGridDeltaToMapDelta(Vector2 delta, float deltaZ)
{
deltaZ /= GridToWorldMultiplier; //z is normally "world" units, translate to grid
return (float)_mapScale * new Vector2((delta.X - delta.Y) * CameraAngleCos, (deltaZ - (delta.X + delta.Y)) * CameraAngleSin);
}
private enum ExpeditionEntityType
{
None,
Relic,
Marker,
Cave,
Boss,
}
private record EntityCacheItem(
string Path,
Lazy<string> BaseAnimatedEntityMetadataCache,
List<string> Mods,
Vector3 Pos,
Vector2 GridPos,
float? RenderZ,
float? RenderSize,
bool? MinimapIconHide)
{
public string BaseAnimatedEntityMetadata => BaseAnimatedEntityMetadataCache.Value;
public EntityCacheItem Merge(EntityCacheItem other)
{
return new EntityCacheItem(
Path ?? other.Path,
BaseAnimatedEntityMetadata == null ? other.BaseAnimatedEntityMetadataCache : BaseAnimatedEntityMetadataCache,
Mods ?? other.Mods,
Pos,
GridPos,
RenderZ ?? other.RenderZ,
RenderSize ?? other.RenderSize,
MinimapIconHide ?? MinimapIconHide);
}
}
public override void EntityAdded(Entity entity)
{
if (entity.Type is EntityType.IngameIcon or EntityType.Terrain && GetEntityType(entity.Path) != ExpeditionEntityType.None)
{
_cachedEntities[entity.Id] = BuildCacheItem(entity);
}
}
private static EntityCacheItem BuildCacheItem(Entity entity)
{
return new EntityCacheItem(
entity.Path,
new Lazy<string>(() => entity.GetComponent<Animated>()?.BaseAnimatedObjectEntity?.Metadata, LazyThreadSafetyMode.None),
entity.GetComponent<ObjectMagicProperties>()?.Mods,
entity.PosNum,
entity.PosNum.WorldToGrid(),
entity.GetComponent<Render>()?.Z,
entity.GetComponent<Render>()?.BoundsNum is { } b ? Math.Min(b.X, b.Y) : null,
entity.GetComponent<MinimapIcon>()?.IsHide);
}
}