Repository navigation
Expand file tree
/
Copy pathFH6SmartShift.cs
More file actions
3679 lines (3288 loc) · 174 KB
/
Copy pathFH6SmartShift.cs
File metadata and controls
3679 lines (3288 loc) · 174 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 System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using GameReaderCommon;
using Newtonsoft.Json;
using SimHub.Plugins;
namespace FH6SmartShift
{
[PluginName("FH6SmartShift")]
[PluginDescription("The Architect's Masterpiece - v1.1.1 (FH6 & Forza Motorsport Virtual Dyno, 100% Map Gate, Dragy & Tuning Advisor)")]
[PluginAuthor("mtowarek01")]
public class FH6SmartShift : IPlugin, IDataPlugin, IWPFSettings
{
private const string StoreKey = "fh6SmartShiftingData";
private const double DownshiftCooldownSeconds = 0.45;
private const double UpshiftCooldownSeconds = 0.25;
private const double RatioLearnShiftSettleSeconds = 0.35;
private const double ClutchSettleSeconds = 0.15;
private const double SaveIntervalSeconds = 15.0;
private const double MathEvalIntervalSeconds = 0.15;
private const double SafeLandingRpmMultiplier = 0.93;
private const double MaxAllowedDownshiftMultiplier = 0.88;
private const double LearnWotThreshold = 240.0;
private const double RatioLearnAccelThreshold = 25.0;
private const double LightWotThreshold = 225.0;
private const double LiftThreshold = 205.0;
private const double BrakeDeadzone = 5.0;
private const double SlipRatioThreshold = 0.20;
private const double SlipAngleThreshold = 0.25;
private const double SusTravelReboundThreshold = 0.08;
private readonly object _lock = new object();
private static readonly HashSet<string> _missingProps = new HashSet<string>();
private static readonly string[] LabelsPeak = { "0: (-)", "1: (P)", "2: (P)", "3: (P)", "4: (P)", "5: (P)", "6: (P)", "7: (P)", "8: (P)", "9: (P)", "10: (P)" };
private static readonly string[] LabelsLimitConfirmed = { "0: (-)", "1: (L)", "2: (L)", "3: (L)", "4: (L)", "5: (L)", "6: (L)", "7: (L)", "8: (L)", "9: (L)", "10: (L)" };
private static readonly string[] LabelsLearn = { "0: (-)", "1: (P?)", "2: (P?)", "3: (P?)", "4: (P?)", "5: (P?)", "6: (P?)", "7: (P?)", "8: (P?)", "9: (P?)", "10: (P?)" };
private static readonly string[] LabelsLimit = { "0: (-)", "1: (L?)", "2: (L?)", "3: (L?)", "4: (L?)", "5: (L?)", "6: (L?)", "7: (L?)", "8: (L?)", "9: (L?)", "10: (L?)" };
private static readonly string[] LabelsRatio = { "0: (-)", "1: (R)", "2: (R)", "3: (R)", "4: (R)", "5: (R)", "6: (R)", "7: (R)", "8: (R)", "9: (R)", "10: (R)" };
private static readonly string[] LabelsZero = { "0: (-)", "1: (-)", "2: (-)", "3: (-)", "4: (-)", "5: (-)", "6: (-)", "7: (-)", "8: (-)", "9: (-)", "10: (-)" };
private enum Drivetrain { FWD = 0, RWD = 1, AWD = 2 }
private readonly double[] _ratioScratch = new double[25];
private readonly double[] _precomputedPower = new double[401];
class GlobalEngineProfile
{
public double[] PowerMap = new double[401];
public double[] TorqueMap = new double[401];
public double[] BoostMap = new double[401];
public double MaxPower = 0;
public double RpmAtMaxPower = 0;
public double MaxTorque = 0;
public double RpmAtMaxTorque = 0;
public double MaxBoost = 0;
public double GhostLimiterRpm = 0;
public double GhostLimiterCandidateRpm = 0;
public double GhostLimiterCandidateTime = 0;
public int GhostLimiterHits = 0;
public int[] BandSamples = new int[401];
public int MinMappedBand = 400;
public int MaxMappedBand = 0;
public double MappingProgress = 0;
public double Best0To100 = 0;
public double Best100To200 = 0;
public double Best0To200 = 0;
}
class GearState
{
public double ShiftTriggerRpm = 0;
public bool PowerPeakCaught = false;
public bool IsConfirmed = false;
public bool IsMathOptimal = false;
public bool TriggerIsEdge = false;
public bool TriggerIsGhost = false;
public double RpmPerRadS = 0;
public double SavedRpmPerRadS = 0;
public double GhostLimiterAccumulator = 0;
public double GhostLimiterBreakAccumulator = 0;
public double[] RatioHistory = new double[25];
public int RatioHistoryIdx = 0;
public int RatioSamples = 0;
public int RatioMismatchCount = 0;
}
private Dictionary<int, GearState> _gearStates = new Dictionary<int, GearState>();
private GlobalEngineProfile _globalEngine = new GlobalEngineProfile();
private Dictionary<string, string> _externalCarList = new Dictionary<string, string>();
private DateTime _lastCarListWriteTime = DateTime.MinValue;
private double _lastCarListCheckTime = -100;
private int _resetCurrentRequested = 0;
private int _resetAllRequested = 0;
private int _resetLimitGearsRequested = 0;
private int _resetRatiosRequested = 0;
private int _resetDragyRequested = 0;
private int _toggleBeepRequested = 0;
private int _lastGear = 0;
private double _lastDownshiftTime = -100;
private double _lastUpshiftTime = -100;
private double _lastDecoupledTime = -100;
private double _lastSaveTime = -100;
private double _lastMathEvalTime = -100;
private double _lastMapScanTime = -100;
private double _frameDt = 0.016;
private double _lastRpmChangeTime = 0;
private double _lastRpmForAccel = 0;
private double _currentRpmAccel = 0;
private double _peakRpmBeforeCut = 0;
private double _smoothedLiveBuffer = 50.0;
private int _cleanWotFrames = 0;
private int _lastLearnedBand = -1;
private double _lastLearnedPower = 0;
private double _lastLearnedTorque = 0;
private double _lastLearnedTime = -100;
private double _lastSusTravelRL = 0;
private double _lastSusTravelRR = 0;
private double _lastSpeedKmhForTrend = 0;
private double _speedTrendKmhPerS = 0;
private bool _climbDownshiftActive = false;
private double _staticChassisDiveBase = 0.0;
private bool _isChassisBaseInitialized = false;
private double _smoothedSlideLevel = 0.0;
private double _prevSmoothedSlideLevel = 0.0;
private double _smoothedSlideTrend = 0.0;
private double _prevSpeedKmhDragy = 0.0;
private double _prevTimeDragy = 0.0;
private bool _dragyArmedFromStop = false;
private bool _dragyRunningFromStop = false;
private bool _dragyPassed100FromStop = false;
private double _dragyStart0Time = 0.0;
private bool _dragyRunning100To200 = false;
private double _dragyStart100Time = 0.0;
private double _lastBeepTime = -100.0;
private int _beepInFlight = 0;
private Stopwatch _appTime = new Stopwatch();
private Stopwatch _dtStopwatch = new Stopwatch();
private bool _shiftLightActive = false;
private double _smoothedLedProximity = 0.0;
private int _currentLedStage = 0;
private bool _lastDownshiftSuggested = false;
private bool _isDataDirty = false;
private bool _mathNeedsEval = false;
private int _saveInFlight = 0;
public PluginManager PluginManager { get; set; }
private CarStore _store;
private CarStore _snapshotStore;
private string _key = "";
private int _lastCarOrdinal = -1;
private int _lastCarPI = -1;
private int _lastCarDrivetrain = -1;
private int _lastCarEngineMaxRpmRounded = -1;
class Outputs
{
public string ActiveGameMode = "FH6";
public string CarKey = "";
public string CarName = "Unknown Car";
public bool IsShiftBeepEnabled = false;
public bool IsTractionGood = true;
public bool IsDownshiftSafe = false;
public bool IsDownshiftSuggested = false;
public bool IsLearningComplete = false;
public bool AeroBottomingWarning = false;
public bool PowerOversteerWarning = false;
public double OversteerSeverity = 0.0;
public bool IsCounterSteering = false;
public double CounterSteerSeverity = 0.0;
public double SlideSeverity = 0.0;
public double SlideTrend = 0.0;
public bool IsSlideDeepening = false;
public bool IsSlideRecovering = false;
public string SlideStateText = "GRIP";
public string SlideBarColor = "#FF9900";
public bool IsTopGear = false;
public bool IsGripLost = false;
public double BodySlipAngle = 0;
public double MaxUsableRpm = 0;
public double RevLimiterProximity = 0;
public int LedActiveCount = 0;
public bool ShiftLightFlash = false;
public double ShiftTriggerRpm = 0;
public double RpmAtMaxPower = 0;
public double RpmAtMaxTorque = 0;
public double DownshiftTriggerRpm = 0;
public double OptimalShiftRpm = 0;
public double LiveMappingProgress = 0;
public double DragyLast0To100 = 0.0;
public double DragyBest0To100 = 0.0;
public double DragyLast100To200 = 0.0;
public double DragyBest100To200 = 0.0;
public double DragyLast0To200 = 0.0;
public double DragyBest0To200 = 0.0;
public string DragyStatus = "READY";
public double DbgSteerRaw = 0;
public double DbgYawRaw = 0;
public double DbgChassisDive = 0.0;
public string EngineMapStatus = "LEARN";
public string MapCoverageBar = "[░░░░░░░░░░░░░░░░░░░░]";
public string CurrentGearStatusText = "-";
public string CurrentGearColor = "#00000000";
public string[] GearText = new string[11];
public string[] GearColor = new string[11];
public Outputs()
{
for(int i = 0; i <= 10; i++) { GearText[i] = LabelsZero[i]; GearColor[i] = "#E74C3C"; }
}
}
private Outputs _out = new Outputs();
private static string GetCommonDataDir()
{
string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PluginsData", "Common");
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
return dir;
}
private static string GetReportFilePath()
{
return Path.Combine(GetCommonDataDir(), "FH6SmartShift_GarageReport.html");
}
private static string GetCarListFilePath()
{
return Path.Combine(GetCommonDataDir(), "FH6SmartShift_CarList.json");
}
private void EnsureAndLoadCarList()
{
try
{
string path = GetCarListFilePath();
if (!File.Exists(path))
{
var starterMap = new Dictionary<string, string>();
File.WriteAllText(path, JsonConvert.SerializeObject(starterMap, Formatting.Indented), Encoding.UTF8);
}
var info = new FileInfo(path);
if (info.LastWriteTimeUtc != _lastCarListWriteTime)
{
string json = File.ReadAllText(path, Encoding.UTF8);
var loaded = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
if (loaded != null)
{
lock (_lock)
{
_externalCarList = loaded;
foreach (var kvp in loaded)
{
_store.CarNames[kvp.Key] = kvp.Value;
_snapshotStore.CarNames[kvp.Key] = kvp.Value;
}
}
}
_lastCarListWriteTime = info.LastWriteTimeUtc;
}
}
catch (Exception ex)
{
Debug.WriteLine("[FH6SmartShift] CarList load error: " + ex.Message);
}
}
private string ResolveCarName(int ordinal, string fullKey)
{
if (!string.IsNullOrEmpty(fullKey) && _store.CarNames.TryGetValue(fullKey, out string exactName) && !string.IsNullOrWhiteSpace(exactName))
return exactName;
string ordKey = ordinal.ToString();
if (_store.CarNames.TryGetValue(ordKey, out string ordName) && !string.IsNullOrWhiteSpace(ordName))
return ordName;
if (!string.IsNullOrEmpty(fullKey) && _externalCarList.TryGetValue(fullKey, out string extExact) && !string.IsNullOrWhiteSpace(extExact))
return extExact;
if (_externalCarList.TryGetValue(ordKey, out string extOrd) && !string.IsNullOrWhiteSpace(extOrd))
return extOrd;
return $"Car #{ordinal}";
}
private void TriggerShiftBeepSound(double now)
{
if (!_store.ShiftBeepEnabled) return;
if (now - _lastBeepTime < 0.40) return;
_lastBeepTime = now;
if (Interlocked.CompareExchange(ref _beepInFlight, 1, 0) == 0)
{
Task.Run(() =>
{
try
{
Console.Beep(2650, 60);
}
catch
{
}
finally
{
Interlocked.Exchange(ref _beepInFlight, 0);
}
});
}
}
public Control GetWPFSettingsControl(PluginManager pluginManager)
{
var bgDark = new SolidColorBrush(Color.FromRgb(13, 17, 23));
var cardBg = new SolidColorBrush(Color.FromRgb(22, 27, 34));
var borderBrush = new SolidColorBrush(Color.FromRgb(48, 54, 61));
var textWhite = new SolidColorBrush(Color.FromRgb(230, 237, 243));
var textMuted = new SolidColorBrush(Color.FromRgb(139, 148, 158));
var accentGreen = new SolidColorBrush(Color.FromRgb(35, 134, 54));
var accentBlue = new SolidColorBrush(Color.FromRgb(31, 111, 235));
var accentRed = new SolidColorBrush(Color.FromRgb(207, 34, 46));
var rootScroll = new ScrollViewer
{
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
Background = bgDark
};
var mainStack = new StackPanel
{
Margin = new Thickness(24),
MaxWidth = 920,
HorizontalAlignment = HorizontalAlignment.Left
};
var titleBlock = new TextBlock
{
Text = "🏎️ FH6SmartShift v1.1.1 — FH6 & Forza Motorsport Control Center",
FontSize = 20,
FontWeight = FontWeights.Bold,
Foreground = textWhite,
Margin = new Thickness(0, 0, 0, 6)
};
var subTitleBlock = new TextBlock
{
Text = "Real-time 401-Band Virtual Dyno (100% Map Gate), 12-LED Shift Engine, Dragy Timer & Gearbox Tuning Advisor.",
FontSize = 13,
Foreground = textMuted,
Margin = new Thickness(0, 0, 0, 18)
};
mainStack.Children.Add(titleBlock);
mainStack.Children.Add(subTitleBlock);
var statusBorder = new Border
{
Background = cardBg,
BorderBrush = borderBrush,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(18),
Margin = new Thickness(0, 0, 0, 16)
};
var statusStack = new StackPanel();
var liveHeader = new TextBlock
{
Text = "📡 LIVE VEHICLE & TELEMETRY STATUS (AUTO-DETECTS FH6 / FORZA MOTORSPORT)",
FontSize = 12,
FontWeight = FontWeights.Bold,
Foreground = accentBlue,
Margin = new Thickness(0, 0, 0, 8)
};
var liveCarText = new TextBlock
{
Text = "Active Car: Waiting for Forza UDP telemetry...",
FontSize = 15,
FontWeight = FontWeights.SemiBold,
Foreground = textWhite,
Margin = new Thickness(0, 0, 0, 4)
};
var liveDynoText = new TextBlock
{
Text = "Dyno Mapping: 0% (LEARN) | Peak Power: — | Optimal Shift Target: —",
FontSize = 13.5,
Foreground = textMuted,
Margin = new Thickness(0, 0, 0, 4)
};
var liveDragyText = new TextBlock
{
Text = "Dragy Records — 0-100 km/h: — | 100-200 km/h: — | 0-200 km/h: —",
FontSize = 13.5,
Foreground = new SolidColorBrush(Color.FromRgb(63, 185, 80))
};
statusStack.Children.Add(liveHeader);
statusStack.Children.Add(liveCarText);
statusStack.Children.Add(liveDynoText);
statusStack.Children.Add(liveDragyText);
statusBorder.Child = statusStack;
mainStack.Children.Add(statusBorder);
var settingsBorder = new Border
{
Background = cardBg,
BorderBrush = borderBrush,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(18),
Margin = new Thickness(0, 0, 0, 16)
};
var settingsStack = new StackPanel();
settingsStack.Children.Add(new TextBlock
{
Text = "⚙️ SHIFT LIGHT & AUDIO CONFIGURATION",
FontSize = 12,
FontWeight = FontWeights.Bold,
Foreground = accentBlue,
Margin = new Thickness(0, 0, 0, 12)
});
var beepCheck = new CheckBox
{
Content = "🔊 Enable F1 / GT3 Audio Shift Beep (2650 Hz tone when all 12 LEDs lock at ShiftLightFlash)",
IsChecked = _store.ShiftBeepEnabled,
Foreground = textWhite,
FontSize = 13.5,
Margin = new Thickness(0, 0, 0, 14)
};
beepCheck.Checked += (s, e) => { lock (_lock) { _store.ShiftBeepEnabled = true; _out.IsShiftBeepEnabled = true; _isDataDirty = true; } TriggerAsyncSave(); };
beepCheck.Unchecked += (s, e) => { lock (_lock) { _store.ShiftBeepEnabled = false; _out.IsShiftBeepEnabled = false; _isDataDirty = true; } TriggerAsyncSave(); };
settingsStack.Children.Add(beepCheck);
double initialBuffer = _store.ReactionBufferFactor > 0.05 ? _store.ReactionBufferFactor : 0.25;
var sliderLabel = new TextBlock
{
Text = $"⚡ Driver Reaction-Time Lead Buffer: {initialBuffer:0.00} s (Scales dynamic RPM lead in lower gears)",
Foreground = textWhite,
FontSize = 13.5,
Margin = new Thickness(0, 0, 0, 6)
};
var bufferSlider = new Slider
{
Minimum = 0.10,
Maximum = 0.40,
Value = initialBuffer,
TickFrequency = 0.01,
IsSnapToTickEnabled = true,
Margin = new Thickness(0, 0, 0, 4)
};
bufferSlider.ValueChanged += (s, e) =>
{
double val = Math.Round(bufferSlider.Value, 2);
sliderLabel.Text = $"⚡ Driver Reaction-Time Lead Buffer: {val:0.00} s (Scales dynamic RPM lead in lower gears)";
lock (_lock)
{
_store.ReactionBufferFactor = val;
_snapshotStore.ReactionBufferFactor = val;
_isDataDirty = true;
}
};
settingsStack.Children.Add(sliderLabel);
settingsStack.Children.Add(bufferSlider);
settingsBorder.Child = settingsStack;
mainStack.Children.Add(settingsBorder);
var actionsBorder = new Border
{
Background = cardBg,
BorderBrush = borderBrush,
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(18)
};
var actionsStack = new StackPanel();
actionsStack.Children.Add(new TextBlock
{
Text = "🛠️ GARAGE INSPECTOR & MEMORY ACTIONS",
FontSize = 12,
FontWeight = FontWeights.Bold,
Foreground = accentBlue,
Margin = new Thickness(0, 0, 0, 12)
});
var wrapButtons = new WrapPanel { Orientation = Orientation.Horizontal };
Button MakeButton(string label, Brush bg, Action onClick)
{
var btn = new Button
{
Content = label,
Background = bg,
Foreground = Brushes.White,
FontWeight = FontWeights.SemiBold,
FontSize = 13,
Padding = new Thickness(14, 8, 14, 8),
Margin = new Thickness(0, 0, 10, 10),
BorderThickness = new Thickness(0),
Cursor = System.Windows.Input.Cursors.Hand
};
btn.Click += (s, e) => onClick();
return btn;
}
wrapButtons.Children.Add(MakeButton("📊 Open Virtual Dyno & Tuning Report (HTML)", accentGreen, () => OpenGarageReportInBrowser()));
wrapButtons.Children.Add(MakeButton("📂 Open Common Data Folder (JSON / CarList)", accentBlue, () =>
{
try { Process.Start(new ProcessStartInfo { FileName = GetCommonDataDir(), UseShellExecute = true }); } catch { }
}));
wrapButtons.Children.Add(MakeButton("⚙️ Reset Current Car Gear Ratios (After Tuning)", new SolidColorBrush(Color.FromRgb(56, 63, 71)), () => Interlocked.Exchange(ref _resetRatiosRequested, 1)));
wrapButtons.Children.Add(MakeButton("⏱️ Reset Current Car Dragy Records", new SolidColorBrush(Color.FromRgb(56, 63, 71)), () => Interlocked.Exchange(ref _resetDragyRequested, 1)));
wrapButtons.Children.Add(MakeButton("🔄 Reset Current Car Full Memory", accentRed, () => Interlocked.Exchange(ref _resetCurrentRequested, 1)));
actionsStack.Children.Add(wrapButtons);
actionsBorder.Child = actionsStack;
mainStack.Children.Add(actionsBorder);
var uiTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
uiTimer.Tick += (s, e) =>
{
if (!mainStack.IsVisible) return;
lock (_lock)
{
if (string.IsNullOrEmpty(_out.CarKey))
{
liveCarText.Text = $"Active Car ({_out.ActiveGameMode}): Waiting for on-track telemetry...";
liveDynoText.Text = $"Saved Cars in Database: {_store.EngineProfiles.Count} | Audio Shift Beep: {(_store.ShiftBeepEnabled ? "ON" : "OFF")}";
liveDragyText.Text = "Dragy Status: READY";
}
else
{
liveCarText.Text = $"Active Car [{_out.ActiveGameMode}]: {_out.CarName} ({_out.CarKey})";
double hp = _globalEngine.MaxPower / 745.7;
liveDynoText.Text = $"Dyno Mapping: {_out.LiveMappingProgress:0.0}% ({_out.EngineMapStatus}) | Peak Power: {hp:0.1} HP @ {_out.RpmAtMaxPower:0} RPM | Shift Target: {_out.OptimalShiftRpm:0} RPM";
string s0100 = _out.DragyBest0To100 > 0 ? $"{_out.DragyBest0To100:0.00} s" : "—";
string s100200 = _out.DragyBest100To200 > 0 ? $"{_out.DragyBest100To200:0.00} s" : "—";
string s0200 = _out.DragyBest0To200 > 0 ? $"{_out.DragyBest0To200:0.00} s" : "—";
liveDragyText.Text = $"Dragy PB — 0-100 km/h: {s0100} | 100-200 km/h: {s100200} | 0-200 km/h: {s0200} ({ _out.DragyStatus })";
}
if (beepCheck.IsChecked != _store.ShiftBeepEnabled)
beepCheck.IsChecked = _store.ShiftBeepEnabled;
}
};
uiTimer.Start();
rootScroll.Content = mainStack;
return rootScroll;
}
public void Init(PluginManager pluginManager)
{
try {
string dir = GetCommonDataDir();
string p = Path.Combine(dir, "FH6SmartShift_fh6SmartShiftingData.json");
if (File.Exists(p)) {
string todayBak = p + ".bak_" + DateTime.Now.ToString("yyyyMMdd");
if (!File.Exists(todayBak)) {
File.Copy(p, todayBak, true);
Debug.WriteLine($"[FH6SmartShift] Utworzono dzienna kopie zapasowa: {todayBak}");
}
var dirInfo = new DirectoryInfo(dir);
var baks = dirInfo.GetFiles("FH6SmartShift_fh6SmartShiftingData.json.bak_*");
if (baks.Length > 3) {
Array.Sort(baks, (a, b) => b.CreationTime.CompareTo(a.CreationTime));
for (int i = 3; i < baks.Length; i++) {
baks[i].Delete();
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"[FH6SmartShift] Blad krytyczny systemu backupu: {ex.Message}");
}
_store = this.ReadCommonSettings<CarStore>(StoreKey, () => new CarStore()) ?? new CarStore();
if (_store.CarNames == null) _store.CarNames = new Dictionary<string, string>();
if (_store.ReactionBufferFactor < 0.10 || _store.ReactionBufferFactor > 0.45) _store.ReactionBufferFactor = 0.25;
if (_store.SchemaVersion < 2) { _store.SchemaVersion = 2; this.SaveCommonSettings(StoreKey, _store); }
bool globalBoostCleaned = false;
foreach (var ep in _store.EngineProfiles.Values)
{
if (ep.BoostMap != null)
{
double maxB = 0;
for (int i = 0; i < ep.BoostMap.Length; i++)
{
if (ep.BoostMap[i] < 0)
{
ep.BoostMap[i] = 0;
globalBoostCleaned = true;
}
if (ep.BoostMap[i] > maxB) maxB = ep.BoostMap[i];
}
if (maxB > ep.MaxBoost) ep.MaxBoost = maxB;
}
}
if (globalBoostCleaned) _isDataDirty = true;
_snapshotStore = CloneCarStore(_store);
EnsureAndLoadCarList();
_out.IsShiftBeepEnabled = _store.ShiftBeepEnabled;
try { WriteHtmlGarageReport(_snapshotStore, ""); }
catch (Exception ex) { Debug.WriteLine("[FH6SmartShift] Initial HTML report error: " + ex.Message); }
_appTime.Start();
_dtStopwatch.Start();
pluginManager.AddAction("ResetPowerMemory", this.GetType(), (a, b) => Interlocked.Exchange(ref _resetCurrentRequested, 1));
pluginManager.AddAction("ResetAllCarsMemory", this.GetType(), (a, b) => Interlocked.Exchange(ref _resetAllRequested, 1));
pluginManager.AddAction("ResetLimitGears", this.GetType(), (a, b) => Interlocked.Exchange(ref _resetLimitGearsRequested, 1));
pluginManager.AddAction("ResetGearRatios", this.GetType(), (a, b) => Interlocked.Exchange(ref _resetRatiosRequested, 1));
pluginManager.AddAction("ResetDragyRecords", this.GetType(), (a, b) => Interlocked.Exchange(ref _resetDragyRequested, 1));
pluginManager.AddAction("ToggleShiftBeep", this.GetType(), (a, b) => Interlocked.Exchange(ref _toggleBeepRequested, 1));
pluginManager.AddAction("OpenDynoReport", this.GetType(), (a, b) => OpenGarageReportInBrowser());
this.AttachDelegate("ActiveGameMode", () => _out.ActiveGameMode);
this.AttachDelegate("MaxUsableRpm", () => _out.MaxUsableRpm);
this.AttachDelegate("RevLimiterProximity", () => _out.RevLimiterProximity);
this.AttachDelegate("LedActiveCount", () => _out.LedActiveCount);
this.AttachDelegate("ShiftLightFlash", () => _out.ShiftLightFlash);
this.AttachDelegate("IsShiftBeepEnabled", () => _out.IsShiftBeepEnabled);
this.AttachDelegate("CurrentCarKey", () => _out.CarKey);
this.AttachDelegate("CurrentCarName", () => _out.CarName);
this.AttachDelegate("IsLearningComplete", () => _out.IsLearningComplete);
this.AttachDelegate("ShiftTriggerRpm", () => _out.ShiftTriggerRpm);
this.AttachDelegate("RpmAtMaxPower", () => _out.RpmAtMaxPower);
this.AttachDelegate("RpmAtMaxTorque", () => _out.RpmAtMaxTorque);
this.AttachDelegate("DownshiftTriggerRpm", () => _out.DownshiftTriggerRpm);
this.AttachDelegate("OptimalShiftRpm", () => _out.OptimalShiftRpm);
this.AttachDelegate("IsDownshiftSafe", () => _out.IsDownshiftSafe);
this.AttachDelegate("IsDownshiftSuggested", () => _out.IsDownshiftSuggested);
this.AttachDelegate("IsTractionGood", () => _out.IsTractionGood);
this.AttachDelegate("BodySlipAngle", () => _out.BodySlipAngle);
this.AttachDelegate("AeroBottomingWarning", () => _out.AeroBottomingWarning);
this.AttachDelegate("PowerOversteerWarning", () => _out.PowerOversteerWarning);
this.AttachDelegate("OversteerSeverity", () => _out.OversteerSeverity);
this.AttachDelegate("IsCounterSteering", () => _out.IsCounterSteering);
this.AttachDelegate("CounterSteerSeverity", () => _out.CounterSteerSeverity);
this.AttachDelegate("SlideSeverity", () => _out.SlideSeverity);
this.AttachDelegate("SlideTrend", () => _out.SlideTrend);
this.AttachDelegate("IsSlideDeepening", () => _out.IsSlideDeepening);
this.AttachDelegate("IsSlideRecovering", () => _out.IsSlideRecovering);
this.AttachDelegate("SlideStateText", () => _out.SlideStateText);
this.AttachDelegate("SlideBarColor", () => _out.SlideBarColor);
this.AttachDelegate("IsTopGear", () => _out.IsTopGear);
this.AttachDelegate("IsGripLost", () => _out.IsGripLost);
this.AttachDelegate("LiveMappingProgress", () => _out.LiveMappingProgress);
this.AttachDelegate("EngineMapStatus", () => _out.EngineMapStatus);
this.AttachDelegate("MapCoverageBar", () => _out.MapCoverageBar);
this.AttachDelegate("CurrentGearStatusText", () => _out.CurrentGearStatusText);
this.AttachDelegate("CurrentGearColor", () => _out.CurrentGearColor);
this.AttachDelegate("Dragy_Last_0_100", () => _out.DragyLast0To100);
this.AttachDelegate("Dragy_Best_0_100", () => _out.DragyBest0To100);
this.AttachDelegate("Dragy_Last_100_200", () => _out.DragyLast100To200);
this.AttachDelegate("Dragy_Best_100_200", () => _out.DragyBest100To200);
this.AttachDelegate("Dragy_Last_0_200", () => _out.DragyLast0To200);
this.AttachDelegate("Dragy_Best_0_200", () => _out.DragyBest0To200);
this.AttachDelegate("Dragy_Status", () => _out.DragyStatus);
this.AttachDelegate("Dbg_SteerRaw", () => _out.DbgSteerRaw);
this.AttachDelegate("Dbg_YawRaw", () => _out.DbgYawRaw);
this.AttachDelegate("Dbg_ChassisDive", () => _out.DbgChassisDive);
this.AttachDelegate("Dbg_GhostLimiter", () => _globalEngine.GhostLimiterRpm);
this.AttachDelegate("Dbg_GhostCandidate", () => _globalEngine.GhostLimiterCandidateRpm);
this.AttachDelegate("Dbg_GhostHits", () => _globalEngine.GhostLimiterHits);
for (int i = 1; i <= 10; i++)
{
int gearIndex = i;
this.AttachDelegate($"Gear{gearIndex}Text", () => _out.GearText[gearIndex]);
this.AttachDelegate($"Gear{gearIndex}Color", () => _out.GearColor[gearIndex]);
}
}
public void End(PluginManager pluginManager)
{
Stopwatch sw = Stopwatch.StartNew();
while (Volatile.Read(ref _saveInFlight) == 1 && sw.ElapsedMilliseconds < 500) { Thread.Sleep(10); }
lock (_lock)
{
if (_isDataDirty)
{
if (!string.IsNullOrEmpty(_key))
{
SaveEngineProfileToStore();
UpdateSnapshotWithCurrentCar();
}
this.SaveCommonSettings(StoreKey, _snapshotStore);
try { WriteHtmlGarageReport(_snapshotStore, _key); }
catch (Exception ex) { Debug.WriteLine("[FH6SmartShift] End HTML report error: " + ex.Message); }
}
}
}
private void OpenGarageReportInBrowser()
{
Task.Run(() =>
{
try
{
EnsureAndLoadCarList();
CarStore snapshotCopy;
string activeKey;
lock (_lock)
{
if (!string.IsNullOrEmpty(_key))
{
SaveEngineProfileToStore();
UpdateSnapshotWithCurrentCar();
}
snapshotCopy = CloneCarStore(_snapshotStore);
activeKey = _key ?? "";
}
string reportPath = GetReportFilePath();
WriteHtmlGarageReport(snapshotCopy, activeKey);
Process.Start(new ProcessStartInfo
{
FileName = reportPath,
UseShellExecute = true
});
}
catch (Exception ex)
{
Debug.WriteLine("[FH6SmartShift] OpenDynoReport failed: " + ex.Message);
}
});
}
private static void WriteHtmlGarageReport(CarStore store, string activeCarKey)
{
string jsonPayload = JsonConvert.SerializeObject(store ?? new CarStore());
string safeActiveKey = JsonConvert.SerializeObject(activeCarKey ?? "");
string reportPath = GetReportFilePath();
string html = @"<!DOCTYPE html>
<html lang=""en"">
<head>
<meta charset=""UTF-8"">
<title>FH6SmartShift v1.1.1 — FH6 & Forza Motorsport Virtual Dyno, Dragy & Tuning Inspector</title>
<style>
* { box-sizing: border-box; }
body {
background: #0d1117;
color: #e6edf3;
font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, Arial, sans-serif;
margin: 0;
padding: 24px;
}
.container { max-width: 1240px; margin: 0 auto; }
.header {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 12px;
background: #161b22;
border: 1px solid #30363d;
border-radius: 10px;
padding: 16px 22px;
margin-bottom: 18px;
}
.header h1 { margin: 0; font-size: 19.5px; color: #fff; }
.controls { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.btn {
background: #21262d;
color: #e6edf3;
border: 1px solid #30363d;
padding: 8px 12px;
border-radius: 6px;
font-weight: 600;
cursor: pointer;
font-size: 12.5px;
transition: background 0.15s;
}
.btn:hover { background: #30363d; }
.btn-green { background: #238636; border-color: #2ea043; color: #fff; }
.btn-green:hover { background: #2ea043; }
.btn-blue { background: #1f6feb; border-color: #388bfd; color: #fff; }
.btn-blue:hover { background: #388bfd; }
input[type=""file""] { display: none; }
select {
background: #0d1117;
color: #e6edf3;
border: 1px solid #30363d;
padding: 8px 12px;
border-radius: 6px;
font-size: 13.5px;
font-weight: 600;
min-width: 320px;
}
.profile-banner {
background: #161b22;
border-left: 4px solid #2f81f7;
border-top: 1px solid #30363d;
border-right: 1px solid #30363d;
border-bottom: 1px solid #30363d;
border-radius: 8px;
padding: 16px 20px;
margin-bottom: 18px;
font-size: 15px;
line-height: 1.5;
}
.dragy-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 14px;
margin-bottom: 20px;
}
.dragy-card {
background: #161b22;
border: 1px solid #30363d;
border-radius: 8px;
padding: 14px 18px;
display: flex;
justify-content: space-between;
align-items: center;
}
.dragy-label { font-size: 12.5px; color: #8b949e; font-weight: 700; text-transform: uppercase; letter-spacing: 0.8px; }
.dragy-val { font-family: 'Consolas', monospace; font-size: 24px; font-weight: 700; color: #3fb950; }
.table-wrap {
background: #ffffff;
color: #1f2328;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 8px 24px rgba(0,0,0,0.4);
margin-bottom: 20px;
}
table { width: 100%; border-collapse: collapse; font-size: 14.5px; }
th {
background: #f6f8fa;
color: #1f2328;
font-weight: 600;
text-align: left;
padding: 10px 14px;
border: 1px solid #d0d7de;
}
td { padding: 9px 14px; border: 1px solid #d0d7de; }
tr:nth-child(even) td { background: #fcfcfd; }
.dot {
display: inline-block;
width: 14px;
height: 14px;
border-radius: 50%;
vertical-align: middle;
margin-right: 6px;
border: 1px solid rgba(0,0,0,0.35);
}
.dot-green { background: #2da44e; }
.dot-orange { background: #f39c12; }
.dot-yellow { background: #d4ac0d; }
.dot-blue { background: #1f6feb; }
.dot-red { background: #cf222e; }
.advisor-card {
background: #161b22;
border: 1px solid #30363d;
border-radius: 10px;
padding: 18px 22px;
margin-bottom: 20px;
}
.advisor-card h3 { margin: 0 0 12px 0; font-size: 16px; color: #fff; }
.adv-item {
padding: 9px 12px;
border-radius: 6px;
margin-bottom: 8px;
font-size: 14px;
line-height: 1.45;
}
.adv-ok { background: rgba(46, 160, 67, 0.12); border-left: 4px solid #3fb950; color: #e6edf3; }
.adv-warn { background: rgba(210, 153, 34, 0.14); border-left: 4px solid #d29922; color: #e6edf3; }
.adv-info { background: rgba(56, 139, 253, 0.12); border-left: 4px solid #58a6ff; color: #e6edf3; }
.chart-card {
background: #161b22;
border: 1px solid #30363d;
border-radius: 10px;
padding: 20px;
}
.chart-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.chart-header h3 { margin: 0; font-size: 16px; color: #fff; }
.legend { font-size: 13px; color: #8b949e; display: flex; gap: 16px; align-items: center; }
.leg-hp { color: #3fb950; font-weight: 700; }
.leg-nm { color: #58a6ff; font-weight: 700; }
canvas { width: 100%; height: 320px; display: block; }
</style>
</head>
<body>
<div class=""container"">
<div class=""header"">
<h1>🏎️ FH6SmartShift — Dyno, Dragy & Gearbox Tuning Inspector</h1>
<div class=""controls"">
<select id=""carSelect"" onchange=""forcePreview=false;renderCar(this.value)""></select>
<button class=""btn"" onclick=""renameCurrentCar()"">✏️ Name Car</button>
<button class=""btn"" onclick=""exportCarListJson()"">💾 CarList.json</button>
<button class=""btn btn-blue"" onclick=""exportSingleCarProfile()"">📤 Export Car</button>
<label class=""btn btn-green"">
📥 Import / Merge JSON
<input type=""file"" id=""mergeFile"" accept="".json"">
</label>
<button class=""btn"" id=""saveMergedBtn"" style=""display:none;border-color:#d29922;color:#e3b341;"" onclick=""downloadFullDatabase()"">💾 Save Merged DB</button>
</div>
</div>
<div class=""profile-banner"" id=""profileSummary"">
No car profiles saved yet. Drive a car at wide-open throttle in Forza Horizon 6 or Forza Motorsport to populate the Virtual Dyno database.
</div>
<div class=""dragy-grid"">
<div class=""dragy-card"">
<div>
<div class=""dragy-label"">⏱️ 0–100 km/h (Best PB)</div>
<div style=""font-size:12px;color:#6e7681;"">Standing Launch Telemetry</div>
</div>
<div class=""dragy-val"" id=""dragy0to100"">—</div>
</div>
<div class=""dragy-card"">
<div>
<div class=""dragy-label"">🚀 100–200 km/h (Best PB)</div>
<div style=""font-size:12px;color:#6e7681;"">Rolling / Standing Pull</div>
</div>
<div class=""dragy-val"" id=""dragy100to200"">—</div>
</div>
<div class=""dragy-card"">
<div>
<div class=""dragy-label"">🏁 0–200 km/h (Best PB)</div>
<div style=""font-size:12px;color:#6e7681;"">Full Standing Sprint</div>
</div>
<div class=""dragy-val"" id=""dragy0to200"">—</div>
</div>
</div>
<div class=""table-wrap"">
<table>
<thead>
<tr>
<th>Gear</th>
<th>Gear Ratio (RpmPerRadS)</th>
<th>RPM Drop on N+1 Upshift (dropRatio)</th>
<th>Next Gear Landing RPM</th>
<th>Saved JSON Threshold (Rpm)</th>
<th>Physical Shift Target (OptimalShiftRpm)</th>
<th>Dashboard Status</th>
</tr>
</thead>
<tbody id=""gearTableBody""></tbody>
</table>
</div>
<div class=""advisor-card"">
<h3>🔧 Automated Gearbox Tuning Advisor (Telemetry Analysis)</h3>
<div id=""tuningAdvisorBody""></div>
</div>
<div class=""chart-card"">
<div class=""chart-header"">
<h3 id=""chartTitle"">📈 401-Band Virtual Dyno Curve (Power HP & Torque Nm)</h3>
<div class=""legend"">
<button class=""btn"" id=""previewBtn"" style=""display:none;padding:4px 10px;font-size:11.5px;"" onclick=""forcePreview=!forcePreview;renderCar(document.getElementById('carSelect').value)"">👁️ Toggle Partial Curve</button>
<span class=""leg-hp"">● Engine Power (HP)</span>
<span class=""leg-nm"">● Engine Torque (Nm)</span>
</div>
</div>
<canvas id=""dynoCanvas"" width=""1120"" height=""320""></canvas>
</div>