Fixed issues, retargeted main view, got compiling

This commit is contained in:
Brychan Dempsey 2021-11-02 15:02:12 +13:00
parent f461603023
commit d54f975b5c
9 changed files with 145 additions and 362 deletions

View File

@ -2,5 +2,5 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RBG_Server" xmlns:local="clr-namespace:RBG_Server"
StartupUri="MainWindow.xaml"> StartupUri="ConnectionPage.xaml">
</Application> </Application>

View File

@ -10,6 +10,7 @@ using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using System.Windows.Navigation;
namespace RBG_Server namespace RBG_Server
{ {
@ -31,6 +32,13 @@ namespace RBG_Server
public const string MIP_HIGH = "_mip_high"; public const string MIP_HIGH = "_mip_high";
public const string MIP_RAW = "_mip_raw"; public const string MIP_RAW = "_mip_raw";
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Context = this;
GameCommunicationHandler = new CommunicationHandler();
}
/// <summary> /// <summary>
/// Loads the specified files from disk, creating mip maps as appropriate /// Loads the specified files from disk, creating mip maps as appropriate
/// </summary> /// </summary>
@ -121,7 +129,8 @@ namespace RBG_Server
BitmapImage bitmapImage = new(); BitmapImage bitmapImage = new();
bitmapImage.BeginInit(); bitmapImage.BeginInit();
bitmapImage.StreamSource = source; bitmapImage.StreamSource = source;
bitmapImage.CacheOption = BitmapCacheOption.None; bitmapImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile | BitmapCreateOptions.PreservePixelFormat;
bitmapImage.CacheOption = BitmapCacheOption.Default;
bitmapImage.EndInit(); bitmapImage.EndInit();
int height = bitmapImage.PixelHeight; int height = bitmapImage.PixelHeight;
int width = bitmapImage.PixelWidth; int width = bitmapImage.PixelWidth;
@ -194,15 +203,28 @@ namespace RBG_Server
GameCommunicationHandler.ImageCollection.Remove(GameCommunicationHandler.BoardName, out CachedByteArray val); GameCommunicationHandler.ImageCollection.Remove(GameCommunicationHandler.BoardName, out CachedByteArray val);
val.Dispose(); val.Dispose();
} }
GameCommunicationHandler.BoardName = path; GameCommunicationHandler.BoardName = Path.GetFileNameWithoutExtension(path);
} }
GameCommunicationHandler.ImageList.Add(path); GameCommunicationHandler.ImageList.Add(Path.GetFileNameWithoutExtension(path));
} }
} }
MemoryStream ScaleImage(BitmapSource source, double scaleRate) static MemoryStream ScaleImage(BitmapSource source, double scaleRate)
{ {
TransformedBitmap modified = new(source, new ScaleTransform(source.PixelWidth * scaleRate, source.PixelHeight * scaleRate)); TransformedBitmap modified = new();
try
{
ScaleTransform transform = new ScaleTransform(scaleRate, scaleRate);
modified.BeginInit();
modified.Source = source;
modified.Transform = transform;
modified.EndInit();
//modified = new(source, );
}
catch (Exception ex)
{
int op = 0;
}
PngBitmapEncoder encoder = new(); PngBitmapEncoder encoder = new();
encoder.Frames.Add(BitmapFrame.Create(modified)); encoder.Frames.Add(BitmapFrame.Create(modified));
MemoryStream ms = new(); MemoryStream ms = new();
@ -210,7 +232,7 @@ namespace RBG_Server
return ms; return ms;
} }
MemoryStream ScaleAnimatedImage(BitmapFrame[] frames, double scaleRate) static MemoryStream ScaleAnimatedImage(BitmapFrame[] frames, double scaleRate)
{ {
PngBitmapEncoder encoder = new(); PngBitmapEncoder encoder = new();
foreach (BitmapFrame frame in frames) foreach (BitmapFrame frame in frames)

View File

@ -1,19 +1,17 @@
<Page x:Class="RBG_Server_WPF.ConnectionPage" <Window x:Class="RBG_Server_WPF.ConnectionPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:RBG_Server_WPF" mc:Ignorable="d"
mc:Ignorable="d" Title="PDG Server" Height="768" Width="1024" Background="#FF4B4B4B">
d:DesignHeight="450" d:DesignWidth="800"
Title="ConnectionPage" MinWidth="1024" MinHeight="762">
<Grid x:Name="RootGrid" IsEnabled="False"> <Grid x:Name="RootGrid">
<StackPanel x:Name="ServerSelectPanel" HorizontalAlignment="Center" VerticalAlignment="Center" d:IsHidden="True" > <StackPanel x:Name="ServerSelectPanel" HorizontalAlignment="Center" VerticalAlignment="Center" >
<Button x:Name="HostButton" Content="Host a Game" Margin="0,0,0,5" Click="HostButton_Click"/> <Button x:Name="HostButton" Content="Host a Game" Margin="0,0,0,5" Click="HostButton_Click"/>
<Button x:Name="ConnectButton" Content="Connect to Server" Margin="0,5,0,0" Click="ConnectButton_Click"/> <Button x:Name="ConnectButton" Content="Connect to Server" Margin="0,5,0,0" Click="ConnectButton_Click"/>
</StackPanel> </StackPanel>
<Grid x:Name="ServerGrid"> <Grid x:Name="ServerGrid" d:IsHidden="True" Visibility="Collapsed">
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition MaxWidth="400"/> <ColumnDefinition MaxWidth="400"/>
<ColumnDefinition/> <ColumnDefinition/>
@ -50,7 +48,7 @@
<Grid x:Name="PreviewImageOverlay" HorizontalAlignment="Center" VerticalAlignment="Center" Width="{Binding ActualWidth, ElementName=PreviewImage}" Height="{Binding ActualHeight, ElementName=PreviewImage}"/> <Grid x:Name="PreviewImageOverlay" HorizontalAlignment="Center" VerticalAlignment="Center" Width="{Binding ActualWidth, ElementName=PreviewImage}" Height="{Binding ActualHeight, ElementName=PreviewImage}"/>
</Grid> </Grid>
</Grid> </Grid>
<Grid x:Name="ClientGrid" d:IsHidden="True"> <Grid x:Name="ClientGrid" d:IsHidden="True" Visibility="Collapsed">
<StackPanel> <StackPanel>
<Button x:Name="ClientBackButton" Content="Back" Margin="0,5,0,0" HorizontalAlignment="Center" Click="ClientBackButton_Click"/> <Button x:Name="ClientBackButton" Content="Back" Margin="0,5,0,0" HorizontalAlignment="Center" Click="ClientBackButton_Click"/>
<TextBlock Text="Server Address:" TextWrapping="Wrap" Padding="0,10,0,0" Foreground="White" HorizontalAlignment="Center"/> <TextBlock Text="Server Address:" TextWrapping="Wrap" Padding="0,10,0,0" Foreground="White" HorizontalAlignment="Center"/>
@ -70,4 +68,4 @@
</Grid> </Grid>
</Page> </Window>

View File

@ -24,7 +24,7 @@ namespace RBG_Server_WPF
/// <summary> /// <summary>
/// Interaction logic for ConnectionPage.xaml /// Interaction logic for ConnectionPage.xaml
/// </summary> /// </summary>
public partial class ConnectionPage : Page public partial class ConnectionPage : Window
{ {
public ConnectionPage() public ConnectionPage()
{ {
@ -260,7 +260,9 @@ namespace RBG_Server_WPF
if (ofd.ShowDialog() == true) if (ofd.ShowDialog() == true)
{ {
ImageSourceTextBox.Text = ofd.FileName; ImageSourceTextBox.Text = ofd.FileName;
UpdateImage().Start();
Task.Run(() => UpdateImage(ofd.FileName));
} }
} }
/// <summary> /// <summary>
@ -270,34 +272,38 @@ namespace RBG_Server_WPF
/// <param name="e"></param> /// <param name="e"></param>
private void ImageSourceTextBox_LostFocus(object sender, RoutedEventArgs e) private void ImageSourceTextBox_LostFocus(object sender, RoutedEventArgs e)
{ {
UpdateImage().Start(); //UpdateImage().Start();
} }
private Task UpdateImage() private void UpdateImage(string sourceFile)
{ {
try try
{ {
CommunicationHandler host = App.Context.GameCommunicationHandler; CommunicationHandler host = App.Context.GameCommunicationHandler;
using FileStream fs = File.OpenRead(ImageSourceTextBox.Text); using FileStream fs = File.OpenRead(sourceFile);
using MemoryStream ms = new(); using MemoryStream ms = new();
fs.CopyTo(ms); fs.CopyTo(ms);
// Calc mips // Calc mips
ms.Position = 0; ms.Position = 0;
App.Context.LoadStream(ms, Name, false); App.Context.LoadStream(ms, sourceFile, false);
ms.Position = 0; ms.Position = 0;
BitmapImage gameBoardImage = new();
gameBoardImage.BeginInit(); this.Dispatcher.Invoke(() => {
gameBoardImage.StreamSource = ms; BitmapImage gameBoardImage = new();
gameBoardImage.EndInit(); gameBoardImage.BeginInit();
PreviewImage.Source = gameBoardImage; gameBoardImage.StreamSource = ms;
RedrawGrid(); gameBoardImage.CacheOption = BitmapCacheOption.OnLoad;
gameBoardImage.EndInit();
PreviewImage.Source = gameBoardImage;
RedrawGrid();
}, System.Windows.Threading.DispatcherPriority.Render);
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine(e); Console.WriteLine(e);
} }
return Task.CompletedTask;
} }
/// <summary> /// <summary>
@ -371,10 +377,44 @@ namespace RBG_Server_WPF
} }
} }
} }
private void GridVisibilityToggleButton_Click(object sender, RoutedEventArgs e)
{
PreviewImageOverlay.Visibility = PreviewImageOverlay.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}
/// <summary>
/// Performs the logic required to start the server
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StartServerButton_Click(object sender, RoutedEventArgs e)
{
CommunicationHandler host = App.Context.GameCommunicationHandler;
host.InitialiseServer((int)NumberOfRows.Value, (int)NumberOfColumns.Value, (int)ZoomBoxStartRow.Value, (int)ZoomBoxStartColumn.Value, (int)ZoomBoxSpan.Value, (int)ZoomBoxSpan.Value, (int)StartingRow.Value, (int)StartingColumn.Value);
}
#endregion #endregion
private void Sliders_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
}
private void NumberOfRows_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
}
private void DrawRandomizedPlayers_Click(object sender, RoutedEventArgs e)
{
}
private void NumberOfColumns_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
}
} }
} }

