-
Notifications
You must be signed in to change notification settings - Fork 1
/
capinibal.py
executable file
·1296 lines (1147 loc) · 53.4 KB
/
capinibal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
"""Main file for Capinibal another anticapitalist images generator."""
from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color
import wand.version
import sys
import random
import subprocess
import time
import os
import tempfile
import argparse
# liblo - see http://das.nasophon.de/pyliblo/examples.html
import liblo
# TODO
# more consistent context/drawing naming
# vertical and oblique text
# connect more OSC parameters
#######
# FABRIQUE
###################
# ~ class CasNormal:
# ~ def uneMethode(self):
# ~ print("normal")
# ~ class CasSpecial:
# ~ def uneMethode(self):
# ~ print("special")
# ~ def casQuiConvient(estNormal=True):
# ~ """Fonction fabrique renvoyant une classe."""
# ~ if estNormal:
# ~ return CasNormal()
# ~ else:
# ~ return CasSpecial()
# ~ def cpb_generator (gen_type):
# ~ if (gen_type == "color"):
# ~ return cpb_gen_color ()
# ~ else if (gen_type == "size"):
# ~ return cpb_gen_color ()
# ~ class cpb_gen_color:
# ~ def __init__ (self):
# see https://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# see https://stackoverflow.com/questions/4092528/how-to-clamp-an-integer-to-some-range
# cpb_clip = lambda x, l, u: l if x < l else u if x > u else x
def cpb_clip(x, l, u):
return l if x < l else u if x > u else x
#TODO remove member function cpb_ prefixe
class Capinibal:
"""Main class of the another anticapitalist images generator."""
# FIXME use annotations to document type
duration = 0
frame = 0
fps = 24
image_width = 1024
image_height = 576
port = 1234
verbose = 0
texts = [
'capital', 'capinal', 'capibal', #FIXME
'catipal', 'catinal', 'catibal',
'canipal', 'canital', 'canibal',
'cabipal', 'cabital', 'cabinal'
]
fonts = [
'Sudbury_Basin_3D.ttf',
'Sudbury_Basin.ttf',
'Esteh.ttf',
'Sheilova.ttf',
'5yearsoldfont.ttf',
'uwch.ttf',
'cubicblock_s.ttf',
'cubicblock_t.ttf'
]
text_font_ref_metrics = []
# The max* lists will be populated with one item per font
max_width = []
max_height = []
# max_max* will be set for all fonts, all texts
max_max_width = 0
max_max_height = 0
ref_font_size = 100
min_font_size = 55
max_font_size = 200
text_font_ref_metrics = []
hspacing = 4
vspacing = 4
ctx_num = 0
def __init__(self): # Todo
print("in init")
def cpb_toss(coin=2):
"""toss: give kind of rand rythm.
"""
# fixme return and default above
coin = int(coin)
if (coin <= 1):
return True
if (random.randrange(1, coin) == 1):
return True
return False
def cpb_toss_by_value(val_max=2, val_min = 1):
"""toss: give kind of rand rythm value between given min and max.
"""
# fixme return and default above
val_max = int(val_max)
if (val_max <= 1):
return 1
return random.randrange(val_min, val_max)
#######
# COLOR UTILS
###################
def cpb_random_color():
#~ color FFFFFF -> 16777215
color = random.randrange(0, 16777215, 15)
red = color >> 16
green = (color >> 8) & 0xFF
blue = color & 0xFF
return Color('rgb({0},{1},{2})'.format(red, green, blue))
def cpb_fill_color_gen(ctx, coin=1):
if Capinibal.cpb_toss(coin):
ctx.fill_color = Capinibal.cpb_random_color()
def cpb_get_bg_start(step_min, step_max, static_color=False):
Capinibal.FxParams.bg_color_steps = Capinibal.cpb_toss_by_value(step_max,step_min)
if not static_color:
Capinibal.FxParams.bg_color_begin = Capinibal.FxParams.bg_color_end
Capinibal.FxParams.bg_color_end = Capinibal.cpb_random_color()
Capinibal.FxParams.bg_color_stepr = (Capinibal.FxParams.bg_color_end.red_int8 - Capinibal.FxParams.bg_color_begin.red_int8) // Capinibal.FxParams.bg_color_steps
Capinibal.FxParams.bg_color_stepg = (Capinibal.FxParams.bg_color_end.green_int8 - Capinibal.FxParams.bg_color_begin.green_int8) // Capinibal.FxParams.bg_color_steps
Capinibal.FxParams.bg_color_stepb = (Capinibal.FxParams.bg_color_end.blue_int8 - Capinibal.FxParams.bg_color_begin.blue_int8) // Capinibal.FxParams.bg_color_steps
def cpb_get_bg_next():
if Capinibal.FxParams.bg_color_steps is None:
return False, None
Capinibal.FxParams.bg_color_steps -= 1
if Capinibal.FxParams.bg_color_steps == 0:
bg_next = Capinibal.FxParams.bg_color_end
Capinibal.FxParams.bg_color_steps = None
else:
red = Capinibal.FxParams.bg_color.red_int8 + Capinibal.FxParams.bg_color_stepr
green = Capinibal.FxParams.bg_color.green_int8 + Capinibal.FxParams.bg_color_stepg
blue = Capinibal.FxParams.bg_color.blue_int8 + Capinibal.FxParams.bg_color_stepb
bg_next = Color('rgb({0},{1},{2})'.format(red, green, blue))
return True, bg_next
def cpb_set_bg(ctx, bg_color):
#~ clone_ctx.composite('clear', 0, 0, image_width, image_height, img) # set to black!
old_color = ctx.fill_color
if bg_color is None:
bg_color = Capinibal.cpb_random_color()
ctx.fill_color = bg_color
ctx.color(0, 0, 'reset')
ctx.fill_color = old_color
#######
# TEXTS GENERATION
###################
def cpb_text_gen_solo():
return random.choice(Capinibal.texts)
def cpb_text_gen_solo_alt():
candidate_letter = ['P', 'B', 'T', 'N']
txt = "CA"
cddt_index = random.randrange(0, len(candidate_letter))
txt = txt + candidate_letter[cddt_index]
candidate_letter.pop(cddt_index)
txt = txt + "I"
txt = txt + candidate_letter[random.randrange(0, len(candidate_letter))]
txt = txt + "AL"
return txt
def cpb_text_gen_full(n=10):
txt_list = []
for i in range(0, n):
txt_list.append(Capinibal.cpb_text_gen_solo())
return txt_list
#######
# RYTHM CONTROL
###################
def cpb_setspeed(speed): # Speed is in changes per second
Capinibal.FxParams.speed = cpb_clip(int(1000.0 * float(speed) / float(Capinibal.fps)), 1, 1000)
# Internal speed is changes per frame * 1000
# 1000 means change every frame, going faster is pointless
if Capinibal.verbose:
print("Speed:", float(speed),
"changes/s becomes", Capinibal.FxParams.speed,
"changes/1000 frames")
def cpb_increase(speed):
Capinibal.FxParams.speed = cpb_clip(Capinibal.FxParams.speed + speed, 1, 1000)
#~ Capinibal.FxParams.speed += 1000*float(speed)/float(Capinibal.fps) # use consistent units
if Capinibal.verbose:
print("Increase speed:", float(speed),
"changes/s becomes", Capinibal.FxParams.speed,
"changes/1000 frames")
def cpb_decrease(speed):
Capinibal.FxParams.speed = cpb_clip(Capinibal.FxParams.speed - speed, 1, 1000)
#~ Capinibal.FxParams.speed -= 1000*float(speed)/float(Capinibal.fps) # use consistent units
if Capinibal.verbose:
print("Decrase speed:", float(speed),
"changes/s becomes", Capinibal.FxParams.speed,
"changes/1000 frames")
class FxParams:
parameters_strenght = [50,50,50,50] #FIXME
speed = 200
cols = 2
rows = 5
ctx = None
img = None
valign_center = False
halign_center = False
# What about align_bottom?
bg_color = Color('lightblue')
bg_color_end = bg_color
bg_color_begin = bg_color
bg_color_steps = None
bg_color_stepr = 0
bg_color_stepg = 0
bg_color_stepb = 0
fg_color = Color('black')
step = 0
random_order = True
reverse_cols = True
reverse_rows = True
# ~ def get_param()
# ~ def inc_rand_param()
# ~ def dec_rand_param()
#END CLASS FxParams
#END CLASS Capinibal
#############
#
# Utils
#
############################
class CpbServer(liblo.ServerThread):
def __init__(self):
liblo.ServerThread.__init__(self, Capinibal.port)
@liblo.make_method('/cpb/speed', 'f')
def speed_callback(self, path, args):
if(Capinibal.verbose):
print("Received OSC message '%s' with argument: %f" % (path, args[0]))
print("Old speed:", Capinibal.FxParams.speed)
Capinibal.cpb_setspeed(args[0])
@liblo.make_method('/cpb/increase', 'i')
def increase_callback(self, path, args):
if(Capinibal.verbose):
print("Received OSC message '%s' with argument: %d" % (path, args[0]))
print("Old speed:", Capinibal.FxParams.speed)
Capinibal.cpb_increase(args[0])
@liblo.make_method('/cpb/decrease', 'i')
def decrease_callback(self, path, args):
if(Capinibal.verbose):
print("Received OSC message '%s' with argument: %d" % (path, args[0]))
print("Old speed:", Capinibal.FxParams.speed)
Capinibal.cpb_decrease(args[0])
@liblo.make_method(None, None)
def fallback(self, path, args):
eprint("Warning : received unknown OSC message '%s'" % path)
def cpb_text_gen_solo():
return random.choice(Capinibal.texts)
def cpb_text_gen_solo_alt():
candidate_letter = ['P', 'B', 'T', 'N']
txt = "CA"
cddt_index = random.randrange(0, len(candidate_letter))
txt = txt + candidate_letter[cddt_index]
candidate_letter.pop(cddt_index)
txt = txt + "I"
txt = txt + candidate_letter[random.randrange(0, len(candidate_letter))]
txt = txt + "AL"
return txt
def cpb_text_gen_full(n=10):
txt_list = []
for i in range(0, n):
txt_list.append(cpb_text_gen_solo())
return txt_list
def cpb_get_cached_text_w_h_a(text_to_measure, ctx, t=None, f=None):
# Scaling cached metrics is close enough to exact metrics
# tests showed results within 2 pixels of exact size
if t is None:
t = Capinibal.texts.index(text_to_measure)
if Capinibal.verbose:
print("text: ", text_to_measure, " #", str(t))
if f is None:
#~ f=Capinibal.fonts.index(ctx.font[2:]) #FIXME relies on font path
f = Capinibal.ctx_num # FIXME Hidden dependency
if Capinibal.verbose:
print("context: ", str(f))
#~ print(ctx.font, f, text_to_measure, t, "font size:", ctx.font_size)
#~ print(Capinibal.text_font_ref_metrics)
#~ print(len(Capinibal.text_font_ref_metrics))
try:
m = Capinibal.text_font_ref_metrics[f][t]
except IndexError:
if Capinibal.verbose:
print('metrics cache miss at', f, t)
dummy_image = Image(filename='wizard:')
m = ctx.get_font_metrics(dummy_image, text_to_measure)
#~ scale = 1.0
return int(m.text_width), int(m.text_height), int(m.ascender)
scale = ctx.font_size / Capinibal.ref_font_size
if Capinibal.verbose > 1:
print('metrics cache hit at', f, t,
'font size', ctx.font_size,
'scale:', round(scale, 3))
return int(m.text_width * scale + 0.5), int(m.text_height * scale + 0.5), int(m.ascender * scale + 0.5)
def cpb_get_text_metrics(text_to_measure, draw):
dummy_image = Image(filename='wizard:')
metrics = draw.get_font_metrics(dummy_image, text_to_measure)
# Compare with cache results for verification
#~ w, h, a = cpb_get_cached_text_w_h_a (text_to_measure, draw)
# These 6 variables for testing only
#~ if w>0:
#~ cpb_get_text_metrics.max_delta_w = max(cpb_get_text_metrics.max_delta_w, w-metrics.text_width)
#~ cpb_get_text_metrics.min_delta_w = min(cpb_get_text_metrics.min_delta_w, w-metrics.text_width)
#~ cpb_get_text_metrics.max_delta_h = max(cpb_get_text_metrics.max_delta_h, h-metrics.text_height)
#~ cpb_get_text_metrics.min_delta_h = min(cpb_get_text_metrics.min_delta_h, h-metrics.text_height)
#~ cpb_get_text_metrics.max_delta_a = max(cpb_get_text_metrics.max_delta_a, a-metrics.ascender)
#~ cpb_get_text_metrics.min_delta_a = min(cpb_get_text_metrics.min_delta_a, a-metrics.ascender)
#~ print(
#~ 'w:', metrics.text_width, w, cpb_get_text_metrics.max_delta_w, cpb_get_text_metrics.min_delta_w,
#~ 'h:', metrics.text_height, h, cpb_get_text_metrics.max_delta_h, cpb_get_text_metrics.min_delta_h,
#~ 'a:', metrics.ascender, a, cpb_get_text_metrics.max_delta_a, cpb_get_text_metrics.min_delta_a
#~ )
#~ print (metrics.text_width, metrics.text_height, metrics.ascender, cpb_get_cached_text_w_h_a (text_to_measure, draw))
#~ print("=" * 79)
return metrics
def cpb_fill_metrics_cache(ctxs):
# Pre-compute metrics
for f in range(len(Capinibal.fonts)):
Capinibal.ctx_num = f
ctx = Drawing()
ctx.font = './' + Capinibal.fonts[f] # FIXME !
ctx.font_size = Capinibal.ref_font_size
ctx.fill_color = Color('black')
# Cache metrics for each text for each font
row = []
max_width = 0
max_height = 0
for t in range(len(Capinibal.texts)):
# Capinibal.text_font_ref_metrics[f][t]=
metrics = cpb_get_text_metrics(Capinibal.texts[t], ctx)
max_width = max(metrics.text_width, max_width)
max_height = max(metrics.text_height, max_height)
row.append(metrics)
Capinibal.text_font_ref_metrics.append(row)
Capinibal.max_width.append(max_width)
Capinibal.max_height.append(max_height)
ctxs.append(ctx)
# Max values across all fonts, all texts
Capinibal.max_max_width = max(Capinibal.max_width)
Capinibal.max_max_height = max(Capinibal.max_height)
def cpb_print_metrics_cache():
print('Reference font size:', Capinibal.ref_font_size)
for f in range(len(Capinibal.fonts)):
for t in range(len(Capinibal.texts)):
print('Font', f, ':', Capinibal.fonts[f],
'text', t, ':', Capinibal.texts[t],
'w:', Capinibal.text_font_ref_metrics[f][t].text_width,
'h:', Capinibal.text_font_ref_metrics[f][t].text_height,
'a:', Capinibal.text_font_ref_metrics[f][t].ascender,
#~ 'metrics:', Capinibal.text_font_ref_metrics[f][t]
)
print('max_width:', Capinibal.max_width[f],
'max_height:', Capinibal.max_height[f])
print("=" * 79)
#############
#
# Image generation routines
#
############################
def cpb_put_text(cpb_textes, ctx, col, row, cols, rows, col_width, row_height):
# Prepare context ctx for displaying a text in grid layout
text_num = (col + cols * row) % len(cpb_textes) # Use random?
text = cpb_textes[text_num]
w, h, a = cpb_get_cached_text_w_h_a(text, ctx, t=text_num)
hmargin = Capinibal.hspacing // 2
vmargin = Capinibal.vspacing // 2
if Capinibal.FxParams.halign_center:
hmargin = (col_width - w) // 2
if Capinibal.verbose > 2:
print("h center:"
'col:', col,
'col width:', col_width,
'cols:', cols,
'text width:', w,
'hmargin:', hmargin,
'x:', col * col_width + hmargin,
)
if Capinibal.FxParams.valign_center:
vmargin = (row_height - h) // 2
if Capinibal.verbose > 2:
print("v center:"
'row:', row,
'row height:', row_height,
'rows:', rows,
'text height:', h, a,
'vmargin:', vmargin,
'y:', row * row_height + vmargin + a,
)
if hmargin < 0:
eprint('Alignment problem:', text, 'width:', w)
hmargin = 0
if vmargin < 0:
eprint('Alignment problem:', text,
'col:', col,
'row height:', row_height,
'rows:', rows,
'text height:', h,
'font size:', ctx.font_size)
vmargin = 0
if Capinibal.FxParams.reverse_cols:
col = cols - col - 1
if Capinibal.FxParams.reverse_rows:
row = rows - row - 1
ctx.text(col * col_width + hmargin,
row * row_height + vmargin + a,
text)
def cpb_clr_text(cpb_textes, ctx, col, row, cols, rows, col_width, row_height):
# Prepare context ctx for clearing a text in grid layout
# Always clear the whole cell, ignore margins
# Caller has to set ctx.fill_color
if Capinibal.FxParams.reverse_cols:
col = cols - col - 1
if Capinibal.FxParams.reverse_rows:
row = rows - row - 1
ctx.stroke_width = 0
# TODO get_clear_color
# FIXME how to clear !!!!
ctx.fill_color = Capinibal.FxParams.bg_color #Color('reset') # ctx.fill_color
ctx.rectangle(left=col * col_width,
top=row * row_height,
width=col_width,
height=row_height)
# ctx.color(0,0,'reset')
def cpb_img_gen_matrix_full(cpb_textes, ctx, img):
# Generate complete matrix in one step
if Capinibal.verbose > 1:
print(img)
cols = Capinibal.FxParams.cols
rows = Capinibal.FxParams.rows
col_width = Capinibal.image_width // cols
row_height = Capinibal.image_height // rows
textes_len = len(cpb_textes) # may be different from grid length
Capinibal.FxParams.step = 0
with Drawing(drawing=ctx) as clone_ctx: # <= Clones & reuse the parent context.
Capinibal.cpb_set_bg(clone_ctx, Capinibal.FxParams.bg_color)
clone_ctx.fill_color = Capinibal.FxParams.fg_color
# Fill grid with text
for col in range(0, cols):
for row in range(0, rows):
cpb_put_text(cpb_textes, clone_ctx, col, row, cols, rows, col_width, row_height)
clone_ctx(img)
return True # Allow clearing matrix
# FIXME The following 3 functions have much in common, should be factored out
def cpb_img_gen_matrix_line(cpb_textes, ctx, img):
# Generate a matrix image, one row at a time
if Capinibal.verbose > 1:
print("gen line step:", Capinibal.FxParams.step, img)
cols = Capinibal.FxParams.cols
col_width = Capinibal.image_width // cols
rows = Capinibal.FxParams.rows
row_height = Capinibal.image_height // rows
textes_len = len(cpb_textes)
with Drawing(drawing=ctx) as clone_ctx: # <= Clones & reuse the parent context.
if Capinibal.FxParams.step == 0:
# FIXME! also keep the version without clearing, leading to a visually interesting accumulation
Capinibal.cpb_set_bg(clone_ctx, Capinibal.FxParams.bg_color)
cpb_img_gen_matrix_line.lines_num = list(range(0, rows))
if Capinibal.FxParams.random_order:
k = random.randrange(0, len(cpb_img_gen_matrix_line.lines_num))
row = cpb_img_gen_matrix_line.lines_num[k]
cpb_img_gen_matrix_line.lines_num.pop(k)
else:
row = Capinibal.FxParams.step % rows
clone_ctx.fill_color = Capinibal.FxParams.fg_color
for col in range(0, cols):
cpb_put_text(cpb_textes, clone_ctx, col, row, cols, rows, col_width, row_height)
clone_ctx(img)
Capinibal.FxParams.step = (Capinibal.FxParams.step + 1) % rows
return True # Allow clearing matrix
def cpb_img_gen_matrix_col(cpb_textes, ctx, img):
# Generate a matrix image, one column at a time
if Capinibal.verbose > 1:
print("gen column step:", Capinibal.FxParams.step, img)
cols = Capinibal.FxParams.cols
col_width = Capinibal.image_width // cols
rows = Capinibal.FxParams.rows
row_height = Capinibal.image_height // rows
textes_len = len(cpb_textes)
with Drawing(drawing=ctx) as clone_ctx: # <= Clones & reuse the parent context.
if Capinibal.FxParams.step == 0:
# FIXME! also keep the version without clearing, leading to a visually interesting accumulation
Capinibal.cpb_set_bg(clone_ctx, Capinibal.FxParams.bg_color)
cpb_img_gen_matrix_col.cols_num = list(range(0, cols))
if Capinibal.FxParams.random_order:
k = random.randrange(0, len(cpb_img_gen_matrix_col.cols_num))
col = cpb_img_gen_matrix_col.cols_num[k]
cpb_img_gen_matrix_col.cols_num.pop(k)
else:
col = Capinibal.FxParams.step % cols
clone_ctx.fill_color = Capinibal.FxParams.fg_color
for row in range(0, rows):
cpb_put_text(cpb_textes, clone_ctx, col, row, cols, rows, col_width, row_height)
clone_ctx(img)
Capinibal.FxParams.step = (Capinibal.FxParams.step + 1) % cols
return True # Allow clearing matrix
def cpb_img_gen_matrix_diag(cpb_textes, ctx, img):
# Generate a matrix image, one diagonal row at a time
if Capinibal.verbose > 1:
print("gen diag step:", Capinibal.FxParams.step, img)
cols = Capinibal.FxParams.cols
col_width = Capinibal.image_width // cols
rows = Capinibal.FxParams.rows
row_height = Capinibal.image_height // rows
with Drawing(drawing=ctx) as clone_ctx: # <= Clones & reuse the parent context.
if Capinibal.FxParams.step == 0:
# FIXME! also keep the version without clearing, leading to a visually interesting accumulation
Capinibal.cpb_set_bg(clone_ctx, Capinibal.FxParams.bg_color)
col_from = max(0, Capinibal.FxParams.step - rows + 1)
col_to = min(cols, Capinibal.FxParams.step + 1)
clone_ctx.fill_color = Capinibal.FxParams.fg_color
for col in range(col_from, col_to):
# col + row is constant for one oblique line
row = Capinibal.FxParams.step - col
cpb_put_text(cpb_textes, clone_ctx, col, row, cols, rows, col_width, row_height)
clone_ctx(img)
Capinibal.FxParams.step = (Capinibal.FxParams.step + 1) % (rows + cols - 1)
return True # Allow clearing matrix
def cpb_img_gen_matrix_grid(cpb_textes, ctx, img):
# Generate a matrix image, one cell at a time
# What about populating adjacent cells, worm-like?
if Capinibal.verbose > 1:
print("gen grid step:", Capinibal.FxParams.step, img)
cols = Capinibal.FxParams.cols
rows = Capinibal.FxParams.rows
grid_len = rows * cols
col_width = Capinibal.image_width // cols
row_height = Capinibal.image_height // rows
with Drawing(drawing=ctx) as clone_ctx: # <= Clones & reuse the parent context.
if cpb_img_gen_matrix_grid.cells_num == []:
Capinibal.FxParams.step = 0
if Capinibal.FxParams.step == 0:
# FIXME! also keep the version without clearing, leading to a visually interesting accumulation
# ~ Capinibal.cpb_set_bg(clone_ctx, Capinibal.FxParams.bg_color) # before trans
# FIXME! could be visually interesting to optionally keep same context for all steps
cpb_img_gen_matrix_grid.cells_num = list(range(0, grid_len))
if Capinibal.verbose:
print(rows, 'rows ', row_height, 'tall.')
if Capinibal.FxParams.random_order:
k = random.randrange(0, len(cpb_img_gen_matrix_grid.cells_num))
i = cpb_img_gen_matrix_grid.cells_num[k]
cpb_img_gen_matrix_grid.cells_num.pop(k)
else:
i = Capinibal.FxParams.step
col = i % cols
row = i // cols
clone_ctx.fill_color = Capinibal.FxParams.fg_color
cpb_put_text(cpb_textes, clone_ctx, col, row, cols, rows, col_width, row_height)
clone_ctx(img)
Capinibal.FxParams.step = (Capinibal.FxParams.step + 1) % grid_len
return True # Allow clearing matrix
def cpb_img_clr_matrix_line(cpb_textes, ctx, img):
# Clear a matrix image, one row at a time
if Capinibal.verbose > 1:
print("clr line step:", Capinibal.FxParams.step, img)
cols = Capinibal.FxParams.cols
col_width = Capinibal.image_width // cols
rows = Capinibal.FxParams.rows
row_height = Capinibal.image_height // rows
if Capinibal.FxParams.step == 0:
cpb_img_gen_matrix_line.lines_num = list(range(0, rows))
if Capinibal.FxParams.random_order:
k = random.randrange(0, len(cpb_img_gen_matrix_line.lines_num))
row = cpb_img_gen_matrix_line.lines_num[k]
cpb_img_gen_matrix_line.lines_num.pop(k)
else:
row = Capinibal.FxParams.step % rows
ctx2 = Drawing()
ctx2.fill_color = Capinibal.FxParams.bg_color # ctx.fill_color
for col in range(0, cols):
cpb_clr_text(cpb_textes, ctx2, col, row, cols, rows, col_width, row_height)
ctx2(img)
Capinibal.FxParams.step = (Capinibal.FxParams.step + 1) % rows
def cpb_img_clr_matrix_col(cpb_textes, ctx, img):
# Clear a matrix image, one column at a time
if Capinibal.verbose > 1:
print("clr column step:", Capinibal.FxParams.step, img)
cols = Capinibal.FxParams.cols
col_width = Capinibal.image_width // cols
rows = Capinibal.FxParams.rows
row_height = Capinibal.image_height // rows
if Capinibal.FxParams.step == 0:
cpb_img_gen_matrix_col.cols_num = list(range(0, cols))
if Capinibal.FxParams.random_order:
k = random.randrange(0, len(cpb_img_gen_matrix_col.cols_num))
col = cpb_img_gen_matrix_col.cols_num[k]
cpb_img_gen_matrix_col.cols_num.pop(k)
else:
col = Capinibal.FxParams.step % cols
ctx2 = Drawing()
ctx2.fill_color = Capinibal.FxParams.bg_color # ctx.fill_color
for row in range(0, rows):
cpb_clr_text(cpb_textes, ctx2, col, row, cols, rows, col_width, row_height)
ctx2(img)
Capinibal.FxParams.step = (Capinibal.FxParams.step + 1) % cols
def cpb_img_clr_matrix_diag(cpb_textes, ctx, img):
# Clear a matrix image, one diagonal row at a time
if Capinibal.verbose > 1:
print("clr diag step", Capinibal.FxParams.step, img)
cols = Capinibal.FxParams.cols
col_width = Capinibal.image_width // cols
rows = Capinibal.FxParams.rows
row_height = Capinibal.image_height // rows
col_from = max(0, Capinibal.FxParams.step - rows + 1)
col_to = min(cols, Capinibal.FxParams.step + 1)
ctx2 = Drawing()
ctx2.fill_color = Capinibal.FxParams.bg_color # ctx.fill_color
for col in range(col_from, col_to):
# col + row is constant for one oblique line
row = Capinibal.FxParams.step - col
cpb_clr_text(cpb_textes, ctx2, col, row, cols, rows, col_width, row_height)
ctx2(img)
Capinibal.FxParams.step = (Capinibal.FxParams.step + 1) % (rows + cols - 1)
def cpb_img_clr_matrix_grid(cpb_textes, ctx, img):
# Clear a matrix image, one cell at a time
if Capinibal.verbose > 1:
print("clr grid step", Capinibal.FxParams.step, img)
cols = Capinibal.FxParams.cols
col_width = Capinibal.image_width // cols
rows = Capinibal.FxParams.rows
row_height = Capinibal.image_height // rows
grid_len = rows * cols
if cpb_img_clr_matrix_grid.cells_num == []:
Capinibal.FxParams.step = 0
if Capinibal.FxParams.step == 0:
cpb_img_clr_matrix_grid.cells_num = list(range(0, grid_len))
if Capinibal.verbose:
print(rows, 'rows ', row_height, 'tall.')
if Capinibal.FxParams.random_order:
k = random.randrange(0, len(cpb_img_clr_matrix_grid.cells_num))
i = cpb_img_clr_matrix_grid.cells_num[k]
cpb_img_clr_matrix_grid.cells_num.pop(k)
else:
i = Capinibal.FxParams.step
col = i % cols
row = i // cols
ctx2 = Drawing()
# ~ ctx2.fill_color = Capinibal.FxParams.bg_color # before trans ctx.fill_color
cpb_clr_text(cpb_textes, ctx2, col, row, cols, rows, col_width, row_height)
ctx2(img)
Capinibal.FxParams.step = (Capinibal.FxParams.step + 1) % grid_len
def cpb_img_gen_cloud(cpb_textes, ctx, img):
# multis-step does not look very good
# How could we prevent multistep from main loop?
# h and v centering together don't look very good
# We can force early exit by setting Capinibal.FxParams.step
# This can lead to switching to a new effect only if effect_images is <0
if Capinibal.verbose > 1:
print(img)
cloud_len = random.randint(6, 12) # FIXME
with Drawing(drawing=ctx) as clone_ctx: # <= Clones & reuse the parent context.
# ~ if Capinibal.FxParams.step == 0: before trans
# ~ Capinibal.cpb_set_bg(clone_ctx, Capinibal.FxParams.bg_color)
text_num = random.randrange(0, len(cpb_textes))
text = cpb_textes[text_num]
clone_ctx.font_size = int(random.randrange(Capinibal.min_font_size, Capinibal.max_font_size, 15))
if Capinibal.verbose > 1:
print("font size ", clone_ctx.font_size)
w, h, a = cpb_get_cached_text_w_h_a(text, clone_ctx, t=text_num)
if Capinibal.FxParams.halign_center:
# Strict centering
#~ x = (Capinibal.image_width - w) // 2
# Statistical centering
x = int(random.gauss((Capinibal.image_width - w) // 2,
(Capinibal.image_width - w) // 6))
else:
x=random.randrange(0, Capinibal.image_width - w)
x = cpb_clip(x, 0, Capinibal.image_width - w)
if Capinibal.FxParams.valign_center:
# Strict centering
#~ y = (Capinibal.image_height - h) // 2
# Statistical centering
y = int(random.gauss((Capinibal.image_height - h) // 2,
(Capinibal.image_height - h) // 6))
else:
y=random.randrange(a, Capinibal.image_height)
y = cpb_clip(y, 0, Capinibal.image_height - a) + a
if Capinibal.verbose > 1:
print("Cloud:", text, "at", x, y, )
clone_ctx.fill_color = Capinibal.FxParams.fg_color
clone_ctx.text(x, y, text)
clone_ctx(img)
Capinibal.FxParams.step = (Capinibal.FxParams.step + 1) % cloud_len
return False # Don't allow clearing matrix (there is none)
# currently unused
def cpb_seq_gen_matrix(cpb_textes, ctx, pipe):
textes_len = len(cpb_textes)
coord_len = int(textes_len * 4)
candidate_coord = []
for i in range(0, coord_len):
candidate_coord.append(i)
clone_ctx = Drawing(drawing=ctx)
with Image(width=Capinibal.image_width, height=Capinibal.image_height, background=Color('lightsalmon')) as img:
quarter_width = Capinibal.image_width / 4
deci_height = int(Capinibal.image_height / 10)
for i in range(0, coord_len):
print(img)
coord_index = random.randrange(0, len(candidate_coord))
coord = candidate_coord[coord_index]
candidate_coord.pop(coord_index)
y = int(coord / 4)
x = coord
if coord > 4:
x = coord % 4
print(coord, ': ', x, ' - ', y)
cddt_text = random.randrange(0, textes_len)
clone_ctx.fill_color = Capinibal.FxParams.fg_color
clone_ctx.text(x * quarter_width, (1 + y) * deci_height, cpb_textes[cddt_text])
clone_ctx(img)
pipe.stdin.write(img.make_blob('RGB'))
def cpb_img_gen_solo_centered(cpb_texte, ctx, img):
w, h, a = cpb_get_cached_text_w_h_a(cpb_texte, ctx)
if Capinibal.verbose > 1:
print(img)
with Drawing(drawing=ctx) as clone_ctx: # <= Clones & reuse the parent context.
Capinibal.cpb_set_bg(clone_ctx, Capinibal.FxParams.bg_color)
x = int(img.width - w) // 2
if x < 0:
x = 0
y = int(img.height + a) // 2
if y < 0:
y = 0
clone_ctx.fill_color = Capinibal.FxParams.fg_color
clone_ctx.text(x, y, cpb_texte)
clone_ctx(img)
def cpb_img_gen_solo_rdn_size_centered(cpb_texte, ctx, img, coin=1):
old_size = ctx.font_size
if Capinibal.cpb_toss(coin):
ctx.font_size = int(random.randrange(Capinibal.min_font_size, Capinibal.max_font_size, 15))
if Capinibal.verbose > 1:
print("font size ", ctx.font_size)
cpb_img_gen_solo_centered(cpb_texte, ctx, img)
ctx.font_size = old_size
###############################
#
# MainLoop (will be slot machine) and Main
#
#########################################
def cpb_capinibal(pipe, frames):
ctxs = []
# These 6 variables for testing only
#~ cpb_get_text_metrics.max_delta_w = 0
#~ cpb_get_text_metrics.min_delta_w = 0
#~ cpb_get_text_metrics.max_delta_h = 0
#~ cpb_get_text_metrics.min_delta_h = 0
#~ cpb_get_text_metrics.max_delta_a = 0
#~ cpb_get_text_metrics.min_delta_a = 0
cpb_fill_metrics_cache(ctxs)
if Capinibal.verbose > 1: # Show precomputed values
cpb_print_metrics_cache()
ctx_count = len(ctxs)
# Comment lines below if a particular fill is not wanted
# functions with a matching clr function must come first
cpb_gen_funs = [
cpb_img_gen_matrix_line,
cpb_img_gen_matrix_grid,
cpb_img_gen_matrix_col,
cpb_img_gen_matrix_diag,
cpb_img_gen_cloud,
cpb_img_gen_matrix_full,
]
cpb_gen_fun = 0
cpb_clr_funs = [
cpb_img_clr_matrix_line,
cpb_img_clr_matrix_grid,
cpb_img_clr_matrix_col,
cpb_img_clr_matrix_diag,
]
cpb_clr_fun = 0
step = 1 if frames > 0 else 0 # 0 => infinite loop
#~ in_loop = 0 # number of matrix image
#~ in_blink = 5 # number of matrix(s) loop
blinking = False
clearing = False
in_matrix = False # Single or multiple text
#~ Capinibal.FxParams.matrix_align = False
Capinibal.FxParams.valign_center = False
Capinibal.FxParams.halign_center = False
phase = 1000 # Ensure first image is generated right away
effect_images = 0
blob = None
# Use two images so that we can use one for matrices/cloud
# and one for single text; this allows switching quickly
# between these two effects
image_combi = Image(width=Capinibal.image_width, height=Capinibal.image_height, background=Color('transparent'))
image_combi_bg = Image(width=Capinibal.image_width, height=Capinibal.image_height, background=Capinibal.FxParams.bg_color)
image_solo = Image(width=Capinibal.image_width, height=Capinibal.image_height, background=Color('transparent'))
Capinibal.FxParams.step = 0
cpb_img_gen_matrix_grid.cells_num = []
cpb_img_clr_matrix_grid.cells_num = []
while False:
Capinibal.cpb_fill_color_gen(ctxs[0], 3)
cpb_textes = Capinibal.cpb_text_gen_solo()
cpb_img_gen_solo_rdn_size_centered(cpb_textes, ctxs[0], image_solo, 5)
blob = image_solo.make_blob('RGB')
pipe.stdin.write(blob)
bg_next_valid = False
try:
# Loop over frames
while frames >= 0:
frames -= step
#~ if Capinibal.verbose:
#~ print ("frames:", frames, " in_loop:", in_loop, "blinking:", blinking, " in_matrix:", in_matrix, " matrix_align:", matrix_align, " phase:", phase)
phase += Capinibal.FxParams.speed
if phase >= 1000: # Time to generate a new image!
if Capinibal.verbose:
print("New image, clearing:", clearing,
"step:", Capinibal.FxParams.step)
phase = phase % 1000
# Pickup new bg color
if not bg_next_valid:
Capinibal.cpb_get_bg_start(10,550, Capinibal.cpb_toss(25))
if not clearing: #FIXME bg fade is suspend time to solve clear rectangle issue (but will be optionnal!!!)
bg_next_valid, bg_next = Capinibal.cpb_get_bg_next()
if bg_next_valid:
Capinibal.FxParams.bg_color = bg_next
Capinibal.ctx_num = random.randrange(0, ctx_count) # Random context means random font
ctx = ctxs[Capinibal.ctx_num]
#~ Capinibal.cpb_fill_color_gen(ctx, 3) # Random color... sometimes!
# FIXME (duplicate ?) Pickup new fg color ,
# TODO fade color fg
if Capinibal.cpb_toss(3):
Capinibal.FxParams.fg_color = Capinibal.cpb_random_color()
ctx.fill_color = Capinibal.FxParams.fg_color
effect_images -= 1 #FIXME test over effect_images<0 always true!
if effect_images < 0 and Capinibal.FxParams.step == 0 and not clearing:
# Time to setup a new effect sequence!
# Also test step to avoid interrupting an effect
# before its end.
# FIXME interrupting might be interesting too
if Capinibal.verbose:
print("new effect")
# FIXME the probabilities below should be controllable through OSC
# FIXME the probabilities below should be effect dependant
# using an effect x parameter probability matrix
#~ clearing = False
effect_images = random.randint(10, 30)
effect_steps = random.randint(1, 4)
blinking = random.random() > 0.8
in_matrix = random.random() > 0.33
#~ Capinibal.FxParams.matrix_align = random.random() > 0.5
Capinibal.FxParams.random_order = random.random() > 0.33
Capinibal.FxParams.reverse_cols = random.random() > 0.5
Capinibal.FxParams.reverse_rows = random.random() > 0.5
Capinibal.FxParams.valign_center = random.random() > 0.5
Capinibal.FxParams.halign_center = random.random() > 0.5
# FIXME how can we clear image from here? Should we?
#~ Capinibal.cpb_fill_color_gen(ctx2) # Random background color
#~ ctx2.color(0, 0, 'reset')
#~ ctx2(image)
# When done with ctx, will keep resetting color at each image
# When done inside effects, uses cloned context, works
Capinibal.FxParams.fg_color = Capinibal.cpb_random_color()
ctx.fill_color = Capinibal.FxParams.fg_color #FIXME could be removed
if Capinibal.verbose:
print("New sequence for", effect_images, "images, ",
effect_steps, "steps at a time,",
"background:", Capinibal.FxParams.bg_color,
"foreground:", Capinibal.FxParams.fg_color,
"blinking:", blinking,
"in matrix:", in_matrix, "."
)
#~ if Capinibal.FxParams.step == -1: # Magic value will start clearing
#~ ctx.fill_color = Capinibal.FxParams.bg_color
#~ Capinibal.FxParams.step = 0
#~ clearing = True
if in_matrix:
# Multiple texts (grid or cloud)
# row and column count and font size need to be set prior to calling effect
# i.e. at step 0
# They must not be changed for any other step
# The same image is reused so that results of previous steps are kept
if Capinibal.FxParams.step == 0 and not clearing:
# Before image generator function is called for step 0,
# we initialize some random variables.
# If clearing, we want to use the same grid as for filling,
# we don't want to set new values for rows and columns.
cpb_textes = cpb_text_gen_full()
cpb_gen_fun = (cpb_gen_fun + 1) % len(cpb_gen_funs) # Ensures each function is used (for testing)
#~ cpb_gen_fun = random.randrange(0, len(cpb_gen_funs))
if Capinibal.verbose:
print('Selected effect:', cpb_gen_funs[cpb_gen_fun], ', effect image counter:', effect_images)
# FIXME How do we know whether effect is multi-step or not?