forked from walmis/VPforce-TelemFFB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaircrafts_msfs.py
1646 lines (1307 loc) · 71 KB
/
aircrafts_msfs.py
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
#
# This file is part of the TelemFFB distribution (https://github.com/walmis/TelemFFB).
# Copyright (c) 2023 Valmantas Palikša.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import time
import math
from math import sin, cos, radians, sqrt, atan2
from simconnect import *
from ctypes import byref, cast, sizeof
from time import sleep
from pprint import pprint
import sys
import logging
import utils
from typing import List, Dict
from utils import clamp, HighPassFilter, Derivative, Dispenser
from ffb_rhino import HapticEffect, FFBReport_SetCondition, FFBReport_Input
from aircraft_base import AircraftBase, effects, HPFs, LPFs
# # from WASimCommander import pyWASimCommander
# from pyWASimCommander import *
# wasim = pyWASimCommander()
deg = 180 / math.pi
slugft3 = 0.00194032 # SI to slugft3
rad = 0.0174532925
ft = 3.28084 # m to ft
kt = 1.94384 # ms to kt
kt2ms = 0.514444 # knots to m/s
sim_connect = None
try:
sim_connect = SimConnect()
except: pass
def set_simdatum_to_msfs(simvar, value, units=None):
try:
sim_connect.set_simdatum(simvar, value, units=units)
except Exception as e:
logging.error(f"Error sending {simvar} value {value} to MSFS: {e}")
def send_event_to_msfs(event, data: int = 0 ):
try:
sim_connect.send_event(event, data)
except Exception as e:
logging.error(f"Error setting event {event} to MSFS: {e}")
class Aircraft(AircraftBase):
"""Base class for Aircraft based FFB"""
buffeting_intensity: float = 0.2 # peak AoA buffeting intensity 0 to disable
buffet_aoa: float = 10.0 # AoA when buffeting starts
stall_aoa: float = 15.0 # Stall AoA
aoa_effect_enabled: int = 1
engine_rumble: int = 0 # Engine Rumble - Disabled by default - set to 1 in config file to enable
runway_rumble_intensity: float = 1.0 # peak runway intensity, 0 to disable
gun_vibration_intensity: float = 0.12 # peak gunfire vibration intensity, 0 to disable
cm_vibration_intensity: float = 0.12 # peak countermeasure release vibration intensity, 0 to disable
weapon_release_intensity: float = 0.12 # peak weapon release vibration intensity, 0 to disable
weapon_effect_direction: int = 45 # Affects the direction of force applied for gun/cm/weapon release effect, Set to -1 for random direction
speedbrake_motion_intensity: float = 0.12 # peak vibration intensity when speed brake is moving, 0 to disable
speedbrake_buffet_intensity: float = 0.15 # peak buffeting intensity when speed brake deployed, 0 to disable
spoiler_motion_intensity: float = 0.0 # peak vibration intensity when spoilers is moving, 0 to disable
spoiler_buffet_intensity: float = 0.15 # peak buffeting intensity when spoilers deployed, 0 to disable
gear_motion_intensity: float = 0.12 # peak vibration intensity when gear is moving, 0 to disable
gear_buffet_intensity: float = 0.15 # peak buffeting intensity when gear down during flight, 0 to disable
flaps_motion_intensity: float = 0.12 # peak vibration intensity when flaps are moving, 0 to disable
flaps_buffet_intensity: float = 0.0 # peak buffeting intensity when flaps are deployed, 0 to disable
canopy_motion_intensity: float = 0.12 # peak vibration intensity when canopy is moving, 0 to disable
canopy_buffet_intensity: float = 0.0 # peak buffeting intensity when canopy is open during flight, 0 to disable
afterburner_effect_intensity = 0.2 # peak intensity for afterburner rumble effect
jet_engine_rumble_intensity = 0.12 # peak intensity for jet engine rumble effect
jet_engine_rumble_freq = 45 # base frequency for jet engine rumble effect (Hz)
####
#### Beta effects - set to 1 to enable
deceleration_effect_enable = 0
deceleration_effect_enable_areyoureallysure = 0
deceleration_max_force = 0.5
###
####
#### Beta effects - set to 1 to enable
gforce_effect_invert_force = 0 # 0=disabled(default),1=enabled (case where "180" degrees does not equal "away from pilot")
gforce_effect_enable = 0
gforce_effect_enable_areyoureallysure = 0
gforce_effect_curvature = 2.2
gforce_effect_max_intensity = 1.0
gforce_min_gs = 1.5 # G's where the effect starts playing
gforce_max_gs = 5.0 # G limit where the effect maxes out at strength defined in gforce_effect_max_intensity
###
### AoA reduction force effect
###
aoa_reduction_effect_enabled = 0
aoa_reduction_max_force = 0.0
critical_aoa_start = 22
critical_aoa_max = 25
rotor_blade_count = 2
heli_engine_rumble_intensity=0.15
aircraft_is_spring_centered = 0
spring_centered_elev_gain = 0.5
spring_centered_ailer_gain = 0.5
aileron_spring_gain = 0.25
elevator_spring_gain = 0.25
rudder_spring_gain = 0.25
aircraft_is_fbw = 0
fbw_elevator_gain = 0.8
fbw_aileron_gain = 0.8
fbw_rudder_gain = 0.8
nosewheel_shimmy = 0
nosewheel_shimmy_intensity = 0.15
nosewheel_shimmy_min_speed = 7
nosewheel_shimmy_min_brakes = 0.6
force_trim_enabled = 0
cyclic_spring_gain = 1.0
force_trim_button = "not_configured"
force_trim_reset_button = "not_configured"
include_dynamic_stick_forces = True
elevator_force_trim = 0
aileron_force_trim = 0
smoother = utils.Smoother()
dampener = utils.Derivative()
center_spring_on_pause = False
use_legacy_bindings = False
def __init__(self, name, **kwargs) -> None:
super().__init__(name)
# clear any existing effects
for e in effects.values(): e.destroy()
effects.clear()
# self.spring = HapticEffect().spring()
self.spring = effects["spring"].spring()
self.pause_spring = effects["pause_spring"].spring()
self.spring_x = FFBReport_SetCondition(parameterBlockOffset=0)
self.spring_y = FFBReport_SetCondition(parameterBlockOffset=1)
self.const_force = HapticEffect().constant(0, 0)
# aileron_max_deflection = 20.0*0.01745329
self.elevator_max_deflection = 12.0 * 0.01745329
# rudder_max_deflection = 20.0*0.01745329
self.aileron_gain = 0.1
self.elevator_gain = 0.1
self.rudder_gain = 0.1
self.slip_gain = 1.0
self.stall_AoA = 18.0 * 0.01745329
self.pusher_start_AoA = 900.0 * 0.01745329
self.pusher_working_angle = 900.0 * 0.01745329
self.wing_shadow_AoA = 900.0 * 0.01745329
self.wing_shadow_angle = 900.0 * 0.01745329
self.stick_shaker_AoA = 16.0 * 0.01745329
# FFB force value per lateral G
self.lateral_force_gain = 0.2
self.aoa_gain = 0.3
self.g_force_gain = 0.1
self.prop_diameter = 1.5
self.elevator_droop_moment = 0.1 # in FFB force units
# how much air flow the elevator receives from the propeller
self.elevator_prop_flow_ratio = 1.0
self.rudder_prop_flow_ratio = 1.0
# scale the dynamic pressure to ffb friendly values
self.dyn_pressure_scale = 0.005
self.max_aoa_cf_force: float = 0.2 # CF force sent to device at %stall_aoa
self.cyclic_trim_release_active = 0
self.cyclic_spring_init = 0
self.cyclic_center = [0, 0] # x, y
self.collective_spring_init = 0
self.force_trim_release_active = 0
self.force_trim_spring_init = 0
self.stick_center = [0, 0] # x, y
self.force_trim_x_offset = 0
self.force_trim_y_offset = 0
self.telemffb_controls_axes = False
self.trim_following = False
self.joystick_x_axis_scale = 1.0
self.joystick_y_axis_scale = 1.0
self.rudder_x_axis_scale = 1.0
self.joystick_trim_follow_gain_physical_x = 1.0
self.joystick_trim_follow_gain_physical_y = 0.2
self.joystick_trim_follow_gain_virtual_x = 1.0
self.joystick_trim_follow_gain_virtual_y = 0.2
self.rudder_trim_follow_gain_physical_x = 1.0
self.rudder_trim_follow_gain_virtual_x = 0.2
self.ap_following = True
self.use_fbw_for_ap_follow = True
self.invert_ap_x_axis = False
global sim_connect
if sim_connect is None:
sim_connect = SimConnect()
def _update_nosewheel_shimmy(self, telem_data):
curve = 2.5
freq = 8
brakes = telem_data.get("Brakes", (0, 0))
wow = sum(telem_data.get("WeightOnWheels", 0))
tas = telem_data.get("TAS", 0)
logging.debug(f"brakes = {brakes}")
avg_brakes = sum(brakes) / len(brakes)
if avg_brakes >= self.nosewheel_shimmy_min_brakes and tas > self.nosewheel_shimmy_min_speed:
shimmy = utils.non_linear_scaling(avg_brakes, self.nosewheel_shimmy_min_brakes, 1.0, curvature=curve)
logging.debug(f"Nosewheel Shimmy intensity calculation: (BrakesPct:{avg_brakes} | TAS:{tas} | RT Inensity: {shimmy}")
effects["nw_shimmy"].periodic(freq, shimmy, 90).start()
else:
effects.dispose("nw_shimmy")
self.cp_int = 0
def _update_fbw_flight_controls(self, telem_data):
ffb_type = telem_data.get("FFBType", "joystick")
ap_active = telem_data.get("APMaster", 0)
self.spring = effects['fbw_spring'].spring()
if ffb_type == "joystick":
if self.trim_following:
if not self.telemffb_controls_axes:
logging.warning("TRIM FOLLOWING ENABLED BUT TELEMFFB IS NOT CONFIGURED TO SEND AXIS POSITION TO MSFS! Forcing to enable!")
self.telemffb_controls_axes = True # Force sending of axis via simconnect if trim following is enabled
elev_trim = telem_data.get("ElevTrimPct", 0)
# derivative_hz = 5 # derivative lpf filter -3db Hz
# derivative_k = 0.1 # derivative gain value, or damping ratio
#
# d_elev_trim = getattr(self, "_d_elev_trim", None)
# if not d_elev_trim: d_elev_trim = self._d_elev_trim = utils.Derivative(derivative_hz)
# d_elev_trim.lpf.cutoff_freq_hz = derivative_hz
#
# elev_trim_deriv = - d_elev_trim.update(elev_trim) * derivative_k
#
# elev_trim += elev_trim_deriv
elev_trim = self.dampener.dampen_value(elev_trim, '_elev_trim', derivative_hz=5, derivative_k=0.15)
# print(f"raw:{raw_elev_trim}, smooth:{elev_trim}")
aileron_trim = telem_data.get("AileronTrimPct", 0)
aileron_trim = clamp(aileron_trim * self.joystick_trim_follow_gain_physical_x, -1, 1)
virtual_stick_x_offs = aileron_trim - (aileron_trim * self.joystick_trim_follow_gain_virtual_x)
elev_trim = clamp(elev_trim * self.joystick_trim_follow_gain_physical_y, -1, 1)
virtual_stick_y_offs = elev_trim - (elev_trim * self.joystick_trim_follow_gain_virtual_y)
phys_stick_y_offs = int(elev_trim*4096)
if self.ap_following and ap_active:
input_data = HapticEffect.device.getInput()
phys_x, phys_y = input_data.axisXY()
aileron_pos = telem_data.get("AileronDeflPctLR", (0, 0))
elevator_pos = telem_data.get("ElevDeflPct", 0)
aileron_pos = aileron_pos[0]
aileron_pos = self.dampener.dampen_value(aileron_pos, '_aileron_pos', derivative_hz=5, derivative_k=0.15)
# derivative_hz = 5 # derivative lpf filter -3db Hz
# derivative_k = 0.1 # derivative gain value, or damping ratio
#
# d_aileron_pos = getattr(self, "_d_aileron_pos", None)
# if not d_aileron_pos: d_aileron_pos = self._d_aileron_pos = utils.Derivative(derivative_hz)
# d_aileron_pos.lpf.cutoff_freq_hz = derivative_hz
#
# aileron_pos_deriv = - d_aileron_pos.update(aileron_pos) * derivative_k
#
# aileron_pos += aileron_pos_deriv
phys_stick_x_offs = int(aileron_pos * 4096)
if self.invert_ap_x_axis:
phys_stick_x_offs = -phys_stick_x_offs
else:
phys_stick_x_offs = int(aileron_trim * 4096)
else:
phys_stick_x_offs = 0
virtual_stick_x_offs = 0
phys_stick_y_offs = 0
virtual_stick_y_offs = 0
if self.telemffb_controls_axes:
input_data = HapticEffect.device.getInput()
phys_x, phys_y = input_data.axisXY()
x_pos = phys_x - virtual_stick_x_offs
y_pos = phys_y - virtual_stick_y_offs
x_scale = clamp(self.joystick_x_axis_scale, 0, 1)
y_scale = clamp(self.joystick_y_axis_scale, 0, 1)
pos_x_pos = -int(utils.scale(x_pos, (-1, 1), (-16383*x_scale, 16384*x_scale)))
pos_y_pos = -int(utils.scale(y_pos, (-1, 1), (-16383*y_scale, 16384*y_scale)))
send_event_to_msfs("AXIS_AILERONS_SET", pos_x_pos)
send_event_to_msfs("AXIS_ELEVATOR_SET", pos_y_pos)
# update spring data
if self.ap_following and ap_active:
y_coeff = 4096
x_coeff = 4096
else:
y_coeff = clamp(int(4096 * self.fbw_elevator_gain), 0, 4096)
x_coeff = clamp(int(4096 * self.fbw_aileron_gain), 0, 4096)
self.spring_y.negativeCoefficient = self.spring_y.positiveCoefficient = y_coeff
# logging.debug(f"Elev Coeef: {elevator_coeff}")
self.spring_y.cpOffset = phys_stick_y_offs
self.spring_x.negativeCoefficient = self.spring_x.positiveCoefficient = x_coeff
self.spring_x.cpOffset = phys_stick_x_offs
self.spring.effect.setCondition(self.spring_y)
self.spring.effect.setCondition(self.spring_x)
elif ffb_type == "pedals":
if self.trim_following:
if not self.telemffb_controls_axes:
logging.warning("TRIM FOLLOWING ENABLED BUT TELEMFFB IS NOT CONFIGURED TO SEND AXIS POSITION TO MSFS! Forcing to enable!")
self.telemffb_controls_axes = True # Force sending of axis via simconnect if trim following is enabled
rudder_trim = telem_data.get("RudderTrimPct", 0)
rudder_trim = clamp(rudder_trim * self.rudder_trim_follow_gain_physical_x, -1, 1)
virtual_rudder_x_offs = rudder_trim - (rudder_trim * self.rudder_trim_follow_gain_virtual_x)
phys_rudder_x_offs = int(rudder_trim * 4096)
if self.ap_following and ap_active:
input_data = HapticEffect.device.getInput()
# print("I am here")
phys_x, phys_y = input_data.axisXY()
rudder_pos = telem_data.get("RudderDeflPct", 0)
rudder_pos = self.dampener.dampen_value(rudder_pos, '_rudder_pos', derivative_hz=5, derivative_k=0.15)
# derivative_hz = 5 # derivative lpf filter -3db Hz
# derivative_k = 0.1 # derivative gain value, or damping ratio
#
# d_rudder_pos = getattr(self, "_d_rudder_pos", None)
# if not d_rudder_pos: d_rudder_pos = self._d_rudder_pos = utils.Derivative(derivative_hz)
# d_rudder_pos.lpf.cutoff_freq_hz = derivative_hz
#
# rudder_pos_deriv = - d_rudder_pos.update(rudder_pos) * derivative_k
#
# rudder_pos += rudder_pos_deriv
phys_rudder_x_offs = int(rudder_pos * 4096)
else:
phys_rudder_x_offs = int(rudder_trim * 4096)
else:
phys_rudder_x_offs = 0
virtual_rudder_x_offs = 0
if self.telemffb_controls_axes:
input_data = HapticEffect.device.getInput()
phys_x, phys_y = input_data.axisXY()
x_pos = phys_x - virtual_rudder_x_offs
x_scale = clamp(self.rudder_x_axis_scale, 0, 1)
pos_x_pos = -int(utils.scale(x_pos, (-1, 1), (-16383 * x_scale, 16384 * x_scale)))
# pos_y_pos = -int(utils.scale(y_pos, (-1, 1), (-16383 * y_scale, 16384 * y_scale)))
send_event_to_msfs("AXIS_RUDDER_SET", pos_x_pos)
# update spring data
if self.ap_following and ap_active:
x_coeff = 4096
else:
x_coeff = clamp(int(4096 * self.fbw_rudder_gain), 0, 4096)
self.spring_x.negativeCoefficient = self.spring_x.positiveCoefficient = x_coeff
# print(f"{phys_rudder_x_offs}")
self.spring_x.cpOffset = phys_rudder_x_offs
logging.debug(f"Elev Coeef: {x_coeff}")
self.spring.effect.setCondition(self.spring_x)
self.spring.start()
def _update_flight_controls(self, telem_data):
# calculations loosely based on FLightGear FFB page:
# https://wiki.flightgear.org/Force_feedback
# https://github.com/viktorradnai/fg-haptic/blob/master/force-feedback.nas
self.spring = effects["dynamic_spring"].spring()
ap_active = telem_data.get("APMaster", 0)
elev_base_gain = 0
ailer_base_gain = 0
rudder_base_gain = 0
ffb_type = telem_data.get("FFBType", "joystick")
if self.aircraft_is_fbw or telem_data.get("ACisFBW"):
logging.debug ("FBW Setting enabled, running fbw_flight_controls")
self._update_fbw_flight_controls(telem_data)
return
if telem_data.get("AircraftClass") == "Helicopter":
logging.debug("Aircraft is Helicopter, aborting update_flight_controls")
return
if self.ap_following and ap_active and self.use_fbw_for_ap_follow:
logging.debug("FBW Setting enabled, running fbw_flight_controls")
self._update_fbw_flight_controls(telem_data)
effects["dynamic_spring"].stop()
return
else:
effects["fbw_spring"].stop()
if self.aircraft_is_spring_centered:
elev_base_gain = self.elevator_spring_gain
ailer_base_gain = self.aileron_spring_gain
rudder_base_gain = self.rudder_spring_gain
logging.debug(f"Aircraft controls are center sprung, setting x:y base gain to{ailer_base_gain}:{elev_base_gain}, rudder base gain to {rudder_base_gain}")
incidence_vec = utils.Vector(telem_data["VelWorld"])
wind_vec = utils.Vector(telem_data["AmbWind"])
incidence_vec = incidence_vec - wind_vec
# Rotate the vector from world frame into body frame
incidence_vec = incidence_vec.rotY(-(telem_data["Heading"] * rad))
incidence_vec = incidence_vec.rotX(-telem_data["Pitch"] * rad)
incidence_vec = incidence_vec.rotZ(-telem_data["Roll"] * rad)
force_trim_x_offset = self.force_trim_x_offset
force_trim_y_offset = self.force_trim_y_offset
_airspeed = incidence_vec.z
telem_data["TAS"] = _airspeed
base_elev_coeff = round(clamp((elev_base_gain * 4096), 0, 4096))
base_ailer_coeff = round(clamp((ailer_base_gain * 4096), 0, 4096))
base_rudder_coeff = round(clamp((rudder_base_gain * 4096), 0, 4096))
#logging.info(f"Base Elev/Ailer coeff = {base_elev_coeff}/{base_ailer_coeff}")
rudder_angle = telem_data["RudderDefl"] * rad # + trim?
# print(data["ElevDefl"] / data["ElevDeflPct"] * 100)
slip_angle = atan2(incidence_vec.x, incidence_vec.z)
telem_data["SideSlip"] = slip_angle*deg # overwrite sideslip with our calculated version (including wind)
g_force = telem_data["G"] # this includes earths gravity
_aoa = -atan2(incidence_vec.y, incidence_vec.z)*deg
telem_data["AoA"] = _aoa
# calculate air flow velocity exiting the prop
# based on https://www.grc.nasa.gov/www/k-12/airplane/propth.html
_prop_thrust1 = telem_data.get('PropThrust1', 0)
if _prop_thrust1 < 0:
_prop_thrust1 = 0
_prop_air_vel = sqrt(2 * _prop_thrust1 / (telem_data["AirDensity"] * (math.pi * (self.prop_diameter / 2) ** 2)) + _airspeed ** 2)
if abs(incidence_vec.y) > 0.5 or _prop_air_vel > 1: # avoid edge cases
_elevator_aoa = atan2(-incidence_vec.y, _prop_air_vel) * deg
else:
_elevator_aoa = 0
telem_data["_elevator_aoa"] = _elevator_aoa
telem_data["Incidence"] = [incidence_vec.x, incidence_vec.y, incidence_vec.z]
# calculate dynamic pressure based on air flow from propeller
# elevator_prop_flow_ratio defines how much prop wash the elevator receives
_elev_dyn_pressure = utils.mix(telem_data["DynPressure"],
0.5 * telem_data["AirDensity"] * _prop_air_vel ** 2,
self.elevator_prop_flow_ratio) * self.dyn_pressure_scale
# scale dynamic pressure to FFB friendly values
_dyn_pressure = telem_data["DynPressure"] * self.dyn_pressure_scale
_slip_gain = 1.0 - self.slip_gain * abs(sin(slip_angle))
telem_data["_slip_gain"] = _slip_gain
# increasing G force causes increase in elevator droop effect
_elevator_droop_term = self.elevator_droop_moment * g_force / (1 + _elev_dyn_pressure)
telem_data["_elevator_droop_term"] = _elevator_droop_term
#logging.debug(f"ailer gain = {self.aileron_gain}")
aileron_coeff = _dyn_pressure * self.aileron_gain * _slip_gain
# add data to telemetry packet so they become visible in the GUI output
telem_data["_prop_air_vel"] = _prop_air_vel
telem_data["_elev_dyn_pressure"] = _elev_dyn_pressure
#logging.debug(f"elev gain = {self.elevator_gain}")
elevator_coeff = (_elev_dyn_pressure) * self.elevator_gain * _slip_gain
# a, b, c = 0.5, 0.3, 0.1
# elevator_coeff = a * (_elev_dyn_pressure ** 2) + b * _elev_dyn_pressure * self.elevator_gain + c * slip_gain
telem_data["_elev_coeff"] = elevator_coeff
telem_data["_aile_coeff"] = aileron_coeff
# force is proportional to elevator deflection vs incoming airflow, this creates a dynamic elevator effect on top of spring
# update: reworking this based on spring center point offset and this below is not physically correct anyways
#_aoa_term = sin(( _aoa - telem_data["ElevDefl"]) * rad) * self.aoa_gain * _elev_dyn_pressure * _slip_gain
#telem_data["_aoa_term"] = _aoa_term
_G_term = (self.g_force_gain * telem_data["AccBody"][1])
telem_data["_G_term"] = _G_term
# hpf_pitch_acc = hpf.get("xacc", 3).update(data["RelWndY"]) # test stuff
# data["_hpf_pitch_acc"] = hpf_pitch_acc # test stuff
_rud_dyn_pressure = utils.mix(telem_data["DynPressure"], 0.5 * telem_data["AirDensity"] * _prop_air_vel ** 2,
self.rudder_prop_flow_ratio) * self.dyn_pressure_scale
rudder_coeff = _rud_dyn_pressure * self.rudder_gain * _slip_gain
telem_data["_rud_coeff"] = rudder_coeff
rud = (slip_angle - rudder_angle) * _dyn_pressure * _slip_gain
rud_force = clamp((rud * self.rudder_gain), -1, 1)
rud_force = self.dampener.dampen_value(rud_force, '_rud_force', derivative_hz=5, derivative_k=.015)
if ffb_type == 'joystick':
if self.trim_following:
self.telemffb_controls_axes = True # Force sending of axis via simconnect if trim following is enabled
elev_trim = telem_data.get("ElevTrimPct", 0)
aileron_trim = telem_data.get("AileronTrimPct", 0)
aileron_trim = clamp(aileron_trim * self.joystick_trim_follow_gain_physical_x, -1, 1)
virtual_stick_x_offs = aileron_trim - (aileron_trim * self.joystick_trim_follow_gain_virtual_x)
elev_trim = clamp(elev_trim * self.joystick_trim_follow_gain_physical_y, -1, 1)
elev_trim = self.dampener.dampen_value(elev_trim, '_elev_trim', derivative_hz=5, derivative_k=0.15)
virtual_stick_y_offs = elev_trim - (elev_trim * self.joystick_trim_follow_gain_virtual_y)
phys_stick_y_offs = int(elev_trim * 4096)
if self.ap_following and ap_active:
aileron_pos = telem_data.get("AileronDeflPctLR", (0, 0))
aileron_pos = aileron_pos[0]
aileron_pos = self.dampener.dampen_value(aileron_pos, '_aileron_pos', derivative_hz=5, derivative_k=0.15)
phys_stick_x_offs = int(aileron_pos * 4096)
else:
phys_stick_x_offs = int(aileron_trim * 4096)
else:
phys_stick_x_offs = 0
virtual_stick_x_offs = 0
phys_stick_y_offs = 0
virtual_stick_y_offs = 0
if self.telemffb_controls_axes:
input_data = HapticEffect.device.getInput()
phys_x, phys_y = input_data.axisXY()
x_pos = phys_x - virtual_stick_x_offs
y_pos = phys_y - virtual_stick_y_offs
x_scale = clamp(self.joystick_x_axis_scale, 0, 1)
y_scale = clamp(self.joystick_y_axis_scale, 0, 1)
pos_x_pos = -int(utils.scale(x_pos, (-1, 1), (-16383 * x_scale, 16384 * x_scale)))
pos_y_pos = -int(utils.scale(y_pos, (-1, 1), (-16383 * y_scale, 16384 * y_scale)))
send_event_to_msfs("AXIS_AILERONS_SET", pos_x_pos)
send_event_to_msfs("AXIS_ELEVATOR_SET", pos_y_pos)
if telem_data["ElevDeflPct"] != 0 and not max(telem_data.get("WeightOnWheels")): # avoid div by zero or calculating while on the ground
#give option to disable if desired by user
if self.aoa_effect_enabled:
# calculate maximum angle based on current angle and percentage
tot = telem_data["ElevDefl"] / telem_data["ElevDeflPct"]
tas = telem_data.get("TAS") # m/s
vc, vs0, vs1 = telem_data.get("DesignSpeed") # m/s
speed_factor = utils.scale_clamp(tas, (0, vc * 1.4), (0.0, 1.0)) # rough estimate that Vne is 1.4x Vc
y_offs = _aoa / tot
y_offs = y_offs + force_trim_y_offset + (phys_stick_y_offs / 4096)
y_offs = clamp(y_offs, -1, 1)
# Take speed in relation to aircraft v speeds into account when moving offset based on aoa
y_offs = int(y_offs * 4096 * speed_factor)
self.spring_y.cpOffset = y_offs
x_offs = phys_stick_x_offs
self.spring_x.cpOffset = x_offs
# logging.debug(f"fto={force_trim_y_offset} | Offset={offs}")
self.spring_y.positiveCoefficient = clamp(int(4096 * elevator_coeff), base_elev_coeff, 4096)
ec = clamp(int(4096 * elevator_coeff), base_elev_coeff, 4096)
logging.debug(f"Elev Coef: {ec}")
self.spring_y.negativeCoefficient = self.spring_y.positiveCoefficient
#self.spring_y.cpOffset = 0 # -clamp(int(4096*elevator_offs), -4096, 4096)
ac = clamp(int(4096 * aileron_coeff), base_elev_coeff, 4096)
logging.debug(f"Ailer Coef: {ac}")
self.spring_x.positiveCoefficient = clamp(int(4096 * aileron_coeff), base_ailer_coeff, 4096)
self.spring_x.negativeCoefficient = self.spring_x.positiveCoefficient
# update spring data
self.spring.effect.setCondition(self.spring_y)
self.spring.effect.setCondition(self.spring_x)
# update constant forces
cf_pitch = -_elevator_droop_term - _G_term # + _aoa_term
cf_pitch = clamp(cf_pitch, -1.0, 1.0)
# add force on lateral axis (sideways)
_side_accel = -telem_data["AccBody"][0] * self.lateral_force_gain
cf_roll = _side_accel
cf = utils.Vector2D(cf_pitch, cf_roll)
if cf.magnitude() > 1.0:
cf = cf.normalize()
mag, theta = cf.to_polar()
self.const_force.constant(mag, theta*deg).start()
self.spring.start() # ensure spring is started
elif ffb_type == 'pedals':
if self.trim_following:
if not self.telemffb_controls_axes:
logging.warning(
"TRIM FOLLOWING ENABLED BUT TELEMFFB IS NOT CONFIGURED TO SEND AXIS POSITION TO MSFS! Forcing to enable!")
self.telemffb_controls_axes = True # Force sending of axis via simconnect if trim following is enabled
rudder_trim = telem_data.get("RudderTrimPct", 0)
rudder_trim = clamp(rudder_trim * self.rudder_trim_follow_gain_physical_x, -1, 1)
virtual_rudder_x_offs = rudder_trim - (rudder_trim * self.rudder_trim_follow_gain_virtual_x)
phys_rudder_x_offs = int(rudder_trim * 4096)
else:
phys_rudder_x_offs = 0
virtual_rudder_x_offs = 0
x_coeff = clamp(int(4096 * rudder_coeff), base_rudder_coeff, 4096)
self.spring_x.negativeCoefficient = self.spring_x.positiveCoefficient = x_coeff
self.spring_x.cpOffset = phys_rudder_x_offs
self.spring.effect.setCondition(self.spring_x)
tas = telem_data.get("TAS")
vc, vs0, vs1 = telem_data.get("DesignSpeed") # m/s
speed_factor = utils.scale_clamp(tas, (0, vc * 1.4), (0.0, 1.0)) # rough estimate that Vne is 1.4x Vc
rud_force = rud_force * speed_factor
# telem_data["RudForce"] = rud_force * speed_factor
if self.telemffb_controls_axes:
input_data = HapticEffect.device.getInput()
phys_x, phys_y = input_data.axisXY()
x_pos = phys_x - virtual_rudder_x_offs
x_scale = clamp(self.rudder_x_axis_scale, 0, 1)
pos_x_pos = -int(utils.scale(x_pos, (-1, 1), (-16383 * x_scale, 16384 * x_scale)))
send_event_to_msfs("AXIS_RUDDER_SET", pos_x_pos)
# if self.ap_following and ap_active:
# y_coeff = 4096
# x_coeff = 4096
# else:
# y_coeff = clamp(int(4096 * self.fbw_elevator_gain), 0, 4096)
# x_coeff = clamp(int(4096 * self.fbw_aileron_gain), 0, 4096)
self.const_force.constant(rud_force, 270).start()
self.spring.start()
def on_event(self, event, *args):
logging.info(f"on_event {event} {args}")
def on_telemetry(self, telem_data):
if telem_data.get("STOP",0):
self.on_timeout()
return
effects["pause_spring"].spring().stop()
if telem_data["Parked"]: # Aircraft is parked, do nothing
return
super().on_telemetry(telem_data)
### Generic Aircraft Class Telemetry Handler
if not "AircraftClass" in telem_data:
telem_data["AircraftClass"] = "GenericAircraft" # inject aircraft class into telemetry
self._update_runway_rumble(telem_data)
self._update_buffeting(telem_data)
self._update_flight_controls(telem_data)
self._decel_effect(telem_data)
if self.flaps_motion_intensity > 0:
flps = max(telem_data.get("Flaps", 0))
self._update_flaps(flps)
retracts = telem_data.get("RetractableGear", 0)
if isinstance(retracts, list):
retracts = max(retracts)
if (self.gear_motion_intensity > 0) and (retracts):
gear = max(telem_data.get("Gear", 0))
self._update_landing_gear(gear, telem_data.get("TAS"), spd_thresh_low=130 * kt2ms, spd_thresh_high=200 * kt2ms)
self._decel_effect(telem_data)
self._aoa_reduction_force_effect(telem_data)
if self.nosewheel_shimmy and telem_data.get("FFBType") == "pedals" and not telem_data.get("IsTaildragger", 0):
self._update_nosewheel_shimmy(telem_data)
def on_timeout(self):
if not self.pause_spring.started:
super().on_timeout()
self.cyclic_spring_init = 0
self.const_force.stop()
self.spring.stop()
if self.center_spring_on_pause:
self.spring_x.negativeCoefficient = self.spring_x.positiveCoefficient = 4096
self.spring_y.negativeCoefficient = self.spring_y.positiveCoefficient = 4096
self.spring_x.cpOffset = self.spring_y.cpOffset = 0
self.pause_spring.effect.setCondition(self.spring_x)
self.pause_spring.effect.setCondition(self.spring_y)
self.pause_spring.start()
class PropellerAircraft(Aircraft):
"""Generic Class for Prop aircraft"""
# run on every telemetry frame
def on_telemetry(self, telem_data):
### Propeller Aircraft Class Telemetry Handler
if telem_data.get("N") == None:
return
telem_data["AircraftClass"] = "PropellerAircraft" # inject aircraft class into telemetry
if telem_data.get("STOP",0):
self.on_timeout()
return
super().on_telemetry(telem_data)
## Engine Rumble
current_rpm = telem_data["PropRPM"]
if isinstance(current_rpm, list):
current_rpm = max(current_rpm)
if self.engine_rumble or self._engine_rumble_is_playing:
self._update_engine_rumble(current_rpm)
#self._update_aoa_effect(telem_data) # currently calculated in _update_flight_controls
if self.spoiler_motion_intensity > 0 or self.spoiler_buffet_intensity > 0:
sp = max(telem_data.get("Spoilers", 0))
self._update_spoiler(sp, telem_data.get("TAS"), spd_thresh_low=800*kt2ms, spd_thresh_hi=140*kt2ms )
#if self.gforce_effect_enable and self.gforce_effect_enable_areyoureallysure:
# super()._gforce_effect(telem_data)
class JetAircraft(Aircraft):
"""Generic Class for Jets"""
# flaps_motion_intensity = 0.0
_ab_is_playing = 0
_jet_rumble_is_playing = 0
# run on every telemetry frame
def on_telemetry(self, telem_data):
## Jet Aircraft Telemetry Manager
if telem_data.get("N") == None:
return
telem_data["AircraftClass"] = "JetAircraft" # inject aircraft class into telemetry
if telem_data.get("STOP",0):
self.on_timeout()
return
super().on_telemetry(telem_data)
if self.spoiler_motion_intensity > 0 or self.spoiler_buffet_intensity > 0:
sp = max(telem_data.get("Spoilers", 0))
self._update_spoiler(sp, telem_data.get("TAS"), spd_thresh_low=150*kt2ms, spd_thresh_hi=300*kt2ms )
if self.engine_rumble or self._jet_rumble_is_playing:
self._update_jet_engine_rumble(telem_data)
self._gforce_effect(telem_data)
self._update_ab_effect(telem_data)
class TurbopropAircraft(PropellerAircraft):
def on_telemetry(self, telem_data):
if telem_data.get("N") == None:
return
telem_data["AircraftClass"] = "TurbopropAircraft" # inject aircraft class into telemetry
if telem_data.get("STOP",0):
self.on_timeout()
return
super().on_telemetry(telem_data)
# if self.spoiler_motion_intensity > 0 or self.spoiler_buffet_intensity > 0:
# sp = max(telem_data.get("Spoilers", 0))
# self._update_spoiler(sp, telem_data.get("TAS"), spd_thresh_low=120*kt2ms, spd_thresh_hi=260*kt2ms )
# if self.gforce_effect_enable and self.gforce_effect_enable_areyoureallysure:
# super()._gforce_effect(telem_data)
if self.engine_rumble or self._jet_rumble_is_playing:
self._update_jet_engine_rumble(telem_data)
class GliderAircraft(Aircraft):
def _update_force_trim(self, telem_data, x_axis=True, y_axis=True):
if not self.force_trim_enabled:
return
self.spring = effects["dynamic_spring"].spring()
ffb_type = telem_data.get("FFBType", "joystick")
offs_x = 0
offs_y = 0
if ffb_type != "joystick":
return
if self.force_trim_button == "not_configured" or self.force_trim_reset_button == "not_configured":
logging.warning("Force trim enabled but buttons not configured")
return
# logging.debug(f"update_force_trim: x={x_axis}, y={y_axis}")
input_data = HapticEffect.device.getInput()
force_trim_pressed = input_data.isButtonPressed(self.force_trim_button)
trim_reset_pressed = input_data.isButtonPressed(self.force_trim_reset_button)
x, y = input_data.axisXY()
if force_trim_pressed:
if x_axis:
self.spring_x.positiveCoefficient = 2048
self.spring_x.negativeCoefficient = 2048
offs_x = round(x * 4096)
self.spring_x.cpOffset = offs_x
self.spring.effect.setCondition(self.spring_x)
if y_axis:
self.spring_y.positiveCoefficient = 2048
self.spring_y.negativeCoefficient = 2048
offs_y = round(y * 4096)
self.spring_y.cpOffset = offs_y
self.spring.effect.setCondition(self.spring_y)
self.stick_center = [x,y]
logging.info(f"Force Trim Disengaged:{round(x * 4096)}:{round(y * 4096)}")
self.force_trim_release_active = 1
if not force_trim_pressed and self.force_trim_release_active:
self.spring_x.positiveCoefficient = clamp(int(4096 * self.aileron_spring_gain), 0, 4096)
self.spring_x.negativeCoefficient = self.spring_x.positiveCoefficient
self.spring_y.positiveCoefficient = clamp(int(4096 * self.elevator_spring_gain), 0, 4096)
self.spring_y.negativeCoefficient = self.spring_y.positiveCoefficient
if x_axis:
offs_x = round(x * 4096)
self.spring_x.cpOffset = offs_x
self.spring.effect.setCondition(self.spring_x)
if y_axis:
offs_y = round(y * 4096)
self.spring_y.cpOffset = offs_y
self.spring.effect.setCondition(self.spring_y)
# self.spring.start()
self.stick_center = [x,y]
logging.info(f"Force Trim Engaged :{offs_x}:{offs_y}")
self.force_trim_release_active = 0
if trim_reset_pressed or not self.force_trim_spring_init:
if trim_reset_pressed:
self.stick_center = [0, 0]
if x_axis:
self.spring_x.positiveCoefficient = clamp(int(4096 * self.aileron_spring_gain), 0, 4096)
self.spring_x.negativeCoefficient = self.spring_x.positiveCoefficient
cpO_x = round(self.cyclic_center[0]*4096)
self.spring_x.cpOffset = cpO_x
self.spring.effect.setCondition(self.spring_x)
if y_axis:
self.spring_y.positiveCoefficient = clamp(int(4096 * self.elevator_spring_gain), 0, 4096)
self.spring_y.negativeCoefficient = self.spring_y.positiveCoefficient
cpO_y = round(self.cyclic_center[1]*4096)
self.spring_y.cpOffset = cpO_y
self.spring.effect.setCondition(self.spring_y)
# self.spring.start()
self.force_trim_spring_init = 1
logging.info("Trim Reset Pressed")
return
telem_data["StickXY"] = [x, y]
telem_data["StickXY_offset"] = self.stick_center
self.force_trim_x_offset = self.stick_center[0]
self.force_trim_y_offset = self.stick_center[1]
def on_telemetry(self, telem_data):
if telem_data.get("N") == None:
return
telem_data["AircraftClass"] = "GliderAircraft" # inject aircraft class into telemetry
if telem_data.get("STOP",0):
self.on_timeout()
return
super().on_telemetry(telem_data)
if self.force_trim_enabled:
self._update_force_trim(telem_data, x_axis=self.aileron_force_trim, y_axis=self.elevator_force_trim)
if self.spoiler_motion_intensity > 0 or self.spoiler_buffet_intensity > 0:
sp = max(telem_data.get("Spoilers", 0))
self._update_spoiler(sp, telem_data.get("TAS"), spd_thresh_low=60*kt2ms, spd_thresh_hi=120*kt2ms )
if self.gforce_effect_enable and self.gforce_effect_enable_areyoureallysure:
super()._gforce_effect(telem_data)
class Helicopter(Aircraft):
"""Generic Class for Helicopters"""
buffeting_intensity = 0.0
etl_start_speed = 6.0 # m/s
etl_stop_speed = 22.0 # m/s
etl_effect_intensity = 0.2 # [ 0.0 .. 1.0]
etl_shake_frequency = 14.0 # value has been deprecated in favor of rotor RPM calculation
overspeed_shake_start = 70.0 # m/s
overspeed_shake_intensity = 0.2
heli_engine_rumble_intensity = 0.12
cpO_x = 0
cpO_y = 0
virtual_cyclic_x_offs = 0
virtual_cyclic_y_offs = 0
phys_cyclic_x_offs = 0
phys_cyclic_y_offs = 0
stepper_dict = {}
trim_reset_complete = 1
last_device_x = 0
last_device_y = 0
last_collective_y = 1
last_pedal_x = 0
collective_init = 0
collective_ap_spring_gain = 1
collective_dampening_gain = 1
collective_spring_coeff_y = 0
pedals_init = 0
pedal_spring_gain = 1
pedal_dampening_gain = 1
pedal_spring_coeff_x = 0
joystick_trim_follow_gain_physical_x = 0.3
joystick_trim_follow_gain_virtual_x = 0.2
joystick_trim_follow_gain_physical_y = 0.3
joystick_trim_follow_gain_virtual_y = 0.2
cyclic_physical_trim_x_offs = 0
cyclic_physical_trim_y_offs = 0
cyclic_virtual_trim_x_offs = 0
cyclic_virtual_trim_y_offs = 0
def __init__(self, name, **kwargs):
super().__init__(name, **kwargs)
def on_timeout(self):
super().on_timeout()
self.cyclic_spring_init = 0
self.collective_init = 0
self.pedals_init = 0
def on_telemetry(self, telem_data):
self.speedbrake_motion_intensity = 0.0
if telem_data.get("N") == None:
return
telem_data["AircraftClass"] = "Helicopter" # inject aircraft class into telemetry
if telem_data.get("STOP",0):
self.on_timeout()
return
super().on_telemetry(telem_data)
self._update_heli_controls(telem_data)
self._update_collective(telem_data)
# self._update_cyclic_trim(telem_data)
self._update_pedals(telem_data)
self._calc_etl_effect(telem_data, blade_ct=self.rotor_blade_count)
self._update_jet_engine_rumble(telem_data)
self._update_heli_engine_rumble(telem_data, blade_ct=self.rotor_blade_count)