View File

@ -11,36 +11,6 @@
<ColumnDefinition/> <ColumnDefinition/>
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<Grid> <Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition MaxWidth="300"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock Text="Game Board File Path" TextWrapping="Wrap" Padding="0,10,0,0" Foreground="White" Margin="2,5,2,0"/>
<TextBox x:Name="ImageSourceTextBox" TextWrapping="Wrap" LostFocus="ImageSourceTextBox_LostFocus" Margin="2,5,2,0"/>
<Button x:Name="BrowseButton" Content="Browse" Click="BrowseButton_Click" Margin="10,5,10,0"/>
<TextBlock Text="Game Sprites Files" TextWrapping="Wrap" Padding="0,10,0,0" Foreground="White" Margin="2,0,2,0"/>
<TextBox x:Name="ImageSourceTextBox_Copy" TextWrapping="Wrap" LostFocus="ImageSourceTextBox_LostFocus" Margin="2,5,2,0"/>
<Button x:Name="GameSpritesBrowser" Content="Browse" Click="GameSpritesBrowser_Click" Margin="10,5,10,0"/>
<TextBlock Text="Number of Rows" TextWrapping="Wrap" Padding="0,10,0,0" Foreground="White" Margin="2,0,2,0"/>
<Slider x:Name="NumberOfRows" IsSnapToTickEnabled="True" Minimum="1" TickPlacement="BottomRight" AutoToolTipPlacement="BottomRight" ValueChanged="NumberOfRows_ValueChanged" Value="9" Margin="2,0,2,0"/>
<TextBlock Text="Number of Columns:" TextWrapping="Wrap" Padding="0,10,0,0" Foreground="White" Margin="2,0,2,0"/>
<Slider x:Name="NumberOfColumns" IsSnapToTickEnabled="True" Minimum="1" TickPlacement="BottomRight" AutoToolTipPlacement="BottomRight" ValueChanged="NumberOfColumns_ValueChanged" Value="9" Margin="2,0,2,0"/>
<TextBlock Text="Starting Row" TextWrapping="Wrap" Padding="0,10,0,0" Foreground="White" Margin="2,0,2,0"/>
<Slider x:Name="StartingRow" IsSnapToTickEnabled="True" Value="8" AutoToolTipPlacement="BottomRight" TickPlacement="BottomRight" ValueChanged="Sliders_ValueChanged" Maximum="9" Margin="2,0,2,0"/>
<TextBlock Text="Starting Column" TextWrapping="Wrap" Padding="0,10,0,0" Foreground="White" Margin="2,0,2,0"/>
<Slider x:Name="StartingColumn" IsSnapToTickEnabled="True" AutoToolTipPlacement="BottomRight" TickPlacement="BottomRight" ValueChanged="Sliders_ValueChanged" Maximum="9" Margin="2,0,2,0"/>
<TextBlock Text="Zoom Box Starting Row" TextWrapping="Wrap" Padding="0,10,0,0" Foreground="White" Margin="2,0,2,0"/>
<Slider x:Name="ZoomBoxStartRow" IsSnapToTickEnabled="True" AutoToolTipPlacement="BottomRight" TickPlacement="BottomRight" Value="3" ValueChanged="Sliders_ValueChanged" Maximum="9" Margin="2,0,2,0"/>
<TextBlock Text="Zoom Box Starting Column" TextWrapping="Wrap" Padding="0,10,0,0" Foreground="White" Margin="2,0,2,0"/>
<Slider x:Name="ZoomBoxStartColumn" IsSnapToTickEnabled="True" AutoToolTipPlacement="BottomRight" TickPlacement="BottomRight" Value="3" ValueChanged="Sliders_ValueChanged" Maximum="9" Margin="2,0,2,0"/>
<TextBlock Text="Zoom Box Span" TextWrapping="Wrap" Padding="0,10,0,0" Foreground="White" Margin="2,0,2,0"/>
<Slider x:Name="ZoomBoxSpan" IsSnapToTickEnabled="True" AutoToolTipPlacement="BottomRight" TickPlacement="BottomRight" Value="3" ValueChanged="Sliders_ValueChanged" Minimum="1" Maximum="6" Margin="2,0,2,0"/>
<Button x:Name="GridVisibilityToggleButton" Content="Show/Hide Grid" Click="GridVisibilityToggleButton_Click" Margin="10,10,10,0"/>
<Button x:Name="StartServerButton" Content="Start Server" HorizontalAlignment="Stretch" Margin="10,25,10,0" Click="StartServerButton_Click" Background="#955FF17A" Foreground="White"/>
<Button x:Name="DrawRandomizedPlayers" Content="Draw Random Players" Margin="10,25,10,0" Click="DrawRandomizedPlayers_Click"/>
<UniformGrid x:Name="LoadedSprites" Columns="6" Margin="2,0,2,0" Rows="6" MinHeight="120" />
</StackPanel>
<Border Grid.Column="1" BorderThickness="1,1,1,1" BorderBrush="DarkGray" Background="#19000000"> <Border Grid.Column="1" BorderThickness="1,1,1,1" BorderBrush="DarkGray" Background="#19000000">
<Grid> <Grid>
<Grid.RowDefinitions> <Grid.RowDefinitions>

