-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGlissModes.cpp
10414 lines (10084 loc) · 296 KB
/
GlissModes.cpp
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
#include "TrillRackInterface.h"
#include "GlissModes.h"
#include "GlissProtocol.h"
#include <vector>
#include <libraries/Trill/Trill.h> // include this above NeoPixel or "HEX" gets screwed up
#include <libraries/Oscillator/Oscillator.h>
#include "LedSliders.h"
#include "preset.h"
#include "packed.h"
#include "bootloader.h"
#include <tuple>
#include <math.h>
#define SIZE(a) (std::tuple_size<decltype(a)>::value) // gives you a constexpr size of the tuple
#define FILL_ARRAY(name, ...) [this](){decltype(name) a; a.fill( __VA_ARGS__); return a;}()
static void updateAllPresets();
void requestNewMode(int mode, bool forceSave = false);
static void requestOldMode();
static constexpr size_t kNumSplits = 2;
float gBrightness = 1;
bool gModeWantsInteractionPreMenu = false;
bool gModeWantsMenuDelay = false;
bool gInPreMenu = false;
static constexpr rgb_t kRgbRed {255, 0, 0};
static constexpr rgb_t kRgbGreen {0, 255, 0};
static constexpr rgb_t kRgbOrange {255, 127, 0};
static constexpr rgb_t kRgbYellow {255, 255, 0};
static constexpr rgb_t kRgbWhite {0, 51, 255};
static constexpr rgb_t kRgbBlack {0, 0, 0};
static constexpr float kMenuButtonDefaultBrightness = 0.2;
static constexpr float kMenuButtonActiveBrightness = 0.7;
static constexpr float kDefaultThreshold = 0.03;
const float kAsymmetricalSplitPoint = 0.2;
static constexpr size_t kRangeLedsPerCentroid = 2;
constexpr size_t kMaxBtnStates = 7;
typedef std::array<rgb_t,kMaxBtnStates> AnimationColors;
static AnimationColors buttonColors = {
kRgbRed,
kRgbOrange,
kRgbYellow,
kRgbGreen,
kRgbWhite,
kRgbBlack, // dummy
kRgbBlack, // dummy
};
static constexpr rgb_t kDefaultSelectorColor = kRgbRed;
static constexpr rgb_t kSettingsContinuousAtDefaultColor = kRgbRed;
static constexpr rgb_t kSettingsContinuousOtherColor = kRgbYellow;
static const rgb_t& getQuantisedColor(const AnimationColors& colors, float v)
{
// sorry about the magic numbers below, I see no better way
unsigned int validColors = std::min(size_t(5), colors.size());
return colors[unsigned(v * 15) % validColors];
}
// When a WithFs kAnimationMode is enabled, there is a kPostAnimationTimeoutMs during
// which if you tap the selector, it is going to advance to the next value.
// If in kAnimationModeSolidGlowingWithFs, during this period (or actually slightly less than that),
// the button will glow to indicate it is "active". The "slightly less" is a perhaps unnecessary
// subtlety so that the glowing is slightly shorter than the actual active time of the selector,
// so if you see it glowing, by the time you tap it it's probably still active.
static constexpr uint32_t kPostAnimationGlowingPeriod = 700;
// ensure full period so that the transition is smooth
static constexpr uint32_t kPostAnimationGlowingMs = kPostAnimationGlowingPeriod * 5;
// + 300 is the "slightly less"
static constexpr uint32_t kPostAnimationTimeoutMs = kPostAnimationGlowingMs + 300;
#define ENABLE_DIRECT_CONTROL_MODE
#define ENABLE_RECORDER_MODE
#define ENABLE_SCALE_METER_MODE
//#define ENABLE_BALANCED_OSCS_MODE
#define ENABLE_EXPR_BUTTONS_MODE
constexpr size_t kNumModes = 3 // calibration, factorytest and erasesettings are always enabled
#ifdef ENABLE_DIRECT_CONTROL_MODE
+ 1
#endif
#ifdef ENABLE_RECORDER_MODE
+ 1
#endif
#ifdef ENABLE_SCALE_METER_MODE
+ 1
#endif
#ifdef ENABLE_BALANCED_OSCS_MODE
+ 1
#endif
#ifdef ENABLE_EXPR_BUTTONS_MODE
+ 1
#endif
#ifdef TEST_MODE
+ 1
#endif
; // kNumModes
static float standardDeviation(const float* data, size_t size)
{
// std (x) = sqrt ((1 / (N-1)) * SUM_i ((x(i) - mean(x))^2))
float mean = 0;
for(size_t n = 0; n < size; ++n)
{
// for small enough size we shouldn't have numerical problems and we save some
// multiplications by accumulating first and dividing in one go
mean += data[n];
}
mean /= float(size);
float sum = 0;
for(size_t n = 0; n < size; ++n)
{
float val = data[n] - mean;
sum += val * val;
}
return sqrtf((1.f / (size - 1)) * sum);
}
template <typename T>
T fixedOrientation(T pos, T max)
{
// allow to get a touchstrip value (e.g.: slider value or LED or PAD number) that represents a fixed point
// on the touch strip, regardless of its swapped state
return uio.touchStripSwapped() ? max - pos : pos;
}
#include <cmath>
size_t msToNumBlocks(BelaContext* context, float ms)
{
if(ms < 0)
ms = 0;
return std::round(context->analogSampleRate * ms / 1000.f / context->analogFrames);
}
static ButtonView ButtonViewSimplify(const ButtonView& in)
{
ButtonView btn = in;
if(btn.tripleClick)
{
btn.doubleClick = false;
btn.onset = false;
}
if(btn.doubleClick)
btn.onset = false;
if(btn.tripleClickOffset)
{
btn.doubleClickOffset = false;
btn.offset = false;
}
if(btn.doubleClickOffset)
btn.offset = false;
return btn;
}
class TouchTracker
{
public:
typedef uint32_t Id;
static constexpr Id kIdInvalid = -1;
typedef CentroidDetection::DATA_T Position;
struct TouchWithId
{
centroid_t touch = centroid_t{0, 0};
Position startLocation = 0;
Id id = kIdInvalid;
bool assigned = false;
};
private:
static_assert(std::is_signed<Position>::value); // if not signed, distance computation below may get fuzzy
static_assert(std::is_same<decltype(centroid_t::location),Position>::value);
static constexpr size_t kMaxTouches = 5;
size_t numTouches = 0;
size_t newId = 0;
Position maxTrackingDistance = 0.2;
std::array<unsigned int,kMaxTouches> sortedTouchIndices {};
std::array<unsigned int,kMaxTouches> sortedTouchIds {};
std::array<TouchWithId,kMaxTouches> sortedTouches {};
public:
static constexpr TouchWithId kInvalidTouch = { // I believe it is a compiler error that I need to defined these values again here
.touch = {0, 0},
.startLocation = 0,
.id = kIdInvalid,
.assigned = false,
};
private:
size_t getTouchOrderById(const Id id)
{
for(size_t n = 0; n < sortedTouches.size() && n < numTouches; ++n)
if(id == sortedTouches[n].id)
return n;
return numTouches;
}
// these are stored only so that we can detect frame changes.
// TODO: if there is a guarantee process() is called only on new frames,
// you can save memory by making these local variables there.
std::array<centroid_t,kMaxTouches> touches;
public:
void setMaxTrackingDistance(Position d)
{
maxTrackingDistance = d;
}
void process(const CentroidDetection& slider) {
// cache previous readings
std::array<TouchWithId,kMaxTouches> prevSortedTouches = sortedTouches;
size_t prevNumTouches = numTouches;
numTouches = slider.getNumTouches();
bool changed = (numTouches != prevNumTouches);
for(size_t n = 0; n < numTouches; ++n)
{
centroid_t newTouch = centroid_t{ .location = slider.touchLocation(n), .size = slider.touchSize(n) };
changed |= memcmp(&newTouch, &touches[n], sizeof(newTouch));
touches[n] = newTouch;
}
if(!changed)
{
// if we are a repetition of the previous frame, no need to process anything
// NOTE: right now we are already avoiding calling on duplicate frames,
// so we will return early only if two successive, distinct frames happen
// to be _exactly_ the same
return;
}
Id firstNewId = newId;
constexpr size_t kMaxPermutations = kMaxTouches * (kMaxTouches - 1);
Position distances[kMaxPermutations];
size_t permCodes[kMaxPermutations];
// calculate all distance permutations between previous and current touches
for(size_t i = 0; i < numTouches; ++i)
{
for(size_t p = 0; p < prevNumTouches; ++p)
{
size_t index = i * prevNumTouches + p; // permutation code [says between which touches we are calculating distance]
distances[index] = std::abs(touches[i].location - prevSortedTouches[p].touch.location);
permCodes[index] = index;
// sort permCodes and distances by distances from min to max
while(index && (distances[index] < distances[index - 1]))
{
std::swap(permCodes[index], permCodes[index - 1]);
std::swap(distances[index], distances[index - 1]);
index--;
}
}
}
size_t sorted = 0;
bool currAssigned[kMaxTouches] = {false};
bool prevAssigned[kMaxTouches] = {false};
// track touches assigning index according to shortest distance
for(size_t i = 0; i < numTouches * prevNumTouches; ++i)
{
size_t currentIndex = permCodes[i] / prevNumTouches;
size_t prevIndex = permCodes[i] % prevNumTouches;
if(distances[i] > maxTrackingDistance)
{
// if distance is too large, it must be a new touch
// TODO: this heuristic could be improved, e.g.: by tracking
// and considering past velocity
continue;
}
// avoid double assignment
if(!currAssigned[currentIndex] && !prevAssigned[prevIndex])
{
currAssigned[currentIndex] = true;
prevAssigned[prevIndex] = true;
sortedTouchIndices[currentIndex] = prevIndex;
sortedTouchIds[currentIndex] = prevSortedTouches[prevIndex].id;
sorted++;
}
}
// assign a free index to new touches
for(size_t i = 0; i < numTouches; i++)
{
if(!currAssigned[i])
{
sortedTouchIndices[i] = sorted++; // assign next free index
sortedTouchIds[i] = newId++;
}
}
// if some touches have disappeared...
// ...we have to shift all indices...
for(size_t i = prevNumTouches - 1; i != (size_t)-1; --i) // things you do to avoid warnings ...
{
if(!prevAssigned[i])
{
for(size_t j = 0; j < numTouches; ++j)
{
// ...only if touches that disappeared were before the current one
if(sortedTouchIndices[j] > i)
sortedTouchIndices[j]--;
}
}
}
// done! now update
for(size_t i = 0; i < numTouches; ++i)
{
// update tracked value
size_t idx = sortedTouchIndices[i];
const Id id = sortedTouchIds[i];
Position startLocation = -1;
bool assigned = false;
if(id >= firstNewId)
startLocation = touches[i].location;
else {
// find it in the prev arrays
// TODO: cache this value earlier so we can be faster here
for(size_t n = 0; n < prevNumTouches; ++n)
{
if(id == prevSortedTouches[n].id)
{
startLocation = prevSortedTouches[n].startLocation;
assigned = prevSortedTouches[n].assigned;
break;
}
}
}
assert(-1 != startLocation);
sortedTouches[idx] = TouchWithId {
.touch = touches[i],
.startLocation = startLocation,
.id = id,
.assigned = assigned,
};
}
// empty remaining touches. Not that they should ever be accessed...
for(size_t i = numTouches; i < sortedTouches.size(); ++i)
sortedTouches[i].id = kIdInvalid;
#if 0
for(size_t n = 0; n < numTouches; ++n)
{
auto& t = getTouchOrdered(n);
printf("[%u]%lu %.2f %.1f %d ", n, t.id, t.touch.location, t.startLocation, t.assigned);
}
if(numTouches)
printf("\n\r");
#endif
}
size_t getNumTouches()
{
return numTouches;
}
const TouchWithId& getTouchById(const Id id)
{
size_t n = getTouchOrderById(id);
if(n >= numTouches)
return kInvalidTouch;
else
return sortedTouches[n];
}
void setStartLocationById(const Id id, Position newLocation)
{
size_t n = getTouchOrderById(id);
if(n < numTouches)
sortedTouches[n].startLocation = newLocation;
}
void assignTouchById(const Id id)
{
size_t n = getTouchOrderById(id);
if(n < numTouches)
sortedTouches[n].assigned = true;
}
// the last is the most recent
const TouchWithId& getTouchOrdered(size_t n)
{
return sortedTouches[n];
}
const TouchWithId& getTouchMostRecent()
{
return sortedTouches[numTouches - 1];
}
const TouchWithId& getTouchOldest()
{
return sortedTouches[0];
}
};
TouchTracker gTouchTracker;
TouchTracker gTouchTrackerAlt;
static_assert(kNumOutChannels >= 2); // too many things to list depend on this in this file.
//#define TRIGGER_IN_TO_CLOCK_USES_MOVING_AVERAGE
// pick one of the two for more or less debugging printf and memory usage
//#define S(...) __VA_ARGS__
#define S(a) ;
//#define M(...) __VA_ARGS__
#define M(a)
//#define printf(...) // disable printf altogether
#define animationDuration(a) a
//#define animationDuration(a) (a * 0.1) // fast animations, useful for quick iterations
#if 0
// a small buffer that we can use to print before the UART is available. Data is cached and can be printed later
static char early_printf_buf[200];
static bool early_printf_done = false;
static size_t early_printf_ptr = 0;
template <typename... Ts>
static int early_printf(Ts... varargs) {
int available = sizeof(early_printf_buf) > early_printf_ptr ? sizeof(early_printf_buf) - early_printf_ptr : 0;
int printed = snprintf(early_printf_buf + early_printf_ptr, available, varargs...);
if(printed > available)
early_printf_ptr = sizeof(early_printf_buf);
else
early_printf_ptr += printed;
return printed;
}
static void do_early_printf()
{
if(!early_printf_done)
printf("%.*s\n", early_printf_ptr, early_printf_buf);
early_printf_done = true;
}
#else
#define early_printf(...)
#define do_early_printf()
#endif
extern int gAlt;
typedef TrillRackInterface TRI; // shorthand
extern TRI tri;
extern const unsigned int kNumLeds;
extern std::vector<unsigned int> padsToOrderMap;
extern NeoPixelT<kNumLeds> np;
extern Trill trill;
extern std::array<float,kNumOutChannels> gManualAnOut;
std::array<Oscillator, 2> oscillators;
const std::array<rgb_t, 2> gBalancedLfoColorsInit = {{kRgbYellow, kRgbGreen}};
std::array<rgb_t, 2> gBalancedLfoColors; // copy so that we can set them via MIDI without changing defaults
std::array<float,kNumOutChannels> gCustomSmoothedAlpha;
std::array<OutMode,kNumOutChannels> gOutMode { kOutModeManualBlock, kOutModeManualBlock };
int gCounter = 0;
int gSubMode = 0;
UiOrientation uio;
enum AnimationMode
{
kAnimationModeSolid,
kAnimationModeSolidWithFs,
kNumAnimationMode,
kAnimationModeSolidGlowingWithFs,
kAnimationModeConsistent,
kAnimationModeConsistentWithFs,
kAnimationModeSolidDefaultWithFs,
kAnimationModeCustom,
};
static AnimationMode gAnimationMode = kAnimationModeSolid;
static bool hasFsAnimation()
{
switch(gAnimationMode)
{
case kAnimationModeConsistentWithFs:
case kAnimationModeSolidWithFs:
case kAnimationModeSolidDefaultWithFs:
case kAnimationModeSolidGlowingWithFs:
return true;
default:
return false;
}
}
Override gOverride;
static bool gInUsesCalibration;
static bool gOutUsesCalibration;
static bool gInUsesRange;
static std::array<bool,kNumOutChannels> gOutUsesRange;
// Recording the gesture
static constexpr size_t kMaxRecordBytes = 80000;
const float kSizeScale = 10000; // value used internally for rescaling the slider
static float gSizeScale = kSizeScale; // current, active value. Gets overriden upon loading from preset
static constexpr float kFixedCentroidSize = 0.3;
static constexpr float kDummySize = 0.4f * kFixedCentroidSize;
LedSliders ledSliders;
LedSliders ledSlidersAlt;
ButtonView menuBtn;
ButtonView performanceBtn;
void resample(float* out, unsigned int nOut, float* in, unsigned int nIn)
{
#if 0 // naive: sum all input energy into outputs
for(unsigned int no = 0; no < nOut; ++no) {
out[no] = 0;
unsigned int niStart = no * nIn / nOut;
unsigned int niEnd = (no + 1) * nIn / nOut;
for(unsigned int ni = niStart; ni < niEnd; ++ni) {
out[no] += in[ni];
}
}
#endif
#if 1 // weighted sum
// How many accompanying LEDs are on
float r = 2;
for(unsigned int no = 0; no < nOut; ++no) {
out[no] = 0;
for(unsigned int ni = 0; ni < nIn; ++ni) {
float fracInIdx = no * nIn / (float)nOut;
float weight = (1 - (std::abs(fracInIdx - ni) / r));
weight = std::max(0.f, weight); // clip to 0
out[no] += in[ni] * weight;
}
}
#endif
}
template <typename T, typename U>
void sort(T* out, U* in, unsigned int* order, unsigned int size)
{
for(unsigned int n = 0; n < size; ++n)
out[n] = in[order[n]];
}
static uint32_t gClockPeriodUpdateCounter = 0;
static float gClockPeriod = 10000; // arbitrary init to avoid divisions by zero. TODO: instead check before using it
static uint64_t gClockPeriodLastUpdate = -1;
static constexpr float kTriggerInOnThreshold = 0.46667; // approx 2V
void triggerInToClock(BelaContext* context)
{
const float kTriggerInOffThreshold = kTriggerInOnThreshold - 0.05;
static bool lastTrigPrimed = false;
static size_t lastTrig = 0;
for(size_t n = 0; n < context->analogFrames; ++n)
{
static bool lastIn = false;
// hysteresis
float threshold = lastIn ? kTriggerInOffThreshold : kTriggerInOnThreshold;
bool in = analogRead(context, n, 0) > threshold;
if(in && !lastIn)
{
size_t newTrig = context->audioFramesElapsed + n;
if(lastTrigPrimed)
{
size_t newPeriod = newTrig - lastTrig;
#ifdef TRIGGER_IN_TO_CLOCK_USES_MOVING_AVERAGE
enum { kInferClockNumPeriods = 5 };
static size_t lastPeriods[kInferClockNumPeriods] = {0};
static size_t currentPeriod = 0;
static size_t periodSum = 0;
// moving average
periodSum -= lastPeriods[currentPeriod];
lastPeriods[currentPeriod] = newPeriod;
periodSum += newPeriod;
// TODO: it may be that when the clock is changing it's best to follow
// it without moving average, especially if it's slow
float averagePeriod = float(periodSum) / kInferClockNumPeriods;
currentPeriod++;
if(currentPeriod == kInferClockNumPeriods)
currentPeriod = 0;
gClockPeriod = averagePeriod;
#else // TRIGGER_IN_TO_CLOCK_USES_MOVING_AVERAGE
gClockPeriod = newPeriod;
gClockPeriodUpdateCounter++;
gClockPeriodLastUpdate = context->audioFramesElapsed + n;
#endif // TRIGGER_IN_TO_CLOCK_USES_MOVING_AVERAGE
}
lastTrig = newTrig;
lastTrigPrimed = true;
}
lastIn = in;
}
}
static bool clockInIsActive(BelaContext* context)
{
uint64_t now = context->audioFramesElapsed + context->analogFrames - 1; // rounded up to the end of the frame
if(now < gClockPeriodLastUpdate)
return false;
else
return now - gClockPeriodLastUpdate < 10.f * context->analogSampleRate;
}
typedef enum {
kBottomUp,
kTopBottom,
} LedSlidersOrder;
template <typename T>
static inline void applyOrder(LedSlidersOrder order, T& first, T& last, T max)
{
if(kBottomUp == order)
return;
first = max - first;
last = max - last;
std::swap(first, last);
};
static void ledSlidersSetupMultiSlider(LedSliders& ls, std::vector<rgb_t> const& colors, const LedSlider::LedMode_t& mode, bool setInitial, size_t maxNumCentroids, LedSlidersOrder order = kBottomUp, bool asymmetricalSplit = false)
{
std::vector<LedSliders::delimiters_t> boundaries;
size_t numSplits = colors.size();
if(!numSplits)
return;
float guardPads = 0.07; //relative to the whole slider
float guardLeds = 2;
float nextPad = 0;
size_t nextLed = 0;
float shortenFirst = 0;
if(uio.menuSwapped() && 5 == numSplits && 2 == LedSlider::kDefaultNumWeights)
{
// With 2 guardLeds, each split uses 3 LEDs; however
// with kDefaultNumWeights == 2, this in practice means that only 2 LEDs are used
// and so the last LEDs will be dark with the normal orientation.
// here we provide an adjustment so that 1U looks like jacks on top.
shortenFirst = 1;
}
for(size_t n = 0; n < numSplits; ++n)
{
float coeff = 1;
if(2 == numSplits && asymmetricalSplit)
{
bool longerSplit;
if(kTopBottom == order)
longerSplit = 0 == n;
else
longerSplit = 1 == n;
coeff = 2 * (longerSplit ? (1.f - kAsymmetricalSplitPoint) : kAsymmetricalSplitPoint);
}
float activeLeds = ((kNumLeds - (guardLeds * (numSplits - 1))) * coeff) / numSplits - (0 == n ? shortenFirst : 0);
size_t firstLed = nextLed;
size_t lastLed = firstLed + activeLeds;
if(2 == numSplits && numSplits - 1 == n && lastLed != kNumLeds)
{
// it's hard to evenly distribute an arbitrary number
// of splits across 23 LEDs.
// In the common case of two splits, we ensure
// they are evenly split and extend to the last LED
int diff = kNumLeds - lastLed;
if(diff > 0)
{
lastLed += diff;
firstLed += diff;
}
}
applyOrder(order, firstLed, lastLed, kNumLeds);
float activePads = ((1.f - (guardPads * (numSplits - 1))) * coeff) / numSplits;
float firstPad = nextPad;
float lastPad = firstPad + activePads;
applyOrder(order, firstPad, lastPad, 1.f);
boundaries.push_back({
.sliderMin = firstPad,
.sliderMax = lastPad,
.firstLed = firstLed,
.lastLed = lastLed,
});
nextPad += activePads + guardPads;
nextLed += activeLeds + guardLeds;
}
LedSliders::Settings settings = {
.sizeScale = gSizeScale,
.boundaries = boundaries,
.maxNumCentroids = {maxNumCentroids},
.np = &np,
};
ls.setup(settings);
assert(numSplits == ls.sliders.size());
for(size_t n = 0; n < numSplits; ++n)
{
ls.sliders[n].setColor(colors[n]);
ls.sliders[n].setLedMode(mode);
if(setInitial)
{
centroid_t centroid;
centroid.location = 0.5;
centroid.size = kMenuButtonDefaultBrightness;
ls.sliders[n].setLedsCentroids(¢roid, 1);
}
}
}
#if 0
template <size_t T>
static void ledSlidersExpButtonsProcess(LedSliders& sl, std::array<float,2>& outs, float scale, std::array<float,T>const& offsets = {})
{
int highest = -1;
for(size_t n = 0; n < sl.sliders.size(); ++n)
{
if(sl.sliders[n].getNumTouches())
highest = n;
}
bool allFollow = false;
for(auto& o : outs)
o = 0;
for(size_t n = 0; n < sl.sliders.size(); ++n)
{
centroid_t centroid;
if(highest == int(n) || allFollow)
{
centroid.location = sl.sliders[n].compoundTouchLocation();
centroid.size = sl.sliders[n].compoundTouchSize();
if(outs.size() > 0)
outs[0] = centroid.location * scale + (offsets.size() > n ? offsets[n] : 0);
if(outs.size() > 1)
outs[1] = centroid.size;
} else {
// dimmed for "inactive"
centroid.size = 0.1;
centroid.location = 0.5;
}
sl.sliders[n].setLedsCentroids(¢roid, 1);
}
}
void ledSlidersFixedButtonsProcess(LedSliders& sl, std::vector<bool>& states, std::vector<size_t>& onsets, std::vector<size_t>& offsets, bool onlyUpdateStates)
{
onsets.resize(0);
offsets.resize(0);
states.resize(sl.sliders.size());
for(size_t n = 0; n < sl.sliders.size(); ++n)
{
bool state = sl.sliders[n].getNumTouches();
bool pastState = states[n];
if(!onlyUpdateStates)
{
bool shouldUpdateCentroids = false;
if(state && !pastState) {
onsets.emplace_back(n);
shouldUpdateCentroids = true;
} else if (!state && pastState) {
offsets.emplace_back(n);
shouldUpdateCentroids = true;
}
if(shouldUpdateCentroids)
{
centroid_t centroid;
centroid.location = 0.5;
// dimmed for "inactive"
// full brightness for "active"
centroid.size = state ? 1 : 0.1;
sl.sliders[n].setLedsCentroids(¢roid, 1);
}
}
states[n] = state;
}
}
#endif
static void ledSlidersSetupOneSlider(rgb_t color, LedSlider::LedMode_t mode)
{
ledSlidersSetupMultiSlider(ledSliders, {color}, mode, false, 1);
}
static void ledSlidersSetupTwoSliders(rgb_t color, LedSlider::LedMode_t mode, LedSlidersOrder order, bool asymmetricalSplit = false)
{
ledSlidersSetupMultiSlider(ledSliders, {color, color}, mode, false, 1, order, asymmetricalSplit);
}
bool modeChangeBlinkSplit(double ms, rgb_t colors[2], size_t endFirst, size_t startSecond)
{
bool done = false;
double period = 200;
// blink on-off-on-off
if(
ms < 1 *period
|| (ms >= 2 * period && ms < 3 * period)
){
for(unsigned int n = 0; n < endFirst; ++n)
np.setPixelColor(kNumLeds - 1 - n, colors[0].r, colors[0].g, colors[0].b);
for(unsigned int n = startSecond; n < kNumLeds; ++n)
np.setPixelColor(kNumLeds - 1 - n, colors[1].r, colors[1].g, colors[1].b);
} else if (
(ms >= 1 * period && ms < 2 * period)
|| (ms >= 3 * period && ms < 4 * period)
){
for(unsigned int n = 0; n < kNumLeds; ++n)
np.setPixelColor(n, 0, 0, 0);
} else if (ms >= 4 * period) {
done = true;
}
return done;
}
// MODE Alt: settings UI
bool modeAlt_setup()
{
ledSlidersSetupMultiSlider(
ledSlidersAlt,
{
kRgbRed,
kRgbRed,
kRgbRed,
kRgbRed,
kRgbGreen,
},
LedSlider::MANUAL_CENTROIDS,
true,
1
);
return true;
}
// A circular buffer. When touch sz goes to zero, retrieve the oldest
// element in the buffer so we can hope to get more stable values instead
// of whatever spurious reading we got while releasing the touch
class AutoLatcher {
public:
AutoLatcher() {
reset();
}
void reset()
{
idx = 0;
validFrames = 0;
lastOutSize = 0;
pastFrames.fill({0, 0});
delay = 0;
}
// return: may modify frame and latchStarts
void process(bool isNew, centroid_t& frame, bool& latchStarts)
{
if(!isNew && validFrames)
{
frame.size = lastOutSize;
return;
}
if(validFrames && pastFrames[getPastFrame(0)].size && !frame.size) // if size went to zero
{
if(validFrames) {
// keep whatever size we have been using,
// which may already be a delayed version,
// designed to jump over the release transient
frame.size = lastOutSize;
// For location, things are more complicated
frame.location = guessHoldValue();
}
latchStarts = true;
idx = 0;
validFrames = 0;
delay = 0;
} else if(frame.size) {
// store current input value for later
pastFrames[idx] = frame;
validFrames++;
++idx;
if(idx >= pastFrames.size())
idx = 0;
// if we are still touching
// apply a variable delay to the output size
if(validFrames < kMaxSizeDelay)
{
// we are just at the beginning of a touch: get the most recent size
delay = 0;
} else if (delay / 2 < kMaxSizeDelay)
{
// the touch has been going on for a while, we need to progressively
// reach the max delay
delay++;
}
float newSize = frame.size; // no delay!
if(delay >= 2)
{
// read increasingly older touch size until maximum kMaxSizeDelay.
// The / 2 here and above ensures we increase the actual delay
// only every other frame which ensures we don't hold the same
// value for a long time while the delay increases.
newSize = pastFrames[getPastFrame(delay / 2 - 1)].size;
}
// output the delayed size
frame.size = newSize;
lastOutSize = frame.size;
} else {
lastOutSize = 0;
}
}
private:
ssize_t getOldestFrame()
{
return getPastFrame(kHistoryLength - 1);
}
// back = 0 : newest frame
// back = kHistoryLength - 1 : oldest frame
ssize_t getPastFrame(size_t back)
{
if(!validFrames)
return -1;
size_t lastGood;
back = std::min(back, kHistoryLength - 1);
back = std::min(back, validFrames - 1);
// go back in the circular buffer to the oldest valid value.
lastGood = (idx - 1 - back + kHistoryLength) % kHistoryLength;
return lastGood;
}
float guessHoldValue()
{
static constexpr size_t kMaxSpuriousRelease = 5;
// guess location value to hold
centroid_t frame0 = pastFrames[getPastFrame(0)];
if(0 == frame0.location || 1 == frame0.location)
{
// If sliding off either edge of the slider,
// latch to the actual edge.
return frame0.location;
} else {
size_t length = std::min(validFrames, kHistoryLength);
if(length < 2 * kMaxSpuriousRelease)
{
// if we don't have enough samples, take them at face value:
// hold the last one
return pastFrames[getPastFrame(0)].location;
}
// otherwise, look at the temporal evolution of the samples in the buffer
std::array<float,kHistoryLength> history;
for(size_t n = 0; n < length; ++n)
history[n] = pastFrames[getPastFrame(length - 1 - n)].location;
float std = standardDeviation(history.data(), length - kMaxSpuriousRelease);
float releaseDiff = 0;
float releaseRef = history[length - kMaxSpuriousRelease - 1];
// see how much the last few frames depart from a 'supposedly good' one
for(size_t n = length - kMaxSpuriousRelease; n < length; ++n)
releaseDiff = std::max(releaseDiff, std::abs(releaseRef - history[n]));
if(std < 0.004 && releaseDiff < 0.035)
{
// recent history was static and the release transient
// was accidental:
// get the oldest frame in history
return pastFrames[getOldestFrame()].location;
} else {
// recent history was dynamic or the release transient
// was intentional:
// get most recent frame
return pastFrames[getPastFrame(0)].location;
}
}
}
static constexpr size_t kHistoryLength = 15;
static constexpr size_t kMaxSizeDelay = std::min(12u, kHistoryLength - 1); // could be even less than this, if desired
std::array<centroid_t,kHistoryLength> pastFrames;
size_t idx;
size_t validFrames;
size_t delay;
float lastOutSize;
#if 0
public: static void test()
{
AutoLatcher a;
std::array<centroid_t,80> inputs;
for(size_t n = 0; n < inputs.size(); ++n)
{
float val = 10 + n;
if(n < 1)
val = 0;
if(n > 40)
val = 0;
inputs[n] = { val, val };
}
a.reset();
for(size_t n = 0; n < inputs.size(); ++n)
{
bool latchStarts = false;
auto frame = inputs[n];
a.process(frame, latchStarts);
printf("%2zu %.f,%.f -->> %.f,%.f %s ",
n, inputs[n].location, inputs[n].size, frame.location,
frame.size, latchStarts ? "LATCH" : " ");
printf("idx: %zu, validFrames: %zu, delay: %zd, latest: %zd, actual oldest: %zd\n",
a.idx, a.validFrames, a.delay / 2 - 1, a.getPastFrame(0), a.getOldestFrame());
if(latchStarts)
{
printf("ITEMS %zu\n", a.validFrames);
for(size_t p = 0; p < a.pastFrames.size(); ++p)
{
auto f = a.pastFrames[p];
printf("[%zu] {%.0f %.0f}, ", p, f.location, f.size);
}
printf("\n");
}
printf("=====================\n");
}
}
#endif
};
class LatchProcessor {
static constexpr size_t kMaxNumValues = 2;
public:
enum Reason {
kLatchNone,
kLatchAuto,
kLatchManual,
kLatchSingleFrame,
};
LatchProcessor() {
reset();
}
void reset()
{
isLatched = {kLatchNone, kLatchNone};
unlatchArmed = {false, false};
latchedValues = {0, 0};
for(auto& al : autoLatchers)
al.reset();