forked from LingFeng-bbben/MajdataEdit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindowCore.cs
1568 lines (1371 loc) · 60.7 KB
/
MainWindowCore.cs
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
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Threading;
using DiscordRPC;
using MajdataEdit.AutoSaveModule;
using MajdataEdit.SyntaxModule;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Semver;
using Un4seen.Bass;
using Un4seen.Bass.AddOn.Fx;
using WPFLocalizeExtension.Engine;
using WPFLocalizeExtension.Extensions;
using Brush = System.Drawing.Brush;
using Color = System.Drawing.Color;
using DashStyle = System.Drawing.Drawing2D.DashStyle;
using LinearGradientBrush = System.Drawing.Drawing2D.LinearGradientBrush;
using Pen = System.Drawing.Pen;
using PixelFormat = System.Drawing.Imaging.PixelFormat;
using Timer = System.Timers.Timer;
namespace MajdataEdit;
public partial class MainWindow : Window
{
private const string majSettingFilename = "majSetting.json";
private const string editorSettingFilename = "EditorSetting.json";
public static readonly string MAJDATA_VERSION_STRING = $"v{Assembly.GetExecutingAssembly().GetName().Version!.ToString(3)}";
public static readonly SemVersion MAJDATA_VERSION = SemVersion.Parse(MAJDATA_VERSION_STRING, SemVersionStyles.Any);
public static string maidataDir = "";
//float[] wavedBs;
private readonly short[][] waveRaws = new short[3][];
public Timer chartChangeTimer = new(1000); // 谱面变更延迟解析]\
private readonly Timer currentTimeRefreshTimer = new(100);
public DiscordRpcClient DCRPCclient = new("1068882546932326481");
private float deltatime = 4f;
public EditorSetting? editorSetting;
private bool fumenOverwriteMode; //谱面文本覆盖模式
private float ghostCusorPositionTime;
private bool isDrawing;
private bool isLoading;
private bool isReplaceConformed;
private bool isSaved = true;
private EditorControlMethod lastEditorState;
private TextSelection? lastFindPosition;
private double lastMousePointX; //Used for drag scroll
private int selectedDifficulty = -1;
private double songLength;
private SoundSetting soundSetting = new();
private bool UpdateCheckLock;
//*UI DRAWING
private readonly Timer visualEffectRefreshTimer = new(1);
private WriteableBitmap? WaveBitmap;
//*TEXTBOX CONTROL
private string GetRawFumenText()
{
var text = new TextRange(FumenContent.Document.ContentStart, FumenContent.Document.ContentEnd).Text!;
text = text.Replace("\r", "");
// 亲爱的bbben在这里对text进行了Trim 引发了行位置不正确的BUG 谨此纪念(
return text;
}
private void SetRawFumenText(string content)
{
isLoading = true;
FumenContent.Document.Blocks.Clear();
if (content == null)
{
isLoading = false;
return;
}
var lines = content.Split('\n');
foreach (var line in lines)
{
var paragraph = new Paragraph();
paragraph.Inlines.Add(line);
FumenContent.Document.Blocks.Add(paragraph);
}
isLoading = false;
}
private long GetRawFumenPosition()
{
long pos = new TextRange(FumenContent.Document.ContentStart, FumenContent.CaretPosition).Text.Replace("\r", "")
.Length;
return pos;
}
private void SeekTextFromTime()
{
//Console.WriteLine("SeekText");
var time = Bass.BASS_ChannelBytes2Seconds(bgmStream, Bass.BASS_ChannelGetPosition(bgmStream));
var timingList = new List<SimaiTimingPoint>();
timingList.AddRange(SimaiProcess.timinglist);
var noteList = SimaiProcess.notelist;
if (SimaiProcess.timinglist.Count <= 0) return;
timingList.Sort((x, y) => Math.Abs(time - x.time).CompareTo(Math.Abs(time - y.time)));
var theNote = timingList[0];
timingList.Clear();
timingList.AddRange(SimaiProcess.timinglist);
var indexOfTheNote = timingList.IndexOf(theNote);
var pointer = FumenContent.Document.Blocks.ToList()[theNote.rawTextPositionY].ContentStart
.GetPositionAtOffset(theNote.rawTextPositionX);
FumenContent.Selection.Select(pointer, pointer);
}
private void SeekTextFromIndex(int noteGroupIndex)
{
if (SimaiProcess.notelist.Count > noteGroupIndex + 1 && noteGroupIndex >= 0)
{
var theNote = SimaiProcess.notelist[noteGroupIndex];
var pointer = FumenContent.Document.Blocks.ToList()[theNote.rawTextPositionY].ContentStart
.GetPositionAtOffset(theNote.rawTextPositionX);
FumenContent.Selection.Select(pointer, pointer);
}
}
public void ScrollToFumenContentSelection(int positionX, int positionY)
{
// 这玩意用于其他窗口来滚动Scroll 因为涉及到好多变量都是private的
var pointer = FumenContent.Document.Blocks.ToList()[positionY].ContentStart.GetPositionAtOffset(positionX);
FumenContent.Focus();
FumenContent.Selection.Select(pointer, pointer);
Focus();
if (Bass.BASS_ChannelIsActive(bgmStream) == BASSActive.BASS_ACTIVE_PLAYING && (bool)FollowPlayCheck.IsChecked!)
return;
var time = SimaiProcess.Serialize(GetRawFumenText(), GetRawFumenPosition());
SetBgmPosition(time);
//Console.WriteLine("SelectionChanged");
SimaiProcess.ClearNoteListPlayedState();
ghostCusorPositionTime = (float)time;
}
//*FIND AND REPLACE
private void Find_icon_MouseDown(object? sender, MouseButtonEventArgs e)
{
FindAndScroll();
}
private void Replace_icon_MouseDown(object? sender, MouseButtonEventArgs e)
{
if (!isReplaceConformed)
{
FindAndScroll();
return;
}
if (FumenContent.Selection == lastFindPosition)
{
FumenContent.Selection.Text = ReplaceText.Text;
FindAndScroll();
}
else
{
isReplaceConformed = false;
}
}
public TextRange? GetTextRangeFromPosition(TextPointer position, string input)
{
TextRange? textRange = null;
while (position != null)
{
if (position.CompareTo(FumenContent.Document.ContentEnd) == 0) break;
if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
var textRun = position.GetTextInRun(LogicalDirection.Forward);
var stringComparison = StringComparison.CurrentCultureIgnoreCase;
var indexInRun = textRun.IndexOf(input, stringComparison);
if (indexInRun >= 0)
{
position = position.GetPositionAtOffset(indexInRun);
var nextPointer = position.GetPositionAtOffset(input.Length);
textRange = new TextRange(position, nextPointer);
// If a none-WholeWord match is found, directly terminate the loop.
position = position.GetPositionAtOffset(input.Length);
break;
}
// If a match is not found, go over to the next context position after the "textRun".
position = position.GetPositionAtOffset(textRun.Length);
}
else
{
//If the current position doesn't represent a text context position, go to the next context position.
// This can effectively ignore the formatting or embed element symbols.
position = position.GetNextContextPosition(LogicalDirection.Forward);
}
}
return textRange;
}
public void FindAndScroll()
{
var position = GetTextRangeFromPosition(FumenContent.CaretPosition, InputText.Text);
if (position == null)
{
isReplaceConformed = false;
return;
}
FumenContent.Selection.Select(position.Start, position.End);
lastFindPosition = FumenContent.Selection;
FumenContent.Focus();
isReplaceConformed = true;
}
//*FILE CONTROL
private void initFromFile(string path) //file name should not be included in path
{
if (soundSetting != null) soundSetting.Close();
if (editorSetting == null) ReadEditorSetting();
var useOgg = File.Exists(path + "/track.ogg");
var audioPath = path + "/track" + (useOgg ? ".ogg" : ".mp3");
var dataPath = path + "/maidata.txt";
if (!File.Exists(audioPath))
{
MessageBox.Show(GetLocalizedString("NoTrack"), GetLocalizedString("Error"));
return;
}
if (!File.Exists(dataPath))
{
MessageBox.Show(GetLocalizedString("NoMaidata_txt"), GetLocalizedString("Error"));
return;
}
maidataDir = path;
SafeTerminationDetector.Of().ChangePath(maidataDir);
SetRawFumenText("");
if (bgmStream != -1024)
{
Bass.BASS_ChannelStop(bgmStream);
Bass.BASS_StreamFree(bgmStream);
}
//soundSetting.Close();
var decodeStream = Bass.BASS_StreamCreateFile(audioPath, 0L, 0L, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_STREAM_PRESCAN);
bgmStream = BassFx.BASS_FX_TempoCreate(decodeStream, BASSFlag.BASS_FX_FREESOURCE);
//Bass.BASS_StreamCreateFile(audioPath, 0L, 0L, BASSFlag.BASS_SAMPLE_FLOAT);
Bass.BASS_ChannelSetAttribute(bgmStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_BGM_Level);
Bass.BASS_ChannelSetAttribute(trackStartStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_BGM_Level);
Bass.BASS_ChannelSetAttribute(allperfectStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_BGM_Level);
Bass.BASS_ChannelSetAttribute(fanfareStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_BGM_Level);
Bass.BASS_ChannelSetAttribute(clockStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_BGM_Level);
Bass.BASS_ChannelSetAttribute(answerStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_Answer_Level);
Bass.BASS_ChannelSetAttribute(judgeStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_Judge_Level);
Bass.BASS_ChannelSetAttribute(judgeBreakStream, BASSAttribute.BASS_ATTRIB_VOL,
editorSetting!.Default_Break_Level);
Bass.BASS_ChannelSetAttribute(judgeBreakSlideStream, BASSAttribute.BASS_ATTRIB_VOL,
editorSetting!.Default_Break_Slide_Level);
Bass.BASS_ChannelSetAttribute(slideStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_Slide_Level);
Bass.BASS_ChannelSetAttribute(breakSlideStartStream, BASSAttribute.BASS_ATTRIB_VOL,
editorSetting!.Default_Slide_Level);
Bass.BASS_ChannelSetAttribute(breakStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_Break_Level);
Bass.BASS_ChannelSetAttribute(breakSlideStream, BASSAttribute.BASS_ATTRIB_VOL,
editorSetting!.Default_Break_Slide_Level);
Bass.BASS_ChannelSetAttribute(judgeExStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_Ex_Level);
Bass.BASS_ChannelSetAttribute(touchStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_Touch_Level);
Bass.BASS_ChannelSetAttribute(hanabiStream, BASSAttribute.BASS_ATTRIB_VOL, editorSetting!.Default_Hanabi_Level);
Bass.BASS_ChannelSetAttribute(holdRiserStream, BASSAttribute.BASS_ATTRIB_VOL,
editorSetting!.Default_Hanabi_Level);
var info = Bass.BASS_ChannelGetInfo(bgmStream);
if (info.freq != 44100) MessageBox.Show(GetLocalizedString("Warn44100Hz"), GetLocalizedString("Attention"));
ReadWaveFromFile();
SimaiProcess.ClearData();
if (!SimaiProcess.ReadData(dataPath)) return;
LevelSelector.SelectedItem = LevelSelector.Items[0];
ReadSetting();
SetRawFumenText(SimaiProcess.fumens[selectedDifficulty]);
SeekTextFromTime();
SimaiProcess.Serialize(GetRawFumenText());
FumenContent.Focus();
DrawWave();
OffsetTextBox.Text = SimaiProcess.first.ToString();
Cover.Visibility = Visibility.Collapsed;
MenuEdit.IsEnabled = true;
VolumnSetting.IsEnabled = true;
MenuMuriCheck.IsEnabled = true;
Menu_ExportRender.IsEnabled = true;
SyntaxCheckButton.IsEnabled = true;
AutoSaveManager.Of().SetAutoSaveEnable(true);
SetSavedState(true);
SyntaxCheck();
}
internal async void SyntaxCheck()
{
if (editorSetting!.SyntaxCheckLevel == 0)
{
SetErrCount(GetLocalizedString("SyntaxCheckLevel1"));
return;
}
#if DEBUG
await SyntaxChecker.ScanAsync(GetRawFumenText());
SetErrCount(SyntaxChecker.GetErrorCount());
#else
try
{
await SyntaxChecker.ScanAsync(GetRawFumenText());
SetErrCount(SyntaxChecker.ErrorList.Count);
}
catch
{
SetErrCount(GetLocalizedString("InternalErr"));
}
#endif
}
void SetErrCount<T>(T eCount) => Dispatcher.Invoke(() => ErrCount.Content = $"{eCount}");
private void ReadWaveFromFile()
{
var useOgg = File.Exists(maidataDir + "/track.ogg");
var bgmDecode = Bass.BASS_StreamCreateFile(maidataDir + "/track" + (useOgg ? ".ogg" : ".mp3"), 0L, 0L, BASSFlag.BASS_STREAM_DECODE);
try
{
songLength = Bass.BASS_ChannelBytes2Seconds(bgmDecode,
Bass.BASS_ChannelGetLength(bgmDecode, BASSMode.BASS_POS_BYTE));
/* int sampleNumber = (int)((songLength * 1000) / (0.02f * 1000));
wavedBs = new float[sampleNumber];
for (int i = 0; i < sampleNumber; i++)
{
wavedBs[i] = Bass.BASS_ChannelGetLevels(bgmDecode, 0.02f, BASSLevel.BASS_LEVEL_MONO)[0];
}*/
Bass.BASS_StreamFree(bgmDecode);
var bgmSample = Bass.BASS_SampleLoad(maidataDir + "/track" + (useOgg ? ".ogg" : ".mp3"), 0, 0, 1, BASSFlag.BASS_DEFAULT);
var bgmInfo = Bass.BASS_SampleGetInfo(bgmSample);
var freq = bgmInfo.freq;
var sampleCount = (long)(songLength * freq * 2);
var bgmRAW = new short[sampleCount];
Bass.BASS_SampleGetData(bgmSample, bgmRAW);
waveRaws[0] = new short[sampleCount / 20 + 1];
for (var i = 0; i < sampleCount; i = i + 20) waveRaws[0][i / 20] = bgmRAW[i];
waveRaws[1] = new short[sampleCount / 50 + 1];
for (var i = 0; i < sampleCount; i = i + 50) waveRaws[1][i / 50] = bgmRAW[i];
waveRaws[2] = new short[sampleCount / 100 + 1];
for (var i = 0; i < sampleCount; i = i + 100) waveRaws[2][i / 100] = bgmRAW[i];
}
catch (Exception e)
{
MessageBox.Show("mp3/ogg解码失败。\nMP3/OGG Decode fail.\n" + e.Message + Bass.BASS_ErrorGetCode());
Bass.BASS_StreamFree(bgmDecode);
Process.Start("https://github.com/LingFeng-bbben/MajdataEdit/issues/26");
}
}
private void SetSavedState(bool state)
{
if (state)
{
isSaved = true;
LevelSelector.IsEnabled = true;
TheWindow.Title = GetWindowsTitleString(SimaiProcess.title!);
}
else
{
isSaved = false;
LevelSelector.IsEnabled = false;
TheWindow.Title = GetWindowsTitleString(GetLocalizedString("Unsaved") + SimaiProcess.title!);
AutoSaveManager.Of().SetFileChanged();
}
}
/// <summary>
/// Ask the user and save fumen.
/// </summary>
/// <returns>Return false if user cancel the action</returns>
private bool AskSave()
{
var result = MessageBox.Show(GetLocalizedString("AskSave"), GetLocalizedString("Warning"),
MessageBoxButton.YesNoCancel);
if (result == MessageBoxResult.Yes)
{
SaveFumen(true);
return true;
}
if (result == MessageBoxResult.Cancel) return false;
return true;
}
private void SaveFumen(bool writeToDisk = false)
{
if (selectedDifficulty == -1) return;
SimaiProcess.fumens[selectedDifficulty] = GetRawFumenText();
SimaiProcess.first = float.Parse(OffsetTextBox.Text);
if (maidataDir == "")
{
var saveDialog = new SaveFileDialog
{
Filter = "maidata.txt|maidata.txt",
OverwritePrompt = true
};
if ((bool)saveDialog.ShowDialog()!) maidataDir = new FileInfo(saveDialog.FileName).DirectoryName!;
}
SimaiProcess.SaveData(maidataDir + "/maidata.bak.txt");
SaveSetting();
if (writeToDisk)
{
SimaiProcess.SaveData(maidataDir + "/maidata.txt");
SetSavedState(true);
}
}
private void SaveSetting()
{
if (maidataDir == "") return;
var setting = new MajSetting
{
lastEditDiff = selectedDifficulty,
lastEditTime = Bass.BASS_ChannelBytes2Seconds(bgmStream, Bass.BASS_ChannelGetPosition(bgmStream))
};
Bass.BASS_ChannelGetAttribute(bgmStream, BASSAttribute.BASS_ATTRIB_VOL, ref setting.BGM_Level);
Bass.BASS_ChannelGetAttribute(answerStream, BASSAttribute.BASS_ATTRIB_VOL, ref setting.Answer_Level);
Bass.BASS_ChannelGetAttribute(judgeStream, BASSAttribute.BASS_ATTRIB_VOL, ref setting.Judge_Level);
Bass.BASS_ChannelGetAttribute(judgeBreakStream, BASSAttribute.BASS_ATTRIB_VOL, ref setting.Break_Level);
Bass.BASS_ChannelGetAttribute(breakSlideStream, BASSAttribute.BASS_ATTRIB_VOL, ref setting.Break_Slide_Level);
Bass.BASS_ChannelGetAttribute(judgeExStream, BASSAttribute.BASS_ATTRIB_VOL, ref setting.Ex_Level);
Bass.BASS_ChannelGetAttribute(touchStream, BASSAttribute.BASS_ATTRIB_VOL, ref setting.Touch_Level);
Bass.BASS_ChannelGetAttribute(slideStream, BASSAttribute.BASS_ATTRIB_VOL, ref setting.Slide_Level);
Bass.BASS_ChannelGetAttribute(hanabiStream, BASSAttribute.BASS_ATTRIB_VOL, ref setting.Hanabi_Level);
var json = JsonConvert.SerializeObject(setting);
File.WriteAllText(maidataDir + "/" + majSettingFilename, json);
}
private void ReadSetting()
{
var path = maidataDir + "/" + majSettingFilename;
if (!File.Exists(path)) return;
var setting = JsonConvert.DeserializeObject<MajSetting>(File.ReadAllText(path));
LevelSelector.SelectedIndex = setting!.lastEditDiff;
selectedDifficulty = setting.lastEditDiff;
SetBgmPosition(setting.lastEditTime);
Bass.BASS_ChannelSetAttribute(bgmStream, BASSAttribute.BASS_ATTRIB_VOL, setting.BGM_Level);
Bass.BASS_ChannelSetAttribute(trackStartStream, BASSAttribute.BASS_ATTRIB_VOL, setting.BGM_Level);
Bass.BASS_ChannelSetAttribute(allperfectStream, BASSAttribute.BASS_ATTRIB_VOL, setting.BGM_Level);
Bass.BASS_ChannelSetAttribute(fanfareStream, BASSAttribute.BASS_ATTRIB_VOL, setting.BGM_Level);
Bass.BASS_ChannelSetAttribute(clockStream, BASSAttribute.BASS_ATTRIB_VOL, setting.BGM_Level);
Bass.BASS_ChannelSetAttribute(answerStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Answer_Level);
Bass.BASS_ChannelSetAttribute(judgeStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Judge_Level);
Bass.BASS_ChannelSetAttribute(judgeBreakStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Break_Level);
Bass.BASS_ChannelSetAttribute(judgeBreakSlideStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Break_Slide_Level);
Bass.BASS_ChannelSetAttribute(slideStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Slide_Level);
Bass.BASS_ChannelSetAttribute(breakSlideStartStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Slide_Level);
Bass.BASS_ChannelSetAttribute(breakStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Break_Level);
Bass.BASS_ChannelSetAttribute(breakSlideStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Break_Slide_Level);
Bass.BASS_ChannelSetAttribute(judgeExStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Ex_Level);
Bass.BASS_ChannelSetAttribute(touchStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Touch_Level);
Bass.BASS_ChannelSetAttribute(hanabiStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Hanabi_Level);
Bass.BASS_ChannelSetAttribute(holdRiserStream, BASSAttribute.BASS_ATTRIB_VOL, setting.Hanabi_Level);
SaveSetting(); // 覆盖旧版本setting
}
private void CreateNewFumen(string path)
{
if (File.Exists(path + "/maidata.txt"))
MessageBox.Show(GetLocalizedString("MaidataExist"));
else
File.WriteAllText(path + "/maidata.txt",
"&title=" + GetLocalizedString("SetTitle") + "\n" +
"&artist=" + GetLocalizedString("SetArtist") + "\n" +
"&des=" + GetLocalizedString("SetDes") + "\n" +
"&first=0\n");
}
private void CreateEditorSetting()
{
editorSetting = new EditorSetting
{
RenderMode =
RenderOptions.ProcessRenderMode == RenderMode.SoftwareOnly ? 1 : 0 // 使用命令行指定强制软件渲染时,同步修改配置值
};
File.WriteAllText(editorSettingFilename, JsonConvert.SerializeObject(editorSetting, Formatting.Indented));
var esp = new EditorSettingPanel(true)
{
Owner = this
};
esp.ShowDialog();
}
private void ReadEditorSetting()
{
if (!File.Exists(editorSettingFilename)) CreateEditorSetting();
var json = File.ReadAllText(editorSettingFilename);
editorSetting = JsonConvert.DeserializeObject<EditorSetting>(json)!;
if (RenderOptions.ProcessRenderMode != RenderMode.SoftwareOnly)
//如果没有通过命令行预先指定渲染模式,则使用设置项的渲染模式
RenderOptions.ProcessRenderMode =
editorSetting.RenderMode == 0 ? RenderMode.Default : RenderMode.SoftwareOnly;
else
//如果通过命令行指定了使用软件渲染模式,则覆盖设置项
editorSetting.RenderMode = 1;
LocalizeDictionary.Instance.Culture = new CultureInfo(editorSetting.Language);
AddGesture(editorSetting.PlayPauseKey, "PlayAndPause");
AddGesture(editorSetting.PlayStopKey, "StopPlaying");
AddGesture(editorSetting.SaveKey, "SaveFile");
AddGesture(editorSetting.SendViewerKey, "SendToView");
AddGesture(editorSetting.IncreasePlaybackSpeedKey, "IncreasePlaybackSpeed");
AddGesture(editorSetting.DecreasePlaybackSpeedKey, "DecreasePlaybackSpeed");
AddGesture("Ctrl+f", "Find");
AddGesture(editorSetting.MirrorLeftRightKey, "MirrorLR");
AddGesture(editorSetting.MirrorUpDownKey, "MirrorUD");
AddGesture(editorSetting.Mirror180Key, "Mirror180");
AddGesture(editorSetting.Mirror45Key, "Mirror45");
AddGesture(editorSetting.MirrorCcw45Key, "MirrorCcw45");
FumenContent.FontSize = editorSetting.FontSize;
ViewerCover.Content = editorSetting.backgroundCover.ToString();
ViewerSpeed.Content = editorSetting.playSpeed.ToString("F1"); // 转化为形如"7.0", "9.5"这样的速度
ViewerTouchSpeed.Content = editorSetting.touchSpeed.ToString("F1");
chartChangeTimer.Interval = editorSetting.ChartRefreshDelay; // 设置更新延迟
SaveEditorSetting(); // 覆盖旧版本setting
}
public void SaveEditorSetting()
{
File.WriteAllText(editorSettingFilename, JsonConvert.SerializeObject(editorSetting, Formatting.Indented));
}
private void AddGesture(string keyGusture, string command)
{
var gesture = (InputGesture) new KeyGestureConverter().ConvertFromString(keyGusture)!;
var inputBinding = new InputBinding((ICommand)FumenContent.Resources[command], gesture);
FumenContent.InputBindings.Add(inputBinding);
}
// This update very freqently to Draw FFT wave.
private void VisualEffectRefreshTimer_Elapsed(object? sender, ElapsedEventArgs e)
{
try
{
DrawFFT();
DrawWave();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
// 谱面变更延迟解析
private void ChartChangeTimer_Elapsed(object? sender, ElapsedEventArgs e)
{
Console.WriteLine("TextChanged");
SyntaxCheck();
Dispatcher.Invoke(
delegate
{
SimaiProcess.Serialize(GetRawFumenText(), GetRawFumenPosition());
DrawWave();
}
);
}
private void DrawFFT()
{
Dispatcher.InvokeAsync(() =>
{
//Scroll WaveView
var currentTime = Bass.BASS_ChannelBytes2Seconds(bgmStream, Bass.BASS_ChannelGetPosition(bgmStream));
//MusicWave.Margin = new Thickness(-currentTime / sampleTime * zoominPower, Margin.Left, MusicWave.Margin.Right, Margin.Bottom);
//MusicWaveCusor.Margin = new Thickness(-currentTime / sampleTime * zoominPower, Margin.Left, MusicWave.Margin.Right, Margin.Bottom);
var writableBitmap = new WriteableBitmap(255, 255, 72, 72, PixelFormats.Pbgra32, null);
FFTImage.Source = writableBitmap;
writableBitmap.Lock();
var backBitmap = new Bitmap(255, 255, writableBitmap.BackBufferStride,
PixelFormat.Format32bppArgb, writableBitmap.BackBuffer);
var graphics = Graphics.FromImage(backBitmap);
graphics.Clear(Color.Transparent);
var fft = new float[1024];
Bass.BASS_ChannelGetData(bgmStream, fft, (int)BASSData.BASS_DATA_FFT1024);
var points = new PointF[1024];
for (var i = 0; i < fft.Length; i++)
points[i] = new PointF((float)Math.Log10(i + 1) * 100f, 240 - fft[i] * 256); //semilog
graphics.DrawCurve(new Pen(Color.LightSkyBlue, 1), points);
//no please
/*
var isSuccess = new Visuals().CreateSpectrumWave(bgmStream, graphics, new System.Drawing.Rectangle(0, 0, 255, 255),
System.Drawing.Color.White, System.Drawing.Color.Red,
System.Drawing.Color.Black, 1,
false, false, false);
Console.WriteLine(isSuccess);
*/
graphics.Flush();
graphics.Dispose();
backBitmap.Dispose();
writableBitmap.AddDirtyRect(new Int32Rect(0, 0, 255, 255));
writableBitmap.Unlock();
});
}
private void InitWave()
{
var width = (int)Width - 2;
var height = (int)MusicWave.Height;
WaveBitmap = new WriteableBitmap(width, height, 72, 72, PixelFormats.Pbgra32, null);
MusicWave.Source = WaveBitmap;
}
private void DrawWave()
{
if (isDrawing) return;
if (WaveBitmap == null) return;
Dispatcher.Invoke(() =>
{
isDrawing = true;
var width = WaveBitmap.PixelWidth;
var height = WaveBitmap.PixelHeight;
if (waveRaws[0] == null)
{
isDrawing = false;
return;
}
WaveBitmap.Lock();
//the process starts
var backBitmap = new Bitmap(width, height, WaveBitmap.BackBufferStride,
PixelFormat.Format32bppArgb, WaveBitmap.BackBuffer);
var graphics = Graphics.FromImage(backBitmap);
var currentTime = Bass.BASS_ChannelBytes2Seconds(bgmStream, Bass.BASS_ChannelGetPosition(bgmStream));
graphics.Clear(Color.FromArgb(100, 0, 0, 0));
var resample = (int)deltatime - 1;
if (resample > 1 && resample <= 3) resample = 1;
if (resample > 3) resample = 2;
var waveLevels = waveRaws[resample];
var step = songLength / waveLevels.Length;
var startindex = (int)((currentTime - deltatime) / step);
var stopindex = (int)((currentTime + deltatime) / step);
var linewidth = backBitmap.Width / (float)(stopindex - startindex);
var pen = new Pen(Color.Green, linewidth);
var points = new List<PointF>();
for (var i = startindex; i < stopindex; i = i + 1)
{
if (i < 0) i = 0;
if (i >= waveLevels.Length - 1) break;
var x = (i - startindex) * linewidth;
var y = waveLevels[i] / 65535f * height + height / 2;
points.Add(new PointF(x, y));
}
graphics.DrawLines(pen, points.ToArray());
//Draw Bpm lines
var lastbpm = -1f;
var bpmChangeTimes = new List<double>(); //在什么时间变成什么值
var bpmChangeValues = new List<float>();
bpmChangeTimes.Clear();
bpmChangeValues.Clear();
foreach (var timing in SimaiProcess.timinglist)
if (timing.currentBpm != lastbpm)
{
bpmChangeTimes.Add(timing.time);
bpmChangeValues.Add(timing.currentBpm);
lastbpm = timing.currentBpm;
}
bpmChangeTimes.Add(Bass.BASS_ChannelBytes2Seconds(bgmStream, Bass.BASS_ChannelGetLength(bgmStream)));
double time = SimaiProcess.first;
var signature = 4; //预留拍号
var currentBeat = 1;
var timePerBeat = 0d;
pen = new Pen(Color.Yellow, 1);
var strongBeat = new List<double>();
var weakBeat = new List<double>();
for (var i = 1; i < bpmChangeTimes.Count; i++)
{
while (time - bpmChangeTimes[i] < -0.05) //在那个时间之前都是之前的bpm
{
if (currentBeat > signature) currentBeat = 1;
timePerBeat = 1d / (bpmChangeValues[i - 1] / 60d);
if (currentBeat == 1)
strongBeat.Add(time);
else
weakBeat.Add(time);
currentBeat++;
time += timePerBeat;
}
time = bpmChangeTimes[i];
currentBeat = 1;
}
foreach (var btime in strongBeat)
{
if (btime - currentTime > deltatime) continue;
var x = ((float)(btime / step) - startindex) * linewidth;
graphics.DrawLine(pen, x, 0, x, 75);
}
foreach (var btime in weakBeat)
{
if (btime - currentTime > deltatime) continue;
var x = ((float)(btime / step) - startindex) * linewidth;
graphics.DrawLine(pen, x, 0, x, 15);
}
//Draw timing lines
pen = new Pen(Color.White, 1);
foreach (var note in SimaiProcess.timinglist)
{
if (note == null) break;
if (note.time - currentTime > deltatime) continue;
var x = ((float)(note.time / step) - startindex) * linewidth;
graphics.DrawLine(pen, x, 60, x, 75);
}
//Draw notes
foreach (var note in SimaiProcess.notelist)
{
if (note == null) break;
if (note.time - currentTime > deltatime) continue;
var notes = note.getNotes();
var isEach = notes.Count(o => !o.isSlideNoHead) > 1;
var x = ((float)(note.time / step) - startindex) * linewidth;
foreach (var noteD in notes)
{
var y = noteD.startPosition * 6.875f + 8f; //与键位有关
if (noteD.isHanabi)
{
var xDeltaHanabi = (float)(1f / step) * linewidth; //Hanabi is 1s due to frame analyze
var rectangleF = new RectangleF(x, 0, xDeltaHanabi, 75);
if (noteD.noteType == SimaiNoteType.TouchHold)
rectangleF.X += (float)(noteD.holdTime / step) * linewidth;
var gradientBrush = new LinearGradientBrush(
rectangleF,
Color.FromArgb(100, 255, 0, 0),
Color.FromArgb(0, 255, 0, 0),
LinearGradientMode.Horizontal
);
graphics.FillRectangle(gradientBrush, rectangleF);
}
if (noteD.noteType == SimaiNoteType.Tap)
{
if (noteD.isForceStar)
{
pen.Width = 3;
if (noteD.isBreak)
pen.Color = Color.OrangeRed;
else if (isEach)
pen.Color = Color.Gold;
else
pen.Color = Color.DeepSkyBlue;
Brush brush = new SolidBrush(pen.Color);
graphics.DrawString("*", new Font("Consolas", 12, System.Drawing.FontStyle.Bold), brush,
new PointF(x - 7f, y - 7f));
}
else
{
pen.Width = 2;
if (noteD.isBreak)
pen.Color = Color.OrangeRed;
else if (isEach)
pen.Color = Color.Gold;
else
pen.Color = Color.LightPink;
graphics.DrawEllipse(pen, x - 2.5f, y - 2.5f, 5, 5);
}
}
if (noteD.noteType == SimaiNoteType.Touch)
{
pen.Width = 2;
pen.Color = isEach ? Color.Gold : Color.DeepSkyBlue;
graphics.DrawRectangle(pen, x - 2.5f, y - 2.5f, 5, 5);
}
if (noteD.noteType == SimaiNoteType.Hold)
{
pen.Width = 3;
if (noteD.isBreak)
pen.Color = Color.OrangeRed;
else if (isEach)
pen.Color = Color.Gold;
else
pen.Color = Color.LightPink;
var xRight = x + (float)(noteD.holdTime / step) * linewidth;
//1h[0:1]
if (!float.IsNormal(xRight)) xRight = ushort.MaxValue;
if (xRight - x < 1f) xRight = x + 5;
graphics.DrawLine(pen, x, y, xRight, y);
}
if (noteD.noteType == SimaiNoteType.TouchHold)
{
pen.Width = 3;
var xDelta = (float)(noteD.holdTime / step) * linewidth / 4f;
//Console.WriteLine("HoldPixel"+ xDelta);
if (!float.IsNormal(xDelta)) xDelta = ushort.MaxValue;
if (xDelta < 1f) xDelta = 1;
pen.Color = Color.FromArgb(200, 255, 75, 0);
graphics.DrawLine(pen, x, y, x + xDelta * 4f, y);
pen.Color = Color.FromArgb(200, 255, 241, 0);
graphics.DrawLine(pen, x, y, x + xDelta * 3f, y);
pen.Color = Color.FromArgb(200, 2, 165, 89);
graphics.DrawLine(pen, x, y, x + xDelta * 2f, y);
pen.Color = Color.FromArgb(200, 0, 140, 254);
graphics.DrawLine(pen, x, y, x + xDelta, y);
}
if (noteD.noteType == SimaiNoteType.Slide)
{
pen.Width = 3;
if (!noteD.isSlideNoHead)
{
if (noteD.isBreak)
pen.Color = Color.OrangeRed;
else if (isEach)
pen.Color = Color.Gold;
else
pen.Color = Color.DeepSkyBlue;
Brush brush = new SolidBrush(pen.Color);
graphics.DrawString("*", new Font("Consolas", 12, System.Drawing.FontStyle.Bold), brush,
new PointF(x - 7f, y - 7f));
}
if (noteD.isSlideBreak)
pen.Color = Color.OrangeRed;
else if (notes.Count(o => o.noteType == SimaiNoteType.Slide) >= 2)
pen.Color = Color.Gold;
else
pen.Color = Color.SkyBlue;
pen.DashStyle = DashStyle.Dot;
var xSlide = (float)(noteD.slideStartTime / step - startindex) * linewidth;
var xSlideRight = (float)(noteD.slideTime / step) * linewidth + xSlide;
if (!float.IsNormal(xSlideRight)) xSlideRight = ushort.MaxValue;
if (!float.IsNormal(xSlide)) xSlide = ushort.MaxValue;
graphics.DrawLine(pen, xSlide, y, xSlideRight, y);
pen.DashStyle = DashStyle.Solid;
}
}
}
if (playStartTime - currentTime <= deltatime)
{
//Draw play Start time
pen = new Pen(Color.Red, 5);
var x1 = (float)(playStartTime / step - startindex) * linewidth;
PointF[] tranglePoints = { new(x1 - 2, 0), new(x1 + 2, 0), new(x1, 3.46f) };
graphics.DrawPolygon(pen, tranglePoints);
}
if (ghostCusorPositionTime - currentTime <= deltatime)
{
//Draw ghost cusor
pen = new Pen(Color.Orange, 5);
var x2 = (float)(ghostCusorPositionTime / step - startindex) * linewidth;
PointF[] tranglePoints2 = { new(x2 - 2, 0), new(x2 + 2, 0), new(x2, 3.46f) };
graphics.DrawPolygon(pen, tranglePoints2);
}
graphics.Flush();
graphics.Dispose();
backBitmap.Dispose();
//MusicWave.Width = waveLevels.Length * zoominPower;
WaveBitmap.AddDirtyRect(new Int32Rect(0, 0, WaveBitmap.PixelWidth, WaveBitmap.PixelHeight));
WaveBitmap.Unlock();
isDrawing = false;
});
}
// This update less frequently. set the time text.
private void CurrentTimeRefreshTimer_Elapsed(object? sender, ElapsedEventArgs e)
{
UpdateTimeDisplay();
}
private void UpdateTimeDisplay()
{
var currentPlayTime = Bass.BASS_ChannelBytes2Seconds(bgmStream, Bass.BASS_ChannelGetPosition(bgmStream));
var minute = (int)currentPlayTime / 60;
double second = (int)(currentPlayTime - 60 * minute);
Dispatcher.Invoke(() => { TimeLabel.Content = string.Format("{0}:{1:00}", minute, second); });
}
private void ScrollWave(double delta)
{
if (Bass.BASS_ChannelIsActive(bgmStream) == BASSActive.BASS_ACTIVE_PLAYING)
TogglePause();
delta = delta * deltatime / (Width / 2);
var time = Bass.BASS_ChannelBytes2Seconds(bgmStream, Bass.BASS_ChannelGetPosition(bgmStream));
SetBgmPosition(time + delta);
SimaiProcess.ClearNoteListPlayedState();
SeekTextFromTime();
Task.Run(() => DrawWave());
}
public static string GetLocalizedString(string key, string resourceFileName = "Langs", bool addSpaceAfter = false)
{
// Build up the fully-qualified name of the key
var assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
var fullKey = assemblyName + ":" + resourceFileName + ":" + key;
var locExtension = new LocExtension(fullKey);
locExtension.ResolveLocalizedValue(out string? localizedString);
// Add a space to the end, if requested
if (addSpaceAfter) localizedString += " ";
return localizedString ?? key;
}
private void TogglePlay(PlayMethod playMethod = PlayMethod.Normal)
{
if (Op_Button.IsEnabled == false) return;
if (lastEditorState == EditorControlMethod.Start || playMethod != PlayMethod.Normal)
if (!sendRequestStop())
return;
FumenContent.Focus();
SaveFumen();
if (CheckAndStartView()) return;
Op_Button.IsEnabled = false;
isPlaying = true;
isPlan2Stop = false;
PlayAndPauseButton.Content = " ▌▌ ";
var CusorTime = SimaiProcess.Serialize(GetRawFumenText(), GetRawFumenPosition()); //scan first