forked from hzeller/rpi-rgb-led-matrix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo-main.cc
1241 lines (1094 loc) · 32.9 KB
/
demo-main.cc
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
// -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
//
// This code is public domain
// (but note, once linked against the led-matrix library, this is
// covered by the GPL v2)
//
// This is a grab-bag of various demos and not very readable.
#include "led-matrix.h"
#include "threaded-canvas-manipulator.h"
#include "pixel-mapper.h"
#include "graphics.h"
#include <assert.h>
#include <getopt.h>
#include <limits.h>
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <algorithm>
using std::min;
using std::max;
#define TERM_ERR "\033[1;31m"
#define TERM_NORM "\033[0m"
using namespace rgb_matrix;
volatile bool interrupt_received = false;
static void InterruptHandler(int signo) {
interrupt_received = true;
}
/*
* The following are demo image generators. They all use the utility
* class ThreadedCanvasManipulator to generate new frames.
*/
// Simple generator that pulses through RGB and White.
class ColorPulseGenerator : public ThreadedCanvasManipulator {
public:
ColorPulseGenerator(RGBMatrix *m) : ThreadedCanvasManipulator(m), matrix_(m) {
off_screen_canvas_ = m->CreateFrameCanvas();
}
void Run() {
uint32_t continuum = 0;
while (running() && !interrupt_received) {
usleep(5 * 1000);
continuum += 1;
continuum %= 3 * 255;
int r = 0, g = 0, b = 0;
if (continuum <= 255) {
int c = continuum;
b = 255 - c;
r = c;
} else if (continuum > 255 && continuum <= 511) {
int c = continuum - 256;
r = 255 - c;
g = c;
} else {
int c = continuum - 512;
g = 255 - c;
b = c;
}
off_screen_canvas_->Fill(r, g, b);
off_screen_canvas_ = matrix_->SwapOnVSync(off_screen_canvas_);
}
}
private:
RGBMatrix *const matrix_;
FrameCanvas *off_screen_canvas_;
};
// Simple generator that pulses through brightness on red, green, blue and white
class BrightnessPulseGenerator : public ThreadedCanvasManipulator {
public:
BrightnessPulseGenerator(RGBMatrix *m)
: ThreadedCanvasManipulator(m), matrix_(m) {}
void Run() {
const uint8_t max_brightness = matrix_->brightness();
const uint8_t c = 255;
uint8_t count = 0;
while (running() && !interrupt_received) {
if (matrix_->brightness() < 1) {
matrix_->SetBrightness(max_brightness);
count++;
} else {
matrix_->SetBrightness(matrix_->brightness() - 1);
}
switch (count % 4) {
case 0: matrix_->Fill(c, 0, 0); break;
case 1: matrix_->Fill(0, c, 0); break;
case 2: matrix_->Fill(0, 0, c); break;
case 3: matrix_->Fill(c, c, c); break;
}
usleep(20 * 1000);
}
}
private:
RGBMatrix *const matrix_;
};
class SimpleSquare : public ThreadedCanvasManipulator {
public:
SimpleSquare(Canvas *m) : ThreadedCanvasManipulator(m) {}
void Run() {
const int width = canvas()->width() - 1;
const int height = canvas()->height() - 1;
// Borders
DrawLine(canvas(), 0, 0, width, 0, Color(255, 0, 0));
DrawLine(canvas(), 0, height, width, height, Color(255, 255, 0));
DrawLine(canvas(), 0, 0, 0, height, Color(0, 0, 255));
DrawLine(canvas(), width, 0, width, height, Color(0, 255, 0));
// Diagonals.
DrawLine(canvas(), 0, 0, width, height, Color(255, 255, 255));
DrawLine(canvas(), 0, height, width, 0, Color(255, 0, 255));
}
};
class GrayScaleBlock : public ThreadedCanvasManipulator {
public:
GrayScaleBlock(Canvas *m) : ThreadedCanvasManipulator(m) {}
void Run() {
const int sub_blocks = 16;
const int width = canvas()->width();
const int height = canvas()->height();
const int x_step = max(1, width / sub_blocks);
const int y_step = max(1, height / sub_blocks);
uint8_t count = 0;
while (running() && !interrupt_received) {
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
int c = sub_blocks * (y / y_step) + x / x_step;
switch (count % 4) {
case 0: canvas()->SetPixel(x, y, c, c, c); break;
case 1: canvas()->SetPixel(x, y, c, 0, 0); break;
case 2: canvas()->SetPixel(x, y, 0, c, 0); break;
case 3: canvas()->SetPixel(x, y, 0, 0, c); break;
}
}
}
count++;
sleep(2);
}
}
};
// Simple class that generates a rotating block on the screen.
class RotatingBlockGenerator : public ThreadedCanvasManipulator {
public:
RotatingBlockGenerator(Canvas *m) : ThreadedCanvasManipulator(m) {}
uint8_t scale_col(int val, int lo, int hi) {
if (val < lo) return 0;
if (val > hi) return 255;
return 255 * (val - lo) / (hi - lo);
}
void Run() {
const int cent_x = canvas()->width() / 2;
const int cent_y = canvas()->height() / 2;
// The square to rotate (inner square + black frame) needs to cover the
// whole area, even if diagnoal. Thus, when rotating, the outer pixels from
// the previous frame are cleared.
const int rotate_square = min(canvas()->width(), canvas()->height()) * 1.41;
const int min_rotate = cent_x - rotate_square / 2;
const int max_rotate = cent_x + rotate_square / 2;
// The square to display is within the visible area.
const int display_square = min(canvas()->width(), canvas()->height()) * 0.7;
const int min_display = cent_x - display_square / 2;
const int max_display = cent_x + display_square / 2;
const float deg_to_rad = 2 * 3.14159265 / 360;
int rotation = 0;
while (running() && !interrupt_received) {
++rotation;
usleep(15 * 1000);
rotation %= 360;
for (int x = min_rotate; x < max_rotate; ++x) {
for (int y = min_rotate; y < max_rotate; ++y) {
float rot_x, rot_y;
Rotate(x - cent_x, y - cent_x,
deg_to_rad * rotation, &rot_x, &rot_y);
if (x >= min_display && x < max_display &&
y >= min_display && y < max_display) { // within display square
canvas()->SetPixel(rot_x + cent_x, rot_y + cent_y,
scale_col(x, min_display, max_display),
255 - scale_col(y, min_display, max_display),
scale_col(y, min_display, max_display));
} else {
// black frame.
canvas()->SetPixel(rot_x + cent_x, rot_y + cent_y, 0, 0, 0);
}
}
}
}
}
private:
void Rotate(int x, int y, float angle,
float *new_x, float *new_y) {
*new_x = x * cosf(angle) - y * sinf(angle);
*new_y = x * sinf(angle) + y * cosf(angle);
}
};
class ImageScroller : public ThreadedCanvasManipulator {
public:
// Scroll image with "scroll_jumps" pixels every "scroll_ms" milliseconds.
// If "scroll_ms" is negative, don't do any scrolling.
ImageScroller(RGBMatrix *m, int scroll_jumps, int scroll_ms = 30)
: ThreadedCanvasManipulator(m), scroll_jumps_(scroll_jumps),
scroll_ms_(scroll_ms),
horizontal_position_(0),
matrix_(m) {
offscreen_ = matrix_->CreateFrameCanvas();
}
virtual ~ImageScroller() {
Stop();
WaitStopped(); // only now it is safe to delete our instance variables.
}
// _very_ simplified. Can only read binary P6 PPM. Expects newlines in headers
// Not really robust. Use at your own risk :)
// This allows reload of an image while things are running, e.g. you can
// life-update the content.
bool LoadPPM(const char *filename) {
FILE *f = fopen(filename, "r");
// check if file exists
if (f == NULL && access(filename, F_OK) == -1) {
fprintf(stderr, "File \"%s\" doesn't exist\n", filename);
return false;
}
if (f == NULL) return false;
char header_buf[256];
const char *line = ReadLine(f, header_buf, sizeof(header_buf));
#define EXIT_WITH_MSG(m) { fprintf(stderr, "%s: %s |%s", filename, m, line); \
fclose(f); return false; }
if (sscanf(line, "P6 ") == EOF)
EXIT_WITH_MSG("Can only handle P6 as PPM type.");
line = ReadLine(f, header_buf, sizeof(header_buf));
int new_width, new_height;
if (!line || sscanf(line, "%d %d ", &new_width, &new_height) != 2)
EXIT_WITH_MSG("Width/height expected");
int value;
line = ReadLine(f, header_buf, sizeof(header_buf));
if (!line || sscanf(line, "%d ", &value) != 1 || value != 255)
EXIT_WITH_MSG("Only 255 for maxval allowed.");
const size_t pixel_count = new_width * new_height;
Pixel *new_image = new Pixel [ pixel_count ];
assert(sizeof(Pixel) == 3); // we make that assumption.
if (fread(new_image, sizeof(Pixel), pixel_count, f) != pixel_count) {
line = "";
EXIT_WITH_MSG("Not enough pixels read.");
}
#undef EXIT_WITH_MSG
fclose(f);
fprintf(stderr, "Read image '%s' with %dx%d\n", filename,
new_width, new_height);
horizontal_position_ = 0;
MutexLock l(&mutex_new_image_);
new_image_.Delete(); // in case we reload faster than is picked up
new_image_.image = new_image;
new_image_.width = new_width;
new_image_.height = new_height;
return true;
}
void Run() {
const int screen_height = offscreen_->height();
const int screen_width = offscreen_->width();
while (running() && !interrupt_received) {
{
MutexLock l(&mutex_new_image_);
if (new_image_.IsValid()) {
current_image_.Delete();
current_image_ = new_image_;
new_image_.Reset();
}
}
if (!current_image_.IsValid()) {
usleep(100 * 1000);
continue;
}
for (int x = 0; x < screen_width; ++x) {
for (int y = 0; y < screen_height; ++y) {
const Pixel &p = current_image_.getPixel(
(horizontal_position_ + x) % current_image_.width, y);
offscreen_->SetPixel(x, y, p.red, p.green, p.blue);
}
}
offscreen_ = matrix_->SwapOnVSync(offscreen_);
horizontal_position_ += scroll_jumps_;
if (horizontal_position_ < 0) horizontal_position_ = current_image_.width;
if (scroll_ms_ <= 0) {
// No scrolling. We don't need the image anymore.
current_image_.Delete();
} else {
usleep(scroll_ms_ * 1000);
}
}
}
private:
struct Pixel {
Pixel() : red(0), green(0), blue(0){}
uint8_t red;
uint8_t green;
uint8_t blue;
};
struct Image {
Image() : width(-1), height(-1), image(NULL) {}
~Image() { Delete(); }
void Delete() { delete [] image; Reset(); }
void Reset() { image = NULL; width = -1; height = -1; }
inline bool IsValid() { return image && height > 0 && width > 0; }
const Pixel &getPixel(int x, int y) {
static Pixel black;
if (x < 0 || x >= width || y < 0 || y >= height) return black;
return image[x + width * y];
}
int width;
int height;
Pixel *image;
};
// Read line, skip comments.
char *ReadLine(FILE *f, char *buffer, size_t len) {
char *result;
do {
result = fgets(buffer, len, f);
} while (result != NULL && result[0] == '#');
return result;
}
const int scroll_jumps_;
const int scroll_ms_;
// Current image is only manipulated in our thread.
Image current_image_;
// New image can be loaded from another thread, then taken over in main thread
Mutex mutex_new_image_;
Image new_image_;
int32_t horizontal_position_;
RGBMatrix* matrix_;
FrameCanvas* offscreen_;
};
// Abelian sandpile
// Contributed by: Vliedel
class Sandpile : public ThreadedCanvasManipulator {
public:
Sandpile(Canvas *m, int delay_ms=50)
: ThreadedCanvasManipulator(m), delay_ms_(delay_ms) {
width_ = canvas()->width() - 1; // We need an odd width
height_ = canvas()->height() - 1; // We need an odd height
// Allocate memory
values_ = new int*[width_];
for (int x=0; x<width_; ++x) {
values_[x] = new int[height_];
}
newValues_ = new int*[width_];
for (int x=0; x<width_; ++x) {
newValues_[x] = new int[height_];
}
// Init values
srand(time(NULL));
for (int x=0; x<width_; ++x) {
for (int y=0; y<height_; ++y) {
values_[x][y] = 0;
}
}
}
~Sandpile() {
for (int x=0; x<width_; ++x) {
delete [] values_[x];
}
delete [] values_;
for (int x=0; x<width_; ++x) {
delete [] newValues_[x];
}
delete [] newValues_;
}
void Run() {
while (running() && !interrupt_received) {
// Drop a sand grain in the centre
values_[width_/2][height_/2]++;
updateValues();
for (int x=0; x<width_; ++x) {
for (int y=0; y<height_; ++y) {
switch (values_[x][y]) {
case 0:
canvas()->SetPixel(x, y, 0, 0, 0);
break;
case 1:
canvas()->SetPixel(x, y, 0, 0, 200);
break;
case 2:
canvas()->SetPixel(x, y, 0, 200, 0);
break;
case 3:
canvas()->SetPixel(x, y, 150, 100, 0);
break;
default:
canvas()->SetPixel(x, y, 200, 0, 0);
}
}
}
usleep(delay_ms_ * 1000); // ms
}
}
private:
void updateValues() {
// Copy values to newValues
for (int x=0; x<width_; ++x) {
for (int y=0; y<height_; ++y) {
newValues_[x][y] = values_[x][y];
}
}
// Update newValues based on values
for (int x=0; x<width_; ++x) {
for (int y=0; y<height_; ++y) {
if (values_[x][y] > 3) {
// Collapse
if (x>0)
newValues_[x-1][y]++;
if (x<width_-1)
newValues_[x+1][y]++;
if (y>0)
newValues_[x][y-1]++;
if (y<height_-1)
newValues_[x][y+1]++;
newValues_[x][y] -= 4;
}
}
}
// Copy newValues to values
for (int x=0; x<width_; ++x) {
for (int y=0; y<height_; ++y) {
values_[x][y] = newValues_[x][y];
}
}
}
int width_;
int height_;
int** values_;
int** newValues_;
int delay_ms_;
};
// Conway's game of life
// Contributed by: Vliedel
class GameLife : public ThreadedCanvasManipulator {
public:
GameLife(Canvas *m, int delay_ms=500, bool torus=true)
: ThreadedCanvasManipulator(m), delay_ms_(delay_ms), torus_(torus) {
width_ = canvas()->width();
height_ = canvas()->height();
// Allocate memory
values_ = new int*[width_];
for (int x=0; x<width_; ++x) {
values_[x] = new int[height_];
}
newValues_ = new int*[width_];
for (int x=0; x<width_; ++x) {
newValues_[x] = new int[height_];
}
// Init values randomly
srand(time(NULL));
for (int x=0; x<width_; ++x) {
for (int y=0; y<height_; ++y) {
values_[x][y]=rand()%2;
}
}
r_ = rand()%255;
g_ = rand()%255;
b_ = rand()%255;
if (r_<150 && g_<150 && b_<150) {
int c = rand()%3;
switch (c) {
case 0:
r_ = 200;
break;
case 1:
g_ = 200;
break;
case 2:
b_ = 200;
break;
}
}
}
~GameLife() {
for (int x=0; x<width_; ++x) {
delete [] values_[x];
}
delete [] values_;
for (int x=0; x<width_; ++x) {
delete [] newValues_[x];
}
delete [] newValues_;
}
void Run() {
while (running() && !interrupt_received) {
updateValues();
for (int x=0; x<width_; ++x) {
for (int y=0; y<height_; ++y) {
if (values_[x][y])
canvas()->SetPixel(x, y, r_, g_, b_);
else
canvas()->SetPixel(x, y, 0, 0, 0);
}
}
usleep(delay_ms_ * 1000); // ms
}
}
private:
int numAliveNeighbours(int x, int y) {
int num=0;
if (torus_) {
// Edges are connected (torus)
num += values_[(x-1+width_)%width_][(y-1+height_)%height_];
num += values_[(x-1+width_)%width_][y ];
num += values_[(x-1+width_)%width_][(y+1 )%height_];
num += values_[(x+1 )%width_][(y-1+height_)%height_];
num += values_[(x+1 )%width_][y ];
num += values_[(x+1 )%width_][(y+1 )%height_];
num += values_[x ][(y-1+height_)%height_];
num += values_[x ][(y+1 )%height_];
}
else {
// Edges are not connected (no torus)
if (x>0) {
if (y>0)
num += values_[x-1][y-1];
if (y<height_-1)
num += values_[x-1][y+1];
num += values_[x-1][y];
}
if (x<width_-1) {
if (y>0)
num += values_[x+1][y-1];
if (y<31)
num += values_[x+1][y+1];
num += values_[x+1][y];
}
if (y>0)
num += values_[x][y-1];
if (y<height_-1)
num += values_[x][y+1];
}
return num;
}
void updateValues() {
// Copy values to newValues
for (int x=0; x<width_; ++x) {
for (int y=0; y<height_; ++y) {
newValues_[x][y] = values_[x][y];
}
}
// update newValues based on values
for (int x=0; x<width_; ++x) {
for (int y=0; y<height_; ++y) {
int num = numAliveNeighbours(x,y);
if (values_[x][y]) {
// cell is alive
if (num < 2 || num > 3)
newValues_[x][y] = 0;
}
else {
// cell is dead
if (num == 3)
newValues_[x][y] = 1;
}
}
}
// copy newValues to values
for (int x=0; x<width_; ++x) {
for (int y=0; y<height_; ++y) {
values_[x][y] = newValues_[x][y];
}
}
}
int** values_;
int** newValues_;
int delay_ms_;
int r_;
int g_;
int b_;
int width_;
int height_;
bool torus_;
};
// Langton's ant
// Contributed by: Vliedel
class Ant : public ThreadedCanvasManipulator {
public:
Ant(Canvas *m, int delay_ms=500)
: ThreadedCanvasManipulator(m), delay_ms_(delay_ms) {
numColors_ = 4;
width_ = canvas()->width();
height_ = canvas()->height();
values_ = new int*[width_];
for (int x=0; x<width_; ++x) {
values_[x] = new int[height_];
}
}
~Ant() {
for (int x=0; x<width_; ++x) {
delete [] values_[x];
}
delete [] values_;
}
void Run() {
antX_ = width_/2;
antY_ = height_/2-3;
antDir_ = 0;
for (int x=0; x<width_; ++x) {
for (int y=0; y<height_; ++y) {
values_[x][y] = 0;
updatePixel(x, y);
}
}
while (running() && !interrupt_received) {
// LLRR
switch (values_[antX_][antY_]) {
case 0:
case 1:
antDir_ = (antDir_+1+4) % 4;
break;
case 2:
case 3:
antDir_ = (antDir_-1+4) % 4;
break;
}
values_[antX_][antY_] = (values_[antX_][antY_] + 1) % numColors_;
int oldX = antX_;
int oldY = antY_;
switch (antDir_) {
case 0:
antX_++;
break;
case 1:
antY_++;
break;
case 2:
antX_--;
break;
case 3:
antY_--;
break;
}
updatePixel(oldX, oldY);
if (antX_ < 0 || antX_ >= width_ || antY_ < 0 || antY_ >= height_)
return;
updatePixel(antX_, antY_);
usleep(delay_ms_ * 1000);
}
}
private:
void updatePixel(int x, int y) {
switch (values_[x][y]) {
case 0:
canvas()->SetPixel(x, y, 200, 0, 0);
break;
case 1:
canvas()->SetPixel(x, y, 0, 200, 0);
break;
case 2:
canvas()->SetPixel(x, y, 0, 0, 200);
break;
case 3:
canvas()->SetPixel(x, y, 150, 100, 0);
break;
}
if (x == antX_ && y == antY_)
canvas()->SetPixel(x, y, 0, 0, 0);
}
int numColors_;
int** values_;
int antX_;
int antY_;
int antDir_; // 0 right, 1 up, 2 left, 3 down
int delay_ms_;
int width_;
int height_;
};
// Imitation of volume bars
// Purely random height doesn't look realistic
// Contributed by: Vliedel
class VolumeBars : public ThreadedCanvasManipulator {
public:
VolumeBars(Canvas *m, int delay_ms=50, int numBars=8)
: ThreadedCanvasManipulator(m), delay_ms_(delay_ms),
numBars_(numBars), t_(0) {
}
~VolumeBars() {
delete [] barHeights_;
delete [] barFreqs_;
delete [] barMeans_;
}
void Run() {
const int width = canvas()->width();
height_ = canvas()->height();
barWidth_ = width/numBars_;
barHeights_ = new int[numBars_];
barMeans_ = new int[numBars_];
barFreqs_ = new int[numBars_];
heightGreen_ = height_*4/12;
heightYellow_ = height_*8/12;
heightOrange_ = height_*10/12;
heightRed_ = height_*12/12;
// Array of possible bar means
int numMeans = 10;
int means[10] = {1,2,3,4,5,6,7,8,16,32};
for (int i=0; i<numMeans; ++i) {
means[i] = height_ - means[i]*height_/8;
}
// Initialize bar means randomly
srand(time(NULL));
for (int i=0; i<numBars_; ++i) {
barMeans_[i] = rand()%numMeans;
barFreqs_[i] = 1<<(rand()%3);
}
// Start the loop
while (running() && !interrupt_received) {
if (t_ % 8 == 0) {
// Change the means
for (int i=0; i<numBars_; ++i) {
barMeans_[i] += rand()%3 - 1;
if (barMeans_[i] >= numMeans)
barMeans_[i] = numMeans-1;
if (barMeans_[i] < 0)
barMeans_[i] = 0;
}
}
// Update bar heights
t_++;
for (int i=0; i<numBars_; ++i) {
barHeights_[i] = (height_ - means[barMeans_[i]])
* sin(0.1*t_*barFreqs_[i]) + means[barMeans_[i]];
if (barHeights_[i] < height_/8)
barHeights_[i] = rand() % (height_/8) + 1;
}
for (int i=0; i<numBars_; ++i) {
int y;
for (y=0; y<barHeights_[i]; ++y) {
if (y<heightGreen_) {
drawBarRow(i, y, 0, 200, 0);
}
else if (y<heightYellow_) {
drawBarRow(i, y, 150, 150, 0);
}
else if (y<heightOrange_) {
drawBarRow(i, y, 250, 100, 0);
}
else {
drawBarRow(i, y, 200, 0, 0);
}
}
// Anything above the bar should be black
for (; y<height_; ++y) {
drawBarRow(i, y, 0, 0, 0);
}
}
usleep(delay_ms_ * 1000);
}
}
private:
void drawBarRow(int bar, int y, uint8_t r, uint8_t g, uint8_t b) {
for (int x=bar*barWidth_; x<(bar+1)*barWidth_; ++x) {
canvas()->SetPixel(x, height_-1-y, r, g, b);
}
}
int delay_ms_;
int numBars_;
int* barHeights_;
int barWidth_;
int height_;
int heightGreen_;
int heightYellow_;
int heightOrange_;
int heightRed_;
int* barFreqs_;
int* barMeans_;
int t_;
};
/// Genetic Colors
/// A genetic algorithm to evolve colors
/// by bbhsu2 + anonymous
class GeneticColors : public ThreadedCanvasManipulator {
public:
GeneticColors(Canvas *m, int delay_ms = 200)
: ThreadedCanvasManipulator(m), delay_ms_(delay_ms) {
width_ = canvas()->width();
height_ = canvas()->height();
popSize_ = width_ * height_;
// Allocate memory
children_ = new citizen[popSize_];
parents_ = new citizen[popSize_];
srand(time(NULL));
}
~GeneticColors() {
delete [] children_;
delete [] parents_;
}
static int rnd (int i) { return rand() % i; }
void Run() {
// Set a random target_
target_ = rand() & 0xFFFFFF;
// Create the first generation of random children_
for (int i = 0; i < popSize_; ++i) {
children_[i].dna = rand() & 0xFFFFFF;
}
while (running() && !interrupt_received) {
swap();
sort();
mate();
std::random_shuffle (children_, children_ + popSize_, rnd);
// Draw citizens to canvas
for(int i=0; i < popSize_; i++) {
int c = children_[i].dna;
int x = i % width_;
int y = (int)(i / width_);
canvas()->SetPixel(x, y, R(c), G(c), B(c));
}
// When we reach the 85% fitness threshold...
if(is85PercentFit()) {
// ...set a new random target_
target_ = rand() & 0xFFFFFF;
// Randomly mutate everyone for sake of new colors
for (int i = 0; i < popSize_; ++i) {
mutate(children_[i]);
}
}
usleep(delay_ms_ * 1000);
}
}
private:
/// citizen will hold dna information, a 24-bit color value.
struct citizen {
citizen() { }
citizen(int chrom)
: dna(chrom) {
}
int dna;
};
/// for sorting by fitness
class comparer {
public:
comparer(int t)
: target_(t) { }
inline bool operator() (const citizen& c1, const citizen& c2) {
return (calcFitness(c1.dna, target_) < calcFitness(c2.dna, target_));
}
private:
const int target_;
};
static int R(const int cit) { return at(cit, 16); }
static int G(const int cit) { return at(cit, 8); }
static int B(const int cit) { return at(cit, 0); }
static int at(const int v, const int offset) { return (v >> offset) & 0xFF; }
/// fitness here is how "similar" the color is to the target
static int calcFitness(const int value, const int target) {
// Count the number of differing bits
int diffBits = 0;
for (unsigned int diff = value ^ target; diff; diff &= diff - 1) {
++diffBits;
}
return diffBits;
}
/// sort by fitness so the most fit citizens are at the top of parents_
/// this is to establish an elite population of greatest fitness
/// the most fit members and some others are allowed to reproduce
/// to the next generation
void sort() {
std::sort(parents_, parents_ + popSize_, comparer(target_));
}
/// let the elites continue to the next generation children
/// randomly select 2 parents of (near)elite fitness and determine
/// how they will mate. after mating, randomly mutate citizens
void mate() {
// Adjust these for fun and profit
const float eliteRate = 0.30f;
const float mutationRate = 0.20f;
const int numElite = popSize_ * eliteRate;
for (int i = 0; i < numElite; ++i) {
children_[i] = parents_[i];
}
for (int i = numElite; i < popSize_; ++i) {
//select the parents randomly
const float sexuallyActive = 1.0 - eliteRate;
const int p1 = rand() % (int)(popSize_ * sexuallyActive);
const int p2 = rand() % (int)(popSize_ * sexuallyActive);
const unsigned matingMask = (~0u) << (rand() % bitsPerPixel);
// Make a baby
unsigned baby = (parents_[p1].dna & matingMask)
| (parents_[p2].dna & ~matingMask);
children_[i].dna = baby;
// Mutate randomly based on mutation rate
if ((rand() / (float)RAND_MAX) < mutationRate) {
mutate(children_[i]);
}
}
}
/// parents make children,
/// children become parents,
/// and they make children...
void swap() {
citizen* temp = parents_;
parents_ = children_;
children_ = temp;
}
void mutate(citizen& c) {
// Flip a random bit
c.dna ^= 1 << (rand() % bitsPerPixel);
}