-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCornerSpeedPlugin.cs
More file actions
1455 lines (1296 loc) · 63.5 KB
/
Copy pathCornerSpeedPlugin.cs
File metadata and controls
1455 lines (1296 loc) · 63.5 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
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using FMOD.Studio;
using GameReaderCommon;
using iRacingSDK;
using MahApps.Metro.Controls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PropertyChanged;
using SimHub;
using SimHub.Plugins;
using SimHub.Plugins.ChartingWindow;
using SimHub.Plugins.Dashstudio.Behaviors.Core.Interfaces;
using SimHub.Plugins.DataPlugins.DataCore;
using SimHub.Plugins.Devices.DevicesExtensionsDummy;
using SimHub.Plugins.Devices.Registry.Impl.TurtleBeach.UI;
using SimHub.Plugins.OutputPlugins.ControlRemapper;
using SimHub.Plugins.OutputPlugins.Dash.GLCDTemplating;
using SimHub.Plugins.OutputPlugins.Dash.WPFUI;
using SimHub.Plugins.OutputPlugins.EditorControls;
using SimHub.Plugins.OutputPlugins.GraphicalDash;
using SimHub.Plugins.OutputPlugins.GraphicalDash.Models;
using SimHub.Plugins.OutputPlugins.GraphicalDash.Render;
using SimHub.Plugins.OutputPlugins.GraphicalDash.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Threading;
using User.CornerSpeed;
using WoteverCommon.Extensions;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Xaml;
using static User.CornerSpeed.CornerSpeedPlugin;
namespace User.CornerSpeed
{
//public class CustomEntry : FormulaPropertyEntry
//{
// public CustomEntry(string Name, string syntax, string description) : base(Name, syntax, description)
// {
// }
//}
public class iRacingTurnNumbers
{
public List<Turn> turns = [];
};
public class Turn
{
public string name;
public float start; // meters
public float end; // meters
public float distance_per_marker = 2.0f;
};
//[AddINotifyPropertyChangedInterface]
public class Corner : Turn, INotifyPropertyChanged
{
public static PluginManager PluginManager;
private static int IncidentCount = -1;
public Corner()
{
PluginManager ??= PluginManager.GetInstance();
}
public Corner(Turn turn, int index) : this()
{
name = turn.name;
start = turn.start;
end = turn.end;
Index = index;
}
[JsonIgnore]
public int Index;
public event PropertyChangedEventHandler PropertyChanged;
public double start_speed { get; set;} = 0.0;
public double end_speed { get; set; } = 0.0;
public double min_speed { get; set; } = 999.9;
public bool init { get; set; } = false;
public DateTime start_time { get; set; }
public DateTime end_time { get; set; }
/// <summary>
/// The session time when the min_speed occured
/// </summary>
public DateTime min_time { get; set; }
/// <summary>
/// The track dist where the min_speed occured
/// </summary>
public double min_dist { get; set; }
[JsonIgnore]
public TimeSpan Duration => end_time - start_time;
[JsonIgnore]
public bool Active { get; set; } = false;
[JsonIgnore]
public bool Valid { get; set; } = true;
[JsonIgnore]
public double curr_dist { get; set; } = 0.0;
public ObservableCollection<TimeSpan> markers = [];
public void Start()
{
Active = true;
start_time = GetTime();
start_speed = Convert.ToDouble(PluginManager.GetPropertyValue("DataCorePlugin.GameData.SpeedLocal"));
// reset vars
end_time = start_time;
min_speed = 999.9;
Valid = true;
markers = [];
//markers = [.. new TimeSpan[((int)((end - start) / distance_per_marker))]];
}
public DateTime GetTime()
{
//TimeSpan.FromSeconds(Convert.ToDouble(PluginManager.GetPropertyValue("DataCorePlugin.GameRawData.Telemetry.SessionTime")));
return Convert.ToDateTime(PluginManager.GetPropertyValue("DataCorePlugin.GameData.PacketTime"));
//return dataBase.PacketTime;
}
public void Update(GameData data)
{
var session_time = GetTime();
var time = session_time - start_time;
//var dist = Convert.ToDouble(PluginManager.GetPropertyValue("DataCorePlugin.GameRawData.Telemetry.LapDist"));
var dist = data.NewData.TrackPositionMeters;
var length = dist - start;
if (start > end)
{
//length += Convert.ToDouble(PluginManager.GetPropertyValue("DataCorePlugin.GameData.TrackLength"));
length += data.NewData.TrackLength;
}
curr_dist = length;
var index = (int)((length) / distance_per_marker);
//markers[(int)((dist - start) / distance_per_marker)] = time;
if (markers.Count < index)
{
markers.Add(time);
}
var incidentCount = Convert.ToInt32(PluginManager.GetPropertyValue("DataCorePlugin.GameRawData.Telemetry.PlayerCarMyIncidentCount"));
if (incidentCount > IncidentCount && IncidentCount != -1)
{
Valid = false;
}
IncidentCount = incidentCount;
//var black_flag = Convert.ToInt32(PluginManager.GetPropertyValue("DataCorePlugin.GameData.Flag_Black"));
var black_flag = data.NewData.Flag_Black;
if (black_flag > 0)
{
Valid = false;
}
//var speed = Convert.ToDouble(PluginManager.GetPropertyValue("DataCorePlugin.GameData.SpeedLocal"));
var speed = data.NewData.SpeedLocal;
if (speed < min_speed)
{
min_speed = speed;
min_time = session_time;
min_dist = dist;
}
end_time = session_time;
end_speed = speed;
}
public void End()
{
Active = false;
init = true;
var time = GetTime();
end_time = time;
var speed = Convert.ToDouble(PluginManager.GetPropertyValue("DataCorePlugin.GameData.SpeedLocal"));
end_speed = speed;
}
public Corner Copy()
{
return new Corner()
{
name = name,
Index = Index,
start = start,
end = end,
Valid = Valid,
start_time = start_time,
end_time = end_time,
min_time = min_time,
min_dist = min_dist,
start_speed = start_speed,
end_speed = end_speed,
min_speed = min_speed,
init = init,
Active = Active,
markers = markers
};
}
};
//[AddINotifyPropertyChangedInterface]
public class CornerViewModel : INotifyPropertyChanged
{
public Corner Corner { get; set; }
public Dictionary<ComparisonMode, Corner> ComparisonCorners { get; set; }
public ComparisonMode Mode { get; set;} = ComparisonMode.CompareToBestCarLap;
public int TurnIndex => Corner.Index;
public string TurnName => Corner.name;
public double StartSpeed => Corner.start_speed;
public double MinSpeed => Corner.min_speed;
public double EndSpeed => Corner.end_speed;
public double StartSpeedDelta => Corner.start_speed - (ComparisonCorners[Mode]?.start_speed ?? 0.0);
public double MinSpeedDelta => Corner.min_speed - (ComparisonCorners[Mode]?.min_speed ?? 0.0);
public double EndSpeedDelta => Corner.end_speed - (ComparisonCorners[Mode]?.end_speed ?? 0.0);
public TimeSpan Duration => Corner.Duration;
public TimeSpan DurationDelta => (IsActive) ? LiveDelta : Corner.Duration - (ComparisonCorners[Mode]?.Duration ?? TimeSpan.Zero);
public TimeSpan Apex => Corner.min_time - Corner.start_time;
public TimeSpan ApexDelta => (Corner.min_time - Corner.start_time) - ((ComparisonCorners[Mode]?.min_time ?? DateTime.UtcNow) - (ComparisonCorners[Mode]?.start_time ?? DateTime.UtcNow));
public double ApexDist => Corner.min_dist - Corner.start;
public double ApexDistDelta => (Corner.min_dist - Corner.start) - ((ComparisonCorners[Mode]?.min_dist ?? 0.0) - (ComparisonCorners[Mode]?.start ?? 0.0));
public bool WasShortestDuration => !IsActive && Corner.Duration < (ComparisonCorners[Mode]?.Duration ?? TimeSpan.Zero);
public bool IsNewEntry => !ComparisonCorners[Mode]?.init ?? true;
public bool IsInvalid => !Corner.Valid;
public bool IsActive => Corner.Active;
public bool Latest { get; set; } = true;
//public TimeSpan LiveDelta { get {
// if (Corner.markers.Count > 0) {
// var comp = ComparisonCorners[Mode];
// var index = Corner.markers.Count - 1;
// if (comp != null && comp.markers.Count > index) {
// return Corner.markers[index] - comp.markers[index];
// }
// }
// return TimeSpan.Zero;
// }
//}
public TimeSpan LiveDelta { get {
var time = TimeSpan.Zero;
var comp_time = TimeSpan.Zero;
var comp = ComparisonCorners[Mode];
if (Corner.markers.Count > 0 && comp != null)
{
var last = Corner.markers.Count - 1;
var diff = DateTime.UtcNow - Corner.start_time;
time += diff;
if (comp.markers.Count > last) {
if (comp.markers.Count > (last + 1))
{
// interpolate the current distance to a time for comparison lap
//var dist = Convert.ToDouble(Corner.PluginManager.GetPropertyValue("DataCorePlugin.GameRawData.Telemetry.LapDist"));
//var index_f = ((dist - Corner.start) / Corner.distance_per_marker) % 1.0;
var index_f = (Corner.curr_dist / Corner.distance_per_marker) % 1.0;
var comp_curr = comp.markers[last];
var comp_next = comp.markers[last + 1];
var add = (comp_curr.TotalSeconds * (1.0 - index_f)) + (comp_next.TotalSeconds * index_f);
comp_time = TimeSpan.FromSeconds(comp_time.TotalSeconds + add);
}
else
{
comp_time += comp.markers[last];
}
}
}
return time - comp_time;
} }
public CornerViewModel()
{
}
public Corner ComparisonCorner => ComparisonCorners[Mode];
public CornerViewModel(Corner corner, ComparisonMode mode, Dictionary<ComparisonMode, Corner> comparisonCorners) : this()
{
Corner = corner;
Mode = mode;
ComparisonCorners = comparisonCorners;
Corner.PropertyChanged += OnPropertyChanged;
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (sender is Corner) {
if (e.PropertyName == nameof(Corner.Duration)) {
PluginManager.GetInstance().UIUpdateDispatcher.Dispatcher.Invoke(() =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Duration)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(DurationDelta)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(WasShortestDuration)));
});
}
if (e.PropertyName == nameof(Corner.markers)) {
PluginManager.GetInstance().UIUpdateDispatcher.Dispatcher.Invoke(() =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(DurationDelta)));
});
}
else if (e.PropertyName == nameof(Corner.Valid))
{
PluginManager.GetInstance().UIUpdateDispatcher.Dispatcher.Invoke(() =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsInvalid)));
});
}
else if (e.PropertyName == nameof(Corner.Active))
{
PluginManager.GetInstance().UIUpdateDispatcher.Dispatcher.Invoke(() =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsActive)));
});
}
else if (e.PropertyName == nameof(Corner.min_speed))
{
PluginManager.GetInstance().UIUpdateDispatcher.Dispatcher.Invoke(() =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MinSpeed)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MinSpeedDelta)));
});
}
else if (e.PropertyName == nameof(Corner.min_time))
{
PluginManager.GetInstance().UIUpdateDispatcher.Dispatcher.Invoke(() =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Apex)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ApexDelta)));
});
}
else if (e.PropertyName == nameof(Corner.min_dist))
{
PluginManager.GetInstance().UIUpdateDispatcher.Dispatcher.Invoke(() =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ApexDist)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ApexDistDelta)));
});
}
else if (e.PropertyName == nameof(Corner.end_speed))
{
PluginManager.GetInstance().UIUpdateDispatcher.Dispatcher.Invoke(() =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(EndSpeed)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(EndSpeedDelta)));
});
}
else if (e.PropertyName == nameof(Corner.init))
{
PluginManager.GetInstance().UIUpdateDispatcher.Dispatcher.Invoke(() =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsNewEntry)));
});
}
} else {
if (System.Windows.Application.Current.Dispatcher.CheckAccess()) {
PropertyChanged?.Invoke(sender, e);
} else {
PluginManager.GetInstance().UIUpdateDispatcher.Dispatcher.Invoke(() => {
PropertyChanged?.Invoke(sender, e);
});
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
};
public class Sector
{
public float start;
public float end;
public uint num_markers;
public float distance_per_marker;
public float sector_start_info;
public float sector_end_info;
public float time;
public uint flags;
public List<Marker> Markers;
};
public class Marker
{
public float sector_time;
public float timing_line_position;
public float YawNorth; // <read=Str("%0.2fdeg (%0.6f)", this*57.2958, this)>;
public float Pitch; // <read=Str("%0.2fdeg (%0.6f)", this*57.2958, this)>;
public float Roll; // <read=Str("%0.2fdeg (%0.6f)", this*57.2958, this)>;
public uint flags; // marker->unk14, off-track?
public byte Throttle; // <read=Str("%d", this)>;
public byte Brake; // <read=Str("%d", this)>;
public byte Clutch; // <read=Str("%d", this)>; // inverse
public byte Gear; // <read=Str("%d", this - 1)>; // gear plus one
};
public static class MyEnumExtensions
{
//public static string ToDescriptionString(this ComparisonMode val)
//{
// DescriptionAttribute[] attributes = (DescriptionAttribute[])val
// .GetType()
// .GetField(val.ToString())
// .GetCustomAttributes(typeof(DescriptionAttribute), false);
// return attributes.Length > 0 ? attributes[0].Description : string.Empty;
//}
public static string ToDescriptionString(this Enum val)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])val
.GetType()
.GetField(val.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}
}
public enum ComparisonMode
{
[Description("vs Best in Car")]
CompareToBestCarLap,
[Description("vs Session Best in Car")]
CompareToBestSessionCarLap,
[Description("vs Comparison Lap")]
CompareToComparisonLap,
Count
};
public enum InputMode {
[Description("Car")] Car,
//[Description("Car2")] Car2,
[Description("Pitting")] Pitting,
[Description("Chat")] Chat,
//[Description("BlackBox")] BlackBox,
Count
};
[PluginDescription("My plugin description")]
[PluginAuthor("Jack Humbert")]
[PluginName("Corner Speed")]
public class CornerSpeedPlugin : IPlugin, IDataPlugin, IWPFSettingsV2, INotifyPropertyChanged
{
private static Program program;
public CornerSpeedPluginSettings Settings;
/// <summary>
/// Instance of the current plugin manager
/// </summary>
public PluginManager PluginManager { get; set; }
//public SimpleChart item;
//public SimHub.Plugins.OutputPlugins.GraphicalDash.SelectionTemplateSelector selector;
/// <summary>
/// Gets the left menu icon. Icon must be 24x24 and compatible with black and white display.
/// </summary>
public ImageSource PictureIcon => this.ToIcon(Properties.Resources.sdkmenuicon);
/// <summary>
/// Gets a short plugin title to show in left menu. Return null if you want to use the title as defined in PluginName attribute.
/// </summary>
public string LeftMenuTitle => "Corner Speed";
public int NumberOfCorners = 20;
public int NumberOfLaps = 10;
public int CurrentLap = 0;
//public int CurrentCorner = -1;
//public int LastCorner = -1;
public TimeSpan CornerDelta;
private double lastLiveDelta = 0.0;
private DateTime lastLiveDeltaTimestamp = DateTime.UtcNow;
public double DLiveDelta { get
{
var now = DateTime.UtcNow;
var d = (LiveDelta - lastLiveDelta) / (now - lastLiveDeltaTimestamp).TotalSeconds;
lastLiveDelta = LiveDelta;
lastLiveDeltaTimestamp = now;
return d;
} }
public double LiveDelta { get {
var time = TimeSpan.Zero;
var comp_time = TimeSpan.Zero;
if (CurrentCornerSpeeds == null || CornersToCompare == null || CurrentCornerSpeeds.Count != CornersToCompare.Count)
return -1.23;
for (int i = 0; i < CurrentCornerSpeeds.Count; i++)
{
if (CurrentCornerSpeeds[i] == null || CornersToCompare[i] == null)
continue;
if (CurrentCornerSpeeds[i].Active && CurrentCornerSpeeds[i].markers.Count > 0)
{
var last = CurrentCornerSpeeds[i].markers.Count - 1;
var diff = DateTime.UtcNow - CurrentCornerSpeeds[i].start_time;
time += diff;
if (CornersToCompare[i].markers.Count > last) {
if (CornersToCompare[i].markers.Count > (last + 1))
{
// interpolate the current distance to a time for comparison lap
//var dist = Convert.ToDouble(PluginManager.GetPropertyValue("DataCorePlugin.GameRawData.Telemetry.LapDist"));
var index_f = (CurrentCornerSpeeds[i].curr_dist / CurrentCornerSpeeds[i].distance_per_marker) % 1.0;
//var index_f = ((dist - CurrentCornerSpeeds[i].start) / CurrentCornerSpeeds[i].distance_per_marker) % 1.0;
var comp_curr = CornersToCompare[i].markers[last];
var comp_next = CornersToCompare[i].markers[last + 1];
var add = (comp_curr.TotalSeconds * (1.0 - index_f)) + (comp_next.TotalSeconds * index_f);
comp_time = TimeSpan.FromSeconds(comp_time.TotalSeconds + add);
}
else
{
comp_time += CornersToCompare[i].markers[last];
}
}
break;
}
else
{
if (Settings.WholeLapDelta == 0) {
time += CurrentCornerSpeeds[i].Duration;
comp_time += CornersToCompare[i]?.Duration ?? TimeSpan.Zero;
}
}
}
return (time - comp_time).TotalSeconds;
} }
// half-second average?
private double[] liveDelta5Storage = new double[30];
private int liveDelta5StorageIndex = 0;
public double LiveDelta5 { get
{
liveDelta5Storage[liveDelta5StorageIndex] = LiveDelta;
liveDelta5StorageIndex = (liveDelta5StorageIndex + 1) % 30;
double sum = 0.0;
for (int i = 0; i < 30; i++)
sum += liveDelta5Storage[i];
return sum / 30.0;
} }
private double lastLiveDelta5 = 0.0;
private DateTime lastLiveDelta5Timestamp = DateTime.UtcNow;
public double DLiveDelta5 { get
{
var now = DateTime.UtcNow;
var d = (LiveDelta5 - lastLiveDelta5) / (now - lastLiveDelta5Timestamp).TotalSeconds;
lastLiveDelta5 = LiveDelta5;
lastLiveDelta5Timestamp = now;
return d; // / 10.0;
} }
private double[] dLiveDelta5Storage = new double[30];
private int dLiveDelta5StorageIndex = 0;
public double D5LiveDelta5 { get
{
dLiveDelta5Storage[dLiveDelta5StorageIndex] = DLiveDelta5;
dLiveDelta5StorageIndex = (dLiveDelta5StorageIndex + 1) % 30;
double sum = 0.0;
for (int i = 0; i < 30; i++)
sum += dLiveDelta5Storage[i];
return sum / 30.0;
} }
[AlsoNotifyFor("OptimalCornerSpeedsLap")]
public CornerSpeedsStorage BestCarCornerSpeeds { get; set; }
//public CornerSpeedsStorage BestCarClassCornerSpeeds;
[AlsoNotifyFor("OptimalCornerSpeedsLap")]
public ObservableCollection<Corner> BestSessionCornerSpeeds;
public ObservableCollection<Corner> CurrentCornerSpeeds;
//[AlsoNotifyFor("OptimalCornerSpeedsLap")]
//public ComparisonMode Mode {
// get => Settings.Mode;
// set {
// //var oldCorners = CornersToCompare;
// Settings?.Mode = value;
// //var new_attempts = new List<CornerViewModel>();
// for (int i = 0; i < CornerAttempts.Count; i++)
// {
// //var turn_index = CornerAttempts[i].TurnIndex;
// //CornerAttempts[i] = new CornerViewModel(CornerAttempts[i], oldCorners[turn_index], CornersToCompare[turn_index]);
// CornerAttempts[i].Mode = value;
// //CornerAttempts[i].UpdateComparison(CornersToCompare[turn_index]);
// //new_attempts.Add(new CornerViewModel(CurrentCornerSpeeds[turn_index], CornersToCompare[turn_index]));
// }
// //CornerAttempts.Clear();
// //CornerAttempts.AddAll(new_attempts);
// }
//}
public ObservableCollection<Corner> CornersToCompare { get
{
switch (Settings.Mode)
{
case ComparisonMode.CompareToComparisonLap:
if (ComparisonLapSectors.Count > 0)
return ComparisonLapCorners;
goto default;
default:
case ComparisonMode.CompareToBestCarLap: return BestCarCornerSpeeds?[TrackId] ?? new ObservableCollection<Corner>();
case ComparisonMode.CompareToBestSessionCarLap: return BestSessionCornerSpeeds;
}
}
}
public ObservableCollection<CornerViewModel> CornerAttempts = new ObservableCollection<CornerViewModel>();
public List<List<TimeSpan>> SectorTimes;
public List<TimeSpan> SectorTimesBest;
public List<TimeSpan> LapTimes;
public List<int> LapNumbers;
public int NumberOfSectors = 10;
public int CurrentSector = -1;
public string CarId;
public string TrackId { get; set; }
public List<Sector> ComparisonLapSectors = [];
public ObservableCollection<Corner> ComparisonLapCorners;
public bool GamePaused = false;
public iRacingTurnNumbers TurnNumbers = new();
public void UpdateTurnNumbers(string trackId)
{
var file = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"iracing-turn-numbers",
trackId + ".json"
);
if (File.Exists(file))
{
using (StreamReader r = new StreamReader(file))
{
string json = r.ReadToEnd();
TurnNumbers = JsonConvert.DeserializeObject<iRacingTurnNumbers>(json);
return;
}
}
else
{
using (StreamWriter w = new StreamWriter(file))
{
TurnNumbers = new iRacingTurnNumbers();
string json = JsonConvert.SerializeObject(TurnNumbers);
w.Write(json);
return;
}
}
}
public TimeSpan OptimalCornerSpeedsLap {
get {
var sum = TimeSpan.Zero;
foreach (TimeSpan value in CornersToCompare.Select(o => o?.Duration ?? TimeSpan.Zero)) {
sum += value;
}
return sum;
}
}
/// <summary>
/// Called one time per game data update, contains all normalized game data,
/// raw data are intentionally "hidden" under a generic object type (A plugin SHOULD NOT USE IT)
///
/// This method is on the critical path, it must execute as fast as possible and avoid throwing any error
///
/// </summary>
/// <param name="pluginManager"></param>
/// <param name="data">Current game data, including current and previous data frame.</param>
public void DataUpdate(PluginManager pluginManager, ref GameData data)
{
//PluginManager.GetPropertyValue("{prop}");
// Define the value of our property (declared in init)
if (data.GameRunning)
{
if (data.OldData != null && data.NewData != null && false)
{
var timeValid = true;
//if (data.OldData.LapInvalidated || data.NewData.LapInvalidated)
//timeValid = false;
if (data.NewData.Rpms < 300)
timeValid = false;
//if (GamePaused)
//timeValid = false;
if (Math.Abs(data.NewData.TrackPositionMeters - data.OldData.TrackPositionMeters) > 100 && data.NewData.CurrentLap == CurrentLap)
timeValid = false;
if (data.NewData.IsInPit > 0 || data.NewData.IsInPitLane > 0)
timeValid = false;
if (CarId != data.NewData.CarId)
{
CarId = data.NewData.CarId;
BestCarCornerSpeeds = this.ReadCommonSettings(CarId, () => new CornerSpeedsStorage());
}
if (TrackId != data.NewData.TrackId)
{
TrackId = data.NewData.TrackId;
Settings.UpdateAvailableLapFiles(TrackId);
UpdateTurnNumbers(TrackId);
if (!BestCarCornerSpeeds.ContainsKey(TrackId) && TurnNumbers.turns.Count > 0)
{
BestCarCornerSpeeds[TrackId] = new ObservableCollection<Corner>(TurnNumbers.turns.Select((o, i) => new Corner(o, i)));
}
if (ComparisonLapSectors.Count > 0 && TurnNumbers.turns.Count > 0)
{
ComparisonLapCorners = GetCornersFromComparisonLapSectors();
}
if (TurnNumbers.turns.Count > 0)
{
CurrentCornerSpeeds = new ObservableCollection<Corner>(TurnNumbers.turns.Select((o, i) => new Corner(o, i)));
BestSessionCornerSpeeds = new ObservableCollection<Corner>(TurnNumbers.turns.Select((o, i) => new Corner(o, i)));
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("OptimalCornerSpeedsLap"));
}
// look at DataCorePlugin.GameRawData.Telemetry.TrackWetness too
// mabye DataCorePlugin.GameRawData.Telemetry.TrackTemp as well
if (data.NewData.SectorsCount != NumberOfSectors)
{
NumberOfSectors = (int)data.NewData.SectorsCount;
//for (int i = 0; i < NumberOfLaps; i++) {
//SectorTimes[i] = new List<TimeSpan>(NumberOfSectors);
//}
}
if (CurrentSector != (data.NewData.CurrentSectorIndex - 1))
{
if (CurrentSector != -1) {
if (SectorTimes[CurrentLap % NumberOfLaps][CurrentSector] < SectorTimesBest[CurrentSector])
{
SectorTimesBest[CurrentSector] = SectorTimes[CurrentLap % NumberOfLaps][CurrentSector];
}
}
CurrentSector = (data.NewData.CurrentSectorIndex - 1);
}
TimeSpan sectorsSum = TimeSpan.Zero;
for (int i = 0; i < CurrentSector; i++)
{
sectorsSum += SectorTimes[CurrentLap % NumberOfLaps][i];
}
//var lapChanged = false;
if (data.NewData.CurrentLap != CurrentLap)
{
//lapChanged = true;
//LapTimes[CurrentLap % NumberOfLaps] = data.NewData.CurrentLapTime;
//LapTimes[CurrentLap % NumberOfLaps] = data.NewData.LastLapTime;
LapNumbers[CurrentLap % NumberOfLaps] = CurrentLap;
CurrentLap = data.NewData.CurrentLap;
for (int sector_i = 0; sector_i < NumberOfSectors; sector_i++) {
SectorTimes[CurrentLap % NumberOfLaps][sector_i] = new TimeSpan();
}
foreach (var corner in CurrentCornerSpeeds.Where(o => o.Active))
{
if (corner.end > corner.start)
{
corner.Valid = false;
}
}
}
LapTimes[CurrentLap % NumberOfLaps] = data.NewData.CurrentLapTime;
SectorTimes[CurrentLap % NumberOfLaps][CurrentSector] = data.NewData.CurrentLapTime - sectorsSum;
//foreach (var corner in CurrentCornerSpeeds.Where(o => !o.Active))
for (int i = 0; i < CurrentCornerSpeeds.Count; i++)
{
var corner = CurrentCornerSpeeds[i];
if (corner.Active || !timeValid)
continue;
if ((corner.end > corner.start && data.NewData.TrackPositionMeters >= corner.start && data.NewData.TrackPositionMeters < corner.end) ||
(corner.end < corner.start && data.NewData.TrackPositionMeters >= corner.start))
{
CurrentCornerSpeeds[i] = corner.Copy();
corner = CurrentCornerSpeeds[i];
corner.Start();
if ((corner.end > corner.start && (
data.OldData.TrackPositionMeters >= corner.start &&
data.OldData.TrackPositionMeters < corner.end
)
) ||
(corner.end < corner.start && (
data.OldData.TrackPositionMeters >= corner.start
)
))
corner.Valid = false;
if (!timeValid)
corner.Valid = false;
pluginManager.UIUpdateDispatcher.Dispatcher.Invoke(() => {
if (CornerAttempts.Count > 1)
CornerAttempts[1].Latest = false;
CornerAttempts.Insert(0, new CornerViewModel(corner, Settings.Mode, new Dictionary<ComparisonMode, Corner> {
[ComparisonMode.CompareToBestCarLap] = BestCarCornerSpeeds[TrackId][corner.Index].Copy(),
[ComparisonMode.CompareToBestSessionCarLap] = BestSessionCornerSpeeds[corner.Index].Copy(),
[ComparisonMode.CompareToComparisonLap] = ComparisonLapCorners?[corner.Index].Copy() ?? null
}));
// show last corner to last lap's same corner
while (CornerAttempts.Count > (TurnNumbers.turns.Count + 1))
{
CornerAttempts.RemoveAt(CornerAttempts.Count - 1);
}
});
}
}
for (int i = 0; i < CurrentCornerSpeeds.Count; i++)
//foreach (var corner in CurrentCornerSpeeds.Where(o => o.Active))
{
var corner = CurrentCornerSpeeds[i];
if (!corner.Active)
continue;
if (!timeValid) {
corner.Valid = false;
corner.End();
continue;
}
if ((corner.end > corner.start && data.NewData.TrackPositionMeters >= corner.end) ||
(corner.end < corner.start && data.NewData.TrackPositionMeters < corner.start && data.NewData.TrackPositionMeters >= corner.end))
{
if ((corner.end > corner.start && data.OldData.TrackPositionMeters >= corner.end) ||
(corner.end < corner.start && data.OldData.TrackPositionMeters < corner.start && data.OldData.TrackPositionMeters >= corner.end))
corner.Valid = false;
if (!timeValid)
corner.Valid = false;
corner.End();
if (corner.Valid) {
if (!BestSessionCornerSpeeds[corner.Index].init || BestSessionCornerSpeeds[corner.Index].Duration > corner.Duration)
{
BestSessionCornerSpeeds[corner.Index] = corner.Copy();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("OptimalCornerSpeedsLap"));
}
if (!BestCarCornerSpeeds[TrackId][corner.Index].init || BestCarCornerSpeeds[TrackId][corner.Index].Duration > corner.Duration)
{
BestCarCornerSpeeds[TrackId][corner.Index] = corner.Copy();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("OptimalCornerSpeedsLap"));
pluginManager.UIUpdateDispatcher.Dispatcher.Invoke(() => {
this.SaveCommonSettings(CarId, BestCarCornerSpeeds);
});
this.TriggerEvent("NewBestCornerTime");
}
}
}
}
//var update = false;
for (int i = 0; i < CurrentCornerSpeeds.Count; i++)
//foreach (var corner in CurrentCornerSpeeds.Where(o => o.Active))
{
//pluginManager.UIUpdateDispatcher.Dispatcher.Invoke(() => {
if (CurrentCornerSpeeds[i].Active) {
CurrentCornerSpeeds[i].Update(data);
//update = true;
}
//});
}
//if (update) {
// PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LiveDelta"));
// PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LiveDelta5"));
//}
}
}
}
/// <summary>
/// Called at plugin manager stop, close/dispose anything needed here !
/// Plugins are rebuilt at game change
/// </summary>
/// <param name="pluginManager"></param>
public void End(PluginManager pluginManager)
{
// Save settings
this.SaveCommonSettings("GeneralSettings", Settings);
}
/// <summary>
/// Returns the settings control, return null if no settings control is required
/// </summary>
/// <param name="pluginManager"></param>
/// <returns></returns>
public System.Windows.Controls.Control GetWPFSettingsControl(PluginManager pluginManager)
{
return new SettingsControlDemo(this);
}
public void LoadLapFile()
{
if (!File.Exists(Settings.LapFile)) {
ComparisonLapSectors.Clear();
return;
}
using (FileStream fs = File.OpenRead(Settings.LapFile))
{
using (BinaryReader reader = new BinaryReader(fs))
{
var header = reader.ReadBytes(1468);
var num_sectors = reader.ReadInt32();
for (int i = 0; i < num_sectors; i++)
{
ComparisonLapSectors.Add(new Sector {
start = reader.ReadSingle(),
end = reader.ReadSingle(),
num_markers = reader.ReadUInt32(),
distance_per_marker = reader.ReadSingle(),
sector_start_info = reader.ReadSingle(),
sector_end_info = reader.ReadSingle(),
time = reader.ReadSingle(),
flags = reader.ReadUInt32(),
Markers = new List<Marker>()
});
}
for (int i = 0; i < num_sectors; i++)
{
for (int j = 0; j < ComparisonLapSectors[i].num_markers; j++)
{
ComparisonLapSectors[i].Markers.Add(new Marker
{
sector_time = reader.ReadSingle(),
timing_line_position = reader.ReadSingle(),
YawNorth = reader.ReadSingle(),
Pitch = reader.ReadSingle(),
Roll = reader.ReadSingle(),
flags = reader.ReadUInt32(),
Throttle = reader.ReadByte(),
Brake = reader.ReadByte(),
Clutch = reader.ReadByte(),
Gear = reader.ReadByte()
});
}
}
if (ComparisonLapSectors.Count > 0 && TurnNumbers.turns.Count > 0)
{
ComparisonLapCorners = GetCornersFromComparisonLapSectors();
}
}
}
}
public ObservableCollection<Corner> GetCornersFromComparisonLapSectors()
{
double total_sector_time_s = 0.0;