View File

@ -35,131 +35,51 @@ namespace RBG_Server.WPF
InitializeComponent(); InitializeComponent();
} }
/// <summary>
/// Browse for game board file button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new();
ofd.Filter = "Image Files|*.png;*.jpg";
if (ofd.ShowDialog() == true)
{
ImageSourceTextBox.Text = ofd.FileName;
UpdateImage();
}
}
/// <summary>
/// Update the image when the text box looses focus
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ImageSourceTextBox_LostFocus(object sender, RoutedEventArgs e)
{
UpdateImage();
}
private void UpdateImage()
{
try
{
using FileStream fs = File.OpenRead(ImageSourceTextBox.Text);
using MemoryStream ms = new();
fs.CopyTo(ms); // Load into memory, so the server can also utilise the stream
gameBoard = ms.ToArray();
BitmapImage gameBoardImage = new();
gameBoardImage.BeginInit();
gameBoardImage.StreamSource = new MemoryStream(gameBoard, false);
//gameBoardImage.CacheOption = BitmapCacheOption.OnLoad; // Must preload the image into memory, before it is unloaded
gameBoardImage.EndInit();
PreviewImage.Source = gameBoardImage;
RedrawGrid();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
/// <summary>
/// Creates and starts the game server
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StartServerButton_Click(object sender, RoutedEventArgs e)
{
gameServer = new((byte)StartingRow.Value, (byte)StartingColumn.Value, (byte)NumberOfRows.Value, (byte)NumberOfColumns.Value, (byte)ZoomBoxStartRow.Value, (byte)ZoomBoxStartColumn.Value, (byte)ZoomBoxSpan.Value, (byte)ZoomBoxSpan.Value, gameBoard);
}
private void NumberOfRows_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (IsInitialized)
{
StartingRow.Maximum = NumberOfRows.Value;
ZoomBoxStartRow.Maximum = NumberOfRows.Value;
ZoomBoxSpan.Maximum = Math.Min(NumberOfRows.Value - ZoomBoxStartRow.Value, NumberOfColumns.Value - ZoomBoxStartColumn.Value);
RedrawGrid();
}
}
private void NumberOfColumns_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (IsInitialized)
{
StartingColumn.Maximum = NumberOfColumns.Value;
ZoomBoxStartColumn.Maximum = NumberOfColumns.Value;
ZoomBoxSpan.Maximum = Math.Min(NumberOfRows.Value - ZoomBoxStartRow.Value, NumberOfColumns.Value - ZoomBoxStartColumn.Value);
RedrawGrid();
}
}
/// <summary> /// <summary>
/// Draws the overlay grid, clearing existing elements if necessary /// Draws the overlay grid, clearing existing elements if necessary
/// </summary> /// </summary>
private void RedrawGrid() //private void RedrawGrid()
{ //{
PreviewImageOverlay.RowDefinitions.Clear(); // PreviewImageOverlay.RowDefinitions.Clear();
PreviewImageOverlay.ColumnDefinitions.Clear(); // PreviewImageOverlay.ColumnDefinitions.Clear();
PreviewImageOverlay.Children.Clear(); // PreviewImageOverlay.Children.Clear();
for (int i = 0; i < NumberOfColumns.Value; i++) // for (int i = 0; i < NumberOfColumns.Value; i++)
{ // {
PreviewImageOverlay.ColumnDefinitions.Add(new ColumnDefinition()); // PreviewImageOverlay.ColumnDefinitions.Add(new ColumnDefinition());
} // }
for (int i = 0; i < NumberOfRows.Value; i++) // for (int i = 0; i < NumberOfRows.Value; i++)
{ // {
PreviewImageOverlay.RowDefinitions.Add(new RowDefinition()); // PreviewImageOverlay.RowDefinitions.Add(new RowDefinition());
} // }
// Draw the overlay // // Draw the overlay
Rectangle overlay = new(); // Rectangle overlay = new();
overlay.Fill = new SolidColorBrush(Color.FromArgb(128, 0, 128, 255)); // overlay.Fill = new SolidColorBrush(Color.FromArgb(128, 0, 128, 255));
_ = PreviewImageOverlay.Children.Add(overlay); // _ = PreviewImageOverlay.Children.Add(overlay);
Grid.SetRow(overlay, (int)ZoomBoxStartRow.Value); // Grid.SetRow(overlay, (int)ZoomBoxStartRow.Value);
Grid.SetColumn(overlay, (int)ZoomBoxStartColumn.Value); // Grid.SetColumn(overlay, (int)ZoomBoxStartColumn.Value);
Grid.SetRowSpan(overlay, (int)ZoomBoxSpan.Value); // Grid.SetRowSpan(overlay, (int)ZoomBoxSpan.Value);
Grid.SetColumnSpan(overlay, (int)ZoomBoxSpan.Value); // Grid.SetColumnSpan(overlay, (int)ZoomBoxSpan.Value);
// Draw the starting position // // Draw the starting position
overlay = new(); // overlay = new();
overlay.Fill = new SolidColorBrush(Color.FromArgb(64, 0, 255, 128)); // overlay.Fill = new SolidColorBrush(Color.FromArgb(64, 0, 255, 128));
_ = PreviewImageOverlay.Children.Add(overlay); // _ = PreviewImageOverlay.Children.Add(overlay);
Grid.SetRow(overlay, (int)StartingRow.Value); // Grid.SetRow(overlay, (int)StartingRow.Value);
Grid.SetColumn(overlay, (int)StartingColumn.Value); // Grid.SetColumn(overlay, (int)StartingColumn.Value);
// Draw grids onto the preview image // // Draw grids onto the preview image
for (int v = 0; v < PreviewImageOverlay.RowDefinitions.Count; v++) // for (int v = 0; v < PreviewImageOverlay.RowDefinitions.Count; v++)
{ // {
for (int u = 0; u < PreviewImageOverlay.ColumnDefinitions.Count; u++) // for (int u = 0; u < PreviewImageOverlay.ColumnDefinitions.Count; u++)
{ // {
Border border = new(); // Border border = new();
border.BorderBrush = borderBrush; // border.BorderBrush = borderBrush;
border.BorderThickness = new Thickness(2); // border.BorderThickness = new Thickness(2);
_ = PreviewImageOverlay.Children.Add(border); // _ = PreviewImageOverlay.Children.Add(border);
Grid.SetRow(border, v); // Grid.SetRow(border, v);
Grid.SetColumn(border, u); // Grid.SetColumn(border, u);
} // }
} // }
} //}
/// <summary> /// <summary>
/// Generates the game board overlay grid /// Generates the game board overlay grid
@ -247,181 +167,6 @@ namespace RBG_Server.WPF
//throw new NotImplementedException(); //throw new NotImplementedException();
} }
} }
private void Sliders_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (IsInitialized)
{
RedrawGrid();
}
}
private void GridVisibilityToggleButton_Click(object sender, RoutedEventArgs e)
{
PreviewImageOverlay.Visibility = PreviewImageOverlay.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}
private static readonly string[] sprites = new string[]
{
"01.png",
"02.png",
"03.png",
"04.png",
};
private void DrawRandomizedPlayers_Click(object sender, RoutedEventArgs e)
{
List<Player> randPlayers = new();
Random rand = new();
int count = rand.Next(1, 10);
for (int i = 0; i < count; i++)
{
// Create a new player at a random location
Player p = new("Player " + i, rand.Next(0, PreviewImageOverlay.RowDefinitions.Count), rand.Next(PreviewImageOverlay.ColumnDefinitions.Count));
// Load the sprite
string[] keys = new string[loadedSprites.Count];
loadedSprites.Keys.CopyTo(keys, 0);
string key = keys[rand.Next(keys.Length)];
if (key.ToLower().EndsWith(".gif"))
{
try
{
AnimatedBitmapImage animatedBitmap = new(new MemoryStream(loadedSprites[key], false), p.PlayerSprite, Application.Current.Dispatcher);
}
catch
{
BitmapSource pSprite;
{
// Scope & create the base data for pSprite
BitmapImage src = new();
src.BeginInit();
src.StreamSource = new MemoryStream(loadedSprites[key],false);
src.EndInit();
pSprite = src;
}
// Recolour:
if (rand.Next(1, 4) == 1)
{
pSprite = ImageProcessing.UpdatePixelColours(pSprite, 0.0, 0.0, 1.0);
}
p.PlayerSprite.Source = pSprite;
}
}
else
{
BitmapSource pSprite;
{
// Scope & create the base data for pSprite
BitmapImage src = new();
src.BeginInit();
src.StreamSource = new MemoryStream(loadedSprites[key], false);
src.EndInit();
pSprite = src;
}
// Recolour:
if (rand.Next(1, 4) == 1)
{
pSprite = ImageProcessing.UpdatePixelColours(pSprite, 0.0, 0.0, 1.0);
}
p.PlayerSprite.Source = pSprite;
}
randPlayers.Add(p);
}
GenerateGameBoard(randPlayers);
}
ConcurrentDictionary<string, byte[]> loadedSprites = new();
Task loadingFiles;
private void GameSpritesBrowser_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new();
ofd.Filter = "Image Files|*.png;*.jpg;*.gif";
ofd.Multiselect = true;
if (ofd.ShowDialog() == true)
{
string[] resultFiles = ofd.FileNames;
loadedSprites.Clear();
// Run the following work in a separate thread
loadingFiles = Task.Run(() =>
{
// Continue in parallel
_ = Parallel.ForEach(resultFiles, (file) =>
{
MemoryStream ms = new();
using FileStream fs = File.OpenRead(file);
if (new FileInfo(file).Length > 512e6) // greater than 512 kB; resize the sprite to something more reasonable
{
BitmapImage gameBoardImage = new();
gameBoardImage.BeginInit();
gameBoardImage.StreamSource = fs;
gameBoardImage.CacheOption = BitmapCacheOption.Default;
gameBoardImage.EndInit();
double vRate = 128 / (double)gameBoardImage.PixelHeight; // Resize so the largest dimension is 128 px
double hRate = 128 / (double)gameBoardImage.PixelWidth;
TransformedBitmap modified = new(gameBoardImage, new ScaleTransform(gameBoardImage.PixelWidth * Math.Min(vRate, hRate), gameBoardImage.PixelHeight * Math.Min(vRate, hRate)));
PngBitmapEncoder encoder = new();
encoder.Frames.Add(BitmapFrame.Create(modified));
encoder.Save(ms);
}
else
{
fs.CopyTo(ms);
}
_ = loadedSprites.TryAdd(file, ms.ToArray());
});
// Invoke the dispatcher to add all of the sprites to the loaded sprites list
_ = Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() =>
{
LoadedSprites.Children.Clear();
foreach (KeyValuePair<string, byte[]> item in loadedSprites)
{
if (item.Key.ToLower().EndsWith(".gif"))
{
try
{
Image spriteImage = new();
// Generate the animatedBitmap
RBG.Helpers.AnimatedBitmapImage animatedBitmap = new(new MemoryStream(item.Value, false), spriteImage, Application.Current.Dispatcher);
_ = LoadedSprites.Children.Add(spriteImage);
}
catch
{
// On failed, use the cached data
BitmapImage image = new();
image.BeginInit();
image.StreamSource = new MemoryStream(item.Value, false);
image.EndInit();
Image spriteImage = new()
{
Source = image
};
_ = LoadedSprites.Children.Add(spriteImage);
}
}
else
{
BitmapImage image = new();
image.BeginInit();
image.StreamSource = new MemoryStream(item.Value, false);
image.EndInit();
Image spriteImage = new()
{
Source = image
};
_ = LoadedSprites.Children.Add(spriteImage);
}
}
}));
});
}
}
} }
} }

