-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUstViz.py
More file actions
2285 lines (1880 loc) · 99.1 KB
/
UstViz.py
File metadata and controls
2285 lines (1880 loc) · 99.1 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
import os
import pygame
import math
from pygame.locals import *
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import threading
from PIL import Image
import json
import re
import numpy as np
from pygame import gfxdraw
# 尝试导入ttkthemes,如果失败则使用默认主题
try:
from ttkthemes import ThemedTk, ThemedStyle
TTKTHEMES_AVAILABLE = True
except ImportError:
TTKTHEMES_AVAILABLE = False
print("警告: ttkthemes 未安装,使用默认主题")
class USTParser:
def __init__(self):
self.notes = []
self.tempo = 120.0 # 设置合理的默认值
self.project_name = ""
self.total_duration = 0
def parse_file(self, filename):
"""解析UST文件"""
try:
# 尝试多种编码格式
encodings = ['utf-8', 'shift_jis', 'gbk', 'big5', 'cp932']
content = None
for encoding in encodings:
try:
with open(filename, 'r', encoding=encoding) as file:
content = file.read()
print(f"成功以 {encoding} 编码读取UST文件")
break
except UnicodeDecodeError:
continue
if content is None:
# 如果所有编码都失败,使用二进制读取并忽略错误
with open(filename, 'rb') as file:
content = file.read().decode('utf-8', errors='ignore')
print("使用忽略错误的方式读取UST文件")
# 解析基本信息
self._parse_metadata(content)
# 解析音符数据
self._parse_notes(content)
# 计算总时长
self._calculate_total_duration()
# 调试信息:打印前几个音符的时间信息
print(f"解析完成,共 {len(self.notes)} 个音符")
for i, note in enumerate(self.notes[:5]):
print(f"音符 {i}: 开始={note['start_time']:.2f}s, 结束={note['end_time']:.2f}s, "
f"歌词='{note['lyric']}', 音高={note['note_num']}")
return True
except Exception as e:
print(f"UST解析错误: {e}")
return False
def _parse_metadata(self, content):
"""解析元数据"""
# 解析速度
tempo_match = re.search(r'Tempo=([\d.]+)', content)
if tempo_match:
try:
tempo_value = float(tempo_match.group(1))
if tempo_value <= 0 or tempo_value > 1000: # 合理的速度范围检查
print(f"警告: 速度值 {tempo_value} 超出合理范围,使用默认值120.0")
self.tempo = 120.0
else:
self.tempo = tempo_value
print(f"解析到速度: {self.tempo} BPM")
except ValueError:
print(f"警告: 速度值解析失败,使用默认值120.0")
self.tempo = 120.0
else:
self.tempo = 120.0
print("未找到速度参数,使用默认值120.0 BPM")
# 解析项目名称
project_match = re.search(r'ProjectName=([^\r\n]+)', content)
if project_match:
self.project_name = project_match.group(1)
print(f"项目名称: {self.project_name}")
def _safe_float_convert(self, value_str, default=0.0):
"""安全地将字符串转换为浮点数"""
if value_str is None or value_str.strip().lower() in ['null', '']:
return default
try:
return float(value_str)
except ValueError:
return default
def _safe_int_convert(self, value_str, default=0):
"""安全地将字符串转换为整数"""
if value_str is None or value_str.strip().lower() in ['null', '']:
return default
try:
return int(value_str)
except ValueError:
return default
def _parse_notes(self, content):
"""解析音符数据"""
self.notes = []
# 使用正则表达式找到所有音符块
note_blocks = re.findall(r'\[#(\d+)\](.*?)(?=\[#\d+\]|$)', content, re.DOTALL)
print(f"找到 {len(note_blocks)} 个音符块")
current_time = 0 # 当前时间(秒)
for note_num, note_content in note_blocks:
# 跳过设置块([#SETTING])和其他非音符块
if note_num == 'SETTING' or note_num == 'TRACKEND' or note_num == 'PREV' or note_num == 'NEXT':
continue
try:
note_number = int(note_num)
except ValueError:
# 如果不是数字,跳过这个块
continue
note_data = {
'number': note_number,
'length': 480, # 默认值(ticks)
'lyric': 'R', # 默认休止符
'note_num': 60, # 默认C5
'pbs': [0, 0], # PBS格式: PBS=X;Y 或 PBS=X
'pbw': [], # PBW点之间的宽度
'pby': [], # PBY点的音高偏移
'pbm': [], # 曲线类型
'pitch_bend': [], # PitchBend数据
'start_time': 0, # 开始时间(秒)
'end_time': 0, # 结束时间(秒)
'duration': 0 # 持续时间(秒)
}
# 解析长度
length_match = re.search(r'Length=(\d+)', note_content)
if length_match:
note_data['length'] = self._safe_int_convert(length_match.group(1), 480)
# 解析歌词
lyric_match = re.search(r'Lyric=([^\r\n]+)', note_content)
if lyric_match:
note_data['lyric'] = lyric_match.group(1).strip()
# 解析音高
note_num_match = re.search(r'NoteNum=(\d+)', note_content)
if note_num_match:
note_data['note_num'] = self._safe_int_convert(note_num_match.group(1), 60)
# 解析PBS (Pitch Bend Start)
pbs_match = re.search(r'PBS=([^\r\n]+)', note_content)
if pbs_match:
pbs_str = pbs_match.group(1)
if pbs_str.strip().lower() != 'null' and pbs_str.strip():
try:
if ';' in pbs_str:
pbs_parts = pbs_str.split(';')
note_data['pbs'] = [
self._safe_float_convert(pbs_parts[0], 0),
self._safe_float_convert(pbs_parts[1], 0)
]
else:
note_data['pbs'] = [self._safe_float_convert(pbs_str, 0), 0]
except Exception as e:
print(f"警告: 音符 #{note_num} 的PBS值 '{pbs_str}' 解析失败: {e}")
note_data['pbs'] = [0, 0]
# 解析PBW (Pitch Bend Width)
pbw_match = re.search(r'PBW=([^\r\n]+)', note_content)
if pbw_match:
pbw_str = pbw_match.group(1)
if pbw_str.strip().lower() != 'null' and pbw_str.strip():
try:
note_data['pbw'] = [self._safe_float_convert(x) for x in pbw_str.split(',') if x.strip()]
except Exception as e:
print(f"警告: 音符 #{note_num} 的PBW值解析失败: {e}")
note_data['pbw'] = []
# 解析PBY (Pitch Bend Y)
pby_match = re.search(r'PBY=([^\r\n]+)', note_content)
if pby_match:
pby_str = pby_match.group(1)
if pby_str.strip().lower() != 'null' and pby_str.strip():
try:
note_data['pby'] = [self._safe_float_convert(x) for x in pby_str.split(',') if x.strip()]
except Exception as e:
print(f"警告: 音符 #{note_num} 的PBY值解析失败: {e}")
note_data['pby'] = []
# 解析PBM (Pitch Bend Mode)
pbm_match = re.search(r'PBM=([^\r\n]+)', note_content)
if pbm_match:
pbm_str = pbm_match.group(1)
if pbm_str.strip().lower() != 'null' and pbm_str.strip():
note_data['pbm'] = [x.strip() for x in pbm_str.split(',')]
# 解析PitchBend
pitch_bend_match = re.search(r'PitchBend=([^\r\n]+)', note_content)
if pitch_bend_match:
pitch_bend_str = pitch_bend_match.group(1)
if pitch_bend_str.strip().lower() != 'null' and pitch_bend_str.strip():
try:
note_data['pitch_bend'] = [self._safe_int_convert(x) for x in pitch_bend_str.split(',') if x.strip()]
except Exception as e:
print(f"警告: 音符 #{note_num} 的PitchBend值解析失败: {e}")
note_data['pitch_bend'] = []
# 计算时间信息(将ticks转换为秒)
# UST中通常使用480 ticks per quarter note
# 正确的计算方式:duration_seconds = (length_in_ticks / 480) * (60 / tempo)
quarter_note_duration = 60.0 / self.tempo # 一个四分音符的秒数
note_duration_seconds = (note_data['length'] / 480.0) * quarter_note_duration
note_data['start_time'] = current_time
note_data['end_time'] = current_time + note_duration_seconds
note_data['duration'] = note_duration_seconds
current_time += note_duration_seconds
# 只添加有意义的音符(非休止符或有音高的音符)
if note_data['lyric'].upper() != 'R' or note_data['note_num'] > 0:
self.notes.append(note_data)
else:
print(f"跳过休止符: 音符 #{note_num}")
def _calculate_total_duration(self):
"""计算总时长"""
if not self.notes:
self.total_duration = 0
return
# 最后一个音符的结束时间
self.total_duration = max(note['end_time'] for note in self.notes)
print(f"总时长: {self.total_duration:.2f} 秒")
def calculate_pitch_curve(self, note_data, resolution=100):
"""计算音符的音高曲线"""
# 如果没有PitchBend数据,尝试使用PBW和PBY生成曲线
if not note_data['pitch_bend'] and note_data['pbw'] and note_data['pby']:
return self._calculate_pitch_curve_from_pb(note_data, resolution)
# 如果没有PitchBend数据,返回平坦曲线
if not note_data['pitch_bend']:
base_pitch = note_data['note_num']
return [(i/resolution, base_pitch) for i in range(resolution + 1)]
# 使用PitchBend数据生成曲线
pitch_points = []
pitch_bend_data = note_data['pitch_bend']
# 计算每个点的音高
for i in range(len(pitch_bend_data)):
progress = i / (len(pitch_bend_data) - 1) if len(pitch_bend_data) > 1 else 0
# PitchBend值转换为半音偏移(需要根据实际转换比例调整)
pitch_offset = pitch_bend_data[i] / 100.0 # 简化转换
actual_pitch = note_data['note_num'] + pitch_offset
pitch_points.append((progress, actual_pitch))
return pitch_points
def _calculate_pitch_curve_from_pb(self, note_data, resolution):
"""使用PBW和PBY数据计算音高曲线"""
base_pitch = note_data['note_num']
pbs_x, pbs_y = note_data['pbs']
pbw = note_data['pbw']
pby = note_data['pby']
# 如果没有PBW数据,返回平坦曲线
if not pbw:
return [(i/resolution, base_pitch) for i in range(resolution + 1)]
# 计算总宽度
total_width = sum(pbw)
# 生成曲线点
pitch_points = []
current_pos = 0
# 添加起点
pitch_points.append((0, base_pitch + pbs_y))
# 处理每个PBW段
for i in range(len(pbw)):
segment_width = pbw[i]
segment_pitch = base_pitch + (pby[i] if i < len(pby) else 0)
# 计算段的起点和终点
start_pos = current_pos / total_width
end_pos = (current_pos + segment_width) / total_width
# 添加段终点
pitch_points.append((end_pos, segment_pitch))
current_pos += segment_width
# 如果点太少,进行插值
if len(pitch_points) < 2:
return [(i/resolution, base_pitch) for i in range(resolution + 1)]
# 对曲线进行插值以获得更平滑的结果
interpolated_points = []
for i in range(resolution + 1):
progress = i / resolution
# 找到当前进度所在的段
for j in range(len(pitch_points) - 1):
if pitch_points[j][0] <= progress <= pitch_points[j+1][0]:
# 线性插值
seg_progress = (progress - pitch_points[j][0]) / (pitch_points[j+1][0] - pitch_points[j][0])
pitch_value = pitch_points[j][1] + seg_progress * (pitch_points[j+1][1] - pitch_points[j][1])
interpolated_points.append((progress, pitch_value))
break
else:
# 如果找不到段,使用最后一个点的值
interpolated_points.append((progress, pitch_points[-1][1]))
return interpolated_points
class NoteRenderer:
def __init__(self):
# 音高到Y坐标的映射 (C0-C8)
self.pitch_to_y = {}
self._create_pitch_mapping()
def _create_pitch_mapping(self):
"""创建音高到Y坐标的映射"""
pitches = []
for octave in range(0, 9): # C0到C8
for step in ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']:
pitches.append(f"{step}{octave}")
# 反转列表,使C8在顶部,C0在底部
pitches.reverse()
self.pitch_to_y = {pitch: i for i, pitch in enumerate(pitches)}
def get_note_y_position(self, note_num, total_height, vertical_offset=0):
"""根据半音值获取Y坐标位置"""
# 将半音值映射到屏幕位置 (C1=24, C2=36, 等等)
# C8 = 108, C0 = 0
max_pitch = 108 # C8
min_pitch = 0 # C0
# 归一化到0-1范围
normalized = (note_num - min_pitch) / (max_pitch - min_pitch)
# 反转Y轴(屏幕坐标:0在顶部)
base_y = total_height * (1 - normalized)
# 应用纵向偏移(按像素计算)
return base_y + vertical_offset
class AudioGenerator:
"""音频生成器,用于生成方波音效"""
def __init__(self, sample_rate=44100, amplitude=0.1):
self.sample_rate = sample_rate
self.amplitude = amplitude
self.notes_playing = {}
def note_to_frequency(self, note_num):
"""将音符编号转换为频率"""
# MIDI音符编号到频率的转换公式
return 440.0 * (2.0 ** ((note_num - 69) / 12.0))
def generate_square_wave(self, frequency, duration):
"""生成方波音频数据"""
samples = int(duration * self.sample_rate)
t = np.linspace(0, duration, samples, False)
# 生成方波 (使用正弦波的符号)
wave = np.sign(np.sin(2 * np.pi * frequency * t))
# 应用振幅
wave = wave * self.amplitude
# 转换为16位整数,并确保是二维数组(立体声)
wave = (wave * 32767).astype(np.int16)
# 将单声道转换为立体声(二维数组)
stereo_wave = np.column_stack((wave, wave))
return stereo_wave
def play_note(self, note_num, duration):
"""播放音符"""
try:
frequency = self.note_to_frequency(note_num)
wave = self.generate_square_wave(frequency, duration)
# 创建pygame声音对象
sound = pygame.sndarray.make_sound(wave)
sound.play()
# 记录正在播放的音符
channel = pygame.mixer.find_channel()
if channel:
self.notes_playing[note_num] = {
'sound': sound,
'channel': channel,
'start_time': pygame.time.get_ticks(),
'duration': duration * 1000 # 转换为毫秒
}
except Exception as e:
print(f"播放音符时出错: {e}")
def stop_note(self, note_num):
"""停止播放音符"""
if note_num in self.notes_playing:
self.notes_playing[note_num]['sound'].stop()
del self.notes_playing[note_num]
def update(self):
"""更新音频状态,停止已播放完成的音符"""
current_time = pygame.time.get_ticks()
finished_notes = []
for note_num, note_info in self.notes_playing.items():
if current_time - note_info['start_time'] >= note_info['duration']:
finished_notes.append(note_num)
for note_num in finished_notes:
self.stop_note(note_num)
class PreviewWindow:
"""预览窗口类"""
def __init__(self, ust_parser, config, parent):
self.ust_parser = ust_parser
self.config = config
self.parent = parent
# 预览状态
self.is_playing = False
self.current_time = 0
self.playback_speed = 1.0
# 计算总时长
pixels_per_second = config['scroll_speed']
lead_in_time = config['width'] / pixels_per_second
lead_out_time = config['width'] / pixels_per_second
self.total_duration = ust_parser.total_duration + lead_in_time + lead_out_time
self.total_frames = int(self.total_duration * config['fps'])
# 音频生成器
self.audio_generator = AudioGenerator()
# 已触发的音符(避免重复触发)
self.triggered_notes = set()
# 初始化pygame
pygame.init()
pygame.mixer.init()
# 创建窗口
self.screen = pygame.display.set_mode((config['width'], config['height']))
pygame.display.set_caption("UST 预览 - 按空格播放/暂停, Z/X前后滚动, ESC退出")
# 字体
self.font = pygame.font.SysFont(config['fallback_font'], 20)
# 渲染器
self.renderer = NoteRenderer()
self.sequence_generator = SequenceGenerator()
self.sequence_generator.ust_parser = ust_parser
self.sequence_generator.renderer = self.renderer
# 时钟
self.clock = pygame.time.Clock()
# 运行预览
self.run()
def run(self):
"""运行预览循环"""
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
elif event.key == pygame.K_SPACE:
self.is_playing = not self.is_playing
elif event.key == pygame.K_z:
# 后退10帧
self.current_time = max(0, self.current_time - 10 / self.config['fps'])
self.triggered_notes.clear() # 清除触发状态
elif event.key == pygame.K_x:
# 前进10帧
self.current_time = min(self.total_duration, self.current_time + 10 / self.config['fps'])
self.triggered_notes.clear() # 清除触发状态
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 4: # 滚轮上滚
self.current_time = max(0, self.current_time - 5 / self.config['fps'])
self.triggered_notes.clear() # 清除触发状态
elif event.button == 5: # 滚轮下滚
self.current_time = min(self.total_duration, self.current_time + 5 / self.config['fps'])
self.triggered_notes.clear() # 清除触发状态
# 更新状态
if self.is_playing:
# 更新时间
self.current_time += 1 / self.config['fps'] * self.playback_speed
if self.current_time >= self.total_duration:
self.current_time = 0
self.triggered_notes.clear() # 清除触发状态
# 渲染当前帧
self.render_frame()
# 检查并触发音符音效
self.check_note_triggers()
# 更新音频状态
self.audio_generator.update()
# 更新显示
pygame.display.flip()
self.clock.tick(self.config['fps'])
# 清理资源
pygame.quit()
def render_frame(self):
"""渲染当前帧"""
# 清空屏幕
if self.config['transparent_background']:
self.screen.fill((0, 0, 0, 0))
else:
self.screen.fill(self.config['background_color'])
# 计算滚动参数
pixels_per_second = self.config['scroll_speed']
judgment_line_x = self.config['width'] * self.config['judgment_line_position']
lead_in_time = self.config['width'] / pixels_per_second
# 绘制判定线
pygame.draw.line(self.screen, self.config['judgment_line_color'],
(judgment_line_x, 0),
(judgment_line_x, self.config['height']), 2)
# 绘制音符
for note in self.ust_parser.notes:
self.draw_note(note, self.current_time, pixels_per_second, judgment_line_x, lead_in_time)
# 绘制音高曲线
if self.config.get('show_pitch_curve', False):
self.draw_pitch_curves(self.current_time, pixels_per_second, judgment_line_x, lead_in_time)
# 绘制信息面板
self.draw_info_panel()
def draw_note(self, note, current_time, pixels_per_second, judgment_line_x, lead_in_time):
"""绘制单个音符"""
# 计算音符位置
note_start_x = self.config['width'] + (note['start_time'] - current_time + lead_in_time) * pixels_per_second
note_end_x = self.config['width'] + (note['end_time'] - current_time + lead_in_time) * pixels_per_second
# 如果音符完全在屏幕外,不绘制
if note_end_x < 0 or note_start_x > self.config['width']:
return False
# 跳过无效的音符
if note['lyric'].upper() == 'R' or note['note_num'] <= 0:
return False
# 计算音符位置和大小
note_y = self.renderer.get_note_y_position(note['note_num'], self.config['height'], self.config['vertical_offset'])
note_width = max(10, note_end_x - note_start_x)
note_height = self.config['note_height']
# 判断是否在判定线上
is_active = note_start_x <= judgment_line_x <= note_end_x
# 选择颜色
note_color = self.config['active_note_color'] if is_active else self.config['note_color']
# 绘制音符阴影
if self.config['note_shadow']:
shadow_color = (0, 0, 0, 100) if self.config['transparent_background'] else (30, 30, 30)
shadow_rect = (note_start_x + 3, note_y - note_height/2 + 3,
note_width, note_height)
if self.config['note_corner_radius'] > 0:
self.draw_rounded_rect(self.screen, shadow_color, shadow_rect, self.config['note_corner_radius'])
else:
pygame.draw.rect(self.screen, shadow_color, shadow_rect)
# 绘制音符主体
note_rect = (note_start_x, note_y - note_height/2, note_width, note_height)
if self.config['note_corner_radius'] > 0:
self.draw_rounded_rect(self.screen, note_color, note_rect, self.config['note_corner_radius'])
else:
pygame.draw.rect(self.screen, note_color, note_rect)
# 绘制歌词
if self.config.get('show_lyric', True) and note['lyric'] and note['lyric'].upper() != 'R':
try:
lyric_color = self.config['lyric_color']
text_surface = self.font.render(note['lyric'], True, lyric_color)
# 计算歌词位置
lyric_x = note_start_x + min(20, note_width / 2)
lyric_y = note_y - note_height/2 - self.config['lyric_offset']
text_rect = text_surface.get_rect(midbottom=(lyric_x, lyric_y))
self.screen.blit(text_surface, text_rect)
except Exception as e:
print(f"渲染歌词失败: {e}")
return True
def draw_pitch_curves(self, current_time, pixels_per_second, judgment_line_x, lead_in_time):
"""绘制音高曲线"""
if not self.ust_parser.notes:
return
curve_color = self.config.get('pitch_curve_color', (255, 255, 0))
curve_width = self.config.get('pitch_curve_width', 3)
show_shadow = self.config.get('pitch_curve_shadow', True)
show_dots = self.config.get('pitch_curve_dots', True)
dot_size = self.config.get('pitch_curve_dot_size', 5)
curve_smoothness = self.config.get('pitch_curve_smoothness', 50)
# 绘制每个音符的音高曲线
for note in self.ust_parser.notes:
# 跳过无效的音符
if note['lyric'].upper() == 'R' or note['note_num'] <= 0:
continue
# 计算音符在屏幕上的位置
note_start_x = self.config['width'] + (note['start_time'] - current_time + lead_in_time) * pixels_per_second
note_end_x = self.config['width'] + (note['end_time'] - current_time + lead_in_time) * pixels_per_second
# 如果音符完全在屏幕外,跳过
if note_end_x < 0 or note_start_x > self.config['width']:
continue
# 计算音高曲线
pitch_points = self.ust_parser.calculate_pitch_curve(note, resolution=curve_smoothness)
if len(pitch_points) < 2:
continue
# 将音高点转换为屏幕坐标
screen_points = []
for progress, pitch_value in pitch_points:
x = note_start_x + progress * (note_end_x - note_start_x)
y = self.renderer.get_note_y_position(pitch_value, self.config['height'], self.config['vertical_offset'])
screen_points.append((x, y))
# 绘制曲线阴影
if show_shadow and curve_width > 1:
shadow_points = [(x + 2, y + 2) for x, y in screen_points]
shadow_color = (0, 0, 0, 100) if self.config['transparent_background'] else (30, 30, 30)
if len(shadow_points) > 1:
pygame.draw.lines(self.screen, shadow_color, False, shadow_points, curve_width)
# 绘制音高曲线
if len(screen_points) > 1:
pygame.draw.lines(self.screen, curve_color, False, screen_points, curve_width)
# 在曲线起点和终点添加标记点
if show_dots and len(screen_points) >= 2:
start_point = screen_points[0]
end_point = screen_points[-1]
pygame.draw.circle(self.screen, curve_color, (int(start_point[0]), int(start_point[1])), dot_size)
pygame.draw.circle(self.screen, curve_color, (int(end_point[0]), int(end_point[1])), dot_size)
def draw_rounded_rect(self, surface, color, rect, radius):
"""绘制圆角矩形"""
x, y, width, height = rect
# 如果圆角半径太大,调整到合适大小
radius = min(radius, min(width, height) // 2)
# 绘制圆角矩形的主体
pygame.draw.rect(surface, color, (x + radius, y, width - 2*radius, height))
pygame.draw.rect(surface, color, (x, y + radius, width, height - 2*radius))
# 绘制四个角
pygame.draw.circle(surface, color, (x + radius, y + radius), radius)
pygame.draw.circle(surface, color, (x + width - radius, y + radius), radius)
pygame.draw.circle(surface, color, (x + radius, y + height - radius), radius)
pygame.draw.circle(surface, color, (x + width - radius, y + height - radius), radius)
def draw_info_panel(self):
"""绘制信息面板"""
# 背景
info_bg = pygame.Surface((300, 80), pygame.SRCALPHA)
info_bg.fill((0, 0, 0, 128))
self.screen.blit(info_bg, (10, self.config['height'] - 90))
# 文本信息
current_frame = int(self.current_time * self.config['fps'])
info_texts = [
f"帧: {current_frame}/{self.total_frames}",
f"时间: {self.current_time:.2f}/{self.total_duration:.2f}s",
f"FPS: {self.config['fps']}",
f"状态: {'播放中' if self.is_playing else '暂停'}"
]
for i, text in enumerate(info_texts):
text_surface = self.font.render(text, True, (255, 255, 255))
self.screen.blit(text_surface, (20, self.config['height'] - 80 + i * 20))
def check_note_triggers(self):
"""检查并触发音符音效"""
if not self.is_playing:
return
# 计算判定线位置
judgment_line_x = self.config['width'] * self.config['judgment_line_position']
pixels_per_second = self.config['scroll_speed']
lead_in_time = self.config['width'] / pixels_per_second
for note in self.ust_parser.notes:
# 跳过无效的音符
if note['lyric'].upper() == 'R' or note['note_num'] <= 0:
continue
# 计算音符位置
note_start_x = self.config['width'] + (note['start_time'] - self.current_time + lead_in_time) * pixels_per_second
note_end_x = self.config['width'] + (note['end_time'] - self.current_time + lead_in_time) * pixels_per_second
# 检查是否在判定线上
if note_start_x <= judgment_line_x <= note_end_x:
# 检查是否已经触发过
if note['number'] not in self.triggered_notes:
# 播放音效
self.audio_generator.play_note(note['note_num'], note['duration'])
# 标记为已触发
self.triggered_notes.add(note['number'])
else:
# 不在判定线上,移除触发标记
if note['number'] in self.triggered_notes:
self.triggered_notes.remove(note['number'])
class SequenceGenerator:
def __init__(self):
self.ust_parser = USTParser()
self.renderer = NoteRenderer()
self.is_generating = True # 生成状态标志
def stop_generation(self):
"""停止生成"""
self.is_generating = False
def generate_frames(self, ust_file, output_folder, config, progress_callback=None):
"""生成序列帧"""
if not self.ust_parser.parse_file(ust_file):
return False
# 重置生成状态
self.is_generating = True
# 创建输出文件夹
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 初始化Pygame
pygame.init()
# 设置屏幕模式,支持透明背景
if config['transparent_background']:
screen = pygame.Surface((config['width'], config['height']), pygame.SRCALPHA)
else:
screen = pygame.Surface((config['width'], config['height']))
# 加载字体
font = None
if config['font_path'] and os.path.exists(config['font_path']):
try:
font = pygame.font.Font(config['font_path'], config['font_size'])
print(f"成功加载字体: {config['font_path']}")
except Exception as e:
print(f"加载字体失败: {e}")
font = pygame.font.SysFont(config['fallback_font'], config['font_size'])
else:
font = pygame.font.SysFont(config['fallback_font'], config['font_size'])
print(f"使用备用字体: {config['fallback_font']}")
# 计算总时长
if not self.ust_parser.notes:
print("没有找到音符")
return False
total_duration = self.ust_parser.total_duration
# 计算滚动速度
pixels_per_second = config['scroll_speed']
judgment_line_x = config['width'] * config['judgment_line_position']
# 第一个音符从屏幕右侧外进入需要的时间
# 修改:音符从屏幕最右侧进入,而不是判定线右侧
lead_in_time = config['width'] / pixels_per_second
# 最后一个音符完全离开屏幕需要的时间
lead_out_time = config['width'] / pixels_per_second
# 调整总时长
total_duration += lead_in_time + lead_out_time
# 计算总帧数
total_frames = int(total_duration * config['fps'])
# 计算淡入淡出时间(秒)
fade_duration = config['fade_duration']
print(f"开始生成序列帧,共 {total_frames} 帧")
print(f"总时长: {total_duration:.2f} 秒, 滚动速度: {pixels_per_second} 像素/秒")
generated_frames = 0
for frame_num in range(total_frames):
# 检查是否停止生成
if not self.is_generating:
print("生成过程被用户中断")
break
current_time = frame_num / config['fps']
# 清空屏幕
if config['transparent_background']:
screen.fill((0, 0, 0, 0)) # 透明背景
else:
screen.fill(config['background_color'])
# 绘制判定线
pygame.draw.line(screen, config['judgment_line_color'],
(judgment_line_x, 0),
(judgment_line_x, config['height']), 2)
# 绘制音符
visible_notes_count = 0
for note in self.ust_parser.notes:
if self._draw_note(screen, note, current_time, config,
pixels_per_second, judgment_line_x, font, total_duration, lead_in_time):
visible_notes_count += 1
# 绘制音高曲线(在音符上层)
if config.get('show_pitch_curve', False):
self._draw_pitch_curves(screen, self.ust_parser.notes, current_time,
config, pixels_per_second, judgment_line_x, total_duration, lead_in_time)
# 保存帧
frame_path = os.path.join(output_folder, f"frame_{frame_num:06d}.png")
pygame.image.save(screen, frame_path)
generated_frames += 1
# 更新进度回调
if progress_callback:
progress_callback(frame_num, total_frames, visible_notes_count)
if frame_num % 30 == 0: # 每30帧打印进度
print(f"生成进度: {frame_num}/{total_frames}, 当前可见音符: {visible_notes_count}")
pygame.quit()
# 返回生成状态
if not self.is_generating:
return "stopped"
elif generated_frames < total_frames:
return "partial"
else:
return True
def _draw_note(self, screen, note, current_time, config, pixels_per_second, judgment_line_x, font, total_duration, lead_in_time):
"""绘制单个音符,返回是否成功绘制"""
# 修改:音符从屏幕最右侧进入
# 计算音符位置 - 确保第一个音符从屏幕最右侧外进入
note_start_x = config['width'] + (note['start_time'] - current_time + lead_in_time) * pixels_per_second
note_end_x = config['width'] + (note['end_time'] - current_time + lead_in_time) * pixels_per_second
# 如果音符完全在屏幕外,不绘制
if note_end_x < 0 or note_start_x > config['width']:
return False
# 跳过无效的音符(休止符或音高为0)
if note['lyric'].upper() == 'R' or note['note_num'] <= 0:
return False
# 计算音符位置和大小(应用纵向偏移)
note_y = self.renderer.get_note_y_position(note['note_num'], config['height'], config['vertical_offset'])
note_width = max(10, note_end_x - note_start_x)
note_height = config['note_height'] # 使用可配置的音符高度
# 如果音符宽度太小,可能是计算错误,跳过
if note_width < 5:
return False
# 判断是否在判定线上
is_active = note_start_x <= judgment_line_x <= note_end_x
# 计算淡入淡出透明度
fade_alpha = 255
fade_duration = config['fade_duration']
# 开头淡入 - 只在序列开始时应用
if current_time < fade_duration:
fade_alpha = int(255 * (current_time / fade_duration))
# 结尾淡出 - 只在序列结束时应用
if current_time > total_duration - fade_duration:
fade_alpha = int(255 * ((total_duration - current_time) / fade_duration))
# 选择颜色
note_color = config['active_note_color'] if is_active else config['note_color']
# 应用淡入淡出效果
if fade_alpha < 255:
note_color = (*note_color[:3], fade_alpha)
# 绘制音符阴影
if config['note_shadow']:
shadow_color = (0, 0, 0, 100) if config['transparent_background'] else (30, 30, 30)
shadow_rect = (note_start_x + 3, note_y - note_height/2 + 3,
note_width, note_height)
if config['note_corner_radius'] > 0:
self._draw_rounded_rect(screen, shadow_color, shadow_rect, config['note_corner_radius'])
else:
pygame.draw.rect(screen, shadow_color, shadow_rect)
# 绘制音符主体
note_rect = (note_start_x, note_y - note_height/2, note_width, note_height)
if config['note_corner_radius'] > 0:
self._draw_rounded_rect(screen, note_color, note_rect, config['note_corner_radius'])
else:
pygame.draw.rect(screen, note_color, note_rect)
# 绘制歌词(如果不是休止符且启用了歌词显示)
if config.get('show_lyric', True) and note['lyric'] and note['lyric'].upper() != 'R':
try:
# 使用传入的字体渲染文本
lyric_color = config['lyric_color']
if fade_alpha < 255:
lyric_color = (*lyric_color[:3], fade_alpha)
text_surface = font.render(note['lyric'], True, lyric_color)
# 计算歌词位置(音符头部上方)
lyric_x = note_start_x + min(20, note_width / 2) # 在音符开头位置
lyric_y = note_y - note_height/2 - config['lyric_offset']
text_rect = text_surface.get_rect(midbottom=(lyric_x, lyric_y))
screen.blit(text_surface, text_rect)
except Exception as e:
print(f"渲染歌词失败: {e}")
return True
def _draw_pitch_curves(self, screen, ust_notes, current_time, config,
pixels_per_second, judgment_line_x, total_duration, lead_in_time):
"""绘制音高曲线"""
if not ust_notes:
return
curve_color = config.get('pitch_curve_color', (255, 255, 0))
curve_width = config.get('pitch_curve_width', 3)
show_shadow = config.get('pitch_curve_shadow', True)
show_dots = config.get('pitch_curve_dots', True)
dot_size = config.get('pitch_curve_dot_size', 5)
curve_smoothness = config.get('pitch_curve_smoothness', 50) # 平滑度参数
# 计算淡入淡出透明度
fade_alpha = 255
fade_duration = config['fade_duration']
if current_time < fade_duration:
fade_alpha = int(255 * (current_time / fade_duration))
elif current_time > total_duration - fade_duration:
fade_alpha = int(255 * ((total_duration - current_time) / fade_duration))
if fade_alpha < 255:
curve_color = (*curve_color[:3], fade_alpha)
# 绘制每个音符的音高曲线
for i, note in enumerate(ust_notes):
# 跳过无效的音符
if note['lyric'].upper() == 'R' or note['note_num'] <= 0: