-
Notifications
You must be signed in to change notification settings - Fork 0
/
fireNFX_Utils.py
1018 lines (861 loc) · 34.4 KB
/
fireNFX_Utils.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
import sys
import math
import transport
import time
import device
from fireNFX_Classes import TnfxParameter, TnfxChannelPlugin, cpChannelPlugin, cpMixerPlugin #, _rd3d2PotParams
import utils
import plugins
import mixer
import playlist
import ui
import channels
import general
from midi import *
from fireNFX_Colors import *
from fireNFX_Defs import *
from fireNFX_DefaultSettings import *
from fireNFX_FireUtils import *
import fireNFX_Anim as anim
# # enum code from https://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python
def enum(**enums):
return type('Enum', (), enums)
dimDim = Settings.DIM_DIM
dimNormal = Settings.DIM_NORMAL
dimBright = Settings.DIM_BRIGHT
dimDefault = dimNormal
dimFull = 0
# snap defs are in MIDI.py aka Snap_Cell, Snap_line, etc
SnapModes = enum( Line = 0,
Cell = 1,
NoSnap = 3, # "None" is a Python built-in constant so I use "NoSnap" instead
Step_6th = 4,
Step_4th = 5,
Step_3rd = 6,
Step_Half = 7,
Step = 8,
Beat_6th = 9,
Beat_4th = 10,
Beat_3rd = 11,
Beat_Half = 12,
Beat = 13,
Bar = 14
)
class SnapModesOld: # no enums :(
Line = 0
Cell = 1
NoSnap = 3
Step_6th = 4
Step_4th = 5
Step_3rd = 6
Step_Half = 7
Step = 8
Beat_6th = 9
Beat_4th = 10
Beat_3rd = 11
Beat_Half = 12
Beat = 13
Bar = 14
SnapModesText = ["Line", "Cell", "?", "None",
"1/6 Step", "1/4 Step", "1/3 Step", "1/2 Step", "Step",
"1/6 Beat", "1/4 Beat", "1/3 Beat", "1/2 Beat", "Beat",
"Bar"]
#define your list of snap modes to cycle through.
SnapModesList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
InitialSnapIndex = 0 #initial value - index of above - 0-based
RepeatSnapIdx = 7 # for repeat mode
BeatLengthNames = ['Bar/Whole', 'Half', 'Quarter', 'Dotted 8th', '8th', '16th', '32nd', '64th']
BeatLengthDivs = [0, .5, 1, 1.5, 2, 4, 8, 16] # or [0, .5, 1, 1.33333, 2, 4, 8, 16] ?
BeatLengthSnap = [Snap_Beat, Snap_Beat, Snap_Beat, Snap_ThirdBeat, Snap_FourthBeat, Snap_Step, Snap_HalfStep, Snap_FourthStep]
BeatLengthsDefaultOffs = 6 # offset of above
def SendCC(ID, Val):
if (not device.isAssigned()):
return
device.midiOutNewMsg(MIDI_CONTROLCHANGE + (ID << 8) + (Val << 16), ID)
def getParamCaption(chanIdx, paramIdx, mixSlotIdx = -1):
return plugins.getParamName(paramIdx, chanIdx, mixSlotIdx) # -1 denotes not mixer
def getPluginParam(chanIdx, paramIdx, prn = False, mixSlotIdx = -1): # -1 denotes not mixer
hasCaption = (len(plugins.getParamName(paramIdx, chanIdx, mixSlotIdx)) > 0)
caption = plugins.getParamName(paramIdx, chanIdx, mixSlotIdx)
value = plugins.getParamValue(paramIdx, chanIdx, mixSlotIdx)
try:
valuestr = plugins.getParamValueString(paramIdx, chanIdx, mixSlotIdx)
except:
valuestr = ''
bipolar = False
name, uname, varName = getPluginNames(chanIdx, mixSlotIdx)
spclCnt = plugins.getPadInfo(chanIdx, mixSlotIdx, PAD_Count, paramIdx)
if(hasCaption): # if(caption != ''):
if prn:
print(varName + ".addParamToGroup('ALL', TnfxParameter(" + str(paramIdx) +", '" + caption +"', 0, '" + valuestr + "', " + str(bipolar) + ") )")
# if( spclCnt > 0 ):
# semitone = plugins.getPadInfo(chanIdx, mixSlotIdx, PAD_Semitone, paramIdx)
# padcolor = plugins.getPadInfo(chanIdx, mixSlotIdx, PAD_Color, paramIdx)
# for spclIdx in range(plugins.getPadInfo(chanIdx, mixSlotIdx, 0, paramIdx)):
# print('# Semitone: ', semitone )
# print('# Color:', hex(padcolor), padcolor )
# print('# ValStr', paramIdx, valuestr )
# print('# Color0', paramIdx, plugins.getColor(chanIdx, -1, 0, paramIdx) )
# print('# Color1', paramIdx, plugins.getColor(chanIdx, -1, 1, paramIdx) )
# print('----------------------')
return TnfxParameter(paramIdx, caption, value, valuestr, bipolar)
def getBeatLenInMS(div):
# 0 = 1 bar whole not
# 0.5 = half
# 1 = Quarter
# 1.33333 = dotted 8?
# 2 = Eighth
# 4 = sixteenth
# 8 = 32nd
# 16 = 64th
tempo = mixer.getCurrentTempo(0)
beatlen = (60000/tempo)
if(div > 0 ):
timeval = (beatlen/div) * 1000 #
else: #when div = 0...
timeval = beatlen * 4000 # one bar aka whole note.
return int(timeval)
def RemoveBadChars(badChars, textStr):
res = textStr
for badChar in badChars:
res = res.replace(badChar, '')
return res
def getAlphaNum(textStr, allowSpaces = False):
res = textStr
for idx, char in enumerate(textStr):
if (allowSpaces) and (char == ' '):
pass
elif(not char.isalnum()):
res = res.replace(char, '')
return res
def getPluginNames(chanIdx = -1, mixSlotIdx = -1):
if(mixSlotIdx > -1):
if (chanIdx == -1):
chanIdx = mixer.trackNumber()
else:
if chanIdx == -1:
chanIdx = channels.selectedChannel()
name = plugins.getPluginName(chanIdx, mixSlotIdx, 0)
uname = plugins.getPluginName(chanIdx, mixSlotIdx, 1)
vname = getAlphaNum("plugin{}".format(name))
return name, uname, vname
def getPluginInfo(chanIdx, prn = False, inclBlanks = False, mixSlotIdx = -1):
if(mixSlotIdx > -1):
if (chanIdx == -1):
chanIdx = mixer.trackNumber()
else:
if chanIdx == -1:
chanIdx = channels.selectedChannel()
name, uname, vname = getPluginNames(chanIdx, mixSlotIdx)
res = TnfxChannelPlugin(name, uname)
res.Type = cpChannelPlugin
type = 'cpChannelPlugin'
if(mixSlotIdx > -1):
res.Type = cpMixerPlugin
type = 'cpMixerPlugin'
res.Parameters.clear()
pCnt = plugins.getParamCount(chanIdx, mixSlotIdx)
knobsSamples = []
varName = vname
fileName = vname + '.py'
if(prn):
print('# -----[ COPY AFTER THIS LINE, BUT DO NOT INCLUDE ]--------------------------------------------------------')
print('# Save this file as: "{}{}"'.format(sys.path[1],fileName))
print('# ')
print('# PluginName: ', res.Name)
print('# Created by: ', '<your name here>')
print('# ')
print('from fireNFX_Classes import TnfxParameter, TnfxChannelPlugin, cpChannelPlugin, cpMixerPlugin')
print('from fireNFX_PluginDefs import USER_PLUGINS')
print(varName + " = TnfxChannelPlugin('" + name + "', '', " + type + ")")
print("if({}.Name not in USER_PLUGINS.keys()):".format(varName))
print(" USER_PLUGINS[{}.Name] = {}".format(varName, varName))
print(" print('{} parameter definitions loaded.')".format(res.Name))
print(" ")
for paramIdx in range(0, pCnt):
param = getPluginParam(chanIdx, paramIdx, prn, mixSlotIdx)
if(param.Caption != "") or (inclBlanks):
if(param.Caption == ""):
param.Caption == "{}.Offset".format(paramIdx)
if('MIDI CC' in param.Caption):
param.Caption = param.Caption.replace('MIDI CC', '').replace('#', '').lstrip()
res.addParamToGroup("MIDI CCs", param)
else:
res.addParamToGroup("ALL", param)
if(False): #(res.Name in _rd3d2PotParams.keys()):
res.addParamToGroup("rd32d3 Ext", param)
knobsSamples.append(param)
elif(len(knobsSamples) < 8):
knobsSamples.append(param)
res.Parameters.append(param)
if(prn):
print('# [PARAMETER OFFSETS] ')
print('# Notice, the code lines above contains the text "TnfxParameter(" followed by a number')
print('# That number represents the parameter offset for the parameter described on that line')
print('# You can use the parameter offset number to program your own USER Knob mappings below')
print("# ")
sampleCount = len(knobsSamples)
if(sampleCount > 0 ):
paramlist = []
for idx, sample in enumerate(knobsSamples):
if idx < 8:
paramlist.append(sample.Offset)
else:
break
print('# [HOW TO SET CUSTOM KNOB MAPPINGS]')
print('# The assignKnobs() function takes a list of up to 8 parameter offsets.')
print('# The list must be in brackets like this [ 21, 12, 3, 7]. Max 8 offsets in list.')
print('# it assigns them in order from :')
print('# USER1, KNOBS 1-4 as the first 4 params')
print('# USER2, KNOBS 1-4 as the second 4 params')
print('')
print('# [ENABLING THE CUSTOM MAPPING]')
print("# Comment/Uncomment the next line to disable/enable the knob mappings. ")
print("#{}.assignKnobs({}) ".format(varName, str(paramlist)))
print(" ")
print("# [LAST STEP. DO NOT FORGET. NEEDED TO INCLUDE YOUR MAPPINGS] ")
print("# Add the following line (without the #) to the end of fireNFX_CustomPlugins.py")
print("#from {} import {}".format(varName, varName) )
print(' ')
print('# -----[ COPY UP TO THIS LINE, BUT DO NOT INCLUDE ]---------------')
return ""
return res
def ShowPluginInfo(chanIdx):
getPluginInfo(chanIdx, True)
def getBarFromAbsTicks(absticks):
return ( absticks // general.getRecPPB() ) + 1
def getAbsTicksFromBar(bar):
# thx to HDSQ from https://forum.image-line.com/viewtopic.php?p=1740588#p1740588
return (bar - 1) * general.getRecPPB()
#from the original AKAI script
def FadeColor(StartColor, EndColor, ColorSteps):
rStart, gStart, bStart = ColorToRGB(StartColor)
rEnd, gEnd, bEnd = ColorToRGB(EndColor)
ratio = ColorSteps / 255
rEnd = round(rStart * (1 - ratio) + (rEnd * ratio))
gEnd = round(gStart * (1 - ratio) + (gEnd * ratio))
bEnd = round(bStart * (1 - ratio) + (bEnd * ratio))
return RGBToColor(rEnd, gEnd, bEnd)
mvUp = 0
mvUpRight = 1
mvRight = 2
mvDownRight = 3
mvDown = 4
mvDownLeft = 5
mvLeft = 6
mvUpLeft = 7
mvStay= 9
def MovePad(PadToMoveIdx, direction, StartColor = cGreen, EndColor = cWhite, colorStep = 0):
padRow = PadToMoveIdx // 16
padCol = PadToMoveIdx % 16
addVal = 0
if(direction != mvStay):
#directions are indicated in a clock wise manner starting with the top
if(direction in [mvUpLeft, mvUp, mvUpRight]): # up
if(padRow > 0):
addVal += -16
if(direction in [mvUpRight, mvRight, mvDownRight]):
if(padCol < 16):
addVal += +1
if(direction in [mvDownLeft, mvDown, mvDownRight]): # down
if(padRow < 3):
addVal += 16
if(direction in [mvUpLeft, mvLeft, mvDownLeft]):
if(padCol > 0):
addVal += -1
newPadIdx = PadToMoveIdx + addVal
stepSize = 255//4
newColor = FadeColor(StartColor, EndColor, colorStep * stepSize)
oldColor = newColor # FadeColor(StartColor, EndColor, (colorStep + 1) * stepSize)
SetPadColor(newPadIdx, newColor, dimBright, False)
SetPadColor(PadToMoveIdx, oldColor, dimDefault, False)
return newPadIdx
_baseDelay = getBeatLenInMS(8)/1000
_testpath = [mvStay, mvLeft, mvUp, mvRight, mvRight, mvDown, mvDown, mvLeft, mvLeft, mvLeft, mvUp, mvUp, mvUp, mvRight, mvRight, mvRight, mvUp]
# ^ 34 start pad
#_testpath = [mvStay, mvDown, mvDown, mvDown, mvRight, mvUp, mvUp, mvUp, mvRight,
# mvDown, mvDown, mvDown, mvRight, mvUp, mvUp, mvUp]
def BankMoves(startpad = 34, path = _testpath, color = cGreen, finishAtStart = True):
delay = _baseDelay
pad = startpad
pad2 = startpad + 4
pad3 = startpad + 8
pad4 = startpad + 12
for step in _testpath:
pad = MovePad(pad, step, color, cBlack, 0)
pad2 = MovePad(pad2, step, color, cBlack, 0)
pad3 = MovePad(pad3, step, color, cBlack, 0)
pad4 = MovePad(pad4, step, color, cBlack, 0)
time.sleep(delay) #getBeatLenInMS(4)/1000
if(finishAtStart):
pad = MovePad(startpad, step, color, cBlack, 0)
pad2 = MovePad(startpad+4, step, color, cBlack, 0)
pad3 = MovePad(startpad+8, step, color, cBlack, 0)
pad4 = MovePad(startpad+12, step, color, cBlack, 0)
def LoopBankTest():
BankMoves()
BankMoves()
BankMoves()
BankMoves()
import _thread
def TestThreadMove():
delay = _baseDelay * 4
startPad = 0
baseColor = cRed
for goOffs in _gradientOffs:
color = getGradientOffs(baseColor, goOffs)
_thread.start_new_thread(BankMoves, (startPad, _testpath, color ) )
time.sleep(delay)
# menu offsets, use a negatwe go negatiove because it is more reliable to move backwards
MainMenu = {'File':'', 'Edit':'LLLL,LLL', 'Add':'LLLL,LL', 'Patterns':'LLL,LL', 'View':'LLL,L', 'Options':'LLL', 'Tools':'LL', 'Help':'L'}
PRToolsMenu = {'Tools', 'LL'}
PRTools = {}
def menuPause(seconds = Settings.MENU_DELAY):
time.sleep(seconds)
def ProcessKeys(cmdStr):
commands = {'U':ui.up, 'D':ui.down, 'L':ui.left, 'R':ui.right,
'E':ui.enter, 'S': ui.escape, 'N': ui.next, ',':menuPause }
for cmd in cmdStr:
commands.get(cmd.upper(), menuPause)()
def NavigateFLMenu(cmdString = '', altmenu = False):
# this code was inspired by HDSQ's implementation:
# https://github.com/MiguelGuthridge/Universal-Controller-Script/blob/main/src/plugs/windows/piano_roll.py
#
if (ui.isInPopupMenu()):
ui.closeActivePopupMenu()
# open the File menu
if(altmenu):
transport.globalTransport(FPT_ItemMenu, 1)
else:
transport.globalTransport(FPT_Menu, 1)
if(ui.getFocused(widPianoRoll) == 1): # auto move to the tools when the PR is active.
ProcessKeys('LL')
if(len(cmdString) > 0):
ProcessKeys(cmdString)
def ShowScriptDebug():
ui.showWindow(widChannelRack) # make CR the active window so it pulls up the main menu
NavigateFLMenu(',LLLLDDDDDDDDDDE') # series of keys to pass
def ShowProject():
ui.showWindow(widChannelRack) # make CR the active window so it pulls up the main menu
NavigateFLMenu(',LLL,LUUUUUELL') # series of keys to pass
def ViewArrangeIntoWorkSpace():
ui.showWindow(widChannelRack) # make CR the active window so it pulls up the main menu
NavigateFLMenu(',LLLLDDDDDDDDDDDDDDDDDDRDE') # series of keys to pass
# VERSION Helpers
# Producer Edition v20.99.3000 [build 3209]
# #
# def getVersionNum():
# return ui.getVersion()[ui.getVersion().index('v')+1:ui.getVersion().index('[')-1]
# def getVersionTuple(v = ''):
# if v == '':
# v = getVersionNum()
# return tuple(map(int, (v.split("."))))
def checkFLVersionAtLeast(version):
res = FLVersionAtLeast(version)
if(not res):
print('* FL Version is not supported at this time. *')
return res
def hidePLRect():
showPLRect(-1,0,0,0)
def showPLRect(startBar, endBar, firstPLTrackIdx, numTracks):
if(startBar>0): # 0-based
startBar = startBar - 1
playlist.liveDisplayZone(startBar, firstPLTrackIdx, endBar, firstPLTrackIdx+numTracks)
def test():
return
"""
Helper code for dealing with version checking.
Authors:
* NFX (main implementation)
* Miguel Guthridge (minor improvements)
"""
def getVersionStr() -> str:
"""
Returns the version string with just the version number (eg '20.9.2')
"""
return ui.getVersion()[ui.getVersion().index('v')+1:ui.getVersion().index('[')-1]
def getVersionTuple(v: str) -> tuple[int, int, int]:
"""
Converts a version string into a tuple for easy comparison with other version strings
"""
if v == '':
v = getVersionStr()
return tuple(map(int, (v.split("."))))
def FLVersionAtLeast(version: str) -> bool:
"""
Expects a three part version string, ie. "20.99.0", return True when FL version is equal or greater than
"""
return getVersionTuple(getVersionStr()) >= getVersionTuple(version)
# color funcs
def ColorToRGBA(Color):
return (Color >> 16) & 0xFF, (Color >> 8) & 0xFF, Color & 0xFF, (Color >> 24) & 0xFF
def RGBAToColor(R,G,B,A = 0xFF):
return (A << 24) | (R << 16) | (G << 8) | B
def ColorToRGB(Color):
return (Color >> 16) & 0xFF, (Color >> 8) & 0xFF, Color & 0xFF
def RGBToColor(R,G,B):
return (R << 16) | (G << 8) | B
def ColorScaleUp(rgb_int):
"""
Scale an RGB color so that the maximum component reaches 255.
:param rgb_int: An integer representing the RGB value (0xRRGGBB).
:return: An integer representing the scaled RGB value (0xRRGGBB).
"""
# Extract the individual color components
red = (rgb_int >> 16) & 0xFF
green = (rgb_int >> 8) & 0xFF
blue = rgb_int & 0xFF
# Find the maximum component value
max_component = max(red, green, blue)
if max_component == 0:
# Avoid division by zero, return black (0x000000)
return 0
# Calculate the scaling factor
desired_scale_factor = 255 / max_component
# Limit the scale factor to a maximum of 2.0
scale_factor = min(2.0, desired_scale_factor)
# Scale each component
red = int(red * scale_factor)
green = int(green * scale_factor)
blue = int(blue * scale_factor)
# Ensure that the values don't exceed 255 due to rounding
red = min(255, red)
green = min(255, green)
blue = min(255, blue)
# Reassemble the RGB components
scaled_rgb_int = (red << 16) | (green << 8) | blue
return scaled_rgb_int
def ColorToDelphiColor(rgb_int):
"""
Convert an RGB integer to a BGR integer.
:param rgb_int: An integer representing the RGB value (0xRRGGBB).
:return: An integer representing the BGR value (0xBBGGRR).
"""
rgb_int = ColorWithAlpha(ColorScaleUp(rgb_int), 20)
# Extract the individual color components
red = (rgb_int >> 16) & 0xFF # Extract the Red component
green = (rgb_int >> 8) & 0xFF # Extract the Green component
blue = rgb_int & 0xFF # Extract the Blue component
# Reassemble in BGR order
bgr_int = (blue << 16) | (green << 8) | red
return bgr_int
def ColorWithAlpha(color, alpha = 0):
"""
Add an alpha channel to an integer RGB value.
:param color: An integer representing the RGB value (0xRRGGBB).
:param alpha: An integer value for the alpha channel (0-255).
:return: An integer representing the RGBA value (0xAARRGGBB).
"""
# Ensure alpha is within the valid range
alpha = max(0, min(255, alpha))
# Shift RGB by 8 bits to the left and add the alpha value
rgba_int = (alpha << 24) | color
return rgba_int
def GradientTest(stepsize = 8):
#def Gradient(color1, color2, stepsize, padOffs=0):
#stepsize = 4 # 255//5
Gradient(cBlue, cOff, stepsize, 0)
Gradient(cPurple, cOff, stepsize, 16)
Gradient(cMagenta, cOff, stepsize, 32)
Gradient(cRed, cOff, stepsize, 48)
Gradient(cOrange, cOff, stepsize, 8)
Gradient(cYellow, cOff, stepsize, 24)
Gradient(cGreen, cOff, stepsize, 40)
Gradient(cCyan, cOff, stepsize, 56)
def ShadeTestOld():
Shades(cBlue,0)
Shades(cPurple, 16)
Shades(cMagenta, 32)
Shades(cRed, 48)
Shades(cOrange, 4)
Shades(cYellow, 20)
Shades(cGreen, 36)
Shades(cCyan, 52)
def ShadeTest():
Shades(cBlue,0)
Shades(cPurple, 16)
Shades(cMagenta, 32)
Shades(cRed, 48)
Shades(cOrange, 4)
Shades(cYellow, 20)
Shades(cGreen, 36)
Shades(cCyan, 52)
Shades(cLime, 8)
Shades(cTeal, 24)
Shades(cWhite, 40)
Shades(cBlack, 56)
def getShadeOld(baseColor, shadeOffs):
multLighten = 1.4 # 1.33
multDarken = .33 #.23
baseColor, r, g, b = AdjustedFirePadColor(baseColor)
if(shadeOffs == shDim):
return ShadeOld(baseColor, multDarken, 2) # dim
elif(shadeOffs == shDark):
return ShadeOld(baseColor, multDarken, 1) # dark
elif(shadeOffs == shNorm):
return baseColor # norm
elif(shadeOffs == shLight):
return ShadeOld(baseColor, multLighten, 1) # light
else:
return baseColor
def getShade(baseColor, shadeOffs):
if(shadeOffs == shDim):
return Shade(baseColor, -0.98) # dim
elif(shadeOffs == shDark):
return Shade(baseColor, -0.89) # dark
elif(shadeOffs == shNorm):
return baseColor # norm
elif(shadeOffs == shLight):
return Shade(baseColor, 0.2) # light
else:
return baseColor
def ShowLayout(pads1, color1, pads2, color2):
for pad in pads1:
SetPadColor(pad, color1, dimDefault)
for pad in pads2:
SetPadColor(pad, color2, dimDefault)
def Dims(color, padOffs=0):
SetPadColor(0+padOffs, color, dimDim)
SetPadColor(1+padOffs, color, dimDefault)
SetPadColor(2+padOffs, color, dimBright)
SetPadColor(3+padOffs, color, dimFull)
def ShadesOld(color, padOffs=0):
SetPadColor(0+padOffs, getShadeOld(color, shDim), 0)
SetPadColor(1+padOffs, getShadeOld(color, shDark), 0)
SetPadColor(2+padOffs, getShadeOld(color, shNorm), 0)
SetPadColor(3+padOffs, getShadeOld(color, shLight), 0)
def Shades(color, padOffs=0):
SetPadColor(0+padOffs, getShade(color, shDim), 0)
SetPadColor(1+padOffs, getShade(color, shDark), 0)
SetPadColor(2+padOffs, getShade(color, shNorm), 0)
SetPadColor(3+padOffs, getShade(color, shLight), 0)
def Grads(color, stepsize = 64):
Gradient(cOff, color, stepsize, 0, 32)
Gradient(color, cWhite, stepsize, 32, 32)
def Gradient(color1, color2, stepsize, padOffs=0, len=8):
gradientList = []
for pad in range(len):
step = (127//stepsize) * pad
col = FadeColor(color1, color2, step)
if(padOffs > -1):
SetPadColor(pad+padOffs, col, 0)
gradientList.append(col)
return gradientList
goDim = 0
goDark = 16
goNorm = 32
goLight = 48
_gradientOffs = [goLight, goNorm, goDark, goDim] # light to dark
def getGradientOffs(baseColor, goVal):
gradientList = Gradient(cOff, baseColor, 64, -1, 32)
gradientList.extend(Gradient(baseColor, cWhite, 64, -1, 32))
return gradientList[goVal] #, gradientList
def Shade(color, factor):
return adjust_color_by_factor(color, factor)
def ShadeOld(color, mul = 1.1, offs = 0):
color1 = color
for i in range(3):
if(i > 0):
color = ColorMult(color, mul)
color1 = ColorMult2(color, mul)
if(i == offs):
return color1
def AnimOff(padIdx, color, steps = 16, wait = 0.1):
OrigColor = ColorMap[padIdx].PadColor
Color1 = cWhite # getShade(color, shLight)
Color2 = cOff # getShade(color, shDim)
for step in range(steps):
stepSize = 255//steps
col = FadeColor(OrigColor, Color2, step * stepSize)
SetPadColor(padIdx, col, 0)
time.sleep(wait)
def AnimOn(padIdx, color, steps = 16, wait = 0.1):
OrigColor = ColorMap[padIdx].PadColor
Color1 = cWhite # getShade(color, shLight)
Color2 = cOff # getShade(color, shDim)
for step in range(steps):
stepSize = 255//steps
col = FadeColor(Color2, OrigColor, step * stepSize)
SetPadColor(padIdx, col, 0)
time.sleep(wait)
def CycleColors(len = 64, steps = 8, freq = 0.5):
center = 128
amplitude = 127
for inc in range(len):
# value = Math.sin(frequency*increment)*amplitude + center;
rPhase = 0
gPhase = 2 * math.pi/2
bPhase = 4 * math.pi/steps
rFreq = 2 * math.pi/steps
gFreq = 2 * math.pi/steps
bFreq = 2 * math.pi/steps
red = int( math.sin(rFreq * inc + rPhase) * amplitude + center )
green = int( math.sin(gFreq * inc + gPhase) * amplitude + center )
blue = int( math.sin(bFreq * inc + bPhase) * amplitude + center )
col = RGBToColor(red, green, blue)
print(inc % 64, "color =",hex(col), '#', col, 'rgb', red, green, blue)
#if(inc < 64):
SetPadColor(inc % 64, col, 0)
#time.sleep(0.001)
def ColorMult(color, mul):
r, g, b = ColorToRGB(color)
r *= mul
g *= mul
b *= mul
r2, g2, b2 = redistribute_rgb(r, g, b)
return RGBToColor(r2, g2, b2)
def ColorMult2(color, mul):
r, g, b = ColorToRGB(color)
r *= mul
g *= mul
b *= mul
r2, g2, b2 = clamp_rgb(r, g, b)
return RGBToColor(r2, g2, b2)
def adjust_color_by_factor(hex_color, factor):
"""
Adjusts the given hex color by the specified factor.
Lightens or darkens the color based on the factor.
:param hex_color: Original color in hex format (e.g., 0x0000ff)
:param factor: A float where positive values lighten and negative values darken the color
:return: Adjusted color in hex format
"""
# Ensure factor is within a reasonable range (-1 to 1)
factor = max(-1, min(1, factor))
# Convert hex color to RGB
r = (hex_color >> 16) & 0xFF
g = (hex_color >> 8) & 0xFF
b = hex_color & 0xFF
# Adjust the RGB values
if factor > 0:
# Lighten the color
r = r + (127 - r) * factor
g = g + (127 - g) * factor
b = b + (127 - b) * factor
else:
# Darken the color
factor = -factor
r = r * (1 - factor)
g = g * (1 - factor)
b = b * (1 - factor)
# Ensure values are within 0-127 range
r = min(127, max(0, int(r)))
g = min(127, max(0, int(g)))
b = min(127, max(0, int(b)))
# Convert back to hex
adjusted_hex_color = (r << 16) + (g << 8) + b
return adjusted_hex_color
def clamp_rgb(r, g, b):
# from https://stackoverflow.com/questions/141855/programmatically-lighten-a-color
return min(127, int(r)), min(127, int(g)), min(127, int(b))
def redistribute_rgb(r, g, b):
# from https://stackoverflow.com/questions/141855/programmatically-lighten-a-color
threshold = 255.999
m = max(r, g, b)
if m <= threshold:
return int(r), int(g), int(b)
total = r + g + b
if total >= 3 * threshold:
return int(threshold), int(threshold), int(threshold)
x = (3 * threshold - total) / (3 * m - total)
gray = threshold - x * m
return int(gray + x * r), int(gray + x * g), int(gray + x * b)
from fireNFX_DefaultSettings import Settings
def TestPallette(dimMult = 4):
for idx, color in enumerate(Settings.Pallette.values()):
SetPadColor(idx+0, color, 0, False, False, dimMult)
SetPadColor(idx+16, color, Settings.DIM_BRIGHT, False, False, dimMult)
SetPadColor(idx+32, color, Settings.DIM_NORMAL, False, False, dimMult)
SetPadColor(idx+48, color, Settings.DIM_DIM, False, False, dimMult)
def Pallette(jumpBy = 64):
pad = 0
offs = 0
for r in range(0,128, jumpBy):
for g in range(0,128, jumpBy):
for b in range(0,128, jumpBy):
#print('pad', pad % 64, 'rgb', r,g,b, 'hex', hex(RGBToColor(r,g,b)) )
SetPadColor(pad % 64, RGBToColor(r,g,b), 0)
pad+= 1
def TestQuad(path = "DRULLDDRRRUUULLL", mirrMode = 0):
TestTraveler(cPurple, 4, 4, path, mirrMode)
def SetColorPadColorMatrix(submatrices, padIdx, color, dimF, altMode = 0):
#altMode 0 = None, 1 = X only, 2 = Y only, 3 = x,y, 4 = x y and xy
for idx, matrix in enumerate(submatrices):
if altMode > 0:
if altMode == 1 and (idx % 2 != 0):
matrix = anim.MirrorMatrix(matrix, True, False)
if altMode == 2 and (idx %2 != 0):
matrix = anim.MirrorMatrix(matrix, False, True)
if altMode == 3 and (idx %2 != 0):
matrix = anim.MirrorMatrix(matrix, True, True)
if altMode == 4:
matrixOffs = idx % 4
if matrixOffs > 0:
if (matrixOffs == 1): # alternate
matrix = anim.MirrorMatrix(matrix, True, False)
if (matrixOffs == 2): # alternate
matrix = anim.MirrorMatrix(matrix, False, True)
if (matrixOffs == 3): # alternate
matrix = anim.MirrorMatrix(matrix, True, True)
pads = anim.FlattenMatrix(matrix)
padNum = pads[padIdx]
SetPadColor(padNum, color, dimF)
def DrawTraveler(submatrices, traveler, mirrorMode = 0):
# modes 0 = none, 1 = X, 2 = y, 3 = x, y
dimF = 0 # no dim
color = traveler.color
SetColorPadColorMatrix(submatrices, traveler.getPadIndex(), color, dimF)
if mirrorMode > 0:
if mirrorMode in [1,3]:
SetColorPadColorMatrix(submatrices, traveler.getPadIndex(True, False), color, dimF)
if mirrorMode in [2,3]:
SetColorPadColorMatrix(submatrices, traveler.getPadIndex(False, True), color, dimF)
if mirrorMode in [3]:
SetColorPadColorMatrix(submatrices, traveler.getPadIndex(True, True), color, dimF)
def DrawTail(submatrices, traveler, mirrorMode = 0):
# modes 0 = none, 1 = X, 2 = y, 3 = x, y
dimF = 0
print('tail', traveler.tail)
sorted_tuples = sorted(traveler.tail.items(), key=lambda x: x[1], reverse=True) # Sort the list of tuples by the values in descending order
sorted_tail = dict(sorted_tuples) # Create a new dictionary from the sorted list of tuples
for padOffs, dimF in sorted_tail.items():
color = traveler.color
print('item', padOffs, dimF, traveler.color)
# if(dimF == 0):
# color = cRed
if(dimF >= traveler.tailSize):
color = cOff
# while we can use the traveler's color, we cannot rely upon it's position
# to give us the mirrored locations of the tail
SetColorPadColorMatrix(submatrices, padOffs, color, dimF, 0)
if mirrorMode > 0:
if mirrorMode in [1]:
x, y = anim.PadIndexToXY(padOffs, traveler.width, traveler.height, 1)
SetColorPadColorMatrix(submatrices, anim.XYToPadIndex(x, y, traveler.width), color, dimF, 1)
if mirrorMode in [2]:
x, y = anim.PadIndexToXY(padOffs, traveler.width, traveler.height, 2)
SetColorPadColorMatrix(submatrices, anim.XYToPadIndex(x, y, traveler.width), color, dimF, 2)
if mirrorMode in [3]:
x, y = anim.PadIndexToXY(padOffs, traveler.width, traveler.height, 3)
SetColorPadColorMatrix(submatrices, anim.XYToPadIndex(x, y, traveler.width), color, dimF, 3)
def TestTravelerLoop(color = cRed, width = 16, height = 4, path = 'LDLLUURRD', mirrMode = 0, centerStart = True, Looptimes = 4):
newpath = ''
for i in range(Looptimes):
newpath += path
TestTraveler(color, width, height, newpath, mirrMode, centerStart)
def TestTraveler(color = cRed, width = 16, height = 4, path = 'LDLLUURRD', mirrMode = 0, centerStart = True):
delay = 0.1
startX = 0
startY = 0
if(centerStart):
startX = (width//2) - 1
startY = (height//2) - 1
traveler = anim.Traveler(color, startX, startY, width, height) # init
submatrices = anim.SubDivideMatrix(anim._PadMatrix, height, width) # h, w
for step in path:
time.sleep(delay)
if step in ["Z", "0"]:
traveler.stay()
if step in ['L', '4']:
traveler.move_left()
if step in ['R', '6']:
traveler.move_right()
if step in ['U', '8']:
traveler.move_up()
if step in ['D', '2']:
traveler.move_down()
if step in ["7"]:
traveler.move_up(False)
traveler.move_left()
if step in ["9"]:
traveler.move_up(False)
traveler.move_right()
if step in ["1"]:
traveler.move_down(False)
traveler.move_left()
if step in ["3"]:
traveler.move_down(False)
traveler.move_right()
DrawTail(submatrices, traveler, mirrMode)
# finish tail
while len(traveler.tail.keys()) > 0:
traveler.stay()
time.sleep(delay)
print('cu', traveler.tail)
DrawTail(submatrices, traveler, mirrMode)
return
def get_note_time(note_length, tempo, dotted=False):
"""
Calculates the time (in milliseconds) for a note of the given length
at the given tempo (in beats per minute).
If `dotted` is True, the note is dotted (lengthened by 50%).
"""
# Define the number of milliseconds per minute
ms_per_minute = 60000
# Calculate the time for one beat at the given tempo
beat_time = ms_per_minute / tempo
# Calculate the time for the requested note length
if note_length == 1:
# Whole note
note_time = 4 * beat_time
elif note_length == 2:
# Half note
note_time = 2 * beat_time
elif note_length == 4:
# Quarter note
note_time = beat_time
elif note_length == 8:
# Eighth note
note_time = beat_time / 2
elif note_length == 16:
# Sixteenth note
note_time = beat_time / 4
elif note_length == 32:
# Thirty-second note
note_time = beat_time / 8
elif note_length == 64:
# Sixty-fourth note
note_time = beat_time / 16
else:
# Invalid note length
raise ValueError("Invalid note length")
# Check if the note is dotted
if dotted:
note_time *= 1.5
return note_time
last_time = None
def printts(text):
global last_time
# Get the current time in milliseconds
current_time = time.time() * 1000
# Calculate the time difference since the last call
if last_time is not None:
time_diff = current_time - last_time
else:
time_diff = 0
# Print the text with the timestamp
print(f"{text} ({time_diff:.2f} ms)")
# Update the last_time variable
last_time = current_time
def pseudo_random(seed=None):
if seed is not None:
# Use provided seed
value = seed
else:
# Use current time as seed
value = int(time.time() * 1000)
# Linear congruential generator parameters
a = 1103515245
c = 12345
m = 2**31