-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGHL_Vocals_Preview.lua
More file actions
2259 lines (1877 loc) · 110 KB
/
Copy pathGHL_Vocals_Preview.lua
File metadata and controls
2259 lines (1877 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
version_num="1.3"
-- Rastrea el proyecto actual
local currentProject = reaper.EnumProjects(-1)
-- Detecta cambios en la pista de voces
local vocalsHash = ""
-- Nota MIDI para Hero Power
HP=116
-- Estado de la reproducción
curBeat=0
-- RGBA -> 1.0
local function rgb2num(r, g, b)
g = g * 256
b = b * 256 * 256
return r + g + b
end
gfx.clear = rgb2num(30, 30, 40) -- color de fondo de la ventana
gfx.init("GHL Vocals Preview", 1000, 300, 0, 480, 150) -- Alto, Ancho, Eje X, Eje Y
-- Configurar conexión con el sintetizador JSFX para el Pitch Guide
reaper.gmem_attach("Effect_PitchGuide")
-- Variables Globales
local char = -1
vocalsTrack = nil
phrases = {}
currentPhrase = 1
local phraseMarkerNote = 105 -- Nota MIDI para el marcador de frases (P1)
local phraseMarkerNoteP2 = 106 -- Marcador de frases alternativo (Rock Band P2 / Harmonías)
local function isPhraseMarker(p) return p == phraseMarkerNote or p == phraseMarkerNoteP2 end
local showLyrics = true -- Controla si se muestra el visualizador de letras
local showNotesHUD = true -- Controla si se muestra el visualizador de líneas de notas
-- Colores para las letras
local textColorInactive = {r = 0.15, g = 0.9, b = 0.0, a = 1.0} -- Verde
local textColorActive = {r = 0.0, g = 1.0, b = 1.0, a = 1.0} -- Azul
local textColorSung = {r = 0.1176471, g = 0.5647059, b = 1.0, a = 1.0} -- Azul claro para letras ya cantadas
local bgColorLyrics = {r = 0.1372549, g = 0.1490196, b = 0.2039216, a = 1.0} -- Fondo para letras
-- Color para la próxima frase (notas con tono)
local textColorNextPhrase = {r = 0.0, g = 1.0, b = 0.5, a = 1.0} -- Verde más claro para próxima frase
-- Color para letras sin tono (marcadas con #)
local textColorToneless = {r = 0.55, g = 0.55, b = 0.55, a = 1.0} -- Gris para letras sin tono
local textColorTonelessActive = {r = 1.0, g = 1.0, b = 1.0, a = 1.0} -- Blanco puro para letras sin tono activas
local textColorTonelessSung = {r = 0.75, g = 0.75, b = 0.75, a = 1.0} -- Blanco opaco para letras sin tono ya cantadas
-- Colores en la sección de colores al inicio del script
local textColorHeroPower = {r = 1.0, g = 1.0, b = 0.15, a = 1.0} -- Amarillo para letras con Hero Power
local textColorHeroPowerActive = {r = 1.0, g = 0.5, b = 0.3, a = 1.0} -- Amarillo brillante para letras Hero Power activas
local textColorHeroPowerSung = {r = 0.9764706, g = 0.8999952, b = 0.5372549, a = 1.0} -- Amarillo más oscuro para letras Hero Power ya cantadas
-- Variables configurables para ajustar la posición y tamaño del visualizador de letras
local lyricsConfig = {
height = 110, -- Altura total del visualizador
bottomMargin = 30, -- Margen inferior (negativo = se superpone con el borde)
phraseHeight = 35, -- Altura de cada frase (reducida ligeramente)
phraseSpacing = 1, -- Espacio entre frases
bgOpacity = 1.0, -- Opacidad del fondo (0.0 - 1.0)
fontSize = { -- Tamaños de fuente
current = 24, -- Tamaño para frase actual
next = 22 -- Tamaño para próxima frase
}
}
function findTrack(trackName)
local numTracks = reaper.CountTracks(0)
for i = 0, numTracks - 1 do
local track = reaper.GetTrack(0, i)
local _, currentTrackName = reaper.GetSetMediaTrackInfo_String(track, "P_NAME", "", false)
if currentTrackName == trackName then
return track
end
end
return nil
end
-- Función para reiniciar el estado cuando cambia el proyecto
function resetState()
vocalsTrack = nil
vocalsHash = ""
phrases = {}
currentPhrase = 1
end
-- Función de seguridad para comprobar si una pista sigue siendo válida
function isTrackValid(track)
if track == nil then return false end
local success, _ = pcall(function()
reaper.GetTrackGUID(track)
end)
return success
end
-- Estructura para una frase de letras
function createPhrase(startTime, endTime)
return {
startTime = startTime,
endTime = endTime,
lyrics = {},
currentLyric = 1
}
end
-- Función para comprobar si hay algún proyecto abierto
function isProjectOpen()
local proj = reaper.EnumProjects(-1)
return proj ~= nil
end
-- Función para verificar si la pista PART VOCALS sigue siendo válida
function checkVocalsTrack()
-- Si la pista PART VOCALS no está definida o no es válida, se resetea
if not vocalsTrack or not isTrackValid(vocalsTrack) then
vocalsTrack = nil
return false
end
return true
end
-- Función completa createLyric con soporte para Hero Power
function createLyric(text, startTime, endTime, pitch, hasHeroPower)
-- Procesar el texto
local processedText = text
local originalText = text -- Guardar el texto original para referencia
-- Detectar si es una letra sin tono (#)
local hasTonelessMarker = processedText:match("#") ~= nil or processedText:match("%^") ~= nil
-- Análisis de conectores en el texto ORIGINAL
-- Buscar todos los posibles patrones de conector al final
local connectsWithNext = false
if originalText:match("%-$") or originalText:match("%+$") or originalText:match("=$") or
originalText:match("%-#$") or originalText:match("%+#$") or originalText:match("=#$") or
originalText:match("%-%^$") or originalText:match("=^$") then
connectsWithNext = true
end
-- Buscar todos los posibles patrones de conector al principio
local connectsWithPrevious = false
if originalText:match("^%-") or originalText:match("^%+") or originalText:match("^=") or
originalText:match("^%-#") or originalText:match("^%+#") or originalText:match("^=#") then
connectsWithPrevious = true
end
-- Busca patrones específicos para tratamiento especial
-- Detectar signos = (que serán visibles como -)
local hasVisibleEquals = processedText:match("=") ~= nil
-- Guardar posiciones donde hay signos = (para no eliminarlos después)
local equalsPositions = {}
local i = 1
while true do
i = string.find(processedText, "=", i)
if i == nil then break end
equalsPositions[i] = true
i = i + 1
end
-- Procesamiento del texto para visualización
-- Convertir = a - (estos guiones serán visibles)
processedText = processedText:gsub("=", "-")
-- Convertir =^ a -
-- processedText = processedText:gsub("=^", "-")
-- Eliminar todos los marcadores #
processedText = processedText:gsub("#", "")
-- Eliminar todos los marcadores ^
processedText = processedText:gsub("%^", "")
-- Eliminar todos los marcadores §
processedText = processedText:gsub("%§", "_")
-- Eliminar todos los símbolos +
processedText = processedText:gsub("%+", "")
-- Eliminar el nombre de las pistas
processedText = processedText:gsub("PART VOCALS", "")
processedText = processedText:gsub("PRO VOCALS", "")
-- Eliminar el nombre del charter de la pista
processedText = processedText:gsub("GHCripto", "") -- Omite el evento de texto de Copyright (de quien hizo el chart Vocal)
-- Eliminar todo el texto entre corchetes, incluyendo los corchetes
processedText = processedText:gsub("%[.-%]", "")
-- Eliminar guiones originales (que no eran =)
-- Hacer esto carácter por carácter para preservar los guiones que eran =
local result = ""
for j = 1, #processedText do
local char = processedText:sub(j, j)
if char == "-" and not equalsPositions[j] then
-- Omitir guiones originales
else
result = result .. char
end
end
processedText = result
-- Elimina espacios extras que pudieran quedar después de eliminar el texto entre corchetes
processedText = processedText:gsub("^%s+", ""):gsub("%s+$", ""):gsub("%s+", " ")
-- Crear y devolver la estructura de datos
return {
originalText = originalText,
text = processedText,
startTime = startTime,
endTime = endTime,
isActive = false,
hasBeenSung = false,
isToneless = hasTonelessMarker,
-- Usar los resultados del análisis de conectores
endsWithHyphen = connectsWithNext,
beginsWithHyphen = connectsWithPrevious,
pitch = pitch or 0,
hasHeroPower = hasHeroPower or false -- Hero Power
}
end
-- Función para actualizar las letras en tiempo real
function updateVocals()
if not showLyrics then
return false
end
-- Verificar que hay un proyecto abierto
if not isProjectOpen() then
return false
end
-- Verificar validez de la pista PART VOCALS
if not checkVocalsTrack() then
-- Intentar encontrar la pista PART VOCALS
if not findVocalsTrack() then
return false
end
end
-- Comprobar si hay cambios en la pista PART VOCALS
local currentHash = ""
-- Usar pcall para evitar errores
local success, result = pcall(function()
-- Recopilar un hash de todos los items MIDI en la pista PART VOCALS
if vocalsTrack then
local numItems = reaper.CountTrackMediaItems(vocalsTrack)
for i = 0, numItems-1 do
local item = reaper.GetTrackMediaItem(vocalsTrack, i)
local take = reaper.GetActiveTake(item)
if take and reaper.TakeIsMIDI(take) then
local _, hash = reaper.MIDI_GetHash(take, true)
currentHash = currentHash .. hash
end
end
end
-- Si el hash ha cambiado, necesitamos actualizar las letras
if vocalsHash ~= currentHash then
vocalsHash = currentHash
return parseVocals() -- Analizar las letras de nuevo
end
return #phrases > 0
end)
-- En caso de error, devolver false
if not success then
return false
end
return result
end
-- Configuración para las líneas de notas (márgenes independientes y rewind correcto)
local noteLineConfig = {
-- COLORES
backgroundColor = {r = 0.1176471, g = 0.1176471, b = 0.1568627, a = 0.1}, -- Fondo del área de las líneas de notas
activeColor = {r = 0.2, g = 0.8, b = 1.0, a = 1.0}, -- Color de notas activas (FRASES COMPLETAS)
inactiveColor = {r = 0.2, g = 0.8, b = 1.0, a = 1.0}, -- Color de notas inactivas (FRASES COMPLETAS)
sungColor = {r = 0.2, g = 0.8, b = 1.0, a = 1.0}, -- Color de notas ya cantadas (pasado)
hitColor = {r = 1.0, g = 1.0, b = 0.3, a = 1.0}, -- Color de notas siendo cantadas (presente)
hitLineColor = {r = 1.0, g = 1.0, b = 1.0, a = 1.0}, -- Color blanco de la línea vertical de golpe
hitLineThickness = 2, -- Grosor en píxeles de la línea
hitLineFadePct = 0.45, -- Porcentaje de la altura total para el degradado (0.25 = 25%)
linesSpacing = 8, -- Espaciado vertical en pixeles de las líneas de las notas
specialNoteRadius = 10, -- Tamaño del círculo de las notas sin tono
specialNoteYOffset = 0.5, -- Desplazamiento vertical de notas sin tono. 0 = Default, Positivo = arriba, Negativo = abajo
noteThickness = 2, -- Grosor en píxeles de las líneas de las notas y sus conectores
noteLineStyle = "default", -- Estilo de las líneas. Opciones: "default", "offset_top", "offset_bottom"
-- RANGO ABSOLUTO DE PITCH
minPitch = 32, -- Nota mínima del "mundo" del HUD
maxPitch = 87, -- Nota máxima del "mundo" del HUD
-- REFERENCIA DE RESOLUCIÓN
referenceScreenHeight = 1080, -- Altura de referencia (1080p)
-- DIMENSIONES DEL HUD
backgroundHeight = 0.50, -- Altura del fondo del gameplay (50% de la pantalla)
yOffset = 0, -- Posición vertical (se calcula dinámicamente)
-- LÍNEA DE GOLPE (HITLINE)
hitLineX = 150, -- Posición horizontal de la línea de golpe (px)
hitLineHeightMultiplier = 1.5, -- Multiplicador de altura de la HIT LINE en base a "highwayGameplayHeight"
hitLineFollowsOffset = false, -- Activar/Desactivar el centrado vertical en base a "verticalCenterOffset"
hitCircleRadius = 10, -- tamaño del círculo
hitCircleYOffset = 1, -- offset vertical
-- ALTURA DEL ÁREA JUGABLE
highwayGameplayHeight = 0.082, -- Altura total del área de juego (8.2% de la pantalla)
verticalCenterOffset = -14.0, -- Desfase vertical del área de juego en pixeles
-- ZOOM DINÁMICO
minimumZoomRange = 18.0, -- Mínimo de semitonos a mostrar
cameraPadding = 2.0, -- Padding +/- 2 semitonos
-- VELOCIDAD DE ANIMACIÓN
panZoomSpeed = 9.0, -- Suavidad de la cámara
panZoomBaseSpeed = 1.0, -- Velocidad base (GHL: 1.0)
-- BUFFERS DE TIEMPO PARA EL CÁLCULO
-- Valores directos del binario GHL (FUN_1402ad7a0): lookahead = 4.5 / vocalScrollSpeed, lookbehind = 1.0 / vocalScrollSpeed
viewFutureSec = 4.5, -- Constante GHL (se divide por vocalScrollSpeed en runtime)
viewPastSec = 1.0, -- Constante GHL (se divide por vocalScrollSpeed en runtime)
-- Estados internos de cámara
currentMinDisplayPitch = 52.0,
currentMaxDisplayPitch = 67.0,
targetMinDisplayPitch = 52.0,
targetMaxDisplayPitch = 67.0,
-- VARIABLE INTERNA PARA CÁLCULO (NO TOCAR)
_lastTimeSec = -1000.0,
vocalScrollSpeed = 1.1, -- Velocidad del desplazamiento de las notas. Mayor valor, más velocidad
vocalScrollSpeedBase = 1920 / 5.5, -- Velocidad base de las notas en píxeles por segundo (GHL: 1920 / 5.5 = ~349.09)
-- PIXEL SNAP POR EJE (GHL)
ghlPerfectPixelSnapX = true, -- Eje X: true = pixel perfecto, false = bordes suaves
ghlPerfectPixelSnapY = true, -- Eje Y: true = pixel perfecto, false = bordes suaves
-- PITCH GUIDE (Guía Tonal)
pitchGuideEnabled = true, -- Activar el tono de guía (requiere plugin JSFX)
pitchGuideBufferSeconds = 5.0, -- Segundos de notas futuras que se envían al sintetizador
pitchGuideFadeSec = 0.0, -- Segundos de fundido (Fade In/Out) para evitar clicks. (0.002 = 2ms). 0 = Sin fundido
-- DEBUG
showPaddingLines = false, -- Activar/Desactivar líneas del padding de pixeles (solo números impares)
paddingLineThickness = 2, -- Grosor en píxeles (solo números impares)
paddingLineColor = {r = 1.0, g = 0.3, b = 0.3, a = 1.0}, -- Rojo semitransparente
staffLineThickness = 2, -- Grosor en pixeles (2 en GH, 1 por defecto)
staffLineYOffset = 0, -- Desplazamiento vertical. 0 = Default, Positivo = arriba, Negativo = abajo
ghlGuideLineAlpha = 0.1, -- Opacidad de las líneas guia
}
-- Función para encontrar la pista vocal (prioriza PRO VOCALS sobre PART VOCALS)
function findVocalsTrack()
-- Primero busca PRO VOCALS
vocalsTrack = findTrack("PRO VOCALS")
-- Si no existe, busca PART VOCALS como respaldo
if not vocalsTrack then
vocalsTrack = findTrack("PART VOCALS")
end
if vocalsTrack then
-- Intentar añadir el FX automáticamente si la guía tonal está activada
if noteLineConfig.pitchGuideEnabled then
local fxExists = false
local fxCount = reaper.TrackFX_GetCount(vocalsTrack)
-- Bucle para leer los nombres de todos los efectos actuales
for i = 0, fxCount - 1 do
local _, fxName = reaper.TrackFX_GetFXName(vocalsTrack, i)
-- Buscamos una coincidencia parcial ignorando prefijos de Reaper y mayúsculas
if string.find(string.lower(fxName), "pitch guide") or
string.find(string.lower(fxName), "pitch_guide") then
fxExists = true
break
end
end
-- Si el bucle termina y no lo encontró, forzamos la creación (usando 1)
if not fxExists then
local fxIndex = reaper.TrackFX_AddByName(vocalsTrack, "Pitch_Guide.jsfx", false, 1)
if fxIndex < 0 then
reaper.TrackFX_AddByName(vocalsTrack, "Pitch Guide", false, 1)
end
end
end
end
return vocalsTrack ~= nil
end
-- Función para parsear eventos de letras/Hero Power
function parseVocals()
phrases = {}
if not vocalsTrack then
if not findVocalsTrack() then
return false
end
end
local numItems = reaper.CountTrackMediaItems(vocalsTrack)
local currentHash = ""
for i = 0, numItems-1 do
local item = reaper.GetTrackMediaItem(vocalsTrack, i)
local take = reaper.GetActiveTake(item)
if reaper.TakeIsMIDI(take) then
local _, hash = reaper.MIDI_GetHash(take, true)
currentHash = currentHash .. hash
end
end
if vocalsHash == currentHash and #phrases > 0 then
return true -- No hay cambios, usar las frases ya parseadas
end
vocalsHash = currentHash
phrases = {} -- Reiniciar frases
for i = 0, numItems-1 do
local item = reaper.GetTrackMediaItem(vocalsTrack, i)
local take = reaper.GetActiveTake(item)
if reaper.TakeIsMIDI(take) then
-- Descomentar para depurar eventos
-- debugTextEvents(take)
local _, noteCount, _, textSysexCount = reaper.MIDI_CountEvts(take)
-- reaper.ShowConsoleMsg("Item " .. i .. ": " .. noteCount .. " notas, " .. textSysexCount .. " eventos de texto\n")
-- Recolectar todas las notas de Hero Power
local heroPowerNotes = {}
for n = 0, noteCount-1 do
local _, _, _, noteStartppq, noteEndppq, _, pitch, _ = reaper.MIDI_GetNote(take, n)
if pitch == HP then
local noteStartTime = reaper.MIDI_GetProjQNFromPPQPos(take, noteStartppq)
local noteEndTime = reaper.MIDI_GetProjQNFromPPQPos(take, noteEndppq)
table.insert(heroPowerNotes, {startTime = noteStartTime, endTime = noteEndTime})
end
end
-- Busca los marcadores de frases (105 P1 y 106 P2).
-- Si una frase tiene ambos marcadores en el mismo tiempo, solo
-- procesamos uno (descartamos el 106 cuando ya hay 105 coincidente).
for j = 0, noteCount-1 do
local _, selected, muted, startppq, endppq, chan, pitch, vel = reaper.MIDI_GetNote(take, j)
local startTime = reaper.MIDI_GetProjQNFromPPQPos(take, startppq)
local endTime = reaper.MIDI_GetProjQNFromPPQPos(take, endppq)
if isPhraseMarker(pitch) then
if pitch == phraseMarkerNoteP2 then
local duplicate = false
for _, existing in ipairs(phrases) do
if math.abs(existing.startTime - startTime) < 0.01 then
duplicate = true
break
end
end
if not duplicate then
table.insert(phrases, createPhrase(startTime, endTime))
end
else
table.insert(phrases, createPhrase(startTime, endTime))
end
end
end
-- Si no hay marcadores de frase, crear una frase que abarque todo el ítem
if #phrases == 0 then
local itemStart = reaper.GetMediaItemInfo_Value(item, "D_POSITION")
local itemEnd = itemStart + reaper.GetMediaItemInfo_Value(item, "D_LENGTH")
local startQN = reaper.TimeMap2_timeToQN(0, itemStart)
local endQN = reaper.TimeMap2_timeToQN(0, itemEnd)
table.insert(phrases, createPhrase(startQN, endQN))
-- reaper.ShowConsoleMsg("Creada frase automática para todo el ítem\n")
end
-- NOTA: En Reaper, los eventos de texto de tipo "Letras"
-- no necesariamente están asociados con notas. Se leerán directamente.
local textEvents = {}
for j = 0, textSysexCount-1 do
local retval, selected, muted, ppqpos, type, msg = reaper.MIDI_GetTextSysexEvt(take, j)
if retval and msg and msg ~= "" then
local time = reaper.MIDI_GetProjQNFromPPQPos(take, ppqpos)
local foundPitch = nil
local noteEndTime = time + 0.25 -- Duración predeterminada
-- Buscar una nota MIDI que coincida con este evento de texto
for n = 0, noteCount-1 do
local _, _, _, noteStartppq, noteEndppq, _, pitch, _ = reaper.MIDI_GetNote(take, n)
local noteStartTime = reaper.MIDI_GetProjQNFromPPQPos(take, noteStartppq)
local nEndTime = reaper.MIDI_GetProjQNFromPPQPos(take, noteEndppq)
-- Si la nota no es un marcador de frase (105 ni 106) y coincide con el tiempo del evento
if not isPhraseMarker(pitch) and math.abs(noteStartTime - time) < 0.01 then
foundPitch = pitch
noteEndTime = nEndTime
break
end
end
table.insert(textEvents, {
text = msg,
time = time,
endTime = noteEndTime,
pitch = foundPitch
})
end
end
-- Ordenar eventos de texto por tiempo
table.sort(textEvents, function(a, b) return a.time < b.time end)
-- Buscar notas asociadas a los eventos de texto para obtener duración
for _, event in ipairs(textEvents) do
for n = 0, noteCount-1 do
local _, _, _, noteStartppq, noteEndppq, _, pitch, _ = reaper.MIDI_GetNote(take, n)
local noteStartTime = reaper.MIDI_GetProjQNFromPPQPos(take, noteStartppq)
local noteEndTime = reaper.MIDI_GetProjQNFromPPQPos(take, noteEndppq)
-- Si la nota no es un marcador de frase (105 ni 106) y coincide con el tiempo del evento
if not isPhraseMarker(pitch) and math.abs(noteStartTime - event.time) < 0.01 then
event.endTime = noteEndTime
break
end
end
end
-- Asignar eventos de texto a frases
for _, event in ipairs(textEvents) do
local assignedToPhrase = false
for k, phrase in ipairs(phrases) do
if event.time >= phrase.startTime and event.time <= phrase.endTime then
-- MODIFICADO: Comprobar si este evento coincide con alguna nota Hero Power
local hasHeroPower = false
for _, hpNote in ipairs(heroPowerNotes) do
-- Comprobar si el evento está dentro del rango de la nota Hero Power
-- o muy cercano a su inicio (con un margen de tolerancia mayor)
if (event.time >= hpNote.startTime and event.time <= hpNote.endTime) or
math.abs(event.time - hpNote.startTime) < 0.03 then
hasHeroPower = true
break
end
end
table.insert(phrase.lyrics, createLyric(
event.text,
event.time,
event.endTime,
event.pitch,
hasHeroPower -- Pasar el flag de Hero Power
))
assignedToPhrase = true
break
end
end
-- Si no se asignó a ninguna frase, crear una nueva frase
if not assignedToPhrase and #phrases > 0 then
-- Asignar al más cercano
local closestPhrase = 1
local minDistance = math.huge
for k, phrase in ipairs(phrases) do
local distance = math.min(
math.abs(event.time - phrase.startTime),
math.abs(event.time - phrase.endTime)
)
if distance < minDistance then
minDistance = distance
closestPhrase = k
end
end
-- MODIFICADO: Comprobar si este evento coincide con alguna nota Hero Power
local hasHeroPower = false
for _, hpNote in ipairs(heroPowerNotes) do
-- Comprobar si el evento está dentro del rango de la nota Hero Power
-- o muy cercano a su inicio (con un margen de tolerancia mayor)
if (event.time >= hpNote.startTime and event.time <= hpNote.endTime) or
math.abs(event.time - hpNote.startTime) < 0.03 then
hasHeroPower = true
break
end
end
table.insert(phrases[closestPhrase].lyrics, createLyric(
event.text,
event.time,
event.endTime,
event.pitch,
hasHeroPower -- Pasar el flag de Hero Power
))
end
end
end
end
-- Ordenar las letras dentro de cada frase por tiempo de inicio
for k, phrase in ipairs(phrases) do
table.sort(phrase.lyrics, function(a, b) return a.startTime < b.startTime end)
-- reaper.ShowConsoleMsg("Frase " .. k .. ": " .. #phrase.lyrics .. " eventos de texto\n")
end
-- Ordenar las frases por tiempo de inicio
table.sort(phrases, function(a, b) return a.startTime < b.startTime end)
return #phrases > 0
end
-- Función para actualizar el estado activo de las letras basado en el tiempo actual
function updateLyricsActiveState(currentTime)
-- Encontrar la frase actual
currentPhrase = 1
for i, phrase in ipairs(phrases) do
if currentTime >= phrase.startTime then
currentPhrase = i
end
end
-- Actualizar todas las letras en todas las frases
for _, phrase in ipairs(phrases) do
for i, lyric in ipairs(phrase.lyrics) do
-- Una letra está activa normalmente si el tiempo actual está entre su inicio y fin
local isCurrentlyActive = (currentTime >= lyric.startTime and currentTime <= lyric.endTime)
-- Comprobar si hay que extender el tiempo activo debido a signos +
local extendedActive = false
local extendedEndTime = lyric.endTime
-- Buscar hacia adelante para encontrar todos los + consecutivos
local j = i + 1
while j <= #phrase.lyrics do
local nextLyric = phrase.lyrics[j]
-- Si la siguiente letra comienza con +, extender la activación
if nextLyric.originalText:find("^%+") then
extendedEndTime = nextLyric.endTime
-- Extender el tiempo activo hasta incluir este +
if currentTime >= lyric.startTime and currentTime <= extendedEndTime then
extendedActive = true
end
j = j + 1 -- Seguir buscando más +
else
break -- No hay más + consecutivos
end
end
-- La letra está activa si cumple los criterios normales o la extensión de los +
lyric.isActive = isCurrentlyActive or extendedActive
-- Una letra está cantada si ya pasó su tiempo final extendido
lyric.hasBeenSung = (currentTime > extendedEndTime)
-- Caso especial: si una letra está activa, no está cantada todavía
if lyric.isActive then
lyric.hasBeenSung = false
end
-- Las letras que son + no deben mostrar su propio estado activo
-- ya que ese tiempo lo absorbe la letra anterior
if lyric.originalText:find("^%+") then
if i > 1 and phrase.lyrics[i-1].isActive then
lyric.isActive = true -- heredar estado activo si la anterior está activa
end
end
end
end
end
-- Calcula los límites físicos de la pantalla
local function getHudBounds(ctxHeight)
local c = noteLineConfig
-- 1. Altura de Notas (0.082) - USANDO REFERENCIA 1080p
-- Esto asegura que las notas siempre tengan ~88px de alto, aunque la ventana sea de 300px
local scaleReference = c.referenceScreenHeight or 1080
local gameplayHeight = scaleReference * (c.highwayGameplayHeight or 0.082)
-- 2. Altura del Fondo (0.50) - USANDO ALTURA REAL DE VENTANA
-- El fondo se adapta a tu ventana pequeña
local hudHeight = ctxHeight * (c.backgroundHeight or 0.50)
-- 3. Centro
-- c.yOffset es la parte inferior del visualizador de notas en Lua (encima de letras)
local hudCenterY = c.yOffset - (hudHeight / 2)
local effectiveCenterY = hudCenterY + (c.verticalCenterOffset or 0)
local halfHeight = gameplayHeight * 0.5
return {
top = effectiveCenterY - halfHeight,
bottom = effectiveCenterY + halfHeight,
height = gameplayHeight,
centerY = effectiveCenterY,
hudCenterY = hudCenterY, -- Centro del fondo (para hitline sin offset)
hudHeight = hudHeight,
hudTop = c.yOffset - hudHeight,
hudBottom = c.yOffset
}
end
-- FÓRMULA DE ÍNDICES
-- Convierte nota MIDI a Índice Visual GHL
-- Esto importa para pitches bajos donde los términos de octava son negativos
local function truncToZero(x)
if x >= 0 then return math.floor(x) else return math.ceil(x) end
end
-- Pixel Snapping
local function snap(x)
return truncToZero(x + 0.5)
end
-- Snap de posición horizontal (eje X)
local function snapX(x)
if noteLineConfig.ghlPerfectPixelSnapX then return snap(x) end
return x
end
-- Snap de posición vertical (eje Y)
local function snapY(x)
if noteLineConfig.ghlPerfectPixelSnapY then return snap(x) end
return x
end
local function calculateGHLIndex(pitch)
local base = pitch
-- Ajuste de Octava 1: truncToZero(val / 12.0 - 3.0)
local term1 = truncToZero(base / 12.0 - 3.0)
-- Ajuste de Octava 2: truncToZero((val - 5.0) / 12.0 - 2.0)
local term2 = truncToZero((base - 5.0) / 12.0 - 2.0)
-- Fórmula maestra
local rawIndex = (base - 40.0 + term1 + term2) * 0.5
return rawIndex
end
-- Función auxiliar: Calcula Y con padding
local function calculatePaddedY(pitchNormalized, bounds)
-- Invertimos porque Canvas Y crece hacia abajo (bottom es mayor Y)
return bounds.bottom - (pitchNormalized * bounds.height)
end
-- Z-Path: Calcula los puntos de la curva Z de GHL para una línea del conector
local function getZPathPoints(startX, endX, startY, endY, isUpper, config)
local dX = endX - startX
local dY = endY - startY
if dX <= 0 or math.abs(dY) * 2 < dX then
return {{x = startX, y = startY}, {x = endX, y = endY}}
end
local basicNoteHeight = config.linesSpacing + config.noteThickness
local curveW = math.min(basicNoteHeight, dX)
local halfCurve = basicNoteHeight / 2
local spacingHalf = config.linesSpacing / 2
local perpInward = (spacingHalf + halfCurve) / 3
local perpSign = isUpper and 1 or -1
local curveAtStart = (dY > 0) == isUpper
if curveAtStart then
return {
{x = startX, y = startY},
{x = startX + curveW * 0.6666667, y = startY + perpInward * perpSign},
{x = endX, y = endY}
}
else
return {
{x = startX, y = startY},
{x = endX - curveW * 0.6666667, y = endY + perpInward * perpSign},
{x = endX, y = endY}
}
end
end
-- Dibuja una línea Z-path en el canvas de REAPER (con grosor y pixel snapping)
local function drawZPath(startX, endX, startY, endY, isUpper, config)
local points = getZPathPoints(startX, endX, startY, endY, isUpper, config)
local thickness = config.noteThickness or 1
local yOff = -math.floor(thickness / 2)
for seg = 1, #points - 1 do
local p0 = points[seg]
local p1 = points[seg + 1]
for i = 0, thickness - 1 do
gfx.line(snapX(p0.x), snapY(p0.y) + yOff + i, snapX(p1.x), snapY(p1.y) + yOff + i, 1)
end
end
end
-- Verifica si el pitch es válido para calcular límites de cámara
local function isValidPitchForCamera(pitch)
if not pitch or pitch <= 0 then return false end
-- GHL ignora notas 26 y 29 para el zoom
local notPitch29 = (pitch < 28.95 or pitch > 29.05)
local notPitch26 = (pitch < 25.95 or pitch > 26.05)
return notPitch29 and notPitch26
end
-- Actualiza los objetivos de la cámara con lógica de Histéresis (Zona Muerta)
local function updateCameraTargets(currentTimeSec, noteList)
local c = noteLineConfig
-- Ventana de tiempo (Lookahead) - Fórmula GHL: fVar13 = 1.0 / vocalScrollSpeed; fVar16 = fVar13 * 4.5
-- lookahead efectivo = viewFutureSec / vocalScrollSpeed; lookbehind efectivo = viewPastSec / vocalScrollSpeed
local invScrollSpeed = 1.0 / c.vocalScrollSpeed
local startT = currentTimeSec - (c.viewPastSec * invScrollSpeed)
local endT = currentTimeSec + (c.viewFutureSec * invScrollSpeed)
local rawMax = -math.huge
local rawMin = math.huge
local foundValid = false
-- 1. Calcular rawMin / rawMax basados en notas visibles
for _, n in ipairs(noteList) do
if n.time >= startT and n.time <= endT then
if isValidPitchForCamera(n.pitch) and not n.isToneless then
rawMin = math.min(rawMin, n.pitch)
rawMax = math.max(rawMax, n.pitch)
foundValid = true
end
end
end
if not foundValid then return end
-- 2. Aplicar Padding
local padding = c.cameraPadding or 2.0
rawMax = rawMax + padding
rawMin = rawMin - padding
-- 3. Lógica de Estabilidad (GHL)
local targetMin = c.targetMinDisplayPitch
local targetMax = c.targetMaxDisplayPitch
local currentRange = rawMax - rawMin
local targetRange = targetMax - targetMin
local minZoom = c.minimumZoomRange
local shouldUpdate = false
if rawMin < targetMin then
shouldUpdate = true
elseif targetMax < rawMax then
shouldUpdate = true
elseif minZoom < targetRange and currentRange < targetRange then
shouldUpdate = true -- "Relax", cerramos la cámara si sobra mucho espacio
end
-- 4. Actualizar Targets si es necesario
if shouldUpdate then
if currentRange < minZoom then
local expansion = (minZoom - currentRange) * 0.5
rawMax = rawMax + expansion
rawMin = rawMin - expansion
end
-- Clampear a límites absolutos
if rawMin < c.minPitch then
rawMin = c.minPitch
rawMax = math.max(rawMax, rawMin + minZoom)
end
if rawMax > c.maxPitch then
rawMax = c.maxPitch
rawMin = math.min(rawMin, rawMax - minZoom)
end
c.targetMinDisplayPitch = rawMin
c.targetMaxDisplayPitch = rawMax
end
end
-- Interpola la cámara con movimiento lineal constante (Mecánico)
local function updateDisplayPitchRange(deltaTime)
local c = noteLineConfig
local speed = c.panZoomBaseSpeed * c.panZoomSpeed
if deltaTime <= 0 then deltaTime = 1/60 end
local maxMovement = speed * deltaTime
-- Animar Max Pitch
local targetMax = c.targetMaxDisplayPitch
local displayMax = c.currentMaxDisplayPitch
if targetMax > displayMax then
displayMax = math.min(targetMax, displayMax + maxMovement)
elseif targetMax < displayMax then
displayMax = math.max(targetMax, displayMax - maxMovement)
end
c.currentMaxDisplayPitch = displayMax
-- Animar Min Pitch
local targetMin = c.targetMinDisplayPitch
local displayMin = c.currentMinDisplayPitch
if targetMin > displayMin then
displayMin = math.min(targetMin, displayMin + maxMovement)
elseif targetMin < displayMin then
displayMin = math.max(targetMin, displayMin - maxMovement)
end
c.currentMinDisplayPitch = displayMin
end
-- Convierte frases a lista de notas
local function phrasesToNotes(phrases)
local out = {}
for _, ph in ipairs(phrases) do
for _, ly in ipairs(ph.lyrics) do
if ly.pitch and ly.pitch > 0 then
local t = reaper.TimeMap2_beatsToTime(0, ly.startTime)
-- Propiedad 'isToneless' agregada para que la use la función de cálculo del HUD
table.insert(out, {time = t, pitch = ly.pitch, isToneless = ly.isToneless})
end
end
end
return out
end
-- Función principal del HUD vocal
function drawLyricsVisualizer()
if #phrases == 0 then
return
end
-- Cálculo de Posición Y usando Índices GHL
-- Réplica exacta de NoteRenderer.calculateExactNoteY en JS
local function getNoteYPosition(pitch, config, bounds)
local yOffset = config.staffLineYOffset or 0
-- 1. Convertir la nota actual a índice GHL
local currentIndex = calculateGHLIndex(pitch)
-- 2. Convertir los límites de la cámara a índices GHL (para zoom suave)
local minIndex = calculateGHLIndex(config.currentMinDisplayPitch)
local maxIndex = calculateGHLIndex(config.currentMaxDisplayPitch)
-- 3. Normalizar
local range = maxIndex - minIndex
local normalized = 0
if range ~= 0 then
normalized = (currentIndex - minIndex) / range
end
-- 4. Clamp a [0, 1] — réplica exacta del JS
if normalized >= 0.0 then
if normalized > 1.0 then normalized = 1.0 end
else
normalized = 0.0
end
-- 5. Convertir a píxeles con pixel snap
local finalY = calculatePaddedY(normalized, bounds) - yOffset
return snapY(finalY)
end
-- Inversa de getNoteYPosition: convierte un píxel Y de la hitline a Pitch (incluyendo conectores)
local function getPitchFromYPosition(y, bounds)
local c = noteLineConfig
local minPaddedY = bounds.top
local maxPaddedY = bounds.bottom
-- clamp y
local clampedY = math.max(minPaddedY, math.min(maxPaddedY, y))
local normalizedPitch = (maxPaddedY - clampedY) / (maxPaddedY - minPaddedY)
local pitch = (normalizedPitch * (c.currentMaxDisplayPitch - c.currentMinDisplayPitch)) + c.currentMinDisplayPitch
return pitch
end
-- Convertidor MIDI a Hz para el sintetizador
local function midiToFrequency(midiNote)
return 440.0 * (2.0 ^ ((midiNote - 69.0) / 12.0))
end
local currentTimeSec = reaper.TimeMap2_beatsToTime(0, curBeat)
local deltaTime = currentTimeSec - (noteLineConfig._lastTimeSec or currentTimeSec)
noteLineConfig._lastTimeSec = currentTimeSec