1
0
mirror of synced 2024-11-24 04:20:10 +01:00

added logging system

This commit is contained in:
NotImplementedLife 2023-07-19 08:10:25 +03:00
parent 69aa56794b
commit e3d17a63de
10 changed files with 240 additions and 53 deletions

8
GZ.cs
View File

@ -13,6 +13,8 @@ namespace TaikoSoundEditor
{ {
public static string DecompressString(string gzPath) public static string DecompressString(string gzPath)
{ {
Logger.Info("GZ Decompressing string");
using FileStream originalFileStream = File.OpenRead(gzPath); using FileStream originalFileStream = File.OpenRead(gzPath);
using GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress); using GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress);
using StreamReader reader = new StreamReader(decompressionStream); using StreamReader reader = new StreamReader(decompressionStream);
@ -21,6 +23,8 @@ namespace TaikoSoundEditor
public static byte[] DecompressBytes(string gzPath) public static byte[] DecompressBytes(string gzPath)
{ {
Logger.Info("GZ Decompressing bytes");
using FileStream originalFileStream = File.OpenRead(gzPath); using FileStream originalFileStream = File.OpenRead(gzPath);
using GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress); using GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress);
using MemoryStream ms = new MemoryStream(); using MemoryStream ms = new MemoryStream();
@ -30,6 +34,8 @@ namespace TaikoSoundEditor
public static byte[] CompressToBytes(string content) public static byte[] CompressToBytes(string content)
{ {
Logger.Info("GZ Compressing bytes");
using var stream = new MemoryStream(); using var stream = new MemoryStream();
using var writer = new StreamWriter(stream); using var writer = new StreamWriter(stream);
writer.Write(content); writer.Write(content);
@ -44,6 +50,8 @@ namespace TaikoSoundEditor
public static string CompressToFile(string fileName, string content) public static string CompressToFile(string fileName, string content)
{ {
Logger.Info("GZ Compressing file");
var tmp = "~ztmp"; var tmp = "~ztmp";
if (!Directory.Exists(tmp)) if (!Directory.Exists(tmp))
Directory.CreateDirectory(tmp); Directory.CreateDirectory(tmp);

View File

@ -11,11 +11,13 @@ namespace TaikoSoundEditor
{ {
public static void WavToIdsp(string source, string dest) public static void WavToIdsp(string source, string dest)
{ {
Logger.Info("Converting WAV to IDSP");
source = Path.GetFullPath(source); source = Path.GetFullPath(source);
dest = Path.GetFullPath(dest); dest = Path.GetFullPath(dest);
Debug.WriteLine(source); Logger.Info($"source = {source}");
Debug.WriteLine(dest); Logger.Info($"dest = {dest}");
var p = new Process(); var p = new Process();
p.StartInfo.FileName = Path.GetFullPath(@"Tools\VGAudio\VGAudioCli.exe"); p.StartInfo.FileName = Path.GetFullPath(@"Tools\VGAudio\VGAudioCli.exe");

View File

@ -9,11 +9,13 @@ namespace TaikoSoundEditor
{ {
public static T Deserialize<T>(string json) public static T Deserialize<T>(string json)
{ {
Logger.Info($"Deserializing {typeof(T)} ({json.Length})");
return JsonSerializer.Deserialize<T>(json); return JsonSerializer.Deserialize<T>(json);
} }
public static string Serialize<T>(T item) public static string Serialize<T>(T item)
{ {
Logger.Info($"Serializing {typeof(T)}:\n{item}");
return JsonSerializer.Serialize(item, new JsonSerializerOptions return JsonSerializer.Serialize(item, new JsonSerializerOptions
{ {
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All), Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),

61
Logger.cs Normal file
View File

@ -0,0 +1,61 @@
using System.Collections;
namespace TaikoSoundEditor
{
internal static class Logger
{
static string LogFile;
static Logger()
{
if (!Directory.Exists("logs"))
Directory.CreateDirectory("logs");
LogFile = $"tse_{DateTime.Now:yyyy-MM-dd_hh-mm-ss}.log";
LogFile = Path.Combine("logs", LogFile);
Info("Session started");
}
private static void Write(string message)
{
try
{
File.AppendAllText(LogFile, message);
}
catch (Exception e)
{
MessageBox.Show("Failed to write log file:\n" + e.Message);
}
}
private static void Write(string type, string message)
{
Write($"[{type} {DateTime.Now:yyyy-MM-dd_hh-mm-ss}]{message}\n");
}
public static void Info(string message)=> Write("INFO", message);
public static void Warning(string message)=> Write("WARN", message);
public static void Error(string message)=> Write("ERROR", message);
public static void Error(Exception e)
{
Error($"Exception raised:\n{e.Message}\n{e.StackTrace}\nFrom {e.Source}\nData:\n");
foreach(DictionaryEntry kv in e.Data)
{
Write($"{kv.Key} = {kv.Value}");
}
Write("\n\n");
if (e.GetBaseException() != null && e.GetBaseException() != e)
{
Error(e.GetBaseException());
Write("Base exception:");
}
if(e.InnerException!=null)
{
Write("Inner exception:");
Error(e.InnerException);
}
}
}
}

View File

@ -1,5 +1,6 @@
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks.Dataflow; using System.Threading.Tasks.Dataflow;
using TaikoSoundEditor.Data; using TaikoSoundEditor.Data;
@ -20,6 +21,12 @@ namespace TaikoSoundEditor
AddedMusicBinding = new BindingSource(); AddedMusicBinding = new BindingSource();
AddedMusicBinding.DataSource = AddedMusic; AddedMusicBinding.DataSource = AddedMusic;
NewSoundsBox.DataSource = AddedMusicBinding; NewSoundsBox.DataSource = AddedMusicBinding;
TabControl.SelectedIndexChanged += TabControl_SelectedIndexChanged;
}
private void TabControl_SelectedIndexChanged(object sender, EventArgs e)
{
Logger.Info($"Commuted to tab {TabControl.SelectedIndex}");
} }
private string MusicAttributePath { get; set; } private string MusicAttributePath { get; set; }
@ -38,26 +45,31 @@ namespace TaikoSoundEditor
private void WordListPathSelector_PathChanged(object sender, EventArgs args) private void WordListPathSelector_PathChanged(object sender, EventArgs args)
{ {
Logger.Info($"WordListPathSelector_PathChanged : {WordListPathSelector.Path}");
WordListPath = WordListPathSelector.Path; WordListPath = WordListPathSelector.Path;
} }
private void MusicInfoPathSelector_PathChanged(object sender, EventArgs args) private void MusicInfoPathSelector_PathChanged(object sender, EventArgs args)
{ {
Logger.Info($"MusicInfoPathSelector_PathChanged : {MusicInfoPathSelector.Path}");
MusicInfoPath = MusicInfoPathSelector.Path; MusicInfoPath = MusicInfoPathSelector.Path;
} }
private void MusicOrderPathSelector_PathChanged(object sender, EventArgs args) private void MusicOrderPathSelector_PathChanged(object sender, EventArgs args)
{ {
Logger.Info($"MusicOrderPathSelector_PathChanged : {MusicOrderPathSelector.Path}");
MusicOrderPath = MusicOrderPathSelector.Path; MusicOrderPath = MusicOrderPathSelector.Path;
} }
private void MusicAttributePathSelector_PathChanged(object sender, EventArgs args) private void MusicAttributePathSelector_PathChanged(object sender, EventArgs args)
{ {
Logger.Info($"MusicAttributePathSelector_PathChanged : {MusicAttributePathSelector.Path}");
MusicAttributePath = MusicAttributePathSelector.Path; MusicAttributePath = MusicAttributePathSelector.Path;
} }
private void DirSelector_PathChanged(object sender, EventArgs args) => RunGuard(() => private void DirSelector_PathChanged(object sender, EventArgs args) => RunGuard(() =>
{ {
Logger.Info($"MusicAttributePathSelector_PathChanged : {DirSelector.Path}");
var dir = DirSelector.Path; var dir = DirSelector.Path;
var files = new string[] { "music_attribute.bin", "music_order.bin", "musicinfo.bin", "wordlist.bin" }; var files = new string[] { "music_attribute.bin", "music_order.bin", "musicinfo.bin", "wordlist.bin" };
var sels = new PathSelector[] { MusicAttributePathSelector, MusicOrderPathSelector, MusicInfoPathSelector, WordListPathSelector }; var sels = new PathSelector[] { MusicAttributePathSelector, MusicOrderPathSelector, MusicInfoPathSelector, WordListPathSelector };
@ -77,12 +89,15 @@ namespace TaikoSoundEditor
if (NotFoundFiles.Count > 0) if (NotFoundFiles.Count > 0)
{ {
Logger.Warning("The following files could not be found:\n\n" + String.Join("\n", NotFoundFiles));
MessageBox.Show("The following files could not be found:\n\n" + String.Join("\n", NotFoundFiles)); MessageBox.Show("The following files could not be found:\n\n" + String.Join("\n", NotFoundFiles));
} }
}); });
private void OkButton_Click(object sender, EventArgs e) => RunGuard(() => private void OkButton_Click(object sender, EventArgs e) => RunGuard(() =>
{ {
Logger.Info($"Clicked 'Looks good' ");
try try
{ {
MusicAttributes = Json.Deserialize<MusicAttributes>(GZ.DecompressString(MusicAttributePath)); MusicAttributes = Json.Deserialize<MusicAttributes>(GZ.DecompressString(MusicAttributePath));
@ -116,6 +131,7 @@ namespace TaikoSoundEditor
throw new Exception($"Failed to parse\n{WordListPath}\nReason:\n{ex.InnerException}"); throw new Exception($"Failed to parse\n{WordListPath}\nReason:\n{ex.InnerException}");
} }
Logger.Info($"Setting LoadedMusicBox DataSource");
LoadedMusicBox.DataSource = MusicInfos.Items; LoadedMusicBox.DataSource = MusicInfos.Items;
TabControl.SelectedIndex = 1; TabControl.SelectedIndex = 1;
@ -139,12 +155,14 @@ namespace TaikoSoundEditor
public static void Error(Exception e) public static void Error(Exception e)
{ {
MessageBox.Show(e.Message, "An error has occured"); MessageBox.Show(e.Message, "An error has occured");
Logger.Error(e);
} }
#region Editor #region Editor
private void GridsShow(MusicInfo item) private void GridsShow(MusicInfo item)
{ {
Logger.Info($"Showing properties for MusicInfo: {item}");
MusicInfoGrid.SelectedObject = item; MusicInfoGrid.SelectedObject = item;
MusicAttributesGrid.SelectedObject = MusicAttributes.GetByUniqueId(item.UniqueId); MusicAttributesGrid.SelectedObject = MusicAttributes.GetByUniqueId(item.UniqueId);
MusicOrderGrid.SelectedObject = MusicOrders.GetByUniqueId(item.UniqueId); MusicOrderGrid.SelectedObject = MusicOrders.GetByUniqueId(item.UniqueId);
@ -157,6 +175,7 @@ namespace TaikoSoundEditor
private void LoadedMusicBox_SelectedIndexChanged(object sender, EventArgs e) private void LoadedMusicBox_SelectedIndexChanged(object sender, EventArgs e)
{ {
var item = LoadedMusicBox.SelectedItem as MusicInfo; var item = LoadedMusicBox.SelectedItem as MusicInfo;
Logger.Info($"Selection Changed MusicItem: {item}");
GridsShow(item); GridsShow(item);
} }
@ -168,6 +187,8 @@ namespace TaikoSoundEditor
private void NewSoundsBox_SelectedIndexChanged(object sender, EventArgs e) private void NewSoundsBox_SelectedIndexChanged(object sender, EventArgs e)
{ {
var item = NewSoundsBox.SelectedItem as NewSongData; var item = NewSoundsBox.SelectedItem as NewSongData;
Logger.Info($"Selection Changed NewSongData: {item}");
Logger.Info($"Showing properties for NewSongData: {item}");
MusicInfoGrid.SelectedObject = item?.MusicInfo; MusicInfoGrid.SelectedObject = item?.MusicInfo;
MusicAttributesGrid.SelectedObject = item?.MusicAttribute; MusicAttributesGrid.SelectedObject = item?.MusicAttribute;
MusicOrderGrid.SelectedObject = item?.MusicOrder; MusicOrderGrid.SelectedObject = item?.MusicOrder;
@ -180,6 +201,7 @@ namespace TaikoSoundEditor
private void CreateButton_Click(object sender, EventArgs e) private void CreateButton_Click(object sender, EventArgs e)
{ {
Logger.Info($"Clicked Create Button");
AudioFileSelector.Path = ""; AudioFileSelector.Path = "";
TJASelector.Path = ""; TJASelector.Path = "";
SongNameBox.Text = "(6 characters id...)"; SongNameBox.Text = "(6 characters id...)";
@ -188,35 +210,50 @@ namespace TaikoSoundEditor
private void CreateBackButton_Click(object sender, EventArgs e) private void CreateBackButton_Click(object sender, EventArgs e)
{ {
Logger.Info($"Clicked Back Button");
TabControl.SelectedIndex = 1; TabControl.SelectedIndex = 1;
} }
private void WarnWithBox(string message)
{
Logger.Warning("Displayed: " + message);
MessageBox.Show(message);
}
private void CreateOkButton_Click(object sender, EventArgs e) => RunGuard(() => private void CreateOkButton_Click(object sender, EventArgs e) => RunGuard(() =>
{ {
Logger.Info($"Clicked Ok Button");
FeedbackBox.Clear(); FeedbackBox.Clear();
var audioFilePath = AudioFileSelector.Path; var audioFilePath = AudioFileSelector.Path;
var tjaPath = TJASelector.Path; var tjaPath = TJASelector.Path;
var songName = SongNameBox.Text; var songName = SongNameBox.Text;
var id = Math.Max(MusicAttributes.GetNewId(), AddedMusic.Count == 0 ? 0 : AddedMusic.Max(_ => _.UniqueId) + 1); var id = Math.Max(MusicAttributes.GetNewId(), AddedMusic.Count == 0 ? 0 : AddedMusic.Max(_ => _.UniqueId) + 1);
if(songName==null || songName.Length!=6) Logger.Info($"Audio File = {audioFilePath}");
Logger.Info($"TJA File = {tjaPath}");
Logger.Info($"Song Name (Id) = {songName}");
Logger.Info($"UniqueId = {id}");
if (songName==null || songName.Length!=6)
{ {
MessageBox.Show("Invalid song name."); WarnWithBox("Invalid song name.");
return; return;
} }
if (!MusicAttributes.IsValidSongId(songName) || AddedMusic.Any(m => m.Id == songName)) if (!MusicAttributes.IsValidSongId(songName) || AddedMusic.Any(m => m.Id == songName))
{ {
MessageBox.Show("Duplicate song name. Choose another"); WarnWithBox("Duplicate song name. Choose another");
return; return;
} }
FeedbackBox.AppendText("Creating temp dir\r\n"); FeedbackBox.AppendText("Creating temp dir\r\n");
CreateTmpDir(); CreateTmpDir();
FeedbackBox.AppendText("Parsing TJA\r\n"); FeedbackBox.AppendText("Parsing TJA\r\n");
Logger.Info("Parsing TJA");
var tja = new TJA(File.ReadAllLines(tjaPath)); var tja = new TJA(File.ReadAllLines(tjaPath));
File.WriteAllText("tja.txt", tja.ToString()); File.WriteAllText("tja.txt", tja.ToString());
@ -228,6 +265,8 @@ namespace TaikoSoundEditor
FeedbackBox.AppendText("Converting to wav\r\n"); FeedbackBox.AppendText("Converting to wav\r\n");
WAV.ConvertToWav(audioFilePath, $@".-tmp\{songName}.wav", seconds); WAV.ConvertToWav(audioFilePath, $@".-tmp\{songName}.wav", seconds);
Logger.Info("Adjusting seconds of silence");
tja.Headers.Offset -= seconds; tja.Headers.Offset -= seconds;
tja.Headers.DemoStart += seconds; tja.Headers.DemoStart += seconds;
@ -242,7 +281,7 @@ namespace TaikoSoundEditor
return l; return l;
}).ToArray(); }).ToArray();
Logger.Info("Creating temporary tja");
var newTja = @$".-tmp\{Path.GetFileName(tjaPath)}"; var newTja = @$".-tmp\{Path.GetFileName(tjaPath)}";
File.WriteAllLines(newTja, text); File.WriteAllLines(newTja, text);
@ -251,6 +290,7 @@ namespace TaikoSoundEditor
var tja_binaries = TJA.RunTja2Fumen(newTja); var tja_binaries = TJA.RunTja2Fumen(newTja);
Logger.Info("Creating new sonud data");
FeedbackBox.AppendText("Creating sound data\r\n"); FeedbackBox.AppendText("Creating sound data\r\n");
NewSongData ns = new NewSongData(); NewSongData ns = new NewSongData();
@ -369,6 +409,8 @@ namespace TaikoSoundEditor
ns.Nus3Bank = NUS3Bank.GetNus3Bank(songName, id, idsp, tja.Headers.DemoStart); ns.Nus3Bank = NUS3Bank.GetNus3Bank(songName, id, idsp, tja.Headers.DemoStart);
Logger.Info("Conversion done");
FeedbackBox.AppendText("Done\r\n"); FeedbackBox.AppendText("Done\r\n");
AddedMusic.Add(ns); AddedMusic.Add(ns);
@ -383,6 +425,7 @@ namespace TaikoSoundEditor
private void CreateTmpDir() private void CreateTmpDir()
{ {
Logger.Info($"Creating .-tmp/");
if (!Directory.Exists(".-tmp")) if (!Directory.Exists(".-tmp"))
Directory.CreateDirectory(".-tmp"); Directory.CreateDirectory(".-tmp");
} }
@ -398,6 +441,7 @@ namespace TaikoSoundEditor
private void ExportDatatable(string path) private void ExportDatatable(string path)
{ {
Logger.Info($"Exporting Datatable to '{path}'");
var mi = new MusicInfos(); var mi = new MusicInfos();
mi.Items.AddRange(MusicInfos.Items); mi.Items.AddRange(MusicInfos.Items);
mi.Items.AddRange(AddedMusic.Select(_ => _.MusicInfo)); mi.Items.AddRange(AddedMusic.Select(_ => _.MusicInfo));
@ -447,7 +491,8 @@ namespace TaikoSoundEditor
private void ExportNusBanks(string path) private void ExportNusBanks(string path)
{ {
foreach(var ns in AddedMusic) Logger.Info($"Exporting NUS3BaNKS to '{path}'");
foreach (var ns in AddedMusic)
{ {
File.WriteAllBytes(Path.Combine(path, $"song_{ns.Id}.nus3bank"), ns.Nus3Bank); File.WriteAllBytes(Path.Combine(path, $"song_{ns.Id}.nus3bank"), ns.Nus3Bank);
} }
@ -455,6 +500,7 @@ namespace TaikoSoundEditor
private void ExportSoundBinaries(string path) private void ExportSoundBinaries(string path)
{ {
Logger.Info($"Exporting Sound .bin's to '{path}'");
foreach (var ns in AddedMusic) foreach (var ns in AddedMusic)
{ {
var sdir = Path.Combine(path, ns.Id); var sdir = Path.Combine(path, ns.Id);
@ -489,6 +535,7 @@ namespace TaikoSoundEditor
private void ExportDatatableButton_Click(object sender, EventArgs e) => RunGuard(() => private void ExportDatatableButton_Click(object sender, EventArgs e) => RunGuard(() =>
{ {
Logger.Info($"Clicked ExportDatatableButton");
var path = PickPath(); var path = PickPath();
if (path == null) if (path == null)
{ {
@ -503,6 +550,7 @@ namespace TaikoSoundEditor
private void ExportSoundFoldersButton_Click(object sender, EventArgs e) => RunGuard(() => private void ExportSoundFoldersButton_Click(object sender, EventArgs e) => RunGuard(() =>
{ {
Logger.Info($"Clicked ExportSoundFoldersButton");
var path = PickPath(); var path = PickPath();
if (path == null) if (path == null)
{ {
@ -517,6 +565,7 @@ namespace TaikoSoundEditor
private void ExportSoundBanksButton_Click(object sender, EventArgs e) => RunGuard(() => private void ExportSoundBanksButton_Click(object sender, EventArgs e) => RunGuard(() =>
{ {
Logger.Info($"Clicked ExportSoundBanksButton");
var path = PickPath(); var path = PickPath();
if (path == null) if (path == null)
{ {
@ -531,6 +580,7 @@ namespace TaikoSoundEditor
private string PickPath() private string PickPath()
{ {
Logger.Info($"Picking path dialog");
var picker = new FolderPicker(); var picker = new FolderPicker();
if (picker.ShowDialog() == true) if (picker.ShowDialog() == true)
return picker.ResultPath; return picker.ResultPath;
@ -539,6 +589,7 @@ namespace TaikoSoundEditor
private void ExportAllButton_Click(object sender, EventArgs e) => RunGuard(() => private void ExportAllButton_Click(object sender, EventArgs e) => RunGuard(() =>
{ {
Logger.Info($"Clicked Export All");
var path = PickPath(); var path = PickPath();
if (path == null) if (path == null)
{ {

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TaikoSoundEditor.Properties; using TaikoSoundEditor.Properties;
using static TaikoSoundEditor.TJA;
namespace TaikoSoundEditor namespace TaikoSoundEditor
{ {
@ -19,6 +20,11 @@ namespace TaikoSoundEditor
public static byte[] GetNus3Bank(string songId, int uniqueId, byte[] idsp, float demostart) public static byte[] GetNus3Bank(string songId, int uniqueId, byte[] idsp, float demostart)
{ {
Logger.Info($"Creating NUS3BANK");
Logger.Info($"songId = {songId}");
Logger.Info($"uniqId = {uniqueId}");
Logger.Info($"idsp.len = {idsp.Length}");
Logger.Info($"demostart = {demostart}");
using var ms = new MemoryStream(); using var ms = new MemoryStream();
var header = Resources.song_ABCDEF_nus3bank.ToArray(); var header = Resources.song_ABCDEF_nus3bank.ToArray();

View File

@ -1,4 +1,5 @@
using System.Diagnostics; using System.Diagnostics;
using System.Globalization;
namespace TaikoSoundEditor namespace TaikoSoundEditor
{ {
@ -10,20 +11,18 @@ namespace TaikoSoundEditor
[STAThread] [STAThread]
static void Main() static void Main()
{ {
/*var tja = new TJA(File.ReadAllLines($@"C:\Users\NotImpLife\Desktop\nus\EXAMPLE .TJA\hoshis\hoshis.tja")); try
File.WriteAllText("tja.txt", tja.ToString());
for (int i = 0; i < 4; i++)
{ {
var c = tja.Courses[i].Converted; int x = 0;
Debug.WriteLine(i+" "+c.Notes.Length); int y = 2 / x;
//Debug.WriteLine(c.Events.Length); }
catch(Exception e)
{
Debug.WriteLine(e);
} }
return;*/
//File.WriteAllText("tja.txt", tja.ToString());
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new MainForm()); Application.Run(new MainForm());
} }

View File

@ -4,7 +4,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
--> -->
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<History>True|2023-07-18T06:25:23.0403589Z;True|2023-07-17T17:57:08.1469738+03:00;True|2023-07-17T11:28:41.9554245+03:00;True|2023-07-17T11:15:26.2194507+03:00;</History> <History>True|2023-07-18T06:38:50.7615921Z;True|2023-07-18T09:25:23.0403589+03:00;True|2023-07-17T17:57:08.1469738+03:00;True|2023-07-17T11:28:41.9554245+03:00;True|2023-07-17T11:15:26.2194507+03:00;</History>
<LastFailureDetails /> <LastFailureDetails />
</PropertyGroup> </PropertyGroup>
</Project> </Project>

71
TJA.cs
View File

@ -7,6 +7,7 @@ using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using TaikoSoundEditor.Extensions; using TaikoSoundEditor.Extensions;
using TaikoSoundEditor.Utils;
using static TaikoSoundEditor.TJA; using static TaikoSoundEditor.TJA;
namespace TaikoSoundEditor namespace TaikoSoundEditor
@ -54,7 +55,7 @@ namespace TaikoSoundEditor
{ {
Match match = null; Match match = null;
Debug.WriteLine(line); Logger.Info($"Parsing line : {line}");
if ((match = line.Match("\\/\\/.*")) != null) if ((match = line.Match("\\/\\/.*")) != null)
{ {
@ -65,16 +66,16 @@ namespace TaikoSoundEditor
{ {
var nameUpper = match.Groups[1].Value.ToUpper(); var nameUpper = match.Groups[1].Value.ToUpper();
var value = match.Groups[2].Value; var value = match.Groups[2].Value;
Debug.WriteLine($"Match = {nameUpper}, {value}"); Logger.Info($"Match = {nameUpper}, {value}");
if (HEADER_GLOBAL.Contains(nameUpper)) if (HEADER_GLOBAL.Contains(nameUpper))
{ {
Debug.WriteLine("Header++"); Logger.Info($"Detected header");
return new Line("header", "global", nameUpper, value.Trim()); return new Line("header", "global", nameUpper, value.Trim());
} }
else if (HEADER_COURSE.Contains(nameUpper)) else if (HEADER_COURSE.Contains(nameUpper))
{ {
Debug.WriteLine("HCourse++"); Logger.Info($"Detected course");
return new Line("header", "course", nameUpper, value.Trim()); return new Line("header", "course", nameUpper, value.Trim());
} }
} }
@ -84,19 +85,27 @@ namespace TaikoSoundEditor
var value = match.Groups[2].Value ?? ""; var value = match.Groups[2].Value ?? "";
if (COMMAND.Contains(nameUpper)) if (COMMAND.Contains(nameUpper))
{
Logger.Info($"Detected command");
return new Line("command", null, nameUpper, value.Trim()); return new Line("command", null, nameUpper, value.Trim());
} }
else
Logger.Warning($"Unknown command : {nameUpper} with value {value.Trim()}");
}
else if ((match = line.Match("^(([0-9]|A|B|C|F|G)*,?)$")) != null) else if ((match = line.Match("^(([0-9]|A|B|C|F|G)*,?)$")) != null)
{ {
Logger.Info($"Detected command");
var data = match.Groups[1].Value; var data = match.Groups[1].Value;
return new Line("data", null, null, data); return new Line("data", null, null, data);
} }
Logger.Warning($"Unknown line : {line}");
return new Line("unknwon", null, null, line); return new Line("unknwon", null, null, line);
} }
public Course GetCourse(Header tjaHeaders, Line[] lines) public Course GetCourse(Header tjaHeaders, Line[] lines)
{ {
Logger.Info($"Getting course from {lines.Length} lines");
var headers = new CourseHeader(); var headers = new CourseHeader();
var measures = new List<Measure>(); var measures = new List<Measure>();
@ -113,21 +122,25 @@ namespace TaikoSoundEditor
{ {
if(line.Type=="header") if(line.Type=="header")
{ {
Logger.Info($"header {line.Name} {line.Value}");
if (line.Name == "COURSE") if (line.Name == "COURSE")
headers.Course = line.Value; headers.Course = line.Value;
else if (line.Name == "LEVEL") else if (line.Name == "LEVEL")
headers.Level = int.Parse(line.Value); headers.Level = Number.ParseInt(line.Value);
else if (line.Name == "BALLOON") else if (line.Name == "BALLOON")
headers.Balloon = new Regex("[^0-9]").Split(line.Value).Where(_ => _ != "").Select(int.Parse).ToArray(); headers.Balloon = new Regex("[^0-9]").Split(line.Value).Where(_ => _ != "").Select(Number.ParseInt).ToArray();
else if (line.Name == "SCOREINIT") else if (line.Name == "SCOREINIT")
headers.ScoreInit = int.Parse(line.Value); headers.ScoreInit = Number.ParseInt(line.Value);
else if (line.Name == "SCOREDIFF") else if (line.Name == "SCOREDIFF")
headers.ScoreDiff = int.Parse(line.Value); headers.ScoreDiff = Number.ParseInt(line.Value);
else if (line.Name == "TTROWBEAT") else if (line.Name == "TTROWBEAT")
headers.TTRowBeat = int.Parse(line.Value); headers.TTRowBeat = Number.ParseInt(line.Value);
} }
else if(line.Type=="command") else if(line.Type=="command")
{ {
Logger.Info($"Command {line.Name} {line.Value}");
if (line.Name == "BRANCHSTART") if (line.Name == "BRANCHSTART")
{ {
if (!flagLevelhold) if (!flagLevelhold)
@ -142,8 +155,8 @@ namespace TaikoSoundEditor
} }
else if (values[0] == "p") else if (values[0] == "p")
{ {
if (values.Length >= 3 && float.Parse(values[2]) <= 100) targetBranch = "M"; if (values.Length >= 3 && Number.ParseFloat(values[2]) <= 100) targetBranch = "M";
else if (values.Length >= 2 && float.Parse(values[1]) <= 100) targetBranch = "E"; else if (values.Length >= 2 && Number.ParseFloat(values[1]) <= 100) targetBranch = "E";
else targetBranch = "N"; else targetBranch = "N";
} }
} }
@ -166,8 +179,8 @@ namespace TaikoSoundEditor
var matchMeasure = line.Value.Match("(\\d+)\\/(\\d+)"); var matchMeasure = line.Value.Match("(\\d+)\\/(\\d+)");
if (matchMeasure != null) if (matchMeasure != null)
{ {
measureDividend = int.Parse(matchMeasure.Groups[1].Value); measureDividend = Number.ParseInt(matchMeasure.Groups[1].Value);
measureDivisor = int.Parse(matchMeasure.Groups[2].Value); measureDivisor = Number.ParseInt(matchMeasure.Groups[2].Value);
} }
} }
else if (line.Name == "GOGOSTART") else if (line.Name == "GOGOSTART")
@ -175,9 +188,9 @@ namespace TaikoSoundEditor
else if (line.Name == "GOGOEND") else if (line.Name == "GOGOEND")
measureEvents.Add(new MeasureEvent("gogoEnd", measureData.Length)); measureEvents.Add(new MeasureEvent("gogoEnd", measureData.Length));
else if (line.Name == "SCROLL") else if (line.Name == "SCROLL")
measureEvents.Add(new MeasureEvent("scroll", measureData.Length, float.Parse(line.Value))); measureEvents.Add(new MeasureEvent("scroll", measureData.Length, Number.ParseFloat(line.Value)));
else if (line.Name == "BPMCHANGE") else if (line.Name == "BPMCHANGE")
measureEvents.Add(new MeasureEvent("bpm", measureData.Length, float.Parse(line.Value))); measureEvents.Add(new MeasureEvent("bpm", measureData.Length, Number.ParseFloat(line.Value)));
else if (line.Name == "TTBREAK") else if (line.Name == "TTBREAK")
measureProperties["ttBreak"] = true; measureProperties["ttBreak"] = true;
else if (line.Name == "LEVELHOLD") else if (line.Name == "LEVELHOLD")
@ -189,6 +202,7 @@ namespace TaikoSoundEditor
} }
else if(line.Type=="data" && currentBranch==targetBranch) else if(line.Type=="data" && currentBranch==targetBranch)
{ {
Logger.Info($"Data {line.Value}");
var data = line.Value; var data = line.Value;
if (data.EndsWith(",")) if (data.EndsWith(","))
{ {
@ -239,7 +253,9 @@ namespace TaikoSoundEditor
else if (courseValue == "edit" || courseValue == "ura"|| courseValue == "4") else if (courseValue == "edit" || courseValue == "ura"|| courseValue == "4")
course = 4; course = 4;
if(measureData!="" || measureData!=null) Logger.Info($"Course difficulty = {course}");
if (measureData!="" || measureData!=null)
{ {
measures.Add(new Measure(new int[] { measureDividend, measureDivisor }, measureProperties, measureData, measureEvents)); measures.Add(new Measure(new int[] { measureDividend, measureDivisor }, measureProperties, measureData, measureEvents));
} }
@ -251,14 +267,15 @@ namespace TaikoSoundEditor
measures[measures.Count - 1].Events.Add(ev); measures[measures.Count - 1].Events.Add(ev);
} }
} }
Debug.WriteLine(measures[measures.Count - 1]); var c = new Course(course, headers, measures);
Logger.Info($"Course created : {c}");
return c;
return new Course(course, headers, measures);
} }
public void Parse(string[] lines) public void Parse(string[] lines)
{ {
Logger.Info($"Parse start");
var headers = new Header(); var headers = new Header();
var courses = new Dictionary<int, Course>(); var courses = new Dictionary<int, Course>();
@ -273,6 +290,8 @@ namespace TaikoSoundEditor
if(parsed.Type=="header" && parsed.Scope=="global") if(parsed.Type=="header" && parsed.Scope=="global")
{ {
Logger.Info($"Header global {parsed.Name} = {parsed.Value}");
if (parsed.Name == "TITLE") if (parsed.Name == "TITLE")
headers.Title = parsed.Value; headers.Title = parsed.Value;
if (parsed.Name == "TITLEJA") if (parsed.Name == "TITLEJA")
@ -280,13 +299,13 @@ namespace TaikoSoundEditor
if (parsed.Name == "SUBTITLE") if (parsed.Name == "SUBTITLE")
headers.Subtitle = parsed.Value.StartsWith("--") ? parsed.Value.Substring(2) : parsed.Value; headers.Subtitle = parsed.Value.StartsWith("--") ? parsed.Value.Substring(2) : parsed.Value;
if (parsed.Name == "BPM") if (parsed.Name == "BPM")
headers.Bpm = float.Parse(parsed.Value); headers.Bpm = Number.ParseFloat(parsed.Value);
if (parsed.Name == "WAVE") if (parsed.Name == "WAVE")
headers.Wave = parsed.Value; headers.Wave = parsed.Value;
if (parsed.Name == "OFFSET") if (parsed.Name == "OFFSET")
headers.Offset = float.Parse(parsed.Value); headers.Offset = Number.ParseFloat(parsed.Value);
if (parsed.Name == "DEMOSTART") if (parsed.Name == "DEMOSTART")
headers.DemoStart = float.Parse(parsed.Value); headers.DemoStart = Number.ParseFloat(parsed.Value);
if (parsed.Name == "GENRE") if (parsed.Name == "GENRE")
headers.Genre = parsed.Value; headers.Genre = parsed.Value;
} }
@ -294,7 +313,7 @@ namespace TaikoSoundEditor
{ {
if (parsed.Name == "COURSE") if (parsed.Name == "COURSE")
{ {
Debug.WriteLine($"Course found : {parsed.Value}"); Logger.Info($"Course found : {parsed.Value}");
if (courseLines.Count>0) if (courseLines.Count>0)
{ {
var course = GetCourse(headers, courseLines.ToArray()); var course = GetCourse(headers, courseLines.ToArray());
@ -316,6 +335,8 @@ namespace TaikoSoundEditor
Headers = headers; Headers = headers;
Courses = courses; Courses = courses;
Logger.Info($"Parse end");
} }
@ -415,7 +436,9 @@ namespace TaikoSoundEditor
public static List<byte[]> RunTja2Fumen(string sourcePath) public static List<byte[]> RunTja2Fumen(string sourcePath)
{ {
Logger.Info("Running tja2fumen");
sourcePath = Path.GetFullPath(sourcePath); sourcePath = Path.GetFullPath(sourcePath);
Logger.Info($"source = {sourcePath}");
var dir = Path.GetDirectoryName(sourcePath); var dir = Path.GetDirectoryName(sourcePath);
var fname = Path.GetFileNameWithoutExtension(sourcePath); var fname = Path.GetFileNameWithoutExtension(sourcePath);

35
Utils/Number.cs Normal file
View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TaikoSoundEditor.Utils
{
internal static class Number
{
public static int ParseInt(string value)
{
try
{
return int.Parse(value);
}
catch(FormatException ex)
{
throw new FormatException($"{ex.Message} : {value} to int", ex);
}
}
public static float ParseFloat(string value)
{
try
{
return float.Parse(value);
}
catch (FormatException ex)
{
throw new FormatException($"{ex.Message} : {value} to float", ex);
}
}
}
}