Merge branch 'develop' into optimize_video

This commit is contained in:
Flamefire committed 2014-03-12 09:46:34 +01:00
commit c091d5635e
62 files changed
+782 -685

No files matched your search

+1 -1
View File
@@ -73,7 +73,7 @@ namespace ServerLib
return; return;
_DiscoverRunning = true; _DiscoverRunning = true;
_DiscoverThread = new Thread(() => _Discover(Timeout)); _DiscoverThread = new Thread(() => _Discover(Timeout)) {Name = "Client discover"};
_OnDiscovered = OnDiscovered; _OnDiscovered = OnDiscovered;
_DiscoverThread.Start(); _DiscoverThread.Start();
} }
+5 -5
View File
@@ -142,14 +142,14 @@ namespace ServerLib
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
smb.HttpGetEnabled = true; smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);*/ host.Description.Behaviors.Add(smb);*/
_RegisterUrlAndCert(_BaseAddress.Port); _RegisterUrlAndCert(_BaseAddress.Port, false);
_Host.Open(); _Host.Open();
} }
catch (CommunicationException e) catch (CommunicationException e)
{ {
if (e is AddressAccessDeniedException || e is AddressAlreadyInUseException) if (e is AddressAccessDeniedException || e is AddressAlreadyInUseException)
{ {
_RegisterUrlAndCert(_BaseAddress.Port); _RegisterUrlAndCert(_BaseAddress.Port, true);
try try
{ {
_Host.Abort(); _Host.Abort();
@@ -178,18 +178,18 @@ namespace ServerLib
} }
} }
private void _RegisterUrlAndCert(int port) private void _RegisterUrlAndCert(int port, bool reserve)
{ {
#if WIN #if WIN
ProcessStartInfo info = new ProcessStartInfo ProcessStartInfo info = new ProcessStartInfo
{ {
FileName = "VocaluxeServerConfig.exe", FileName = "VocaluxeServerConfig.exe",
Arguments = port + " " + (_Encrypted ? "true" : "false"), WorkingDirectory = Environment.CurrentDirectory,
Arguments = port + " " + (_Encrypted ? "true" : "false") + (reserve ? " reserve" : ""),
UseShellExecute = true, UseShellExecute = true,
CreateNoWindow = true, CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden, WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas"
}; };
Process p = Process.Start(info); Process p = Process.Start(info);
p.WaitForExit(); p.WaitForExit();
@@ -28,32 +28,27 @@ namespace ServerLib
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/sendKeyEvent?key={key}")] UriTemplate = "/sendKeyEvent?key={key}")]
void SendKeyEvent(string key); void SendKeyEvent(string key);
#region profile #region profile
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getOwnProfileId")] UriTemplate = "/getOwnProfileId")]
int GetOwnProfileId(); int GetOwnProfileId();
[OperationContract, WebInvoke(Method = "POST", [OperationContract, WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/sendProfile")] UriTemplate = "/sendProfile")]
void SendProfile(SProfileData profile); void SendProfile(SProfileData profile);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getProfile?profileId={profileId}")] UriTemplate = "/getProfile?profileId={profileId}")]
SProfileData GetProfile(int profileId); SProfileData GetProfile(int profileId);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getProfileList")] UriTemplate = "/getProfileList")]
SProfileData[] GetProfileList(); SProfileData[] GetProfileList();
#endregion #endregion
@@ -62,7 +57,6 @@ namespace ServerLib
RequestFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/sendPhoto")] UriTemplate = "/sendPhoto")]
void SendPhoto(SPhotoData photo); void SendPhoto(SPhotoData photo);
#endregion #endregion
@@ -70,55 +64,46 @@ namespace ServerLib
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/login?username={username}&password={password}")] UriTemplate = "/login?username={username}&password={password}")]
Guid Login(string username, string password); Guid Login(string username, string password);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "")] UriTemplate = "")]
Stream Index(); Stream Index();
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/js/{filename}")] UriTemplate = "/js/{filename}")]
Stream GetJsFile(String filename); Stream GetJsFile(String filename);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/css/{filename}")] UriTemplate = "/css/{filename}")]
Stream GetCssFile(String filename); Stream GetCssFile(String filename);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/css/images/{filename}")] UriTemplate = "/css/images/{filename}")]
Stream GetCssImageFile(String filename); Stream GetCssImageFile(String filename);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/img/{filename}")] UriTemplate = "/img/{filename}")]
Stream GetImgFile(String filename); Stream GetImgFile(String filename);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/locales/{filename}")] UriTemplate = "/locales/{filename}")]
Stream GetLocaleFile(String filename); Stream GetLocaleFile(String filename);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/delayedImage?id={id}")] UriTemplate = "/delayedImage?id={id}")]
CBase64Image GetDelayedImage(String id); CBase64Image GetDelayedImage(String id);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/isServerOnline")] UriTemplate = "/isServerOnline")]
bool IsServerOnline(); bool IsServerOnline();
#endregion #endregion
@@ -126,19 +111,16 @@ namespace ServerLib
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getSong?songId={songId}")] UriTemplate = "/getSong?songId={songId}")]
SSongInfo GetSong(int songId); SSongInfo GetSong(int songId);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getCurrentSongId")] UriTemplate = "/getCurrentSongId")]
int GetCurrentSongId(); int GetCurrentSongId();
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getAllSongs")] UriTemplate = "/getAllSongs")]
SSongInfo[] GetAllSongs(); SSongInfo[] GetAllSongs();
#endregion #endregion
@@ -146,43 +128,36 @@ namespace ServerLib
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getPlaylists")] UriTemplate = "/getPlaylists")]
SPlaylistInfo[] GetPlaylists(); SPlaylistInfo[] GetPlaylists();
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getPlaylist?id={playlistId}")] UriTemplate = "/getPlaylist?id={playlistId}")]
SPlaylistInfo GetPlaylist(int playlistId); SPlaylistInfo GetPlaylist(int playlistId);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/addSongToPlaylist?songId={songId}&playlistId={playlistId}&duplicates={allowDuplicates}")] UriTemplate = "/addSongToPlaylist?songId={songId}&playlistId={playlistId}&duplicates={allowDuplicates}")]
void AddSongToPlaylist(int songId, int playlistId, bool allowDuplicates); void AddSongToPlaylist(int songId, int playlistId, bool allowDuplicates);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/removeSongFromPlaylist?position={position}&playlistId={playlistId}&songId={songId}")] UriTemplate = "/removeSongFromPlaylist?position={position}&playlistId={playlistId}&songId={songId}")]
void RemoveSongFromPlaylist(int position, int playlistId, int songId); void RemoveSongFromPlaylist(int position, int playlistId, int songId);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/moveSongInPlaylist?newPosition={newPosition}&playlistId={playlistId}&songId={songId}")] UriTemplate = "/moveSongInPlaylist?newPosition={newPosition}&playlistId={playlistId}&songId={songId}")]
void MoveSongInPlaylist(int newPosition, int playlistId, int songId); void MoveSongInPlaylist(int newPosition, int playlistId, int songId);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/playlistContainsSong?songId={songId}&playlistId={playlistId}")] UriTemplate = "/playlistContainsSong?songId={songId}&playlistId={playlistId}")]
bool PlaylistContainsSong(int songId, int playlistId); bool PlaylistContainsSong(int songId, int playlistId);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getPlaylistSongs?playlistId={playlistId}")] UriTemplate = "/getPlaylistSongs?playlistId={playlistId}")]
SPlaylistSongInfo[] GetPlaylistSongs(int playlistId); SPlaylistSongInfo[] GetPlaylistSongs(int playlistId);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
@@ -200,19 +175,16 @@ namespace ServerLib
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getUserRole?profileId={profileId}")] UriTemplate = "/getUserRole?profileId={profileId}")]
int GetUserRole(int profileId); int GetUserRole(int profileId);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/setUserRole?profileId={profileId}&userRole={userRole}")] UriTemplate = "/setUserRole?profileId={profileId}&userRole={userRole}")]
void SetUserRole(int profileId, int userRole); void SetUserRole(int profileId, int userRole);
[OperationContract, WebInvoke(Method = "GET", [OperationContract, WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/hasUserRight?right={right}")] UriTemplate = "/hasUserRight?right={right}")]
bool HasUserRight(int right); bool HasUserRight(int right);
#endregion #endregion
} }
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<ScreenOptionsRecord> <ScreenOptionsRecord>
<ScreenVersion>3</ScreenVersion> <ScreenVersion>4</ScreenVersion>
<Background1> <Background1>
<!--<Type>: Background type: None, Color, Texture, Video--> <!--<Type>: Background type: None, Color, Texture, Video-->
<Type>Video</Type> <Type>Video</Type>
@@ -216,6 +216,35 @@
<!-- <Height>: Reflection Height--> <!-- <Height>: Reflection Height-->
</Text2> </Text2>
<Text3> <Text3>
<!--<X>, <Y>: Text position-->
<X>75</X>
<Y>347</Y>
<!--<Z>: Text position-->
<Z>0,00</Z>
<!--<H>: Text height-->
<H>27</H>
<!--<MaxW>: Maximum text width (if exists)-->
<!--<Color>: Text color from ColorScheme (high priority)-->
<!--or <R>, <G>, <B>, <A> (lower priority)-->
<Color>StaticColor</Color>
<!--<SColor>: Selected Text color from ColorScheme (high priority)-->
<!--or <SR>, <SG>, <SB>, <SA> (lower priority)-->
<SColor>TextSColor</SColor>
<!--<Align>: Text align horizontal: Left, Center, Right-->
<Align>Left</Align>
<!--<ResizeAlign>: Text align vertical (on downsizing): Top, Center, Bottom-->
<HAlign>Center</HAlign>
<!--<Style>: Text style: Normal, Italic, Bold, BoldItalic-->
<Style>Bold</Style>
<!--<Font>: Text font name-->
<Font>Outline</Font>
<!--<Text>: Nothing or translation tag-->
<Text>TR_SCREENORECORD_MIC_DELAY</Text>
<!--<Reflection> If exists:-->
<!-- <Space>: Reflection Space-->
<!-- <Height>: Reflection Height-->
</Text3>
<TextChannel1>
<!--<X>, <Y>: Text position--> <!--<X>, <Y>: Text position-->
<X>75</X> <X>75</X>
<Y>227</Y> <Y>227</Y>
@@ -243,8 +272,8 @@
<!--<Reflection> If exists:--> <!--<Reflection> If exists:-->
<!-- <Space>: Reflection Space--> <!-- <Space>: Reflection Space-->
<!-- <Height>: Reflection Height--> <!-- <Height>: Reflection Height-->
</Text3> </TextChannel1>
<Text4> <TextChannel2>
<!--<X>, <Y>: Text position--> <!--<X>, <Y>: Text position-->
<X>75</X> <X>75</X>
<Y>287</Y> <Y>287</Y>
@@ -272,36 +301,7 @@
<!--<Reflection> If exists:--> <!--<Reflection> If exists:-->
<!-- <Space>: Reflection Space--> <!-- <Space>: Reflection Space-->
<!-- <Height>: Reflection Height--> <!-- <Height>: Reflection Height-->
</Text4> </TextChannel2>
<Text5>
<!--<X>, <Y>: Text position-->
<X>75</X>
<Y>347</Y>
<!--<Z>: Text position-->
<Z>0,00</Z>
<!--<H>: Text height-->
<H>27</H>
<!--<MaxW>: Maximum text width (if exists)-->
<!--<Color>: Text color from ColorScheme (high priority)-->
<!--or <R>, <G>, <B>, <A> (lower priority)-->
<Color>StaticColor</Color>
<!--<SColor>: Selected Text color from ColorScheme (high priority)-->
<!--or <SR>, <SG>, <SB>, <SA> (lower priority)-->
<SColor>TextSColor</SColor>
<!--<Align>: Text align horizontal: Left, Center, Right-->
<Align>Left</Align>
<!--<ResizeAlign>: Text align vertical (on downsizing): Top, Center, Bottom-->
<HAlign>Center</HAlign>
<!--<Style>: Text style: Normal, Italic, Bold, BoldItalic-->
<Style>Bold</Style>
<!--<Font>: Text font name-->
<Font>Outline</Font>
<!--<Text>: Nothing or translation tag-->
<Text>TR_SCREENORECORD_MIC_DELAY</Text>
<!--<Reflection> If exists:-->
<!-- <Space>: Reflection Space-->
<!-- <Height>: Reflection Height-->
</Text5>
<TextWarning> <TextWarning>
<!--<X>, <Y>: Text position--> <!--<X>, <Y>: Text position-->
<X>640</X> <X>640</X>
@@ -7,3 +7,6 @@ Add:
<EqualizerChannel1> and <EqualizerChannel2>. <EqualizerChannel1> and <EqualizerChannel2>.
This is a new theme-element. Check ScreenOptionsRecord.xml for style-possibilities. This is a new theme-element. Check ScreenOptionsRecord.xml for style-possibilities.
++++++++++ ++++++++++
Version 4:
Rename Text 3/4 to TextChannel1/2
Rename Text5 to Text3
+4 -4
View File
@@ -60,10 +60,10 @@ namespace Vocaluxe.Base
public static int ScreenW = 1024; public static int ScreenW = 1024;
public static int ScreenH = 576; public static int ScreenH = 576;
public static int BorderLeft = 0; public static int BorderLeft;
public static int BorderRight = 0; public static int BorderRight;
public static int BorderTop = 0; public static int BorderTop;
public static int BorderBottom = 0; public static int BorderBottom;
public static EAntiAliasingModes AAMode = EAntiAliasingModes.X0; public static EAntiAliasingModes AAMode = EAntiAliasingModes.X0;
+106 -106
View File
@@ -63,8 +63,16 @@ namespace Vocaluxe.Base
_CreditsRessourcesFilePath = Path.Combine(Environment.CurrentDirectory, CSettings.FileCreditsRessourcesDB); _CreditsRessourcesFilePath = Path.Combine(Environment.CurrentDirectory, CSettings.FileCreditsRessourcesDB);
_InitHighscoreDB(); _InitHighscoreDB();
_InitCoverDB(); if (!_InitCoverDB())
_InitCreditsRessourcesDB(); {
CLog.LogError("Error initializing Cover-DB", true, true);
return;
}
if (!_InitCreditsRessourcesDB())
{
CLog.LogError("Error initializing Cover-DB", true, true);
return;
}
GC.Collect(); GC.Collect();
} }
@@ -93,26 +101,6 @@ namespace Vocaluxe.Base
return _GetDataBaseSongInfos(songID, out sArtist, out sTitle, out numPlayed, out dateAdded, _HighscoreFilePath); return _GetDataBaseSongInfos(songID, out sArtist, out sTitle, out numPlayed, out dateAdded, _HighscoreFilePath);
} }
public static void IncreaseSongCounter(SPlayer player)
{
using (var connection = new SQLiteConnection())
{
connection.ConnectionString = "Data Source=" + _HighscoreFilePath;
try
{
connection.Open();
}
catch (Exception) {}
using (var command = new SQLiteCommand(connection))
{
int dataBaseSongID = _GetDataBaseSongID(player, command);
_IncreaseSongCounter(dataBaseSongID, command);
}
}
}
public static void IncreaseSongCounter(int dataBaseSongID) public static void IncreaseSongCounter(int dataBaseSongID)
{ {
using (var connection = new SQLiteConnection()) using (var connection = new SQLiteConnection())
@@ -170,11 +158,27 @@ namespace Vocaluxe.Base
return -1; return -1;
} }
int medley = 0;
int duet = 0;
int shortSong = 0;
switch (player.GameMode)
{
case EGameMode.TR_GAMEMODE_MEDLEY:
medley = 1;
break;
case EGameMode.TR_GAMEMODE_DUET:
duet = 1;
break;
case EGameMode.TR_GAMEMODE_SHORTSONG:
shortSong = 1;
break;
}
using (var command = new SQLiteCommand(connection)) using (var command = new SQLiteCommand(connection))
{ {
int dataBaseSongID = CSongs.GetSong(player.SongID).DataBaseSongID; int dataBaseSongID = CSongs.GetSong(player.SongID).DataBaseSongID;
return _AddScore(CProfiles.GetPlayerName(player.ProfileID), (int)Math.Round(player.Points), player.VoiceNr, player.DateTicks, player.Medley ? 1 : 0, return _AddScore(CProfiles.GetPlayerName(player.ProfileID), (int)Math.Round(player.Points), player.VoiceNr, player.DateTicks, medley,
player.Duet ? 1 : 0, player.ShortSong ? 1 : 0, (int)CProfiles.GetDifficulty(player.ProfileID), dataBaseSongID, command); duet, shortSong, (int)CProfiles.GetDifficulty(player.ProfileID), dataBaseSongID, command);
} }
} }
} }
@@ -243,70 +247,74 @@ namespace Vocaluxe.Base
return lastInsertID; return lastInsertID;
} }
public static void LoadScore(out List<SScores> scores, SPlayer player) public static List<SDBScoreEntry> LoadScore(int songID, EGameMode gameMode)
{ {
var scores = new List<SDBScoreEntry>();
using (var connection = new SQLiteConnection()) using (var connection = new SQLiteConnection())
{ {
connection.ConnectionString = "Data Source=" + _HighscoreFilePath; connection.ConnectionString = "Data Source=" + _HighscoreFilePath;
scores = new List<SScores>();
try try
{ {
connection.Open(); connection.Open();
} }
catch (Exception) catch (Exception)
{ {
return; return scores;
} }
using (var command = new SQLiteCommand(connection)) using (var command = new SQLiteCommand(connection))
{ {
int medley = 0; int medley = 0;
if (player.Medley)
medley = 1;
int duet = 0; int duet = 0;
if (player.Duet)
duet = 1;
int shortSong = 0; int shortSong = 0;
if (player.ShortSong) switch (gameMode)
shortSong = 1;
int dataBaseSongID = _GetDataBaseSongID(player, command);
if (dataBaseSongID >= 0)
{ {
command.CommandText = "SELECT PlayerName, Score, Date, Difficulty, LineNr, id FROM Scores " + case EGameMode.TR_GAMEMODE_MEDLEY:
"WHERE [SongID] = @SongID AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + medley = 1;
"ORDER BY [Score] DESC"; break;
command.Parameters.Add("@SongID", DbType.Int32, 0).Value = dataBaseSongID; case EGameMode.TR_GAMEMODE_DUET:
command.Parameters.Add("@Medley", DbType.Int32, 0).Value = medley; duet = 1;
command.Parameters.Add("@Duet", DbType.Int32, 0).Value = duet; break;
command.Parameters.Add("@ShortSong", DbType.Int32, 0).Value = shortSong; case EGameMode.TR_GAMEMODE_SHORTSONG:
shortSong = 1;
break;
}
SQLiteDataReader reader = command.ExecuteReader(); int dataBaseSongID = _GetDataBaseSongID(songID, command);
if (reader != null && reader.HasRows) if (dataBaseSongID < 0)
return scores;
command.CommandText = "SELECT PlayerName, Score, Date, Difficulty, LineNr, id FROM Scores " +
"WHERE [SongID] = @SongID AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " +
"ORDER BY [Score] DESC";
command.Parameters.Add("@SongID", DbType.Int32, 0).Value = dataBaseSongID;
command.Parameters.Add("@Medley", DbType.Int32, 0).Value = medley;
command.Parameters.Add("@Duet", DbType.Int32, 0).Value = duet;
command.Parameters.Add("@ShortSong", DbType.Int32, 0).Value = shortSong;
SQLiteDataReader reader = command.ExecuteReader();
if (reader != null && reader.HasRows)
{
while (reader.Read())
{ {
while (reader.Read()) var score = new SDBScoreEntry
{ {
var score = new SScores Name = reader.GetString(0),
{ Score = reader.GetInt32(1),
Name = reader.GetString(0), Date = new DateTime(reader.GetInt64(2)).ToString("dd/MM/yyyy"),
Score = reader.GetInt32(1), Difficulty = (EGameDifficulty)reader.GetInt32(3),
Date = new DateTime(reader.GetInt64(2)).ToString("dd/MM/yyyy"), VoiceNr = reader.GetInt32(4),
Difficulty = (EGameDifficulty)reader.GetInt32(3), ID = reader.GetInt32(5)
LineNr = reader.GetInt32(4), };
ID = reader.GetInt32(5)
};
scores.Add(score); scores.Add(score);
}
reader.Dispose();
} }
reader.Dispose();
} }
} }
} }
return scores;
} }
private static void _IncreaseSongCounter(int dataBaseSongID, SQLiteCommand command) private static void _IncreaseSongCounter(int dataBaseSongID, SQLiteCommand command)
@@ -316,9 +324,9 @@ namespace Vocaluxe.Base
command.ExecuteNonQuery(); command.ExecuteNonQuery();
} }
private static int _GetDataBaseSongID(SPlayer player, SQLiteCommand command) private static int _GetDataBaseSongID(int songID, SQLiteCommand command)
{ {
CSong song = CSongs.GetSong(player.SongID); CSong song = CSongs.GetSong(songID);
if (song == null) if (song == null)
return -1; return -1;
@@ -430,21 +438,35 @@ namespace Vocaluxe.Base
{ {
if (File.Exists(_HighscoreFilePath)) if (File.Exists(_HighscoreFilePath))
{ {
_CreateOrConvert(oldDBFilePath); if (!_CreateOrConvert(oldDBFilePath))
_CreateOrConvert(_HighscoreFilePath); {
_ImportData(oldDBFilePath); CLog.LogError("Cannot init Highscore DB: Error opening database: " + oldDBFilePath, true, true);
return;
File.Delete(oldDBFilePath); }
if (!_CreateOrConvert(_HighscoreFilePath))
{
CLog.LogError("Cannot init Highscore DB: Error opening database: " + _HighscoreFilePath, true, true);
return;
}
if (!_ImportData(oldDBFilePath))
{
CLog.LogError("Cannot init Highscore DB: Error importing data", true, true);
return;
}
} }
else else
{ {
File.Copy(oldDBFilePath, _HighscoreFilePath); File.Copy(oldDBFilePath, _HighscoreFilePath);
_CreateOrConvert(_HighscoreFilePath); if (!_CreateOrConvert(_HighscoreFilePath))
File.Delete(oldDBFilePath); {
CLog.LogError("Cannot init Highscore DB: Error opening database: " + _HighscoreFilePath, true, true);
return;
}
} }
File.Delete(oldDBFilePath);
} }
else else if (!_CreateOrConvert(_HighscoreFilePath))
_CreateOrConvert(_HighscoreFilePath); CLog.LogError("Cannot init Highscore DB: Error opening database: " + _HighscoreFilePath, true, true);
} }
private static void _CreateHighscoreDB(string filePath) private static void _CreateHighscoreDB(string filePath)
@@ -525,6 +547,7 @@ namespace Vocaluxe.Base
/// <returns></returns> /// <returns></returns>
private static bool _CreateOrConvert(string filePath) private static bool _CreateOrConvert(string filePath)
{ {
bool result = true;
using (var connection = new SQLiteConnection()) using (var connection = new SQLiteConnection())
{ {
connection.ConnectionString = "Data Source=" + filePath; connection.ConnectionString = "Data Source=" + filePath;
@@ -565,46 +588,24 @@ namespace Vocaluxe.Base
} }
catch (Exception) {} catch (Exception) {}
if (reader == null) if (reader == null || reader.FieldCount == 0)
{ {
// create new database/tables // create new database/tables
if (version == 1) if (version == 1)
{ {
//Check for USDX 1.1 DB //Check for USDX 1.1 DB
_CreateHighscoreDBV1(filePath); _CreateHighscoreDBV1(filePath);
_ConvertFrom110(filePath); result &= !_ConvertFrom110(filePath);
_UpdateDatabase(1, connection); result &= _UpdateDatabase(1, connection);
_UpdateDatabase(2, connection); result &= _UpdateDatabase(2, connection);
} }
else if (version == 0 && scoresTableExists) else if (version == 0 && scoresTableExists)
{ {
//Check for USDX 1.01 or CMD Mod DB //Check for USDX 1.01 or CMD Mod DB
_CreateHighscoreDBV1(filePath); _CreateHighscoreDBV1(filePath);
_ConvertFrom101(filePath); result &= _ConvertFrom101(filePath);
_UpdateDatabase(1, connection); result &= _UpdateDatabase(1, connection);
_UpdateDatabase(2, connection); result &= _UpdateDatabase(2, connection);
}
else
_CreateHighscoreDB(filePath);
}
else if (reader.FieldCount == 0)
{
// create new database/tables
if (version == 1)
{
//Check for USDX 1.1 DB
_CreateHighscoreDBV1(filePath);
_ConvertFrom110(filePath);
_UpdateDatabase(1, connection);
_UpdateDatabase(2, connection);
}
else if (version == 0 && scoresTableExists)
{
//Check for USDX 1.01 or CMD Mod DB
_CreateHighscoreDBV1(filePath);
_ConvertFrom101(filePath);
_UpdateDatabase(1, connection);
_UpdateDatabase(2, connection);
} }
else else
_CreateHighscoreDB(filePath); _CreateHighscoreDB(filePath);
@@ -616,7 +617,7 @@ namespace Vocaluxe.Base
if (currentVersion < CSettings.DatabaseHighscoreVersion) if (currentVersion < CSettings.DatabaseHighscoreVersion)
{ {
// update database // update database
_UpdateDatabase(currentVersion, connection); result &= _UpdateDatabase(currentVersion, connection);
} }
} }
@@ -625,7 +626,7 @@ namespace Vocaluxe.Base
} }
} }
return true; return result;
} }
/// <summary> /// <summary>
@@ -972,8 +973,7 @@ namespace Vocaluxe.Base
lastDateAdded = dateAdded; lastDateAdded = dateAdded;
} }
} }
if (reader != null) reader.Dispose();
reader.Dispose();
foreach (int id in ids) foreach (int id in ids)
_IncreaseSongCounter(id, command); _IncreaseSongCounter(id, command);
+15 -25
View File
@@ -131,7 +131,7 @@ namespace Vocaluxe.Base
public static void NextRound() public static void NextRound()
{ {
_SongQueue.NextRound(Players); _SongQueue.StartNextRound(Players);
} }
public static bool IsFinished() public static bool IsFinished()
@@ -149,14 +149,14 @@ namespace Vocaluxe.Base
return _SongQueue.GetSong(); return _SongQueue.GetSong();
} }
public static CSong GetSong(int num) public static CSong GetSong(int round)
{ {
return _SongQueue.GetSong(num); return _SongQueue.GetSong(round);
} }
public static EGameMode GetGameMode(int num) public static EGameMode GetGameMode(int round)
{ {
return _SongQueue.GetGameMode(num); return _SongQueue.GetGameMode(round);
} }
public static int GetNumSongs() public static int GetNumSongs()
@@ -197,9 +197,7 @@ namespace Vocaluxe.Base
Players[i].CurrentLine = -1; Players[i].CurrentLine = -1;
Players[i].CurrentNote = -1; Players[i].CurrentNote = -1;
Players[i].SongID = -1; Players[i].SongID = -1;
Players[i].Medley = false; Players[i].GameMode = EGameMode.TR_GAMEMODE_NORMAL;
Players[i].Duet = false;
Players[i].ShortSong = false;
Players[i].DateTicks = DateTime.Now.Ticks; Players[i].DateTicks = DateTime.Now.Ticks;
Players[i].SongFinished = false; Players[i].SongFinished = false;
} }
@@ -210,7 +208,7 @@ namespace Vocaluxe.Base
public static void UpdatePoints(float time) public static void UpdatePoints(float time)
{ {
bool DEBUG_HIT = false; const bool DEBUG_HIT = false;
CSong song = _SongQueue.GetSong(); CSong song = _SongQueue.GetSong();
@@ -276,8 +274,6 @@ namespace Vocaluxe.Base
{ {
int tone = notes[note].Tone; int tone = notes[note].Tone;
int tonePlayer = CSound.RecordGetTone(p); int tonePlayer = CSound.RecordGetTone(p);
if (DEBUG_HIT)
tonePlayer = tone;
while (tonePlayer - tone > 6) while (tonePlayer - tone > 6)
tonePlayer -= 12; tonePlayer -= 12;
@@ -364,7 +360,7 @@ namespace Vocaluxe.Base
public static void ResetToLastLine(int soundStream, int vidStream) public static void ResetToLastLine(int soundStream, int vidStream)
{ {
float[] time = GetLastSungLineStart(); float[] time = _GetLastSungLineStart();
ResetToTime(time[0], time[1], soundStream, vidStream); ResetToTime(time[0], time[1], soundStream, vidStream);
} }
@@ -413,23 +409,20 @@ namespace Vocaluxe.Base
} }
Players[p].SungLines.RemoveRange(deleteLine, Players[p].SungLines.Count - deleteLine); Players[p].SungLines.RemoveRange(deleteLine, Players[p].SungLines.Count - deleteLine);
} }
//CSong song = GetSong();
//for (int i = 0; i < GetSong().Notes.Voices[0].Lines.Length; i++)
// CLog.LogError((i + 1) + ". " + song.Notes.Voices[0].Lines[i].NoteCount + " - " + Players[0].SungLines[i].NoteCount);
CSound.SetPosition(soundStream, time); CSound.SetPosition(soundStream, time);
CVideo.Skip(vidStream, time, GetSong().VideoGap); CVideo.Skip(vidStream, time, GetSong().VideoGap);
} }
private static float[] GetLastSungLineStart() private static float[] _GetLastSungLineStart()
{ {
return GetNoteTimeBeforeBeat(CurrentBeat); return _GetNoteTimeBeforeBeat(CurrentBeat);
} }
private static float[] GetNoteTimeBeforeBeat(int beat) private static float[] _GetNoteTimeBeforeBeat(int beat)
{ {
CSong song = GetSong(); CSong song = GetSong();
int StartBeat = (int)Math.Floor(beat - GetBeatFromTime(CSettings.PauseResetTime, song.BPM, 0f)); int startBeat = (int)Math.Floor(beat - GetBeatFromTime(CSettings.PauseResetTime, song.BPM, 0f));
int lastStart = 0; int lastStart = 0;
int nextStart = 0; int nextStart = 0;
foreach (CVoice voice in song.Notes.Voices) foreach (CVoice voice in song.Notes.Voices)
@@ -441,16 +434,13 @@ namespace Vocaluxe.Base
{ {
foreach (CSongNote note in line.Notes) foreach (CSongNote note in line.Notes)
{ {
if (note.StartBeat > StartBeat) if (note.StartBeat > startBeat)
{ {
nextStartNote = note.StartBeat; nextStartNote = note.StartBeat;
break; break;
} }
else voiceStart = note.StartBeat;
{ lastEnd = note.EndBeat;
voiceStart = note.StartBeat;
lastEnd = note.EndBeat;
}
} }
if (nextStartNote > 0) if (nextStartNote > 0)
break; break;
-3
View File
@@ -404,9 +404,6 @@ namespace Vocaluxe.Base
CConfig.BorderTop = 0; CConfig.BorderTop = 0;
CConfig.BorderBottom = 0; CConfig.BorderBottom = 0;
break; break;
default:
break;
} }
CConfig.SaveConfig(); CConfig.SaveConfig();
break; break;
+58 -25
View File
@@ -28,6 +28,7 @@ namespace Vocaluxe.Base
private readonly string _LogFileName; private readonly string _LogFileName;
private readonly string _LogName; private readonly string _LogName;
private StreamWriter _LogFile; private StreamWriter _LogFile;
private readonly Object _FileMutex = new Object();
public CLogFile(string fileName, string logName) public CLogFile(string fileName, string logName)
{ {
@@ -37,26 +38,34 @@ namespace Vocaluxe.Base
private void _Open() private void _Open()
{ {
_LogFile = new StreamWriter(Path.Combine(CSettings.DataPath, _LogFileName), false, Encoding.UTF8); lock (_FileMutex)
{
if (_LogFile != null)
return;
_LogFile = new StreamWriter(Path.Combine(CSettings.DataPath, _LogFileName), false, Encoding.UTF8);
_LogFile.WriteLine(_LogName + " " + CSettings.GetFullVersionText() + " " + DateTime.Now); _LogFile.WriteLine(_LogName + " " + CSettings.GetFullVersionText() + " " + DateTime.Now);
_LogFile.WriteLine("----------------------------------------"); _LogFile.WriteLine("----------------------------------------");
_LogFile.WriteLine(); _LogFile.WriteLine();
}
} }
public void Close() public void Close()
{ {
if (_LogFile == null) lock (_FileMutex)
return;
try
{ {
_LogFile.Flush(); if (_LogFile == null)
_LogFile.Close(); return;
try
{
_LogFile.Flush();
_LogFile.Close();
}
catch (Exception) {}
} }
catch (Exception) {}
} }
public void Add(string text) public virtual void Add(string text)
{ {
if (_LogFile == null) if (_LogFile == null)
_Open(); _Open();
@@ -69,15 +78,28 @@ namespace Vocaluxe.Base
public void Dispose() public void Dispose()
{ {
if (_LogFile != null) Close();
{
_LogFile.Dispose();
_LogFile = null;
}
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
} }
class CErrorLogFile : CLogFile
{
private int _NumErrors;
private readonly Object _WriteMutex = new Object();
public CErrorLogFile(string fileName, string logName) : base(fileName, logName) {}
public override void Add(string errorText)
{
lock (_WriteMutex)
{
_NumErrors++;
base.Add(_NumErrors + ") " + errorText);
}
}
}
static class CLog static class CLog
{ {
private const int _MaxBenchmarks = 10; private const int _MaxBenchmarks = 10;
@@ -85,18 +107,20 @@ namespace Vocaluxe.Base
private static CLogFile _ErrorLog; private static CLogFile _ErrorLog;
private static CLogFile _PerformanceLog; private static CLogFile _PerformanceLog;
private static CLogFile _BenchmarkLog; private static CLogFile _BenchmarkLog;
private static CLogFile _DebugLog;
private static CLogFile _SongInfoLog;
private static int _NumErrors;
private static Stopwatch[] _BenchmarkTimer; private static Stopwatch[] _BenchmarkTimer;
private static readonly double _NanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency; private static readonly double _NanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency;
public static void Init() public static void Init()
{ {
_ErrorLog = new CLogFile(CSettings.FileErrorLog, "ErrorLog"); _ErrorLog = new CErrorLogFile(CSettings.FileErrorLog, "Error-Log");
_PerformanceLog = new CLogFile(CSettings.FilePerformanceLog, "PerformanceLog"); _PerformanceLog = new CLogFile(CSettings.FilePerformanceLog, "Performance-Log");
_BenchmarkLog = new CLogFile(CSettings.FileBenchmarkLog, "BenchmarkLog"); _BenchmarkLog = new CLogFile(CSettings.FileBenchmarkLog, "Benchmark-Log");
_DebugLog = new CLogFile(CSettings.FileDebugLog, "Debug-Log");
_SongInfoLog = new CLogFile(CSettings.FileSongInfoLog, "Song-Information-Log");
_NumErrors = 0;
_BenchmarkTimer = new Stopwatch[_MaxBenchmarks]; _BenchmarkTimer = new Stopwatch[_MaxBenchmarks];
for (int i = 0; i < _BenchmarkTimer.Length; i++) for (int i = 0; i < _BenchmarkTimer.Length; i++)
_BenchmarkTimer[i] = new Stopwatch(); _BenchmarkTimer[i] = new Stopwatch();
@@ -107,29 +131,38 @@ namespace Vocaluxe.Base
_ErrorLog.Close(); _ErrorLog.Close();
_PerformanceLog.Close(); _PerformanceLog.Close();
_BenchmarkLog.Close(); _BenchmarkLog.Close();
_DebugLog.Close();
_SongInfoLog.Close();
} }
#region LogError #region LogError
public static void LogError(string errorText, bool show = false, bool exit = false, Exception e = null) public static void LogError(string errorText, bool show = false, bool exit = false, Exception e = null)
{ {
_NumErrors++;
if (show) if (show)
MessageBox.Show(errorText, CSettings.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(errorText, CSettings.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error);
if (e != null) if (e != null)
errorText += ": " + e; errorText += ": " + e;
_ErrorLog.Add(_NumErrors + ") " + errorText); _ErrorLog.Add(errorText);
if (exit) if (exit)
Environment.Exit(Environment.ExitCode); Environment.Exit(Environment.ExitCode);
} }
#endregion LogError #endregion LogError
#region LogPerformance public static void LogDebug(string text)
{
_DebugLog.Add(String.Format("{0:HH:mm:ss.ffff}", DateTime.Now) + ":" + text);
}
public static void LogSongInfo(string text)
{
_SongInfoLog.Add(text);
}
public static void LogPerformance(string text) public static void LogPerformance(string text)
{ {
_PerformanceLog.Add(text); _PerformanceLog.Add(text);
_PerformanceLog.Add("-------------------------------"); _PerformanceLog.Add("-------------------------------");
} }
#endregion LogPerformance
#region LogBenchmark #region LogBenchmark
public static void StartBenchmark(int benchmarkNr, string text) public static void StartBenchmark(int benchmarkNr, string text)
+10
View File
@@ -443,6 +443,16 @@ namespace Vocaluxe.Base
{ {
CLog.LogError(errorText); CLog.LogError(errorText);
} }
public void LogDebug(string text)
{
CLog.LogDebug(text);
}
public void LogSongInfo(string text)
{
CLog.LogSongInfo(text);
}
} }
class CBfonts : IFonts class CBfonts : IFonts
+3 -1
View File
@@ -85,6 +85,8 @@ namespace Vocaluxe.Base
public const string FilePerformanceLog = "Performance.log"; public const string FilePerformanceLog = "Performance.log";
public const string FileErrorLog = "Error.log"; public const string FileErrorLog = "Error.log";
public const string FileBenchmarkLog = "Benchmark.log"; public const string FileBenchmarkLog = "Benchmark.log";
public const string FileDebugLog = "Debug.log";
public const string FileSongInfoLog = "SongInformation.log";
public const string SoundT440 = "440Hz.mp3"; public const string SoundT440 = "440Hz.mp3";
@@ -102,7 +104,7 @@ namespace Vocaluxe.Base
#endif #endif
Path.Combine(DataPath, FolderProfiles) Path.Combine(DataPath, FolderProfiles)
}; };
public static string FolderPhotos = "Photos"; public const string FolderPhotos = "Photos";
public const string FolderSongs = "Songs"; public const string FolderSongs = "Songs";
public const string FolderSounds = "Sounds"; public const string FolderSounds = "Sounds";
public const string FolderLanguages = "Languages"; public const string FolderLanguages = "Languages";
+1 -3
View File
@@ -221,9 +221,7 @@ namespace Vocaluxe.Base
return; return;
//Calc avarage sing-count //Calc avarage sing-count
int totalCounts = 0; int totalCounts = VisibleSongs.Sum(song => song.NumPlayedSession);
foreach (CSong song in VisibleSongs)
totalCounts += song.NumPlayedSession;
int averageCount = totalCounts / NumSongsVisible; int averageCount = totalCounts / NumSongsVisible;
foreach (CSong song in VisibleSongs) foreach (CSong song in VisibleSongs)
+2 -12
View File
@@ -18,7 +18,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml; using System.Xml;
using Vocaluxe.Base.Fonts; using Vocaluxe.Base.Fonts;
@@ -789,14 +788,8 @@ namespace Vocaluxe.Base
public static SColorF GetPlayerColor(int playerNr) public static SColorF GetPlayerColor(int playerNr)
{ {
var color = new SColorF(1f, 1f, 1f, 1f); bool dummy;
return GetPlayerColor(playerNr, out dummy);
int skinIndex = GetSkinIndex(-1);
if (_Skins[skinIndex].ThemeColors.Player.Length < playerNr)
return color;
return _Skins[skinIndex].ThemeColors.Player[playerNr - 1];
} }
public static SColorF GetPlayerColor(string playerNrString) public static SColorF GetPlayerColor(string playerNrString)
@@ -823,9 +816,6 @@ namespace Vocaluxe.Base
{ {
success = false; success = false;
if (_Skins[skinIndex].PartyModeID != -1)
skinIndex = GetSkinIndex(-1);
if (_Skins[skinIndex].ThemeColors.Player.Length < playerNr || playerNr < 1) if (_Skins[skinIndex].ThemeColors.Player.Length < playerNr || playerNr < 1)
return new SColorF(1f, 1f, 1f, 1f); return new SColorF(1f, 1f, 1f, 1f);
+1 -2
View File
@@ -96,9 +96,8 @@ namespace Vocaluxe.Base.Server
var stream = new MemoryStream(); var stream = new MemoryStream();
stream.Write(cmd, 0, cmd.Length); stream.Write(cmd, 0, cmd.Length);
byte[] data;
string json = JsonConvert.SerializeObject(obj); string json = JsonConvert.SerializeObject(obj);
data = _Encoder.GetBytes(json); byte[] data = _Encoder.GetBytes(json);
stream.Write(data, 0, data.Length); stream.Write(data, 0, data.Length);
return stream.ToArray(); return stream.ToArray();
} }
+7 -8
View File
@@ -26,7 +26,6 @@ using ServerLib;
using Vocaluxe.Lib.Input; using Vocaluxe.Lib.Input;
using Vocaluxe.Lib.Playlist; using Vocaluxe.Lib.Playlist;
using VocaluxeLib; using VocaluxeLib;
using VocaluxeLib.Draw;
using VocaluxeLib.Menu; using VocaluxeLib.Menu;
using VocaluxeLib.Profile; using VocaluxeLib.Profile;
using VocaluxeLib.Songs; using VocaluxeLib.Songs;
@@ -314,7 +313,7 @@ namespace Vocaluxe.Base.Server
#endregion #endregion
#region photo #region photo
private static List<string> photosOfThisRound = new List<string>(); private static readonly List<string> _PhotosOfThisRound = new List<string>();
private static bool _SendPhoto(SPhotoData photoData) private static bool _SendPhoto(SPhotoData photoData)
{ {
@@ -325,17 +324,17 @@ namespace Vocaluxe.Base.Server
string filePath = _SaveImage(photoData.Photo, name, CSettings.FolderPhotos); string filePath = _SaveImage(photoData.Photo, name, CSettings.FolderPhotos);
if (!string.IsNullOrEmpty(filePath)) if (!string.IsNullOrEmpty(filePath))
{ {
photosOfThisRound.Add(filePath); _PhotosOfThisRound.Add(filePath);
return true; return true;
} }
return false; return false;
} }
internal static string[] getPhotosOfThisRound() internal static string[] GetPhotosOfThisRound()
{ {
string[] result = photosOfThisRound.ToArray(); string[] result = _PhotosOfThisRound.ToArray();
photosOfThisRound.Clear(); _PhotosOfThisRound.Clear();
return result; return result;
} }
#endregion #endregion
@@ -583,11 +582,11 @@ namespace Vocaluxe.Base.Server
return false; return false;
} }
byte[] salt = profile.PasswordSalt; //byte[] salt = profile.PasswordSalt;
return hashedPassword.SequenceEqual(profile.PasswordHash); return hashedPassword.SequenceEqual(profile.PasswordHash);
} }
private static byte[] _GetPassowordSalt(int profileId) private static byte[] _GetPasswordSalt(int profileId)
{ {
CProfile profile = CProfiles.GetProfile(profileId); CProfile profile = CProfiles.GetProfile(profileId);
if (profile == null) if (profile == null)
-4
View File
@@ -16,12 +16,8 @@
#endregion #endregion
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Security; using System.Security;
using System.Text;
using Microsoft.Win32; using Microsoft.Win32;
using Vocaluxe.Base; using Vocaluxe.Base;
+6 -6
View File
@@ -161,25 +161,25 @@ namespace Vocaluxe.Lib.Input
public static int ReadTimeout(IntPtr device, ref byte[] data, int length, int milliseconds) public static int ReadTimeout(IntPtr device, ref byte[] data, int length, int milliseconds)
{ {
IntPtr dataPtr = Marshal.AllocHGlobal(length); IntPtr dataPtr = Marshal.AllocHGlobal(length);
int result; int bytesRead;
try try
{ {
result = hid_read_timeout(device, dataPtr, length, milliseconds); bytesRead = hid_read_timeout(device, dataPtr, length, milliseconds);
} }
catch (Exception e) catch (Exception e)
{ {
result = -1; bytesRead = -1;
CLog.LogError("Error CHIDAPI.ReadTimeout(): " + e); CLog.LogError("Error CHIDAPI.ReadTimeout(): " + e);
} }
if (result != -1) if (bytesRead != -1)
Marshal.Copy(dataPtr, data, 0, result); Marshal.Copy(dataPtr, data, 0, bytesRead);
else else
data = null; data = null;
Marshal.FreeHGlobal(dataPtr); Marshal.FreeHGlobal(dataPtr);
return result; return bytesRead;
} }
[DllImport(_HIDApiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_read", CharSet = CharSet.Unicode)] [DllImport(_HIDApiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_read", CharSet = CharSet.Unicode)]
+3 -14
View File
@@ -25,7 +25,7 @@ using VocaluxeLib;
namespace Vocaluxe.Lib.Input.WiiMote namespace Vocaluxe.Lib.Input.WiiMote
{ {
class CWiiMote : IController, IDisposable class CWiiMote : IController
{ {
private CWiiMoteLib _WiiMote; private CWiiMoteLib _WiiMote;
@@ -54,7 +54,7 @@ namespace Vocaluxe.Lib.Input.WiiMote
_RumbleTimer = new CRumbleTimer(); _RumbleTimer = new CRumbleTimer();
_Gesture = new CGesture(); _Gesture = new CGesture();
_HandlerThread = new Thread(_MainLoop) {Priority = ThreadPriority.BelowNormal}; _HandlerThread = new Thread(_MainLoop) {Name = "WiiMote", Priority = ThreadPriority.BelowNormal};
_KeysPool = new List<SKeyEvent>(); _KeysPool = new List<SKeyEvent>();
_CurrentKeysPool = new List<SKeyEvent>(); _CurrentKeysPool = new List<SKeyEvent>();
@@ -151,8 +151,7 @@ namespace Vocaluxe.Lib.Input.WiiMote
if (startRumble) if (startRumble)
_WiiMote.SetRumble(true); _WiiMote.SetRumble(true);
else if (stopRumble)
if (stopRumble)
_WiiMote.SetRumble(false); _WiiMote.SetRumble(false);
} }
} }
@@ -314,15 +313,5 @@ namespace Vocaluxe.Lib.Input.WiiMote
_MousePool.Clear(); _MousePool.Clear();
} }
} }
public void Dispose()
{
if (_WiiMote != null)
{
_WiiMote.Dispose();
_WiiMote = null;
}
GC.SuppressFinalize(this);
}
} }
} }
+59 -104
View File
@@ -137,7 +137,7 @@ namespace Vocaluxe.Lib.Input.WiiMote
} }
#endregion Events #endregion Events
public sealed class CWiiMoteLib : IDisposable public sealed class CWiiMoteLib
{ {
// ReSharper disable InconsistentNaming // ReSharper disable InconsistentNaming
private const ushort _VID = 0x057e; private const ushort _VID = 0x057e;
@@ -178,8 +178,7 @@ namespace Vocaluxe.Lib.Input.WiiMote
private int _Address; private int _Address;
private short _Size; private short _Size;
private readonly Thread _Reader; private Thread _Reader;
private bool _Active;
private readonly bool _Error; private readonly bool _Error;
public bool Connected { get; private set; } public bool Connected { get; private set; }
@@ -191,72 +190,63 @@ namespace Vocaluxe.Lib.Input.WiiMote
#region Interface #region Interface
public CWiiMoteLib() public CWiiMoteLib()
{ {
Connected = false;
_Active = true;
_Error = false;
_Reader = new Thread(_ReaderLoop);
_Reader.Start();
if (!CHIDApi.Init()) if (!CHIDApi.Init())
{ {
CLog.LogError("WiiMoteLib: Can't initialize HID API"); CLog.LogError("WiiMoteLib: Can't initialize HID API");
const string msg = "Please install the Visual C++ Redistributable Packages 2008!"; CLog.LogError("Please install the Visual C++ Redistributable Packages 2008!");
CLog.LogError(msg);
_Active = false;
_Error = true; _Error = true;
} }
} }
~CWiiMoteLib() ~CWiiMoteLib()
{ {
Dispose(false); Disconnect();
//Wait for thread to finish (if any)
_WaitForReader();
CHIDApi.Exit();
_ReadDone.Dispose();
} }
private bool _TryConnect(ushort pid) private void _StartReader()
{ {
bool connected = CHIDApi.Open(_VID, pid, out _Handle); _Reader = new Thread(_ReaderLoop) {Name = "WiiMoteLib"};
if (connected) _Reader.Start();
}
private void _WaitForReader()
{
if (_Reader == null)
return;
_Reader.Join();
_Reader = null;
}
private void _TryConnect(ushort pid)
{
//We might have had a reader thread, that is not finished yet, so let it finish and close it's handle first or it will close the new one
_WaitForReader();
Connected = CHIDApi.Open(_VID, pid, out _Handle);
if (Connected)
{ {
connected = _ReadCalibration(); _StartReader();
if (!connected) if (!_ReadCalibration())
CHIDApi.Close(_Handle); Connected = false;
} }
return connected;
} }
public bool Connect() public bool Connect()
{ {
Connected = false; if (Connected)
return true;
if (_Error) if (_Error)
return false; return false;
//Try WiiMotion _TryConnect(_PID); //Try WiiMotion
Connected = CHIDApi.Open(_VID, _PID, out _Handle);
if (Connected)
{
Connected = _ReadCalibration();
if (!Connected)
CHIDApi.Close(_Handle);
}
else
CHIDApi.Close(_Handle);
if (Connected)
return true;
//Try WiiMotion Plus
Connected = CHIDApi.Open(_VID, _PIDPlus, out _Handle);
if (Connected)
{
Connected = _ReadCalibration();
if (!Connected)
CHIDApi.Close(_Handle);
}
else
CHIDApi.Close(_Handle);
if (!Connected)
_TryConnect(_PIDPlus); //Try WiiMotion Plus
return Connected; return Connected;
} }
@@ -264,8 +254,6 @@ namespace Vocaluxe.Lib.Input.WiiMote
public void Disconnect() public void Disconnect()
{ {
Connected = false; Connected = false;
_Active = false;
CHIDApi.Exit();
} }
public void SetReportType(EInputReport type, EIRSensitivity irSensitivity, bool continuous) public void SetReportType(EInputReport type, EIRSensitivity irSensitivity, bool continuous)
@@ -328,68 +316,54 @@ namespace Vocaluxe.Lib.Input.WiiMote
#region Private stuff #region Private stuff
private void _ReaderLoop() private void _ReaderLoop()
{ {
while (_Active) var buff = new byte[_ReportLength];
while (Connected)
{ {
Thread.Sleep(5); int bytesRead;
try
if (_Handle != IntPtr.Zero && Connected)
{ {
var buff = new byte[_ReportLength]; bytesRead = CHIDApi.ReadTimeout(_Handle, ref buff, _ReportLength, 400);
if (bytesRead == -1)
try
{ {
CHIDApi.ReadTimeout(_Handle, ref buff, _ReportLength, 200); Connected = false; //Disconnected
} break;
catch (Exception e)
{
CLog.LogError("(WiiMoteLib) Error reading from device: " + e);
}
if (_ParseInputReport(buff))
{
if (WiiMoteChanged != null)
WiiMoteChanged(this, new CWiiMoteChangedEventArgs(_WiiMoteState));
} }
} }
catch (Exception e)
{
CLog.LogError("(WiiMoteLib) Error reading from device: " + e);
Connected = false;
break;
}
if (bytesRead > 0 && _ParseInputReport(buff))
{
if (WiiMoteChanged != null)
WiiMoteChanged(this, new CWiiMoteChangedEventArgs(_WiiMoteState));
}
Thread.Sleep(5);
} }
CHIDApi.Close(_Handle);
} }
private bool _ParseInputReport(byte[] buff) private bool _ParseInputReport(byte[] buff)
{ {
if (buff == null)
{
Connected = false;
return false;
}
var type = (EInputReport)buff[0]; var type = (EInputReport)buff[0];
switch (type) switch (type)
{ {
case EInputReport.Buttons: case EInputReport.Buttons:
_ParseButtons(buff);
break;
case EInputReport.ButtonsAccel:
_ParseButtons(buff);
_ParseAccel(buff);
break;
case EInputReport.IRAccel:
_ParseButtons(buff);
_ParseAccel(buff);
_ParseIR(buff);
break;
case EInputReport.ButtonsExtension: case EInputReport.ButtonsExtension:
_ParseButtons(buff); _ParseButtons(buff);
break; break;
case EInputReport.ButtonsAccel:
case EInputReport.ExtensionAccel: case EInputReport.ExtensionAccel:
_ParseButtons(buff); _ParseButtons(buff);
_ParseAccel(buff); _ParseAccel(buff);
break; break;
case EInputReport.IRAccel:
case EInputReport.IRExtensionAccel: case EInputReport.IRExtensionAccel:
_ParseButtons(buff); _ParseButtons(buff);
_ParseAccel(buff); _ParseAccel(buff);
@@ -693,24 +667,5 @@ namespace Vocaluxe.Lib.Input.WiiMote
Thread.Sleep(100); Thread.Sleep(100);
} }
#endregion Private stuff #endregion Private stuff
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// ReSharper disable InconsistentNaming
private void Dispose(bool disposing)
// ReSharper restore InconsistentNaming
{
if (disposing)
{
Disconnect();
_ReadDone.Close();
}
}
#endregion
} }
} }
-1
View File
@@ -18,7 +18,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text;
using System.Xml; using System.Xml;
using Vocaluxe.Base; using Vocaluxe.Base;
using VocaluxeLib; using VocaluxeLib;
+1 -1
View File
@@ -326,7 +326,7 @@ namespace Vocaluxe.Lib.Sound
for (int i = 0; i < _Notifications.Count; i++) for (int i = 0; i < _Notifications.Count; i++)
_WaitHandles[i] = _Notifications[i].Event; _WaitHandles[i] = _Notifications[i].Event;
_CaptureThread = new Thread(_DoCapture) {IsBackground = true}; _CaptureThread = new Thread(_DoCapture) {Name = "DirectSoundCapture", IsBackground = true};
_Running = true; _Running = true;
_CaptureThread.Start(); _CaptureThread.Start();
+25 -6
View File
@@ -37,10 +37,10 @@ namespace Vocaluxe.Lib.Sound
public bool Init() public bool Init()
{ {
#if ARCH_X86 #if ARCH_X86
string path = ".\\x86\\gstreamer"; const string path = ".\\x86\\gstreamer";
#endif #endif
#if ARCH_X64 #if ARCH_X64
string path = ".\\x64\\gstreamer"; const string path = ".\\x64\\gstreamer";
#endif #endif
SetDllDirectory(path); SetDllDirectory(path);
Application.Init(); Application.Init();
@@ -213,9 +213,9 @@ namespace Vocaluxe.Lib.Sound
private class CGstreamerSharpAudioStream private class CGstreamerSharpAudioStream
{ {
private readonly Element _Element; private Element _Element;
private bool _Loop; private bool _Loop;
public volatile bool Closed; public volatile bool Closed = true;
public volatile bool Finished; public volatile bool Finished;
private bool _Fading; private bool _Fading;
@@ -240,7 +240,10 @@ namespace Vocaluxe.Lib.Sound
var audioSinkBin = new Bin("Audiosink"); var audioSinkBin = new Bin("Audiosink");
if (convert == null || audiosink == null) if (convert == null || audiosink == null)
{
CLog.LogError("Could not create pipeline"); CLog.LogError("Could not create pipeline");
return;
}
audioSinkBin.Add(convert); audioSinkBin.Add(convert);
audioSinkBin.Add(audiosink); audioSinkBin.Add(audiosink);
@@ -249,21 +252,35 @@ namespace Vocaluxe.Lib.Sound
GhostPad ghostpad = new GhostPad("sink", pad); GhostPad ghostpad = new GhostPad("sink", pad);
if (pad == null) if (pad == null)
{
CLog.LogError("Could not create pads"); CLog.LogError("Could not create pads");
return;
}
if (!ghostpad.SetActive(true)) if (!ghostpad.SetActive(true))
{
CLog.LogError("Could not link pads"); CLog.LogError("Could not link pads");
return;
}
if (!audioSinkBin.AddPad(ghostpad)) if (!audioSinkBin.AddPad(ghostpad))
{
CLog.LogError("Could not add pad"); CLog.LogError("Could not add pad");
return;
}
_Element = ElementFactory.Make("playbin", "playbin"); _Element = ElementFactory.Make("playbin", "playbin");
if (_Element == null) if (_Element == null)
{
CLog.LogError("Could not create playbin"); CLog.LogError("Could not create playbin");
return;
}
_Element["audio-sink"] = audioSinkBin; _Element["audio-sink"] = audioSinkBin;
_Element["flags"] = 1 << 1; _Element["flags"] = 1 << 1;
_Element["uri"] = new Uri(media).AbsoluteUri; _Element["uri"] = new Uri(media).AbsoluteUri;
_Element.SetState(State.Paused); _Element.SetState(State.Paused);
Closed = false; //Enable stream
// Passing CLOCK_TIME_NONE here causes the pipeline to block for a long time so with // Passing CLOCK_TIME_NONE here causes the pipeline to block for a long time so with
// prescan enabled the pipeline will wait 500ms for stream to initialize and then continue // prescan enabled the pipeline will wait 500ms for stream to initialize and then continue
// if it takes more than 500ms, duration queries will be performed asynchronously // if it takes more than 500ms, duration queries will be performed asynchronously
@@ -307,7 +324,7 @@ namespace Vocaluxe.Lib.Sound
{ {
Closed = true; Closed = true;
Finished = true; Finished = true;
var t = new Thread(_TerminateStream); var t = new Thread(_TerminateStream) {Name = "GSt Terminate"};
t.Start(); t.Start();
} }
} }
@@ -318,6 +335,7 @@ namespace Vocaluxe.Lib.Sound
{ {
_Element.SetState(State.Null); _Element.SetState(State.Null);
_Element.Dispose(); _Element.Dispose();
_Element = null;
} }
} }
@@ -388,7 +406,8 @@ namespace Vocaluxe.Lib.Sound
{ {
if (_Duration < 0 && !_QueryingDuration) if (_Duration < 0 && !_QueryingDuration)
{ {
var t = new Thread(_UpdateDuration); _QueryingDuration = true; // Set this to avoid race conditions
var t = new Thread(_UpdateDuration) {Name = "GSt Update Duration"};
t.Start(); t.Start();
} }
return _Duration > 0 ? _Duration : -1; return _Duration > 0 ? _Duration : -1;
+1 -1
View File
@@ -416,7 +416,7 @@ namespace Vocaluxe.Lib.Sound
public COpenAlStream() public COpenAlStream()
{ {
_Initialized = false; _Initialized = false;
_DecoderThread = new Thread(_Execute); _DecoderThread = new Thread(_Execute) {Name = "OpenAL Decode"};
} }
public void Free(Closeproc closeProc, int streamID, Object closeMutex) public void Free(Closeproc closeProc, int streamID, Object closeMutex)
+2 -4
View File
@@ -401,7 +401,7 @@ namespace Vocaluxe.Lib.Sound
public CPortAudioStream() public CPortAudioStream()
{ {
_SyncTimer = new CSyncTimer(0f, 1f, 0.02f); _SyncTimer = new CSyncTimer(0f, 1f, 0.02f);
_DecoderThread = new Thread(_Execute); _DecoderThread = new Thread(_Execute) {Name = "PortAudio Decode"};
} }
~CPortAudioStream() ~CPortAudioStream()
@@ -665,7 +665,7 @@ namespace Vocaluxe.Lib.Sound
return -1; return -1;
} }
public bool Skip(float time) public void Skip(float time)
{ {
lock (_LockSyncSignals) lock (_LockSyncSignals)
{ {
@@ -673,8 +673,6 @@ namespace Vocaluxe.Lib.Sound
_SetSkip = true; _SetSkip = true;
_Waiting = true; _Waiting = true;
} }
return true;
} }
#region Threading #region Threading
+2
View File
@@ -259,6 +259,7 @@ namespace Vocaluxe
Environment.Exit(Environment.ExitCode); Environment.Exit(Environment.ExitCode);
} }
#if !DEBUG
[HandleProcessCorruptedStateExceptions] [HandleProcessCorruptedStateExceptions]
private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{ {
@@ -273,6 +274,7 @@ namespace Vocaluxe
CLog.LogError("Unhandled exception: " + e.Message + stackTrace); CLog.LogError("Unhandled exception: " + e.Message + stackTrace);
_CloseProgram(); _CloseProgram();
} }
#endif
private static Assembly _AssemblyResolver(Object sender, ResolveEventArgs args) private static Assembly _AssemblyResolver(Object sender, ResolveEventArgs args)
{ {
-6
View File
@@ -15,7 +15,6 @@
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>. // along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
using ServerLib;
using Vocaluxe.Base; using Vocaluxe.Base;
using Vocaluxe.Base.Server; using Vocaluxe.Base.Server;
using VocaluxeLib; using VocaluxeLib;
@@ -56,11 +55,6 @@ namespace Vocaluxe.Screens
_ThemeTexts = new string[] {_TextServerAddress, _TextServerNotRunning}; _ThemeTexts = new string[] {_TextServerAddress, _TextServerNotRunning};
} }
public override void LoadTheme(string xmlPath)
{
base.LoadTheme(xmlPath);
}
public override void OnShow() public override void OnShow()
{ {
base.OnShow(); base.OnShow();
+17 -13
View File
@@ -183,24 +183,28 @@ namespace Vocaluxe.Screens
public override void LoadTheme(string xmlPath) public override void LoadTheme(string xmlPath)
{ {
bool ressourceOK = true;
//Vocaluxe-Logo //Vocaluxe-Logo
CDataBase.GetCreditsRessource("Logo_voc.png", ref _TexLogo); ressourceOK &= CDataBase.GetCreditsRessource("Logo_voc.png", ref _TexLogo);
//Little stars for logo //Little stars for logo
CDataBase.GetCreditsRessource("PerfectNoteStar.png", ref _TexPerfectNoteStar); ressourceOK &= CDataBase.GetCreditsRessource("PerfectNoteStar.png", ref _TexPerfectNoteStar);
CDataBase.GetCreditsRessource("redDot.png", ref _TexRedDot); ressourceOK &= CDataBase.GetCreditsRessource("redDot.png", ref _TexRedDot);
CDataBase.GetCreditsRessource("blueDot.png", ref _TexBlueDot); ressourceOK &= CDataBase.GetCreditsRessource("blueDot.png", ref _TexBlueDot);
CDataBase.GetCreditsRessource("brunzel.png", ref _TexNameBrunzel); ressourceOK &= CDataBase.GetCreditsRessource("brunzel.png", ref _TexNameBrunzel);
CDataBase.GetCreditsRessource("Darkice.png", ref _TexNameDarkice); ressourceOK &= CDataBase.GetCreditsRessource("Darkice.png", ref _TexNameDarkice);
CDataBase.GetCreditsRessource("flokuep.png", ref _TexNameFlokuep); ressourceOK &= CDataBase.GetCreditsRessource("flokuep.png", ref _TexNameFlokuep);
CDataBase.GetCreditsRessource("flamefire.png", ref _TexNameFlamefire); ressourceOK &= CDataBase.GetCreditsRessource("flamefire.png", ref _TexNameFlamefire);
CDataBase.GetCreditsRessource("bohning.png", ref _TexNameBohning); ressourceOK &= CDataBase.GetCreditsRessource("bohning.png", ref _TexNameBohning);
CDataBase.GetCreditsRessource("mesand.png", ref _TexNameMesand); ressourceOK &= CDataBase.GetCreditsRessource("mesand.png", ref _TexNameMesand);
CDataBase.GetCreditsRessource("babene03.png", ref _TexNameBabene03); ressourceOK &= CDataBase.GetCreditsRessource("babene03.png", ref _TexNameBabene03);
CDataBase.GetCreditsRessource("pantero.png", ref _TexNamePantero); ressourceOK &= CDataBase.GetCreditsRessource("pantero.png", ref _TexNamePantero);
CDataBase.GetCreditsRessource("Pinky007.png", ref _TexNamePinky007); ressourceOK &= CDataBase.GetCreditsRessource("Pinky007.png", ref _TexNamePinky007);
if (!ressourceOK)
CLog.LogError("Could not load all ressources!", true, true);
//Prepare Text //Prepare Text
int lastY = 280; int lastY = 280;
+16 -29
View File
@@ -44,7 +44,7 @@ namespace Vocaluxe.Screens
private string[] _TextDate; private string[] _TextDate;
private string[] _ParticleEffectNew; private string[] _ParticleEffectNew;
private List<SScores>[] _Scores; private List<SDBScoreEntry>[] _Scores;
private List<int> _NewEntryIDs; private List<int> _NewEntryIDs;
private int _Round; private int _Round;
private int _Pos; private int _Pos;
@@ -169,7 +169,7 @@ namespace Vocaluxe.Screens
string name = _Scores[_Round][_Pos + p].Name; string name = _Scores[_Round][_Pos + p].Name;
name += " [" + CLanguage.Translate(Enum.GetName(typeof(EGameDifficulty), _Scores[_Round][_Pos + p].Difficulty)) + "]"; name += " [" + CLanguage.Translate(Enum.GetName(typeof(EGameDifficulty), _Scores[_Round][_Pos + p].Difficulty)) + "]";
if (_IsDuet) if (_IsDuet)
name += " (P" + (_Scores[_Round][_Pos + p].LineNr + 1) + ")"; name += " (P" + (_Scores[_Round][_Pos + p].VoiceNr + 1) + ")";
_Texts[_TextName[p]].Text = name; _Texts[_TextName[p]].Text = name;
_Texts[_TextScore[p]].Text = _Scores[_Round][_Pos + p].Score.ToString("00000"); _Texts[_TextScore[p]].Text = _Scores[_Round][_Pos + p].Score.ToString("00000");
@@ -194,10 +194,6 @@ namespace Vocaluxe.Screens
base.OnShow(); base.OnShow();
_Round = 0; _Round = 0;
_Pos = 0; _Pos = 0;
CPoints points = CGame.GetPoints();
_Scores = new List<SScores>[points.NumRounds];
for (int i = 0; i < _Scores.Length; i++)
_Scores[i] = new List<SScores>();
_NewEntryIDs.Clear(); _NewEntryIDs.Clear();
_AddScoresToDB(); _AddScoresToDB();
_LoadScores(); _LoadScores();
@@ -231,15 +227,14 @@ namespace Vocaluxe.Screens
private void _LoadScores() private void _LoadScores()
{ {
CPoints points = CGame.GetPoints();
if (points == null)
return;
_Pos = 0; _Pos = 0;
for (int round = 0; round < points.NumRounds; round++) int rounds = CGame.NumRounds;
_Scores = new List<SDBScoreEntry>[rounds];
for (int round = 0; round < rounds; round++)
{ {
SPlayer player = points.GetPlayer(round, CGame.NumPlayer)[0]; int songID = CGame.GetSong(round).ID;
CDataBase.LoadScore(out _Scores[round], player); EGameMode gameMode = CGame.GetGameMode(round);
_Scores[round] = CDataBase.LoadScore(songID, gameMode);
} }
} }
@@ -247,7 +242,7 @@ namespace Vocaluxe.Screens
{ {
_IsDuet = false; _IsDuet = false;
CPoints points = CGame.GetPoints(); CPoints points = CGame.GetPoints();
CSong song = CGame.GetSong(_Round + 1); CSong song = CGame.GetSong(_Round);
if (song == null) if (song == null)
return; return;
@@ -255,7 +250,7 @@ namespace Vocaluxe.Screens
if (points.NumRounds > 1) if (points.NumRounds > 1)
_Texts[_TextSongName].Text += " (" + (_Round + 1) + "/" + points.NumRounds + ")"; _Texts[_TextSongName].Text += " (" + (_Round + 1) + "/" + points.NumRounds + ")";
switch (CGame.GetGameMode(_Round + 1)) switch (CGame.GetGameMode(_Round))
{ {
case EGameMode.TR_GAMEMODE_NORMAL: case EGameMode.TR_GAMEMODE_NORMAL:
_Texts[_TextSongMode].Text = "TR_GAMEMODE_NORMAL"; _Texts[_TextSongMode].Text = "TR_GAMEMODE_NORMAL";
@@ -284,28 +279,20 @@ namespace Vocaluxe.Screens
private void _ChangePos(int num) private void _ChangePos(int num)
{ {
if (num > 0) if (_Scores[_Round].Count == 0)
{ _Pos = 0;
if (_Pos + num + _NumEntrys < _Scores[_Round].Count) else
_Pos += num;
}
if (num < 0)
{ {
_Pos += num; _Pos += num;
if (_Pos < 0) _Pos = _Pos.Clamp(0, _Scores[_Round].Count - 1);
_Pos = 0;
} }
} }
private void _ChangeRound(int num) private void _ChangeRound(int num)
{ {
CPoints points = CGame.GetPoints(); CPoints points = CGame.GetPoints();
if (_Round + num < points.NumRounds && _Round + num > -1) _Round += num;
_Round += num; _Round = _Round.Clamp(0, points.NumRounds - 1);
else if (_Round + num >= points.NumRounds)
_Round = points.NumRounds - 1;
else if (_Round + num < 0)
_Round = 0;
_UpdateRound(); _UpdateRound();
} }
-11
View File
@@ -15,7 +15,6 @@
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>. // along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
using System.Diagnostics;
using System.Threading; using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;
using Vocaluxe.Base; using Vocaluxe.Base;
@@ -38,7 +37,6 @@ namespace Vocaluxe.Screens
private readonly string[] _IntroVideo = new string[] {"IntroIn", "IntroMid", "IntroOut"}; private readonly string[] _IntroVideo = new string[] {"IntroIn", "IntroMid", "IntroOut"};
private Thread _SongLoaderThread; private Thread _SongLoaderThread;
private Stopwatch _Timer;
private bool _SkipIntro; private bool _SkipIntro;
private int _CurrentIntroVideoNr; private int _CurrentIntroVideoNr;
private bool _IntroOutPlayed; private bool _IntroOutPlayed;
@@ -54,7 +52,6 @@ namespace Vocaluxe.Screens
_Intros = new CVideoPlayer[_IntroVideo.Length]; _Intros = new CVideoPlayer[_IntroVideo.Length];
for (int i = 0; i < _Intros.Length; i++) for (int i = 0; i < _Intros.Length; i++)
_Intros[i] = new CVideoPlayer(); _Intros[i] = new CVideoPlayer();
_Timer = new Stopwatch();
} }
public override bool HandleInput(SKeyEvent keyEvent) public override bool HandleInput(SKeyEvent keyEvent)
@@ -135,7 +132,6 @@ namespace Vocaluxe.Screens
CLog.StartBenchmark(0, "Load Songs Full"); CLog.StartBenchmark(0, "Load Songs Full");
_SongLoaderThread.IsBackground = true; _SongLoaderThread.IsBackground = true;
_SongLoaderThread.Start(); _SongLoaderThread.Start();
_Timer.Start();
if (CConfig.BackgroundMusic == EOffOn.TR_CONFIG_ON && if (CConfig.BackgroundMusic == EOffOn.TR_CONFIG_ON &&
CConfig.BackgroundMusicSource == EBackgroundMusicSource.TR_CONFIG_NO_OWN_MUSIC && !_BGMusicStarted) CConfig.BackgroundMusicSource == EBackgroundMusicSource.TR_CONFIG_NO_OWN_MUSIC && !_BGMusicStarted)
@@ -155,11 +151,6 @@ namespace Vocaluxe.Screens
{ {
_CheckStartIntroVideos(); _CheckStartIntroVideos();
if (CSettings.GameState == EGameState.EditTheme)
_Timer.Stop();
else
_Timer.Start();
bool next = CConfig.CoverLoading != ECoverLoading.TR_CONFIG_COVERLOADING_ATSTART || CSongs.CoverLoaded; bool next = CConfig.CoverLoading != ECoverLoading.TR_CONFIG_COVERLOADING_ATSTART || CSongs.CoverLoaded;
if ((_IntroOutPlayed || _SkipIntro) && next && CSettings.GameState != EGameState.EditTheme && CSongs.SongsLoaded) if ((_IntroOutPlayed || _SkipIntro) && next && CSettings.GameState != EGameState.EditTheme && CSongs.SongsLoaded)
@@ -201,8 +192,6 @@ namespace Vocaluxe.Screens
public override void OnClose() public override void OnClose()
{ {
base.OnClose(); base.OnClose();
_Timer.Stop();
_Timer.Reset();
foreach (CVideoPlayer videoPlayer in _Intros) foreach (CVideoPlayer videoPlayer in _Intros)
videoPlayer.Close(); videoPlayer.Close();
+5 -6
View File
@@ -241,7 +241,7 @@ namespace Vocaluxe.Screens
break; break;
case Keys.F10: case Keys.F10:
if (CGame.GetNumSongs() == 1 && CGame.GetSong(1).IsDuet) if (CGame.GetNumSongs() == 1 && CGame.GetSong(0).IsDuet)
{ {
CSelectSlide selectSlideDuetPart = _SelectSlides[_SelectSlideDuetPlayer[_SelectingFastPlayerNr - 1]]; CSelectSlide selectSlideDuetPart = _SelectSlides[_SelectSlideDuetPlayer[_SelectingFastPlayerNr - 1]];
selectSlideDuetPart.Selection = (selectSlideDuetPart.Selection + 1) % 2; selectSlideDuetPart.Selection = (selectSlideDuetPart.Selection + 1) % 2;
@@ -599,7 +599,7 @@ namespace Vocaluxe.Screens
_CheckMics(); _CheckMics();
_CheckPlayers(); _CheckPlayers();
CSong firstSong = CGame.GetSong(1); CSong firstSong = CGame.GetSong(0);
for (int i = 0; i < CSettings.MaxNumPlayer; i++) for (int i = 0; i < CSettings.MaxNumPlayer; i++)
{ {
@@ -627,12 +627,11 @@ namespace Vocaluxe.Screens
private void _StartSong() private void _StartSong()
{ {
for (int i = 0; i < CGame.NumPlayer; i++) if (CGame.GetNumSongs() == 1 && CGame.GetSong(0).IsDuet)
{ {
if (CGame.GetNumSongs() == 1 && CGame.GetSong(1).IsDuet) for (int i = 0; i < CGame.NumPlayer; i++)
CGame.Players[i].VoiceNr = _SelectSlides[_SelectSlideDuetPlayer[i]].Selection; CGame.Players[i].VoiceNr = _SelectSlides[_SelectSlideDuetPlayer[i]].Selection;
} }
CGraphics.FadeTo(EScreens.ScreenSing); CGraphics.FadeTo(EScreens.ScreenSing);
} }
@@ -658,7 +657,7 @@ namespace Vocaluxe.Screens
if (_Texts["TextPlayer" + i].Text == "") if (_Texts["TextPlayer" + i].Text == "")
_Texts["TextPlayer" + i].Text = CProfiles.GetPlayerName(-1, i); _Texts["TextPlayer" + i].Text = CProfiles.GetPlayerName(-1, i);
_Equalizers["EqualizerPlayer" + i].Visible = true; _Equalizers["EqualizerPlayer" + i].Visible = true;
if (CGame.GetNumSongs() == 1 && CGame.GetSong(1).IsDuet) if (CGame.GetNumSongs() == 1 && CGame.GetSong(0).IsDuet)
_SelectSlides["SelectSlideDuetPlayer" + i].Visible = true; _SelectSlides["SelectSlideDuetPlayer" + i].Visible = true;
} }
else else
+14 -4
View File
@@ -37,7 +37,7 @@ namespace Vocaluxe.Screens
// Version number for theme files. Increment it, if you've changed something on the theme files! // Version number for theme files. Increment it, if you've changed something on the theme files!
protected override int _ScreenVersion protected override int _ScreenVersion
{ {
get { return 3; } get { return 4; }
} }
private const float _MaxDelayTime = 1f; private const float _MaxDelayTime = 1f;
@@ -53,6 +53,9 @@ namespace Vocaluxe.Screens
private const string _ButtonExit = "ButtonExit"; private const string _ButtonExit = "ButtonExit";
private const string _ButtonDelayTest = "ButtonDelayTest"; private const string _ButtonDelayTest = "ButtonDelayTest";
private const string _TextChannel1 = "TextChannel1";
private const string _TextChannel2 = "TextChannel2";
private const string _TextDelayChannel1 = "TextDelayChannel1"; private const string _TextDelayChannel1 = "TextDelayChannel1";
private const string _TextDelayChannel2 = "TextDelayChannel2"; private const string _TextDelayChannel2 = "TextDelayChannel2";
@@ -77,7 +80,7 @@ namespace Vocaluxe.Screens
values.AddRange(_StaticEnergyChannel); values.AddRange(_StaticEnergyChannel);
_ThemeStatics = values.ToArray(); _ThemeStatics = values.ToArray();
_ThemeTexts = new string[] {_TextWarning, _TextDelayChannel1, _TextDelayChannel2}; _ThemeTexts = new string[] {_TextWarning, _TextChannel1, _TextChannel2, _TextDelayChannel1, _TextDelayChannel2};
_ThemeButtons = new string[] {_ButtonExit, _ButtonDelayTest}; _ThemeButtons = new string[] {_ButtonExit, _ButtonDelayTest};
_ThemeSelectSlides = new string[] {_SelectSlideRecordDevices, _SelectSlideRecordChannel1, _SelectSlideRecordChannel2, _SelectSlideDelay}; _ThemeSelectSlides = new string[] {_SelectSlideRecordDevices, _SelectSlideRecordChannel1, _SelectSlideRecordChannel2, _SelectSlideDelay};
_ThemeEqualizers = new string[] {_EqualizerChannel1, _EqualizerChannel2}; _ThemeEqualizers = new string[] {_EqualizerChannel1, _EqualizerChannel2};
@@ -248,8 +251,7 @@ namespace Vocaluxe.Screens
_DelayTest[i].Timer.Stop(); _DelayTest[i].Timer.Stop();
_DelayTestRunning = false; _DelayTestRunning = false;
} }
else if (CSound.RecordGetMaxVolume(player - 1) > 0.1f && else if (CSound.RecordGetMaxVolume(player - 1) > 0.1f && CSound.RecordGetToneAbs(player - 1) % 12 == 9)
(CSound.RecordGetToneAbs(player - 1) == 9 || CSound.RecordGetToneAbs(player - 1) == 21 || CSound.RecordGetToneAbs(player - 1) == 33))
{ {
_DelayTest[i].Delay = _DelayTest[i].Timer.ElapsedMilliseconds; _DelayTest[i].Delay = _DelayTest[i].Timer.ElapsedMilliseconds;
_DelayTest[i].Timer.Stop(); _DelayTest[i].Timer.Stop();
@@ -444,6 +446,12 @@ namespace Vocaluxe.Screens
CSound.RecordStart(); CSound.RecordStart();
} }
private void _SetPlayerColors()
{
_Texts[_TextChannel1].Color = CTheme.GetPlayerColor(_SelectSlides[_SelectSlideRecordChannel1].Selection);
_Texts[_TextChannel2].Color = CTheme.GetPlayerColor(_SelectSlides[_SelectSlideRecordChannel2].Selection);
}
private void _SetMicConfig() private void _SetMicConfig()
{ {
if (_DeviceNr < 0) if (_DeviceNr < 0)
@@ -451,6 +459,7 @@ namespace Vocaluxe.Screens
CRecordDevice device = _Devices[_DeviceNr]; CRecordDevice device = _Devices[_DeviceNr];
device.PlayerChannel1 = _SelectSlides[_SelectSlideRecordChannel1].Selection; device.PlayerChannel1 = _SelectSlides[_SelectSlideRecordChannel1].Selection;
device.PlayerChannel2 = _SelectSlides[_SelectSlideRecordChannel2].Selection; device.PlayerChannel2 = _SelectSlides[_SelectSlideRecordChannel2].Selection;
_SetPlayerColors();
} }
private void _UpdateChannels() private void _UpdateChannels()
@@ -459,6 +468,7 @@ namespace Vocaluxe.Screens
_SelectSlides[_SelectSlideRecordChannel2].Selection = _Devices[_DeviceNr].PlayerChannel2; _SelectSlides[_SelectSlideRecordChannel2].Selection = _Devices[_DeviceNr].PlayerChannel2;
_SaveMicConfig(); _SaveMicConfig();
_SetPlayerColors();
} }
private bool _CheckMicConfig() private bool _CheckMicConfig()
@@ -15,12 +15,10 @@
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>. // along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
using System;
using System.Windows.Forms; using System.Windows.Forms;
using Vocaluxe.Base; using Vocaluxe.Base;
using VocaluxeLib; using VocaluxeLib;
using VocaluxeLib.Menu; using VocaluxeLib.Menu;
using VocaluxeLib.Draw;
namespace Vocaluxe.Screens namespace Vocaluxe.Screens
{ {
+18 -19
View File
@@ -124,7 +124,8 @@ namespace Vocaluxe.Screens
public override void OnShow() public override void OnShow()
{ {
base.OnShow(); base.OnShow();
_Round = CGame.NumRounds > 1 ? 0 : 1; //-1 --> Show average
_Round = CGame.NumRounds > 1 ? -1 : 0;
_Points = CGame.GetPoints(); _Points = CGame.GetPoints();
_SavePlayedSongs(); _SavePlayedSongs();
@@ -137,8 +138,8 @@ namespace Vocaluxe.Screens
public override bool UpdateGame() public override bool UpdateGame()
{ {
var players = new SPlayer[CGame.NumPlayer]; var players = new SPlayer[CGame.NumPlayer];
if (_Round != 0) if (_Round >= 0)
players = _Points.GetPlayer(_Round - 1, CGame.NumPlayer); players = _Points.GetPlayer(_Round, CGame.NumPlayer);
else else
{ {
for (int i = 0; i < CGame.NumRounds; i++) for (int i = 0; i < CGame.NumRounds; i++)
@@ -186,8 +187,8 @@ namespace Vocaluxe.Screens
if (_SlideShowBGAvailable) if (_SlideShowBGAvailable)
_SlideShowBG.Draw(); _SlideShowBG.Draw();
else else
base._DrawBG(); _DrawBG();
base._DrawFG(); _DrawFG();
return true; return true;
} }
@@ -274,7 +275,7 @@ namespace Vocaluxe.Screens
{ {
CSong song = null; CSong song = null;
var players = new SPlayer[CGame.NumPlayer]; var players = new SPlayer[CGame.NumPlayer];
if (_Round != 0) if (_Round >= 0)
{ {
song = CGame.GetSong(_Round); song = CGame.GetSong(_Round);
if (song == null) if (song == null)
@@ -282,8 +283,8 @@ namespace Vocaluxe.Screens
_Texts[_TextSong].Text = song.Artist + " - " + song.Title; _Texts[_TextSong].Text = song.Artist + " - " + song.Title;
if (_Points.NumRounds > 1) if (_Points.NumRounds > 1)
_Texts[_TextSong].Text += " (" + _Round + "/" + _Points.NumRounds + ")"; _Texts[_TextSong].Text += " (" + (_Round + 1) + "/" + _Points.NumRounds + ")";
players = _Points.GetPlayer(_Round - 1, CGame.NumPlayer); players = _Points.GetPlayer(_Round, CGame.NumPlayer);
} }
else else
{ {
@@ -395,16 +396,14 @@ namespace Vocaluxe.Screens
private void _ChangeRound(int num) private void _ChangeRound(int num)
{ {
if ((_Round + num) <= _Points.NumRounds && (_Round + num > 0)) if (_Points.NumRounds < 1)
{ return;
_Round += num; _Round += num;
_UpdateRatings(); _Round = _Round.Clamp(-1, _Points.NumRounds - 1);
} if (_Round >= _Points.NumRounds)
else if (num < 0 && _Round == 1 && CGame.NumRounds > 1) _Round = _Points.NumRounds - 1;
{
_Round = 0; _UpdateRatings();
_UpdateRatings();
}
} }
private void _SavePlayedSongs() private void _SavePlayedSongs()
@@ -429,7 +428,7 @@ namespace Vocaluxe.Screens
private bool _UpdateBackground() private bool _UpdateBackground()
{ {
string[] photos = CVocaluxeServer.getPhotosOfThisRound(); string[] photos = CVocaluxeServer.GetPhotosOfThisRound();
_SlideShowBG.RemoveSlideShowTextures(); _SlideShowBG.RemoveSlideShowTextures();
foreach (string photo in photos) foreach (string photo in photos)
_SlideShowBG.AddSlideShowTexture(photo); _SlideShowBG.AddSlideShowTexture(photo);
+49 -29
View File
@@ -39,7 +39,7 @@ namespace Vocaluxe.SongQueue
class CSongQueue : ISongQueue class CSongQueue : ISongQueue
{ {
private List<SSongQueueEntry> _SongQueue; private List<SSongQueueEntry> _SongQueue;
private int _CurrentSong; private int _CurrentRound;
private CPoints _Points; private CPoints _Points;
#region Implementation #region Implementation
@@ -52,9 +52,7 @@ namespace Vocaluxe.SongQueue
public EGameMode GetCurrentGameMode() public EGameMode GetCurrentGameMode()
{ {
if (_CurrentSong >= 0 && _CurrentSong < _SongQueue.Count) return GetGameMode(_CurrentRound);
return _SongQueue[_CurrentSong].GameMode;
return EGameMode.TR_GAMEMODE_NORMAL;
} }
public bool AddVisibleSong(int visibleIndex, EGameMode gameMode) public bool AddVisibleSong(int visibleIndex, EGameMode gameMode)
@@ -105,7 +103,7 @@ namespace Vocaluxe.SongQueue
public void Reset() public void Reset()
{ {
_CurrentSong = -1; _CurrentRound = -1;
} }
public void Start(SPlayer[] players) public void Start(SPlayer[] players)
@@ -113,39 +111,51 @@ namespace Vocaluxe.SongQueue
_Points = new CPoints(_SongQueue.Count, players); _Points = new CPoints(_SongQueue.Count, players);
} }
public void NextRound(SPlayer[] players) public void StartNextRound(SPlayer[] players)
{ {
if (_CurrentSong < _SongQueue.Count && _SongQueue.Count > 0) if (IsFinished())
return;
if (_CurrentRound > -1)
{ {
if (_CurrentSong > -1) _Points.SetPoints(
{ _CurrentRound,
_Points.SetPoints( _SongQueue[_CurrentRound].SongID,
_CurrentSong, players,
_SongQueue[_CurrentSong].SongID, _SongQueue[_CurrentRound].GameMode);
players,
_SongQueue[_CurrentSong].GameMode == EGameMode.TR_GAMEMODE_MEDLEY,
_SongQueue[_CurrentSong].GameMode == EGameMode.TR_GAMEMODE_DUET,
_SongQueue[_CurrentSong].GameMode == EGameMode.TR_GAMEMODE_SHORTSONG);
}
_CurrentSong++;
} }
_CurrentRound++;
} }
public bool IsFinished() public bool IsFinished()
{ {
return _CurrentSong == _SongQueue.Count || _SongQueue.Count == 0; return _CurrentRound >= _SongQueue.Count || _SongQueue.Count == 0;
} }
/// <summary>
/// Get current round nr (1 ~ n)
/// </summary>
/// <returns>current round nr (1 ~ n)</returns>
public int GetCurrentRoundNr() public int GetCurrentRoundNr()
{ {
return _CurrentSong + 1; return _CurrentRound + 1;
} }
/// <summary>
/// Returns current round
/// </summary>
/// <returns>Current round (0 based)</returns>
public int GetCurrentRound()
{
return _CurrentRound;
}
/// <summary>
/// Get current song
/// </summary>
/// <returns>Song of current round or null if there is none/game finished</returns>
public CSong GetSong() public CSong GetSong()
{ {
if (_CurrentSong >= 0 && _CurrentSong < _SongQueue.Count) return GetSong(_CurrentRound);
return CGameModes.Get(_SongQueue[_CurrentSong].GameMode).GetSong(_SongQueue[_CurrentSong].SongID);
return null;
} }
public int GetNumSongs() public int GetNumSongs()
@@ -153,18 +163,28 @@ namespace Vocaluxe.SongQueue
return _SongQueue.Count; return _SongQueue.Count;
} }
public CSong GetSong(int num) /// <summary>
/// Get song of specified round
/// </summary>
/// <param name="round">Round (0 based)</param>
/// <returns>Current song or null if out of bounds</returns>
public CSong GetSong(int round)
{ {
if (num - 1 < _SongQueue.Count && num > 0) if (round < _SongQueue.Count && round >= 0)
return CSongs.GetSong(_SongQueue[num - 1].SongID); return CSongs.GetSong(_SongQueue[round].SongID);
return null; return null;
} }
public EGameMode GetGameMode(int num) /// <summary>
/// Get gameMode of specified round
/// </summary>
/// <param name="round">Round (0 based)</param>
/// <returns>Current song or null if out of bounds</returns>
public EGameMode GetGameMode(int round)
{ {
if (num - 1 < _SongQueue.Count && num > 0) if (round < _SongQueue.Count && round >= 0)
return _SongQueue[num - 1].GameMode; return _SongQueue[round].GameMode;
return EGameMode.TR_GAMEMODE_NORMAL; return EGameMode.TR_GAMEMODE_NORMAL;
} }
+6 -6
View File
@@ -25,8 +25,6 @@ namespace Vocaluxe.SongQueue
{ {
void Init(); void Init();
EGameMode GetCurrentGameMode();
bool AddVisibleSong(int visibleIndex, EGameMode gameMode); bool AddVisibleSong(int visibleIndex, EGameMode gameMode);
bool AddSong(int absoluteIndex, EGameMode gameMode); bool AddSong(int absoluteIndex, EGameMode gameMode);
bool RemoveVisibleSong(int visibleIndex); bool RemoveVisibleSong(int visibleIndex);
@@ -35,15 +33,17 @@ namespace Vocaluxe.SongQueue
void Reset(); void Reset();
void Start(SPlayer[] players); void Start(SPlayer[] players);
void NextRound(SPlayer[] players); void StartNextRound(SPlayer[] players);
bool IsFinished(); bool IsFinished();
int GetCurrentRoundNr();
CPoints GetPoints(); CPoints GetPoints();
int GetNumSongs(); int GetNumSongs();
int GetCurrentRoundNr();
CSong GetSong(); CSong GetSong();
CSong GetSong(int num); CSong GetSong(int round);
EGameMode GetGameMode(int num); EGameMode GetCurrentGameMode();
EGameMode GetGameMode(int round);
} }
} }
+2
View File
@@ -22,6 +22,7 @@
position: relative; position: relative;
height: 100%; height: 100%;
width: 100%; width: 100%;
background-color: #000000;
background-color: rgba(0,0,0,0.7); background-color: rgba(0,0,0,0.7);
} }
@@ -30,6 +31,7 @@
height: 100%; height: 100%;
top: 0; top: 0;
margin: 0; margin: 0;
background: #000000;
background: rgba(0, 0, 0, 0.3); background: rgba(0, 0, 0, 0.3);
display: none; display: none;
position: fixed; position: fixed;
+9
View File
@@ -47,6 +47,15 @@ namespace VocaluxeLib
return (int)result; return (int)result;
} }
public static T Clamp<T>(this T val, T min, T max) where T : IComparable<T>
{
if (val.CompareTo(min) < 0)
return min;
if (val.CompareTo(max) > 0)
return max;
return val;
}
/// <summary> /// <summary>
/// Concat strings into one string with ", " as separator. /// Concat strings into one string with ", " as separator.
/// </summary> /// </summary>
+2
View File
@@ -355,6 +355,7 @@ namespace VocaluxeLib
[Flags] [Flags]
public enum EUserRole public enum EUserRole
{ {
// ReSharper disable InconsistentNaming
TR_USERROLE_GUEST = 0, TR_USERROLE_GUEST = 0,
TR_USERROLE_NORMAL = 1, TR_USERROLE_NORMAL = 1,
TR_USERROLE_ADMIN = 2, TR_USERROLE_ADMIN = 2,
@@ -362,5 +363,6 @@ namespace VocaluxeLib
TR_USERROLE_ADDSONGSUSER = 8, TR_USERROLE_ADDSONGSUSER = 8,
TR_USERROLE_PLAYLISTEDITOR = 16, TR_USERROLE_PLAYLISTEDITOR = 16,
TR_USERROLE_PROFILEEDITOR = 32 TR_USERROLE_PROFILEEDITOR = 32
// ReSharper restore InconsistentNaming
} }
} }
+1 -2
View File
@@ -19,11 +19,10 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using System.Text;
namespace VocaluxeLib namespace VocaluxeLib
{ {
public static class Extensions public static class CExtensions
{ {
/// <summary> /// <summary>
/// Resizes the given list to the given size. Removes elements or adds default values /// Resizes the given list to the given size. Removes elements or adds default values
+4 -10
View File
@@ -35,15 +35,13 @@ namespace VocaluxeLib.Game
_Rounds[round, player].Points = 0f; _Rounds[round, player].Points = 0f;
_Rounds[round, player].PointsGoldenNotes = 0f; _Rounds[round, player].PointsGoldenNotes = 0f;
_Rounds[round, player].PointsLineBonus = 0f; _Rounds[round, player].PointsLineBonus = 0f;
_Rounds[round, player].Medley = false; _Rounds[round, player].GameMode = EGameMode.TR_GAMEMODE_NORMAL;
_Rounds[round, player].Duet = false;
_Rounds[round, player].ShortSong = false;
_Rounds[round, player].SongFinished = false; _Rounds[round, player].SongFinished = false;
} }
} }
} }
public void SetPoints(int round, int songID, SPlayer[] players, bool medley, bool duet, bool shortSong) public void SetPoints(int round, int songID, SPlayer[] players, EGameMode gameMode)
{ {
long dateTicks = DateTime.Now.Ticks; long dateTicks = DateTime.Now.Ticks;
for (int player = 0; player < players.Length; player++) for (int player = 0; player < players.Length; player++)
@@ -53,9 +51,7 @@ namespace VocaluxeLib.Game
_Rounds[round, player].Points = players[player].Points; _Rounds[round, player].Points = players[player].Points;
_Rounds[round, player].PointsGoldenNotes = players[player].PointsGoldenNotes; _Rounds[round, player].PointsGoldenNotes = players[player].PointsGoldenNotes;
_Rounds[round, player].PointsLineBonus = players[player].PointsLineBonus; _Rounds[round, player].PointsLineBonus = players[player].PointsLineBonus;
_Rounds[round, player].Medley = medley; _Rounds[round, player].GameMode = gameMode;
_Rounds[round, player].Duet = duet;
_Rounds[round, player].ShortSong = shortSong;
_Rounds[round, player].DateTicks = dateTicks; _Rounds[round, player].DateTicks = dateTicks;
_Rounds[round, player].SongFinished = players[player].SongFinished; _Rounds[round, player].SongFinished = players[player].SongFinished;
} }
@@ -87,9 +83,7 @@ namespace VocaluxeLib.Game
players[p].PointsLineBonus = _Rounds[round, p].PointsLineBonus; players[p].PointsLineBonus = _Rounds[round, p].PointsLineBonus;
players[p].SongID = _Rounds[round, p].SongID; players[p].SongID = _Rounds[round, p].SongID;
players[p].VoiceNr = _Rounds[round, p].VoiceNr; players[p].VoiceNr = _Rounds[round, p].VoiceNr;
players[p].Medley = _Rounds[round, p].Medley; players[p].GameMode = _Rounds[round, p].GameMode;
players[p].Duet = _Rounds[round, p].Duet;
players[p].ShortSong = _Rounds[round, p].ShortSong;
players[p].DateTicks = _Rounds[round, p].DateTicks; players[p].DateTicks = _Rounds[round, p].DateTicks;
players[p].SongFinished = _Rounds[round, p].SongFinished; players[p].SongFinished = _Rounds[round, p].SongFinished;
players[p].ProfileID = _Rounds[round, p].ProfileID; players[p].ProfileID = _Rounds[round, p].ProfileID;
+2
View File
@@ -155,6 +155,8 @@ namespace VocaluxeLib
public interface ILog public interface ILog
{ {
void LogError(string errorText); void LogError(string errorText);
void LogDebug(string text);
void LogSongInfo(string text);
} }
public interface IFonts public interface IFonts
+4 -5
View File
@@ -54,8 +54,8 @@ namespace VocaluxeLib.Menu
private bool _ThemeLoaded; private bool _ThemeLoaded;
private int _SlideShowCurrent; private int _SlideShowCurrent;
private Stopwatch _SlideShowTimer = new Stopwatch(); private readonly Stopwatch _SlideShowTimer = new Stopwatch();
private List<CTexture> _SlideShowTextures = new List<CTexture>(); private readonly List<CTexture> _SlideShowTextures = new List<CTexture>();
public SColorF Color; public SColorF Color;
@@ -69,8 +69,7 @@ namespace VocaluxeLib.Menu
{ {
_PartyModeID = partyModeID; _PartyModeID = partyModeID;
_ThemeLoaded = false; _ThemeLoaded = false;
_Theme = new SThemeBackground(); _Theme = new SThemeBackground {SlideShowTextures = new List<string>()};
_Theme.SlideShowTextures = new List<string>();
Color = new SColorF(0f, 0f, 0f, 1f); Color = new SColorF(0f, 0f, 0f, 1f);
} }
@@ -102,11 +101,11 @@ namespace VocaluxeLib.Menu
_ThemeLoaded &= success; _ThemeLoaded &= success;
} }
string slideShow = "";
int i = 1; int i = 1;
while (xmlReader.ItemExists(item + "/SlideShow" + i)) while (xmlReader.ItemExists(item + "/SlideShow" + i))
{ {
string slideShow;
xmlReader.GetValue(item + "/SlideShow" + i, out slideShow, String.Empty); xmlReader.GetValue(item + "/SlideShow" + i, out slideShow, String.Empty);
if (slideShow != "") if (slideShow != "")
_Theme.SlideShowTextures.Add(slideShow); _Theme.SlideShowTextures.Add(slideShow);
-2
View File
@@ -16,8 +16,6 @@
#endregion #endregion
using System; using System;
using System.Collections.Generic;
using System.Drawing;
using System.Xml; using System.Xml;
using VocaluxeLib.Songs; using VocaluxeLib.Songs;
-1
View File
@@ -19,7 +19,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml; using System.Xml;
using VocaluxeLib.Draw; using VocaluxeLib.Draw;
+56 -19
View File
@@ -15,11 +15,8 @@
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>. // along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms; using System.Windows.Forms;
using VocaluxeLib.PartyModes;
using VocaluxeLib.Draw; using VocaluxeLib.Draw;
using VocaluxeLib.Profile; using VocaluxeLib.Profile;
@@ -94,10 +91,7 @@ namespace VocaluxeLib.Menu
_NumPlayer = numPlayer; _NumPlayer = numPlayer;
_NumPlayerTeams = numPlayerTeams; _NumPlayerTeams = numPlayerTeams;
if (_NumTeams > 0) _TeamList = new List<int>[_NumTeams > 0 ? _NumTeams : 1];
_TeamList = new List<int>[_NumTeams];
else
_TeamList = new List<int>[1];
if (_NumTeams != _NumPlayerTeams.Length) if (_NumTeams != _NumPlayerTeams.Length)
_NumPlayerTeams = new int[_NumTeams]; _NumPlayerTeams = new int[_NumTeams];
@@ -126,7 +120,7 @@ namespace VocaluxeLib.Menu
{ {
//Handle left/right/up/down //Handle left/right/up/down
_NameSelections[_NameSelection].HandleInput(keyEvent); _NameSelections[_NameSelection].HandleInput(keyEvent);
int numberPressed = -1; int numPressed = -1;
bool resetSelection = false; bool resetSelection = false;
switch (keyEvent.Key) switch (keyEvent.Key)
{ {
@@ -157,20 +151,65 @@ namespace VocaluxeLib.Menu
case Keys.Back: case Keys.Back:
resetSelection = true; resetSelection = true;
break; break;
case Keys.D1:
case Keys.NumPad1:
numPressed = 1;
break;
case Keys.D2:
case Keys.NumPad2:
numPressed = 2;
break;
case Keys.D3:
case Keys.NumPad3:
numPressed = 3;
break;
case Keys.D4:
case Keys.NumPad4:
numPressed = 4;
break;
case Keys.D5:
case Keys.NumPad5:
numPressed = 5;
break;
case Keys.D6:
case Keys.NumPad6:
numPressed = 6;
break;
case Keys.D7:
case Keys.NumPad7:
numPressed = 7;
break;
case Keys.D8:
case Keys.NumPad8:
numPressed = 8;
break;
case Keys.D9:
case Keys.NumPad9:
numPressed = 9;
break;
} }
if (numberPressed > 0 || resetSelection) if (numPressed > 0 || resetSelection)
{ {
if (numberPressed == _SelectingFastPlayerNr || resetSelection) if (numPressed == _SelectingFastPlayerNr || resetSelection)
{ {
//Reset all values //Reset all values
_SelectingFastPlayerNr = 0; _SelectingFastPlayerNr = 0;
_SelectingKeyboardActive = false; _SelectingKeyboardActive = false;
_NameSelections[_NameSelection].FastSelection(false, -1); _NameSelections[_NameSelection].FastSelection(false, -1);
} }
else if (numberPressed <= _NumPlayerTeams[_CurrentTeam]) else if (numPressed <= _NumPlayerTeams[_CurrentTeam])
{ {
_SelectingFastPlayerNr = numberPressed; _SelectingFastPlayerNr = numPressed;
_NameSelections[_NameSelection].FastSelection(true, numberPressed); _NameSelections[_NameSelection].FastSelection(true, numPressed);
} }
_SelectingFast = false; _SelectingFast = false;
} }
@@ -530,9 +569,7 @@ namespace VocaluxeLib.Menu
public SPartyNameOptions GetData() public SPartyNameOptions GetData()
{ {
SPartyNameOptions option = new SPartyNameOptions(); SPartyNameOptions option = new SPartyNameOptions {NumPlayerTeams = _NumPlayerTeams, TeamList = _TeamList};
option.NumPlayerTeams = _NumPlayerTeams;
option.TeamList = _TeamList;
return option; return option;
} }
@@ -692,7 +729,7 @@ namespace VocaluxeLib.Menu
{ {
if (_NumPlayerTeams[team] == _TeamList[team].Count && !_ChangePlayerNumDynamic) if (_NumPlayerTeams[team] == _TeamList[team].Count && !_ChangePlayerNumDynamic)
return; return;
else if (_NumPlayerTeams[team] == _PartyMode.GetMaxPlayerPerTeam()) if (_NumPlayerTeams[team] == _PartyMode.GetMaxPlayerPerTeam())
return; return;
_NameSelections[_NameSelection].UseProfile(profileID); _NameSelections[_NameSelection].UseProfile(profileID);
@@ -707,8 +744,8 @@ namespace VocaluxeLib.Menu
{ {
List<int> ids = new List<int>(); List<int> ids = new List<int>();
ids.AddRange(_TeamList[t]); ids.AddRange(_TeamList[t]);
for (int p = 0; p < ids.Count; p++) foreach (int id in ids)
_RemovePlayer(t, ids[p]); _RemovePlayer(t, id);
} }
} }
+1 -2
View File
@@ -94,7 +94,7 @@ namespace VocaluxeLib.Menu
private int _Player = -1; private int _Player = -1;
private readonly List<int> _VisibleProfiles; private readonly List<int> _VisibleProfiles;
private List<int> _UsedProfiles; private readonly List<int> _UsedProfiles;
private CStatic _PlayerSelector; private CStatic _PlayerSelector;
@@ -416,7 +416,6 @@ namespace VocaluxeLib.Menu
_Tiles[i].Avatar.Texture = CBase.Profiles.GetAvatar(_VisibleProfiles[i + offset * _Tiles.Count]); _Tiles[i].Avatar.Texture = CBase.Profiles.GetAvatar(_VisibleProfiles[i + offset * _Tiles.Count]);
_Tiles[i].Avatar.Color = new SColorF(1, 1, 1, 1); _Tiles[i].Avatar.Color = new SColorF(1, 1, 1, 1);
_Tiles[i].Name.Text = CBase.Profiles.GetPlayerName(_VisibleProfiles[i + offset * _Tiles.Count]); _Tiles[i].Name.Text = CBase.Profiles.GetPlayerName(_VisibleProfiles[i + offset * _Tiles.Count]);
;
_Tiles[i].ProfileID = _VisibleProfiles[i + offset * _Tiles.Count]; _Tiles[i].ProfileID = _VisibleProfiles[i + offset * _Tiles.Count];
} }
else else
+2 -3
View File
@@ -214,7 +214,8 @@ namespace VocaluxeLib.Menu.SongMenu
if (_SongMenu != null) if (_SongMenu != null)
_SongMenu.OnHide(); _SongMenu.OnHide();
switch (CBase.Config.GetSongMenuType()) _Type = CBase.Config.GetSongMenuType();
switch (_Type)
{ {
//case ESongMenu.TR_CONFIG_LIST: //case ESongMenu.TR_CONFIG_LIST:
// _SongMenu = new CSongMenuList(); // _SongMenu = new CSongMenuList();
@@ -231,8 +232,6 @@ namespace VocaluxeLib.Menu.SongMenu
// _SongMenu = new CSongMenuBook(); // _SongMenu = new CSongMenuBook();
// break; // break;
} }
_Type = CBase.Config.GetSongMenuType();
} }
} }
} }
+20 -21
View File
@@ -67,11 +67,11 @@ namespace VocaluxeLib.Menu.SongMenu
{ {
set set
{ {
base._PlaySong(value); _PlaySong(value);
base._PreviewIdInternal = value; _PreviewIdInternal = value;
_UpdatePreview(); _UpdatePreview();
} }
get { return base._PreviewIdInternal; } get { return _PreviewIdInternal; }
} }
public override int GetActualSelection() public override int GetActualSelection()
@@ -138,7 +138,7 @@ namespace VocaluxeLib.Menu.SongMenu
} }
if (_Length < 0 && CBase.Sound.GetLength(_PreviewSongStream) > 0 && CBase.Songs.IsInCategory()) if (_Length < 0 && CBase.Sound.GetLength(_PreviewSongStream) > 0 && CBase.Songs.IsInCategory())
UpdateLength(CBase.Songs.GetVisibleSong(_PreviewId)); _UpdateLength(CBase.Songs.GetVisibleSong(_PreviewId));
} }
private void _UpdatePreview() private void _UpdatePreview()
@@ -181,7 +181,7 @@ namespace VocaluxeLib.Menu.SongMenu
_MedleyCalcIcon.Visible = song.Medley.Source == EDataSource.Calculated; _MedleyCalcIcon.Visible = song.Medley.Source == EDataSource.Calculated;
_MedleyTagIcon.Visible = song.Medley.Source == EDataSource.Tag; _MedleyTagIcon.Visible = song.Medley.Source == EDataSource.Tag;
UpdateLength(song); _UpdateLength(song);
} }
else else
{ {
@@ -198,23 +198,22 @@ namespace VocaluxeLib.Menu.SongMenu
} }
} }
private void UpdateLength(CSong song) private void _UpdateLength(CSong song)
{ {
if (song != null) if (song == null)
{ return;
float time = CBase.Sound.GetLength(_PreviewSongStream); float time = CBase.Sound.GetLength(_PreviewSongStream);
if (Math.Abs(song.Finish) > 0.001) if (Math.Abs(song.Finish) > 0.001)
time = song.Finish; time = song.Finish;
// The audiobackend is not yet ready to return the length // The audiobackend is ready to return the length
if (time > 0) if (time > 0)
{ {
time -= song.Start; time -= song.Start;
var min = (int)Math.Floor(time / 60f); var min = (int)Math.Floor(time / 60f);
var sec = (int)(time - min * 60f); var sec = (int)(time - min * 60f);
_SongLength.Text = min.ToString("00") + ":" + sec.ToString("00"); _SongLength.Text = min.ToString("00") + ":" + sec.ToString("00");
_Length = time; _Length = time;
}
} }
} }
@@ -556,7 +555,7 @@ namespace VocaluxeLib.Menu.SongMenu
public override void SetSelectedSong(int visibleSongNr) public override void SetSelectedSong(int visibleSongNr)
{ {
base._PlaySong(visibleSongNr); _PlaySong(visibleSongNr);
base.SetSelectedSong(visibleSongNr); base.SetSelectedSong(visibleSongNr);
if (visibleSongNr >= 0 && visibleSongNr < CBase.Songs.GetNumSongsVisible()) if (visibleSongNr >= 0 && visibleSongNr < CBase.Songs.GetNumSongsVisible())
+1 -1
View File
@@ -49,7 +49,7 @@ namespace VocaluxeLib.Profile
CBase.Drawing.RemoveTexture(ref Texture); CBase.Drawing.RemoveTexture(ref Texture);
} }
public string getFileName() public string GetFileName()
{ {
return FileName; return FileName;
} }
+6 -5
View File
@@ -17,7 +17,6 @@
using System; using System;
using System.IO; using System.IO;
using System.Text;
using System.Xml; using System.Xml;
namespace VocaluxeLib.Profile namespace VocaluxeLib.Profile
@@ -71,9 +70,11 @@ namespace VocaluxeLib.Profile
FileName = String.Empty; FileName = String.Empty;
} }
public bool LoadProfile() public bool LoadProfile(string pathName, string fileName)
{ {
return LoadProfile(FilePath, FileName); FilePath = pathName;
FileName = fileName;
return LoadProfile();
} }
public bool LoadProfile(string file) public bool LoadProfile(string file)
@@ -81,10 +82,10 @@ namespace VocaluxeLib.Profile
FileName = Path.GetFileName(file); FileName = Path.GetFileName(file);
FilePath = Path.GetDirectoryName(file); FilePath = Path.GetDirectoryName(file);
return LoadProfile(FilePath, FileName); return LoadProfile();
} }
public bool LoadProfile(string pathName, string fileName) public bool LoadProfile()
{ {
CXMLReader xmlReader = CXMLReader.OpenFile(Path.Combine(FilePath, FileName)); CXMLReader xmlReader = CXMLReader.OpenFile(Path.Combine(FilePath, FileName));
if (xmlReader == null) if (xmlReader == null)
+5 -11
View File
@@ -63,15 +63,10 @@ namespace VocaluxeLib.Songs
{ {
get get
{ {
int min = int.MaxValue; if (_Notes.Count == 0)
int max = int.MinValue; return 0;
foreach (T note in _Notes) int min = _Notes.Min(note => note.Tone);
{ int max = _Notes.Max(note => note.Tone);
if (note.Tone < min)
min = note.Tone;
if (note.Tone > max)
max = note.Tone;
}
return min - (max - min) / 4; return min - (max - min) / 4;
} }
@@ -140,11 +135,10 @@ namespace VocaluxeLib.Songs
return false; return false;
} }
public bool IncLastNoteLength() public void IncLastNoteLength()
{ {
if (_Notes.Count > 0) if (_Notes.Count > 0)
_Notes[NoteCount - 1].Duration++; _Notes[NoteCount - 1].Duration++;
return false;
} }
public void DeleteAllNotes() public void DeleteAllNotes()
+1 -1
View File
@@ -97,7 +97,7 @@ namespace VocaluxeLib.Songs
public string MP3FileName = String.Empty; public string MP3FileName = String.Empty;
public string CoverFileName = String.Empty; public string CoverFileName = String.Empty;
public List<string> BackgroundFileNames = new List<string>(); public readonly List<string> BackgroundFileNames = new List<string>();
public string VideoFileName = String.Empty; public string VideoFileName = String.Empty;
public EAspect VideoAspect = EAspect.Crop; public EAspect VideoAspect = EAspect.Crop;
+1 -1
View File
@@ -81,7 +81,7 @@ namespace VocaluxeLib.Songs
msg = (error ? "Error: " : "Warning: ") + msg; msg = (error ? "Error: " : "Warning: ") + msg;
if (withLineNr) if (withLineNr)
msg += " in line #" + _LineNr; msg += " in line #" + _LineNr;
CBase.Log.LogError(msg + " (" + Path.Combine(_Song.Folder, _Song.FileName) + ")"); CBase.Log.LogSongInfo(msg + " (" + Path.Combine(_Song.Folder, _Song.FileName) + ")");
} }
private void _LogError(string msg, bool withLineNr = true) private void _LogError(string msg, bool withLineNr = true)
+1
View File
@@ -41,6 +41,7 @@ namespace VocaluxeLib.Songs
/// <param name="duration"></param> /// <param name="duration"></param>
/// <param name="tone"></param> /// <param name="tone"></param>
/// <param name="hitNote"></param> /// <param name="hitNote"></param>
/// <param name="points"></param>
public CSungNote(int startBeat, int duration, int tone, CSongNote hitNote, double points) : this(startBeat, duration, tone) public CSungNote(int startBeat, int duration, int tone, CSongNote hitNote, double points) : this(startBeat, duration, tone)
{ {
HitNote = hitNote; HitNote = hitNote;
+1 -3
View File
@@ -205,15 +205,13 @@ namespace VocaluxeLib.Songs
public void UpdateTimings() public void UpdateTimings()
{ {
CSongNote lastNote;
if (_Lines.Count == 0) if (_Lines.Count == 0)
return; return;
_Lines[0].StartBeat = -10000; _Lines[0].StartBeat = -10000;
for (int i = 1; i < _Lines.Count; i++) for (int i = 1; i < _Lines.Count; i++)
{ {
lastNote = _Lines[i - 1].LastNote; CSongNote lastNote = _Lines[i - 1].LastNote;
CSongNote firstNote = _Lines[i].FirstNote; CSongNote firstNote = _Lines[i].FirstNote;
if ((lastNote != null) && (firstNote != null)) if ((lastNote != null) && (firstNote != null))
+3 -5
View File
@@ -190,20 +190,18 @@ namespace VocaluxeLib
public int CurrentNote; public int CurrentNote;
public int SongID; public int SongID;
public bool Medley; public EGameMode GameMode;
public bool Duet;
public bool ShortSong;
public long DateTicks; public long DateTicks;
public bool SongFinished; public bool SongFinished;
} }
public struct SScores public struct SDBScoreEntry
{ {
public string Name; public string Name;
public int Score; public int Score;
public string Date; public string Date;
public EGameDifficulty Difficulty; public EGameDifficulty Difficulty;
public int LineNr; public int VoiceNr;
public int ID; public int ID;
} }
+144 -49
View File
@@ -15,6 +15,8 @@
// along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>. // along with Vocaluxe. If not, see <http://www.gnu.org/licenses/>.
#endregion #endregion
using System.Security.Authentication;
using System.Security.Principal;
using Security.Cryptography; using Security.Cryptography;
using Security.Cryptography.X509Certificates; using Security.Cryptography.X509Certificates;
using System; using System;
@@ -26,34 +28,64 @@ using NetFwTypeLib;
namespace WebserverInitalConfig namespace WebserverInitalConfig
{ {
public static class CConfigHttpApi public class CConfigHttpApi
{ {
// ReSharper disable InconsistentNaming // ReSharper disable InconsistentNaming
private const String CLSID_NetFwMgr = "{304CE942-6E39-40D8-943A-B913C40C9CD4}"; private const String CLSID_NetFwMgr = "{304CE942-6E39-40D8-943A-B913C40C9CD4}";
private const String CLSID_NetAuthApp = "{EC9846B3-2762-4A6B-A214-6ACB603462D2}"; private const String CLSID_NetAuthApp = "{EC9846B3-2762-4A6B-A214-6ACB603462D2}";
private const String CLSID_NetOpenPort = "{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}"; private const String CLSID_NetOpenPort = "{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}";
private const string _AppGUID = "{7baf41f1-48b7-42cb-b145-f815499cb48f}";
// ReSharper restore InconsistentNaming // ReSharper restore InconsistentNaming
public static void ReserveUrl(string networkString)
private readonly string _RuleName;
private readonly string _ExePath;
private readonly string _IP;
private readonly int _Port;
private readonly bool _IsTCP;
public CConfigHttpApi(string ruleName, string exePath, string ip, int port, bool isTCP)
{ {
_ExePath = exePath;
_Port = port;
_IsTCP = isTCP;
_IP = ip;
_RuleName = ruleName;
}
private static void _ReserveUrl(string networkString)
{
if (!IsAdministrator())
throw new AuthenticationException();
HttpApi.ReserveURL(networkString, "D:(A;;GX;;;S-1-1-0)"); HttpApi.ReserveURL(networkString, "D:(A;;GX;;;S-1-1-0)");
} }
public static void BindCert(string ip, int port, X509Certificate2 cert) public void ReserveUrl()
{ {
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ip), port); _ReserveUrl("https://+:" + _Port + "/");
if (HttpApi.QuerySslCertificateInfo(endpoint) != null)
HttpApi.DeleteCertificateBinding(endpoint);
HttpApi.BindCertificate(endpoint, cert.GetCertHash(), StoreName.My, new Guid("{7baf41f1-48b7-42cb-b145-f815499cb48f}"));
} }
public static void AddCertToStore(X509Certificate2 cert) private void _BindCert(X509Certificate cert)
{
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(_IP), _Port);
HttpApi.SslCertificateInfo certificateInfo = HttpApi.QuerySslCertificateInfo(endpoint);
if (certificateInfo != null && !certificateInfo.Hash.SequenceEqual(cert.GetCertHash()))
{
if (!IsAdministrator())
throw new AuthenticationException();
HttpApi.DeleteCertificateBinding(endpoint);
HttpApi.BindCertificate(endpoint, cert.GetCertHash(), StoreName.My, new Guid(_AppGUID));
}
}
private static void _AddCertToStore(X509Certificate2 cert)
{ {
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite); store.Open(OpenFlags.ReadWrite);
X509Certificate2Collection oldCerts = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, // ReSharper disable AssignNullToNotNullAttribute
cert.SubjectName.Name, false); X509Certificate2Collection oldCerts = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.SubjectName.Name, false);
// ReSharper restore AssignNullToNotNullAttribute
foreach (X509Certificate2 oldCert in oldCerts) foreach (X509Certificate2 oldCert in oldCerts)
store.Remove(oldCert); store.Remove(oldCert);
@@ -62,7 +94,25 @@ namespace WebserverInitalConfig
store.Close(); store.Close();
} }
public static X509Certificate2 GetSelfSignedCert(string subjectName) private static X509Certificate2 _GetCert(string name)
{
X509Certificate2 result = null;
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var name2 = new X500DistinguishedName(name);
// ReSharper disable AssignNullToNotNullAttribute
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, name2.Name, false);
// ReSharper restore AssignNullToNotNullAttribute
if (certs.Count > 0)
result = certs[0];
store.Close();
return result;
}
private X509Certificate2 _GetSelfSignedCert(string subjectName)
{ {
var keyParam = new CngKeyCreationParameters var keyParam = new CngKeyCreationParameters
{ {
@@ -91,58 +141,103 @@ namespace WebserverInitalConfig
byte[] rawData = key.CreateSelfSignedCertificate(param).Export(X509ContentType.Pfx, ""); byte[] rawData = key.CreateSelfSignedCertificate(param).Export(X509ContentType.Pfx, "");
var cert = new X509Certificate2(rawData, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet) var cert = new X509Certificate2(rawData, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet)
{ {
FriendlyName = "Vocaluxe Server Certificate" FriendlyName = _RuleName + " Server Certificate"
}; };
return cert; return cert;
} }
private static void _AddFirewallRuleForProfile(INetFwProfile profile, string exePath, int port, bool isTCP) public void CreateAndAddCert(string hostName)
{ {
bool isFirewallEnabled = profile.FirewallEnabled; string certName = "CN=" + hostName + ", C=DE, O=" + _RuleName + ", OU=" + _RuleName + " Server";
if (!isFirewallEnabled) X509Certificate2 cert = _GetCert(certName);
return; if (cert == null)
INetFwAuthorizedApplications applications = profile.AuthorizedApplications;
if (!(from INetFwAuthorizedApplication a in applications
where a.ProcessImageFileName == exePath
select a).Any())
{ {
INetFwAuthorizedApplication application = (INetFwAuthorizedApplication)Activator.CreateInstance( if (!IsAdministrator())
Type.GetTypeFromCLSID(new Guid(CLSID_NetAuthApp))); throw new AuthenticationException();
cert = _GetSelfSignedCert(certName);
application.Name = "Vocaluxe"; _AddCertToStore(cert);
application.ProcessImageFileName = exePath;
application.Enabled = true;
application.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
applications.Add(application);
}
INetFwOpenPorts openPorts = profile.GloballyOpenPorts;
NET_FW_IP_PROTOCOL_ protocol = isTCP ? NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP : NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
if (!(from INetFwOpenPort p in openPorts
where (p.Port == port &&
(p.Protocol == protocol))
select p).Any())
{
INetFwOpenPort openPort = (INetFwOpenPort)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSID_NetOpenPort)));
openPort.Enabled = true;
openPort.Port = port;
openPort.Protocol = protocol;
openPort.Name = "Vocaluxe(" + port + ")";
openPort.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
openPorts.Add(openPort);
} }
_BindCert(cert);
} }
public static void AddFirewallRule(string exePath, int port, bool isTCP) private bool _IsAppAuthorized(INetFwProfile profile)
{
if (!profile.FirewallEnabled)
return true;
return profile.AuthorizedApplications.Cast<INetFwAuthorizedApplication>().Any(a => a.ProcessImageFileName == _ExePath);
}
private bool _IsPortOpen(INetFwProfile profile)
{
NET_FW_IP_PROTOCOL_ protocol = _GetProtocol();
if (!profile.FirewallEnabled)
return true;
return profile.GloballyOpenPorts.Cast<INetFwOpenPort>().Any(p => p.Protocol == protocol && p.Port == _Port);
}
private NET_FW_IP_PROTOCOL_ _GetProtocol()
{
return _IsTCP ? NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP : NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
}
private void _AddFirewallRuleForProfile(INetFwProfile profile)
{
bool isAppAuthorized = _IsAppAuthorized(profile);
bool isPortOpen = _IsPortOpen(profile);
if ((!isAppAuthorized || !isPortOpen) && !IsAdministrator())
throw new AuthenticationException();
if (!isAppAuthorized)
_AddAppToFirewall(profile);
if (!isPortOpen)
_AddPortToFirewall(profile);
}
private void _AddPortToFirewall(INetFwProfile profile)
{
INetFwOpenPort openPort = (INetFwOpenPort)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSID_NetOpenPort)));
openPort.Enabled = true;
openPort.Port = _Port;
openPort.Protocol = _GetProtocol();
openPort.Name = _RuleName + "(" + _Port + ")";
openPort.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
profile.GloballyOpenPorts.Add(openPort);
}
private void _AddAppToFirewall(INetFwProfile profile)
{
INetFwAuthorizedApplication application = (INetFwAuthorizedApplication)Activator.CreateInstance(
Type.GetTypeFromCLSID(new Guid(CLSID_NetAuthApp)));
application.Name = _RuleName;
application.ProcessImageFileName = _ExePath;
application.Enabled = true;
application.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
profile.AuthorizedApplications.Add(application);
}
public static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
// ReSharper disable AssignNullToNotNullAttribute
WindowsPrincipal principal = new WindowsPrincipal(identity);
// ReSharper restore AssignNullToNotNullAttribute
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
public void AddFirewallRule()
{ {
INetFwMgr manage = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSID_NetFwMgr))); INetFwMgr manage = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSID_NetFwMgr)));
//AddFirewallRuleForProfile(manage.LocalPolicy.CurrentProfile, exePath, port, isTCP); //_AddFirewallRuleForProfile(manage.LocalPolicy.CurrentProfile);
//if (manage.CurrentProfileType != NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD) //if (manage.CurrentProfileType != NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD)
//Add to Home/Work(Private) and current net //Add to Home/Work(Private) and current net
//TODO: This somewhow adds 2 entries each instead of only one that is activated for Home/Work and public nets //TODO: This somewhow adds 2 entries each instead of only one that is activated for Home/Work and public nets
_AddFirewallRuleForProfile(manage.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD), exePath, port, isTCP); _AddFirewallRuleForProfile(manage.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD));
_AddFirewallRuleForProfile(manage.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_CURRENT), exePath, port, isTCP); _AddFirewallRuleForProfile(manage.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_CURRENT));
} }
/*public static X509Certificate2 getCert(string subject) /*public static X509Certificate2 getCert(string subject)
-3
View File
@@ -18,13 +18,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace WebserverInitalConfig namespace WebserverInitalConfig
{ {
+43 -15
View File
@@ -16,34 +16,62 @@
#endregion #endregion
using System; using System;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Security.Cryptography.X509Certificates; using System.Security.Authentication;
namespace WebserverInitalConfig namespace WebserverInitalConfig
{ {
class Program static class CProgram
{ {
// ReSharper disable InconsistentNaming
private static void Main(string[] args) private static void Main(string[] args)
// ReSharper restore InconsistentNaming
{ {
if (args.Length != 2) int port;
if (args.Length < 2 || !int.TryParse(args[0], out port))
{ {
Console.WriteLine("Usage: VocaluxeServerConfig port isHttps"); Console.WriteLine("Usage: VocaluxeServerConfig port isHttps");
Environment.Exit(-1); Environment.Exit(-1);
} }
CConfigHttpApi.AddFirewallRule(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Vocaluxe.exe"), Int32.Parse(args[0]), true);
if (args[1].ToLower() == "true")
{
string hostname = Dns.GetHostName();
X509Certificate2 cert = CConfigHttpApi.GetSelfSignedCert("CN=" + hostname + " C=DE O=Vocaluxe OU=Vocaluxe Server");
CConfigHttpApi.AddCertToStore(cert);
CConfigHttpApi.BindCert("0.0.0.0", Int32.Parse(args[0]), cert);
CConfigHttpApi.ReserveUrl("https://+:" + args[0] + "/");
}
else else
CConfigHttpApi.ReserveUrl("http://+:" + args[0] + "/"); {
CConfigHttpApi config = new CConfigHttpApi("Vocaluxe", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Vocaluxe.exe"), "0.0.0.0", port, true);
try
{
config.AddFirewallRule();
if (args[1].ToLower() == "true")
config.CreateAndAddCert(Dns.GetHostName());
if ((args.Length >= 3 && args[2] == "reserve") || CConfigHttpApi.IsAdministrator())
config.ReserveUrl();
}
catch (AuthenticationException)
{
ProcessStartInfo proc = new ProcessStartInfo
{
UseShellExecute = true,
WorkingDirectory = Environment.CurrentDirectory,
FileName = Process.GetCurrentProcess().MainModule.FileName,
Arguments = args[0] + " " + args[1],
Verb = "runas",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
};
try
{
Process.Start(proc);
}
catch
{
// The user refused the elevation.
// Do nothing and return directly ...
Environment.Exit(-1);
}
}
}
} }
} }
} }
@@ -16,7 +16,6 @@
#endregion #endregion
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden // Allgemeine Informationen über eine Assembly werden über die folgenden
@@ -32,9 +32,6 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup>
<PropertyGroup> <PropertyGroup>
<ApplicationIcon>Vocaluxe.ico</ApplicationIcon> <ApplicationIcon>Vocaluxe.ico</ApplicationIcon>
</PropertyGroup> </PropertyGroup>