-
-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathEffectsCalculator.cpp
More file actions
1064 lines (922 loc) · 35.3 KB
/
EffectsCalculator.cpp
File metadata and controls
1064 lines (922 loc) · 35.3 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
/*
* EffectsCalculator.cpp
*
* Created on: 27.01.21
* Author: Jon Lidgard, Yannick Richter, Vincent Manoukian
*/
#include <stdint.h>
#include <math.h>
#include "EffectsCalculator.h"
#include "Axis.h"
#define X_AXIS_ENABLE 1
#define Y_AXIS_ENABLE 2
#define Z_AXIS_ENABLE 4
#define DIRECTION_ENABLE(AXES) (1 << AXES)
#define EFFECT_STATE_INACTIVE 0
ClassIdentifier EffectsCalculator::info = {
.name = "Effects" ,
.id = CLSID_EFFECTSCALC,
.visibility = ClassVisibility::hidden
};
const ClassIdentifier EffectsCalculator::getInfo(){
return info;
}
EffectsCalculator::EffectsCalculator() : CommandHandler("fx", CLSID_EFFECTSCALC),
Thread("EffectsCalculator", EFFECT_THREAD_MEM, EFFECT_THREAD_PRIO)
{
restoreFlash();
CommandHandler::registerCommands();
registerCommand("interpFactor", EffectsCalculator_commands::ffbinterpf, "Constant force interpolation factor", CMDFLAG_GET | CMDFLAG_SET);
registerCommand("filterCfFreq", EffectsCalculator_commands::ffbfiltercf, "Constant force filter frequency", CMDFLAG_GET | CMDFLAG_SET);
registerCommand("filterCfQ", EffectsCalculator_commands::ffbfiltercf_q, "Constant force filter Q-factor", CMDFLAG_GET | CMDFLAG_SET);
registerCommand("spring", EffectsCalculator_commands::spring, "Spring gain", CMDFLAG_GET | CMDFLAG_SET | CMDFLAG_INFOSTRING);
registerCommand("friction", EffectsCalculator_commands::friction, "Friction gain", CMDFLAG_GET | CMDFLAG_SET | CMDFLAG_INFOSTRING);
registerCommand("damper", EffectsCalculator_commands::damper, "Damper gain", CMDFLAG_GET | CMDFLAG_SET | CMDFLAG_INFOSTRING);
registerCommand("inertia", EffectsCalculator_commands::inertia, "Inertia gain", CMDFLAG_GET | CMDFLAG_SET | CMDFLAG_INFOSTRING);
registerCommand("effects", EffectsCalculator_commands::effects, "USed effects since reset (Info print as str). set 0 to reset", CMDFLAG_GET | CMDFLAG_SET | CMDFLAG_INFOSTRING);
registerCommand("effectsDetails", EffectsCalculator_commands::effectsDetails, "List effects details. set 0 to reset", CMDFLAG_GET | CMDFLAG_SET | CMDFLAG_STR_ONLY);
registerCommand("effectsForces", EffectsCalculator_commands::effectsForces, "List actual effects forces.", CMDFLAG_GET);
// registerCommand("monitorEffect", EffectsCalculator_commands::monitorEffect, "Get monitoring status. set to 1 to enable.", CMDFLAG_GET | CMDFLAG_SET);
registerCommand("damper_f", EffectsCalculator_commands::damper_f, "Damper biquad freq", CMDFLAG_GET | CMDFLAG_SET);
registerCommand("damper_q", EffectsCalculator_commands::damper_q, "Damper biquad q", CMDFLAG_GET | CMDFLAG_SET);
registerCommand("friction_f", EffectsCalculator_commands::friction_f, "Friction biquad freq", CMDFLAG_GET | CMDFLAG_SET);
registerCommand("friction_q", EffectsCalculator_commands::friction_q, "Friction biquad q", CMDFLAG_GET | CMDFLAG_SET);
registerCommand("inertia_f", EffectsCalculator_commands::inertia_f, "Inertia biquad freq", CMDFLAG_GET | CMDFLAG_SET);
registerCommand("inertia_q", EffectsCalculator_commands::inertia_q, "Inertia biquad q", CMDFLAG_GET | CMDFLAG_SET);
registerCommand("filterProfile_id", EffectsCalculator_commands::filterProfileId, "Conditional effects filter profile: 0 default; 1 custom", CMDFLAG_GET | CMDFLAG_SET);
// registerCommand("scaler_damper", EffectsCalculator_commands::scaler_damper, "Scaler damper", CMDFLAG_GET | CMDFLAG_INFOSTRING);
// registerCommand("scaler_friction", EffectsCalculator_commands::scaler_friction, "Scaler friction", CMDFLAG_GET | CMDFLAG_INFOSTRING);
// registerCommand("scaler_inertia", EffectsCalculator_commands::scaler_inertia, "Scaler inertia", CMDFLAG_GET | CMDFLAG_INFOSTRING);
registerCommand("frictionPctSpeedToRampup", EffectsCalculator_commands::frictionPctSpeedToRampup, "% of max speed for gradual increase", CMDFLAG_GET | CMDFLAG_SET);
//this->Start(); // Enable if we want to periodically monitor
}
EffectsCalculator::~EffectsCalculator()
{
}
bool EffectsCalculator::isActive()
{
return effects_active;
}
void EffectsCalculator::setActive(bool active)
{
effects_active = active;
}
/**
* Sets the mask where the direction enable bit is in the effect
*/
void EffectsCalculator::setDirectionEnableMask(uint8_t mask){
this->directionEnableMask = mask;
}
/*
If the metric is less than CP Offset - Dead Band, then the resulting force is given by the following formula:
force = Negative Coefficient * (q - (CP Offset – Dead Band))
Similarly, if the metric is greater than CP Offset + Dead Band, then the resulting force is given by the
following formula:
force = Positive Coefficient * (q - (CP Offset + Dead Band))
A spring condition uses axis position as the metric.
A damper condition uses axis velocity as the metric.
An inertia condition uses axis acceleration as the metric.
If the number of Condition report blocks is equal to the number of axes for the effect, then the first report
block applies to the first axis, the second applies to the second axis, and so on. For example, a two-axis
spring condition with CP Offset set to zero in both Condition report blocks would have the same effect as
the joystick self-centering spring. When a condition is defined for each axis in this way, the effect must
not be rotated.
If there is a single Condition report block for an effect with more than one axis, then the direction along
which the parameters of the Condition report block are in effect is determined by the direction parameters
passed in the Direction field of the Effect report block. For example, a friction condition rotated 45
degrees (in polar coordinates) would resist joystick motion in the northeast-southwest direction but would
have no effect on joystick motion in the northwest-southeast direction.
*/
/*
* Calculates the resulting torque for FFB effects
* Takes current position input scaled from -0x7fff to 0x7fff
* Outputs a torque value from -0x7fff to 0x7fff (not yet clipped)
*/
void EffectsCalculator::calculateEffects(std::vector<std::unique_ptr<Axis>> &axes)
{
for (auto &axis : axes) {
axis->calculateAxisEffects(isActive());
}
if(!isActive()){
return;
}
int32_t forceX = 0;
int32_t forceY = 0;
int32_t forceVector = 0;
uint8_t axisCount = axes.size();
bool validY = axisCount > 1;
#if MAX_AXIS == 3
int32_t forceZ = 0;
bool validZ = axisCount > 2;
#endif
for (uint8_t i = 0; i < effects_stats.size(); i++)
{
effects_stats[i].current = 0; // Reset active effect forces
}
for (uint8_t i = 0; i < MAX_EFFECTS; i++)
{
FFB_Effect *effect = &effects[i];
// Effect activated and not infinite (0 or 0xffff)
if (effect->state != EFFECT_STATE_INACTIVE && effect->duration != FFB_EFFECT_DURATION_INFINITE && effect->duration != 0){
// Start delay not yet reached
if(HAL_GetTick() < effect->startTime){
continue;
}
// If effect has expired make inactive
if (HAL_GetTick() > effect->startTime + effect->duration)
{
effect->state = EFFECT_STATE_INACTIVE;
calcStatsEffectType(effect->type, 0); // record a 0 on the ended force
}
}
// Filter out inactive effects
if (effect->state == EFFECT_STATE_INACTIVE)
{
continue;
}
//if (effect->conditionsCount == 0) {
forceVector = calcNonConditionEffectForce(effect);
//}
uint8_t directionEnableMask = this->directionEnableMask ? this->directionEnableMask : DIRECTION_ENABLE(axisCount);
if ( (effect->enableAxis & directionEnableMask) || (effect->enableAxis & X_AXIS_ENABLE))
{
int32_t newEffectForce = calcComponentForce(effect, forceVector, axes, 0);
calcStatsEffectType(effect->type, newEffectForce);
forceX += newEffectForce;
forceX = clip<int32_t, int32_t>(forceX, -0x7fff, 0x7fff); // Clip
}
if (validY && ((effect->enableAxis & directionEnableMask) || (effect->enableAxis & Y_AXIS_ENABLE)))
{
int32_t newEffectForce = calcComponentForce(effect, forceVector, axes, 0);
calcStatsEffectType(effect->type, newEffectForce);
forceY += newEffectForce;
forceY = clip<int32_t, int32_t>(forceY, -0x7fff, 0x7fff); // Clip
}
}
axes[0]->setEffectTorque(forceX);
if (validY)
{
axes[1]->setEffectTorque(forceY);
}
}
/**
* Calculates forces from a non conditional effect
* Periodic and constant effects
*/
int32_t EffectsCalculator::calcNonConditionEffectForce(FFB_Effect *effect) {
int32_t force_vector = 0;
int32_t magnitude = effect->magnitude;
// If using an envelope modulate the magnitude based on time
if(effect->useEnvelope){
magnitude = getEnvelopeMagnitude(effect);
}
switch (effect->type){
case FFB_EFFECT_CONSTANT:
{ // Constant force is just the force
force_vector = (int32_t)magnitude;
break;
}
case FFB_EFFECT_RAMP:
{
uint32_t elapsed_time = HAL_GetTick() - effect->startTime;
int32_t duration = effect->duration;
force_vector = (int32_t)effect->startLevel + ((int32_t)elapsed_time * (effect->endLevel - effect->startLevel)) / duration;
break;
}
case FFB_EFFECT_SQUARE:
{
uint32_t elapsed_time = HAL_GetTick() - effect->startTime;
int32_t force = ((elapsed_time + effect->phase) % ((uint32_t)effect->period + 2)) < (uint32_t)(effect->period + 2) / 2 ? -magnitude : magnitude;
force_vector = force + effect->offset;
break;
}
case FFB_EFFECT_TRIANGLE:
{
int32_t force = 0;
int32_t offset = effect->offset;
uint32_t elapsed_time = HAL_GetTick() - effect->startTime;
uint32_t phase = effect->phase;
uint32_t period = effect->period;
float periodF = period;
int32_t maxMagnitude = offset + magnitude;
int32_t minMagnitude = offset - magnitude;
uint32_t phasetime = (phase * period) / 35999;
uint32_t timeTemp = elapsed_time + phasetime;
float remainder = timeTemp % period;
float slope = ((maxMagnitude - minMagnitude) * 2) / periodF;
if (remainder > (periodF / 2))
force = slope * (periodF - remainder);
else
force = slope * remainder;
force += minMagnitude;
force_vector = force;
break;
}
case FFB_EFFECT_SAWTOOTHUP:
{
float offset = effect->offset;
uint32_t elapsed_time = HAL_GetTick() - effect->startTime;
uint32_t phase = effect->phase;
uint32_t period = effect->period;
float periodF = effect->period;
float maxMagnitude = offset + magnitude;
float minMagnitude = offset - magnitude;
int32_t phasetime = (phase * period) / 35999;
uint32_t timeTemp = elapsed_time + phasetime;
float remainder = timeTemp % period;
float slope = (maxMagnitude - minMagnitude) / periodF;
force_vector = (int32_t)(minMagnitude + slope * (period - remainder));
break;
}
case FFB_EFFECT_SAWTOOTHDOWN:
{
float offset = effect->offset;
uint32_t elapsed_time = HAL_GetTick() - effect->startTime;
float phase = effect->phase;
uint32_t period = effect->period;
float periodF = effect->period;
float maxMagnitude = offset + magnitude;
float minMagnitude = offset - magnitude;
int32_t phasetime = (phase * period) / 35999;
uint32_t timeTemp = elapsed_time + phasetime;
float remainder = timeTemp % period;
float slope = (maxMagnitude - minMagnitude) / periodF;
force_vector = (int32_t)(minMagnitude + slope * (remainder)); // reverse time
break;
}
case FFB_EFFECT_SINE:
{
float t = HAL_GetTick() - effect->startTime;
float freq = 1.0f / (float)(std::max<uint16_t>(effect->period, 2));
float phase = (float)effect->phase / (float)35999; //degrees
float sine = sinf(2.0 * M_PI * (t * freq + phase)) * magnitude;
force_vector = (int32_t)(effect->offset + sine);
break;
}
default:
return 0;
break;
}
return (force_vector * effect->gain) / 255;
}
void EffectsCalculator::setCfEffectsFreq(uint16_t freq){
this->cf_effects_freq = freq;
}
/*
* If the number of Condition report blocks is equal to the number of axes for the effect, then the first report
block applies to the first axis, the second applies to the second axis, and so on. For example, a two-axis
spring condition with CP Offset set to zero in both Condition report blocks would have the same effect as
the joystick self-centering spring. When a condition is defined for each axis in this way, the effect must
not be rotated.
If there is a single Condition report block for an effect with more than one axis, then the direction along
which the parameters of the Condition report block are in effect is determined by the direction parameters
passed in the Direction field of the Effect report block. For example, a friction condition rotated 45
degrees (in polar coordinates) would resist joystick motion in the northeast-southwest direction but would
have no effect on joystick motion in the northwest-southeast direction.
*/
int32_t EffectsCalculator::calcComponentForce(FFB_Effect *effect, int32_t forceVector, std::vector<std::unique_ptr<Axis>> &axes, uint8_t axis)
{
int32_t result_torque = 0;
uint16_t direction;
uint8_t con_idx = 0; // condition block index
metric_t *metrics = axes[axis]->getMetrics();
uint8_t axisCount = axes.size();
uint8_t directionEnableMask = this->directionEnableMask ? this->directionEnableMask : DIRECTION_ENABLE(axisCount);
if (effect->enableAxis & directionEnableMask)
{
direction = effect->directionX;
con_idx = axis;
}
else
{
direction = axis == 0 ? effect->directionX : effect->directionY;
con_idx = axis;
}
//bool useForceDirectionForConditionEffect = (effect->enableAxis == DIRECTION_ENABLE && axisCount > 1 && effect->conditionsCount == 1);
bool rotateConditionForce = (axisCount > 1); // && effect->conditionsCount < axisCount
float angle = ((float)direction * (2*M_PI) / 36000.0);
float angle_ratio = axis == 0 ? sin(angle) : -1 * cos(angle);
angle_ratio = rotateConditionForce ? angle_ratio : 1.0;
switch (effect->type)
{
case FFB_EFFECT_CONSTANT:
{
// Optional filtering to reduce spikes
if(effect->filter[con_idx] != nullptr) {
// if the filter is enabled we apply it
if (effect->filter[con_idx]->getFc() < 0.5 && effect->filter[0]->getFc() != 0.0)
{
forceVector = effect->filter[con_idx]->process(forceVector);
}
}
// Optional interpolation to smooth ffb
if(effect->interp[con_idx] != nullptr) {
// if the filter is enabled we apply it
uint8_t auto_interp_factor = floor(calcfrequency / this->cf_effects_freq);
if (effect->interp[con_idx]->getInterpFactor() == 1 && auto_interp_factor >= 2) //IF 1 or 0, Filter Disabled
{
forceVector = effect->interp[con_idx]->interpFloat(forceVector, auto_interp_factor);
}
else if(effect->interp[con_idx]->getInterpFactor() > 1)
{
forceVector = effect->interp[con_idx]->interpFloat(forceVector, 1);
}
}
}
case FFB_EFFECT_RAMP:
case FFB_EFFECT_SQUARE:
case FFB_EFFECT_TRIANGLE:
case FFB_EFFECT_SAWTOOTHUP:
case FFB_EFFECT_SAWTOOTHDOWN:
case FFB_EFFECT_SINE:
{
result_torque = -forceVector * angle_ratio;
break;
}
case FFB_EFFECT_SPRING:
{
float pos = metrics->pos;
result_torque -= calcConditionEffectForce(effect, pos, gain.spring, con_idx, scaler.spring, angle_ratio);
break;
}
/** | (rampup is from 0..5% of max velocity)
* | __________ (after use max coefficient)
* | /
* | /
* |-
* ------------------------ Velocity
* -|
* / |
* / |
* ------- |
* |
*/
case FFB_EFFECT_FRICTION: // TODO sometimes unstable.
{
float speed = metrics->speed * INTERNAL_SCALER_FRICTION;
int16_t offset = effect->conditions[con_idx].cpOffset;
int16_t deadBand = effect->conditions[con_idx].deadBand;
int32_t force = 0;
float speedRampupCeil = speedRampupPct();
// Effect is only active outside deadband + offset
if (abs((int32_t)speed - offset) > deadBand){
// remove offset/deadband from metric to compute force
speed -= (offset + (deadBand * (speed < offset ? -1 : 1)) );
// check if speed is in the 0..x% to rampup, if is this range, apply a sinusoidale function to smooth the torque (slow near 0, slow around the X% rampup
float rampupFactor = 1.0;
if (fabs (speed) < speedRampupCeil) { // if speed in the range to rampup we apply a sinus curbe to ramup
float phaseRad = M_PI * ((fabs (speed) / speedRampupCeil) - 0.5);// we start to compute the normalized angle (speed / normalizedSpeed@5%) and translate it of -1/2PI to translate sin on 1/2 periode
rampupFactor = ( 1 + sin(phaseRad ) ) / 2; // sin value is -1..1 range, we translate it to 0..2 and we scale it by 2
}
int8_t sign = speed >= 0 ? 1 : -1;
uint16_t coeff = speed < 0 ? effect->conditions[con_idx].negativeCoefficient : effect->conditions[con_idx].positiveCoefficient;
force = coeff * rampupFactor * sign;
//if there is a saturation, used it to clip result
if (effect->conditions[con_idx].negativeSaturation !=0 || effect->conditions[con_idx].positiveSaturation !=0) {
force = clip<int32_t, int32_t>(force, -effect->conditions[con_idx].negativeSaturation, effect->conditions[con_idx].positiveSaturation);
}
result_torque -= effect->filter[con_idx]->process( (((gain.friction + 1) * force) >> 8) * angle_ratio * scaler.friction);
}
break;
}
case FFB_EFFECT_DAMPER:
{
float speed = metrics->speed * INTERNAL_SCALER_DAMPER;
result_torque -= effect->filter[con_idx]->process(calcConditionEffectForce(effect, speed, gain.damper, con_idx, scaler.damper, angle_ratio));
break;
}
case FFB_EFFECT_INERTIA:
{
float accel = metrics->accel * INTERNAL_SCALER_INERTIA;
result_torque -= effect->filter[con_idx]->process(calcConditionEffectForce(effect, accel, gain.inertia, con_idx, scaler.inertia, angle_ratio)); // Bump *60 the inertia feedback
break;
}
default:
// Unsupported effect
break;
}
return (result_torque * global_gain) / 255; // Apply global gain
}
float EffectsCalculator::speedRampupPct() {
return (frictionPctSpeedToRampup / 100.0) * 32767; // compute the normalizedSpeed of pctToRampup factor
}
/**
* Calculates a conditional effect
* Takes care of deadband and offsets and scalers
* Gain of 255 = 1x. Prescale with scale factor
*/
int32_t EffectsCalculator::calcConditionEffectForce(FFB_Effect *effect, float metric, uint8_t gain,
uint8_t idx, float scale, float angle_ratio)
{
int16_t offset = effect->conditions[idx].cpOffset;
int16_t deadBand = effect->conditions[idx].deadBand;
int32_t force = 0;
float gainfactor = (float)(gain+1) / 256.0;
// Effect is only active outside deadband + offset
if (abs(metric - offset) > deadBand){
float coefficient = effect->conditions[idx].negativeCoefficient;
if(metric > offset){
coefficient = effect->conditions[idx].positiveCoefficient;
}
coefficient /= 0x7fff; // rescale the coefficient of effect
// remove offset/deadband from metric to compute force
metric = metric - (offset + (deadBand * (metric < offset ? -1 : 1)) );
force = clip<int32_t, int32_t>((coefficient * gainfactor * scale * (float)(metric)),
-effect->conditions[idx].negativeSaturation,
effect->conditions[idx].positiveSaturation);
}
return force * angle_ratio;
}
/**
* Modulates the magnitude of an effect based on time and attack/fade levels
* During attack time the strength changes from the initial attack level to the normal magnitude which is sustained
* until the fade time where the strength changes to the fade level until the stop time of the effect.
* Infinite effects can't have an envelope and return the normal magnitude.
*/
int32_t EffectsCalculator::getEnvelopeMagnitude(FFB_Effect *effect)
{
if(effect->duration == FFB_EFFECT_DURATION_INFINITE || effect->duration == 0){
return effect->magnitude; // Effect is infinite. envelope is invalid
}
int32_t scaler = abs(effect->magnitude);
uint32_t elapsed_time = HAL_GetTick() - effect->startTime;
if (elapsed_time < effect->attackTime && effect->attackTime != 0)
{
scaler = (scaler - effect->attackLevel) * elapsed_time;
scaler /= (int32_t)effect->attackTime;
scaler += effect->attackLevel;
}
if (elapsed_time > (effect->duration - effect->fadeTime) && effect->fadeTime != 0)
{
scaler = (scaler - effect->fadeLevel) * (effect->duration - elapsed_time); // Reversed
scaler /= (int32_t)effect->fadeTime;
scaler += effect->fadeLevel;
}
scaler = signbit(effect->magnitude) ? -scaler : scaler; // Follow original sign of magnitude because envelope has no sign (important for constant force)
return scaler;
}
void EffectsCalculator::setFilters(FFB_Effect *effect){
std::function<void(std::unique_ptr<Biquad> &)> fnptr = [=](std::unique_ptr<Biquad> &filter){};
std::function<void(std::unique_ptr<InterpFFB> &)> fnptr2 = [=](std::unique_ptr<InterpFFB> &interp){};
switch (effect->type)
{
case FFB_EFFECT_DAMPER:
fnptr = [=](std::unique_ptr<Biquad> &filter){
if (filter != nullptr)
filter->setBiquad(BiquadType::lowpass, this->filter[filterProfileId].damper.freq/ (float)calcfrequency, this->filter[filterProfileId].damper.q * qfloatScaler , (float)0.0);
else
filter = std::make_unique<Biquad>(BiquadType::lowpass, this->filter[filterProfileId].damper.freq / (float)calcfrequency, this->filter[filterProfileId].damper.q * qfloatScaler, (float)0.0);
};
break;
case FFB_EFFECT_FRICTION:
fnptr = [=](std::unique_ptr<Biquad> &filter){
if (filter != nullptr)
filter->setBiquad(BiquadType::lowpass, this->filter[filterProfileId].friction.freq / (float)calcfrequency, this->filter[filterProfileId].friction.q * qfloatScaler, (float)0.0);
else
filter = std::make_unique<Biquad>(BiquadType::lowpass, this->filter[filterProfileId].friction.freq / (float)calcfrequency, this->filter[filterProfileId].friction.q * qfloatScaler, (float)0.0);
};
break;
case FFB_EFFECT_INERTIA:
fnptr = [=](std::unique_ptr<Biquad> &filter){
if (filter != nullptr)
filter->setBiquad(BiquadType::lowpass, this->filter[filterProfileId].inertia.freq / (float)calcfrequency, this->filter[filterProfileId].inertia.q * qfloatScaler, (float)0.0);
else
filter = std::make_unique<Biquad>(BiquadType::lowpass, this->filter[filterProfileId].inertia.freq / (float)calcfrequency, this->filter[filterProfileId].inertia.q * qfloatScaler, (float)0.0);
};
break;
case FFB_EFFECT_CONSTANT:
fnptr = [=](std::unique_ptr<Biquad> &filter){
if (filter != nullptr)
filter->setBiquad(BiquadType::lowpass, this->filter[0].constant.freq / (float)calcfrequency, this->filter[0].constant.q * qfloatScaler, (float)0.0);
else
filter = std::make_unique<Biquad>(BiquadType::lowpass, this->filter[0].constant.freq / (float)calcfrequency, this->filter[0].constant.q * qfloatScaler, (float)0.0);
};
fnptr2 = [=](std::unique_ptr<InterpFFB> &interp){
if (interp != nullptr)
interp->setInterpFactor(this->interp.factor);
else
interp = std::make_unique<InterpFFB>(this->interp.factor);
};
break;
}
for (int i=0; i<MAX_AXIS; i++) {
fnptr(effect->filter[i]);
fnptr2(effect->interp[i]);
}
}
void EffectsCalculator::setGain(uint8_t gain)
{
global_gain = gain;
}
uint8_t EffectsCalculator::getGain() { return global_gain; }
void EffectsCalculator::setEffectsArray(FFB_Effect *pEffects)
{
effects = pEffects;
}
/*
* Read parameters from flash and restore settings
*/
void EffectsCalculator::restoreFlash()
{
uint16_t filterStorage;
if(Flash_Read(ADR_FFB_INTERP_FILTER, &filterStorage)){
this->interp.factor = filterStorage;
updateFilterSettingsForEffects(FFB_EFFECT_CONSTANT);
}
if (Flash_Read(ADR_FFB_CF_FILTER, &filterStorage))
{
uint32_t freq = filterStorage & 0x1FF;
uint8_t q = (filterStorage >> 9) & 0x7F;
checkFilterCoeff(&(this->filter[0].constant), freq, q);
updateFilterSettingsForEffects(FFB_EFFECT_CONSTANT);
}
if (Flash_Read(ADR_FFB_FR_FILTER, &filterStorage))
{
uint32_t freq = filterStorage & 0x1FF;
uint8_t q = (filterStorage >> 9) & 0x7F;
checkFilterCoeff(&(this->filter[CUSTOM_PROFILE_ID].friction), freq, q);
updateFilterSettingsForEffects(FFB_EFFECT_FRICTION);
}
if (Flash_Read(ADR_FFB_DA_FILTER, &filterStorage))
{
uint32_t freq = filterStorage & 0x1FF;
uint8_t q = (filterStorage >> 9) & 0x7F;
checkFilterCoeff(&(this->filter[CUSTOM_PROFILE_ID].damper), freq, q);
updateFilterSettingsForEffects(FFB_EFFECT_DAMPER);
}
if (Flash_Read(ADR_FFB_IN_FILTER, &filterStorage))
{
uint32_t freq = filterStorage & 0x1FF;
uint8_t q = (filterStorage >> 9) & 0x7F;
checkFilterCoeff(&(this->filter[CUSTOM_PROFILE_ID].inertia), freq, q);
updateFilterSettingsForEffects(FFB_EFFECT_INERTIA);
}
uint16_t effects = 0;
if(Flash_Read(ADR_FFB_EFFECTS1, &effects)){
gain.friction = (effects >> 8) & 0xff;
gain.inertia = (effects & 0xff);
}
if(Flash_Read(ADR_FFB_EFFECTS2, &effects)){
gain.damper = (effects >> 8) & 0xff;
gain.spring = (effects & 0xff);
}
if(Flash_Read(ADR_FFB_EFFECTS3, &effects)){
filterProfileId = (effects >> 8) & 0x03;
frictionPctSpeedToRampup = (effects & 0xff);
}
}
// Saves parameters to flash
void EffectsCalculator::saveFlash()
{
uint16_t filterStorage;
//save CF interpolation
Flash_Write(ADR_FFB_INTERP_FILTER, (uint16_t)interp.factor);
// save CF biquad
filterStorage = (uint16_t)filter[0].constant.freq & 0x1FF;
filterStorage |= ( (uint16_t)filter[0].constant.q & 0x7F ) << 9 ;
Flash_Write(ADR_FFB_CF_FILTER, filterStorage);
if(filterProfileId == CUSTOM_PROFILE_ID){ // Only attempt saving if custom profile active
// save Friction biquad
filterStorage = (uint16_t)filter[CUSTOM_PROFILE_ID].friction.freq & 0x1FF;
filterStorage |= ( (uint16_t)filter[CUSTOM_PROFILE_ID].friction.q & 0x7F ) << 9 ;
Flash_Write(ADR_FFB_FR_FILTER, filterStorage);
// save Damper biquad
filterStorage = (uint16_t)filter[CUSTOM_PROFILE_ID].damper.freq & 0x1FF;
filterStorage |= ( (uint16_t)filter[CUSTOM_PROFILE_ID].damper.q & 0x7F ) << 9 ;
Flash_Write(ADR_FFB_DA_FILTER, filterStorage);
// save Inertia biquad
filterStorage = (uint16_t)filter[CUSTOM_PROFILE_ID].inertia.freq & 0x1FF;
filterStorage |= ( (uint16_t)filter[CUSTOM_PROFILE_ID].inertia.q & 0x7F ) << 9 ;
Flash_Write(ADR_FFB_IN_FILTER, filterStorage);
}
// save the effect gain
uint16_t effects = gain.inertia | (gain.friction << 8);
Flash_Write(ADR_FFB_EFFECTS1, effects);
effects = gain.spring | (gain.damper << 8);
Flash_Write(ADR_FFB_EFFECTS2, effects);
// save the friction rampup zone
effects = frictionPctSpeedToRampup | (filterProfileId << 8);
Flash_Write(ADR_FFB_EFFECTS3, effects);
}
void EffectsCalculator::checkFilterCoeff(biquad_constant_t *filter, uint32_t freq,uint8_t q)
{
if(q == 0) {
q = 1;
}
if(freq == 0){
freq = calcfrequency / 2;
}
filter->freq = clip<uint32_t, uint32_t>(freq, 1, (calcfrequency / 2));
filter->q = clip<uint8_t, uint8_t>(q,0,127);
}
void EffectsCalculator::updateFilterSettingsForEffects(uint8_t type_effect) {
// loop on all effect in memory and setup new constant filter
for (uint8_t i = 0; i < MAX_EFFECTS; i++)
{
if (effects[i].type == type_effect)
{
setFilters(&effects[i]);
}
}
}
void EffectsCalculator::logEffectType(uint8_t type,bool remove){
if(type > 0 && type < 32){
if(remove){
if(effects_stats[type-1].nb > 0)
effects_stats[type-1].nb--;
if(!effects_stats[type-1].nb){
//effects_used &= ~(1<<(type-1)); // Only manual reset
//effects_stats[type-1].max = 0;
effects_stats[type-1].current = 0;
}
}else{
effects_used |= 1<<(type-1);
if( effects_stats[type-1].nb < 65535 ) {
effects_stats[type-1].nb ++;
}
}
}
}
void EffectsCalculator::logEffectState(uint8_t type,uint8_t state){
if(type > 0 && type < 32){
if(!state){
// effects_stats[type-1].max = 0;
effects_stats[type-1].current = 0;
}
}
}
void EffectsCalculator::calcStatsEffectType(uint8_t type, int16_t force){
if(type > 0 && type < 13) {
uint8_t arrayLocation = type - 1;
effects_stats[arrayLocation].current += force;
effects_stats[arrayLocation].max = std::max(effects_stats[arrayLocation].max, (int16_t)abs(force));
}
}
/**
* Prints a list of effects that were active at some point
* Does not reset when an effect is deactivated
*/
std::string EffectsCalculator::listEffectsUsed(bool details){
std::string effects_list = "";
if (!details) {
if(effects_used == 0){
return "None";
}
static const char *effects[12] = {"Constant,","Ramp,","Square,","Sine,","Triangle,","Sawtooth Up,","Sawtooth Down,","Spring,","Damper,","Inertia,","Friction,","Custom,"};
for (int i=0;i < 12; i++) {
if((effects_used >> i) & 1) {
effects_list += effects[i];
}
}
effects_list.pop_back();
} else {
bool firstItem = true;
for (int i=0;i < 12; i++) {
if (!firstItem) effects_list += ", ";
effects_list += "{\"max\":" + std::to_string(effects_stats[i].max);
effects_list += ", \"curr\":" + std::to_string(effects_stats[i].current);
effects_list += ", \"nb\":" + std::to_string(effects_stats[i].nb) + "}";
firstItem = false;
}
}
return effects_list.c_str();
}
/**
* Resets the effects_used flags
* If reinit is true it will set the flag again if the currently active effect number is not 0
*/
void EffectsCalculator::resetLoggedActiveEffects(bool reinit){
effects_used = 0;
if(reinit){
for (int i=0;i < 12; i++) {
if(effects_stats[i].nb > 0) {
effects_used |= 1<<(i);
}
}
}
}
CommandStatus EffectsCalculator::command(const ParsedCommand& cmd,std::vector<CommandReply>& replies){
switch(static_cast<EffectsCalculator_commands>(cmd.cmdId)){
case EffectsCalculator_commands::ffbinterpf:
if (cmd.type == CMDtype::get)
{
replies.emplace_back(interp.factor);
}
else if (cmd.type == CMDtype::set)
{
interp.factor = cmd.val;
updateFilterSettingsForEffects(FFB_EFFECT_CONSTANT);
}
break;
case EffectsCalculator_commands::ffbfiltercf:
if (cmd.type == CMDtype::get)
{
replies.emplace_back(filter[0].constant.freq);
}
else if (cmd.type == CMDtype::set)
{
checkFilterCoeff(&filter[0].constant, cmd.val, filter[0].constant.q);
updateFilterSettingsForEffects(FFB_EFFECT_CONSTANT);
}
break;
case EffectsCalculator_commands::ffbfiltercf_q:
if(cmd.type == CMDtype::info){
replies.emplace_back("scale:"+std::to_string(this->qfloatScaler));
}
else if (cmd.type == CMDtype::get)
{
replies.emplace_back(filter[0].constant.q);
}
else if (cmd.type == CMDtype::set)
{
checkFilterCoeff(&filter[0].constant, filter[0].constant.freq, cmd.val);
updateFilterSettingsForEffects(FFB_EFFECT_CONSTANT);
}
break;
case EffectsCalculator_commands::effects:
if (cmd.type == CMDtype::get)
{
replies.emplace_back(effects_used); //listEffectsUsed(cmd.val)
}
else if (cmd.type == CMDtype::set)
{
resetLoggedActiveEffects(cmd.val == 0);
}
else if (cmd.type == CMDtype::info)
{
replies.emplace_back(listEffectsUsed(cmd.val));
}
break;
case EffectsCalculator_commands::effectsDetails:
if (cmd.type == CMDtype::get)
{
replies.emplace_back(listEffectsUsed(true));
}
else if (cmd.type == CMDtype::set && cmd.val >= 0)
{
for (int i=0; i<12; i++) {
effects_stats[i].max = 0;
if(cmd.val > 0){
effects_stats[i].current = 0;
effects_stats[i].nb = 0;
}
}
resetLoggedActiveEffects(true);
}
break;
case EffectsCalculator_commands::effectsForces:
if (cmd.type == CMDtype::get)
{
for (size_t i=0; i < effects_stats.size(); i++) {
replies.emplace_back(effects_stats[i].current,effects_stats[i].nb);
}
}
break;
case EffectsCalculator_commands::spring:
if(cmd.type == CMDtype::info){
replies.emplace_back("scale:"+std::to_string(this->scaler.spring));
}else
return handleGetSet(cmd, replies, this->gain.spring);
break;
case EffectsCalculator_commands::friction:
if(cmd.type == CMDtype::info){
replies.emplace_back("scale:"+std::to_string(this->scaler.friction)+",factor:"+std::to_string(INTERNAL_SCALER_FRICTION));
}else
return handleGetSet(cmd, replies, this->gain.friction);
break;
case EffectsCalculator_commands::damper:
if(cmd.type == CMDtype::info){
replies.emplace_back("scale:"+std::to_string(this->scaler.damper)+",factor:"+std::to_string(INTERNAL_SCALER_DAMPER));
}else
return handleGetSet(cmd, replies, this->gain.damper);
break;
case EffectsCalculator_commands::inertia:
if(cmd.type == CMDtype::info){
replies.emplace_back("scale:"+std::to_string(this->scaler.inertia)+",factor:"+std::to_string(INTERNAL_SCALER_INERTIA));
}else
return handleGetSet(cmd, replies, this->gain.inertia);
break;
case EffectsCalculator_commands::damper_f:
if (cmd.type == CMDtype::get)
{
replies.emplace_back(filter[filterProfileId].damper.freq);
}
else if (cmd.type == CMDtype::set)
{
checkFilterCoeff(&filter[CUSTOM_PROFILE_ID].damper, cmd.val, filter[CUSTOM_PROFILE_ID].damper.q);
if (filterProfileId == CUSTOM_PROFILE_ID) updateFilterSettingsForEffects(FFB_EFFECT_DAMPER);
}
break;
case EffectsCalculator_commands::damper_q:
if (cmd.type == CMDtype::get)
{
replies.emplace_back(filter[filterProfileId].damper.q);
}
else if (cmd.type == CMDtype::set)
{
checkFilterCoeff(&filter[CUSTOM_PROFILE_ID].damper, filter[CUSTOM_PROFILE_ID].damper.freq, cmd.val);
if (filterProfileId == CUSTOM_PROFILE_ID) updateFilterSettingsForEffects(FFB_EFFECT_DAMPER);
}
break;
case EffectsCalculator_commands::friction_f:
if (cmd.type == CMDtype::get)
{
replies.emplace_back(filter[filterProfileId].friction.freq);
}
else if (cmd.type == CMDtype::set)
{
checkFilterCoeff(&filter[CUSTOM_PROFILE_ID].friction, cmd.val, filter[CUSTOM_PROFILE_ID].friction.q);
if (filterProfileId == CUSTOM_PROFILE_ID) updateFilterSettingsForEffects(FFB_EFFECT_FRICTION);
}
break;
case EffectsCalculator_commands::friction_q:
if (cmd.type == CMDtype::get)
{
replies.emplace_back(filter[filterProfileId].friction.q);
}
else if (cmd.type == CMDtype::set)
{
checkFilterCoeff(&filter[CUSTOM_PROFILE_ID].friction, filter[CUSTOM_PROFILE_ID].friction.freq, cmd.val);
if (filterProfileId == CUSTOM_PROFILE_ID) updateFilterSettingsForEffects(FFB_EFFECT_FRICTION);
}
break;
case EffectsCalculator_commands::inertia_f:
if (cmd.type == CMDtype::get)
{
replies.emplace_back(filter[filterProfileId].inertia.freq);
}
else if (cmd.type == CMDtype::set)
{
checkFilterCoeff(&filter[CUSTOM_PROFILE_ID].inertia, cmd.val, filter[CUSTOM_PROFILE_ID].inertia.q);
if (filterProfileId == CUSTOM_PROFILE_ID) updateFilterSettingsForEffects(FFB_EFFECT_INERTIA);
}
break;
case EffectsCalculator_commands::inertia_q:
if (cmd.type == CMDtype::get)
{
replies.emplace_back(filter[filterProfileId].inertia.q);
}
else if (cmd.type == CMDtype::set)
{
checkFilterCoeff(&filter[CUSTOM_PROFILE_ID].inertia, filter[CUSTOM_PROFILE_ID].inertia.freq, cmd.val);
if (filterProfileId == CUSTOM_PROFILE_ID) updateFilterSettingsForEffects(FFB_EFFECT_INERTIA);
}
break;
case EffectsCalculator_commands::frictionPctSpeedToRampup:
if (cmd.type == CMDtype::get)