View File

@ -25,6 +25,14 @@ namespace RBG_Server
private static int memoryLimit = 1024 * 1024 * 1; // Start with a memory limit of 1 MB private static int memoryLimit = 1024 * 1024 * 1; // Start with a memory limit of 1 MB
private static readonly string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Remote Board Game\\Cache Objects"); private static readonly string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Remote Board Game\\Cache Objects");
/// <summary>
/// Ensure the folder path exists
/// </summary>
static CachedByteArray()
{
Directory.CreateDirectory(folderPath);
}
// static properties // static properties
public static long MemoryAllocationRAM { get { return memoryAllocationRAM; } } public static long MemoryAllocationRAM { get { return memoryAllocationRAM; } }
public static long MemoryAllocationTotal { get { return memoryAllocationTotal; } } public static long MemoryAllocationTotal { get { return memoryAllocationTotal; } }

View File

@ -61,7 +61,7 @@ namespace RBG_Server
public int StartingRow { get;private set; } public int StartingRow { get;private set; }
public void InitialiseServer() public void InitialiseServer(int rowCount, int colCount, int zoomRowStart, int zoomColStart, int zoomRowSpan, int zoomColSpan, int startingRow, int startingColumn)
{ {
// Find the server's active (reliable) network adapter, by creating a remote connection and retrieving our IP from it: // Find the server's active (reliable) network adapter, by creating a remote connection and retrieving our IP from it:
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))

View File

@ -208,7 +208,7 @@ namespace RBG_Server
{ {
// TODO: // TODO:
// Check that the player isn't reconnecting // Check that the player isn't reconnecting
Player newPlayer = new("<loading>", startRow, startColumn); Player newPlayer = new("<loading>", "", Array.Empty<byte>(), startRow, startColumn);
Players.Add(newPlayer); Players.Add(newPlayer);
clients.Add(poppedClient, newPlayer); clients.Add(poppedClient, newPlayer);
Console.WriteLine("New player added."); Console.WriteLine("New player added.");