More code cleanup

This commit is contained in:
adelikat 2013-04-16 00:19:31 +00:00
parent 7199b64a95
commit e32eaeeb9a
15 changed files with 292 additions and 429 deletions

View File

@ -1,11 +1,7 @@
using System; using System;
using System.IO; using System.IO;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq; using System.Linq;
using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
namespace BizHawk.MultiClient namespace BizHawk.MultiClient
@ -17,12 +13,12 @@ namespace BizHawk.MultiClient
InitializeComponent(); InitializeComponent();
foreach (var item in hawkfile.ArchiveItems) foreach (var item in hawkfile.ArchiveItems)
{ {
var lvi = new ListViewItem(); var lvi = new ListViewItem {Tag = item};
lvi.Tag = item;
lvi.SubItems.Add(new ListViewItem.ListViewSubItem()); lvi.SubItems.Add(new ListViewItem.ListViewSubItem());
lvi.Text = item.name; lvi.Text = item.name;
long size = item.size; long size = item.size;
if (size % 1024 == 16 && Path.GetExtension(item.name).ToUpper() == ".NES") var extension = Path.GetExtension(item.name);
if (extension != null && (size % 1024 == 16 && extension.ToUpper() == ".NES"))
size -= 16; size -= 16;
lvi.SubItems[1].Text = Util.FormatFileSize(size); lvi.SubItems[1].Text = Util.FormatFileSize(size);
lvMembers.Items.Add(lvi); lvMembers.Items.Add(lvi);
@ -59,11 +55,7 @@ namespace BizHawk.MultiClient
private void SortItems() private void SortItems()
{ {
List<ListViewItem> lvitems = new List<ListViewItem>(); List<ListViewItem> lvitems = lvMembers.Items.Cast<ListViewItem>().ToList();
foreach(ListViewItem item in lvMembers.Items)
{
lvitems.Add(item);
}
List<ListViewItem> sorteditems = new List<ListViewItem>(); List<ListViewItem> sorteditems = new List<ListViewItem>();
@ -97,7 +89,14 @@ namespace BizHawk.MultiClient
{ {
if (lvMembers.SelectedIndices.Count == 0) return -1; if (lvMembers.SelectedIndices.Count == 0) return -1;
var ai = lvMembers.SelectedItems[0].Tag as HawkFile.ArchiveItem; var ai = lvMembers.SelectedItems[0].Tag as HawkFile.ArchiveItem;
return ai.index; if (ai != null)
{
return ai.index;
}
else
{
return -1;
}
} }
} }
@ -122,17 +121,5 @@ namespace BizHawk.MultiClient
{ {
lvMembers.Items[0].Selected = true; lvMembers.Items[0].Selected = true;
} }
private void SetItem(int num)
{
if (num <= lvMembers.Items.Count)
{
foreach (ListViewItem item in lvMembers.SelectedItems)
{
item.Selected = false;
}
lvMembers.Items[num - 1].Selected = true;
}
}
} }
} }

View File

@ -541,6 +541,9 @@
<EmbeddedResource Include="GBtools\GBGPUView.resx"> <EmbeddedResource Include="GBtools\GBGPUView.resx">
<DependentUpon>GBGPUView.cs</DependentUpon> <DependentUpon>GBGPUView.cs</DependentUpon>
</EmbeddedResource> </EmbeddedResource>
<EmbeddedResource Include="MainForm.Movie.resx">
<DependentUpon>MainForm.Movie.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="MainForm.resx"> <EmbeddedResource Include="MainForm.resx">
<DependentUpon>MainForm.cs</DependentUpon> <DependentUpon>MainForm.cs</DependentUpon>
<SubType>Designer</SubType> <SubType>Designer</SubType>

View File

@ -18,8 +18,7 @@ namespace BizHawk.MultiClient
if (file.Exists) if (file.Exists)
using (var reader = file.OpenText()) using (var reader = file.OpenText())
{ {
var s = new JsonSerializer(); var s = new JsonSerializer {SuppressMissingMemberException = true};
s.SuppressMissingMemberException = true;
var r = new JsonReader(reader); var r = new JsonReader(reader);
config = (T)s.Deserialize(r, typeof(T)); config = (T)s.Deserialize(r, typeof(T));
} }

View File

@ -174,8 +174,8 @@ namespace BizHawk.MultiClient
public static readonly Dictionary<string, Dictionary<string, string>> COMMANDS = new Dictionary<string, Dictionary<string, string>> public static readonly Dictionary<string, Dictionary<string, string>> COMMANDS = new Dictionary<string, Dictionary<string, string>>
{ {
{"Atari 2600 Basic Controller", new Dictionary<string, string> {{"Reset", "r"}, {"Select", "s"}}}, {"Atari 2600 Basic Controller", new Dictionary<string, string> {{"Reset", "r"}, {"Select", "s"}}},
{"Atari 7800 ProLine Joystick Controller", new Dictionary<string, string>() {{"Reset", "r"}, {"Select", "s"}}}, {"Atari 7800 ProLine Joystick Controller", new Dictionary<string, string> {{"Reset", "r"}, {"Select", "s"}}},
{"Gameboy Controller", new Dictionary<string, string>() {{"Power", "P"}}}, {"Gameboy Controller", new Dictionary<string, string> {{"Power", "P"}}},
{"GBA Controller", new Dictionary<string, string> {{"Power", "P"}}}, {"GBA Controller", new Dictionary<string, string> {{"Power", "P"}}},
{"Genesis 3-Button Controller", new Dictionary<string, string> {{"Reset", "r"}}}, {"Genesis 3-Button Controller", new Dictionary<string, string> {{"Reset", "r"}}},
{"NES Controller", new Dictionary<string, string> {{"Reset", "r"}, {"Power", "P"}, {"FDS Eject", "E"}, {"FDS Insert 0", "0"}, {"FDS Insert 1", "1"}, {"VS Coin 1", "c"}, {"VS Coin 2", "C"}}}, {"NES Controller", new Dictionary<string, string> {{"Reset", "r"}, {"Power", "P"}, {"FDS Eject", "E"}, {"FDS Insert 0", "0"}, {"FDS Insert 1", "1"}, {"VS Coin 1", "c"}, {"VS Coin 2", "C"}}},

View File

@ -24,15 +24,10 @@ namespace BizHawk.MultiClient
static LogWindow window; static LogWindow window;
static LogStream logStream; static LogStream logStream;
static StringBuilder sbLog; static bool NeedToRelease;
static bool NeedToRelease = false;
class LogStream : Stream class LogStream : Stream
{ {
public LogStream()
{
}
public override bool CanRead { get { return false; } } public override bool CanRead { get { return false; } }
public override bool CanSeek { get { return false; } } public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return true; } } public override bool CanWrite { get { return true; } }
@ -78,7 +73,7 @@ namespace BizHawk.MultiClient
{ {
//TODO - buffer undecoded characters (this may be important) //TODO - buffer undecoded characters (this may be important)
//(use decoder = System.Text.Encoding.Unicode.GetDecoder()) //(use decoder = System.Text.Encoding.Unicode.GetDecoder())
string str = System.Text.Encoding.ASCII.GetString(buffer, offset, count); string str = Encoding.ASCII.GetString(buffer, offset, count);
if (Emit != null) if (Emit != null)
Emit(str); Emit(str);
} }
@ -146,7 +141,7 @@ namespace BizHawk.MultiClient
attachedConsole = false; attachedConsole = false;
//ever since a recent KB, XP-based systems glitch out when attachconsole is called and theres no console to attach to. //ever since a recent KB, XP-based systems glitch out when attachconsole is called and theres no console to attach to.
if (System.Environment.OSVersion.Version.Major != 5) if (Environment.OSVersion.Version.Major != 5)
{ {
if (Win32.AttachConsole(-1)) if (Win32.AttachConsole(-1))
{ {
@ -161,8 +156,8 @@ namespace BizHawk.MultiClient
if (Win32.AllocConsole()) if (Win32.AllocConsole())
{ {
//set icons for the console so we can tell them apart from the main window //set icons for the console so we can tell them apart from the main window
Win32.SendMessage(Win32.GetConsoleWindow(), 0x0080/*WM_SETICON*/, 0/*ICON_SMALL*/, global::BizHawk.MultiClient.Properties.Resources.console16x16.GetHicon().ToInt32()); Win32.SendMessage(Win32.GetConsoleWindow(), 0x0080/*WM_SETICON*/, 0/*ICON_SMALL*/, Properties.Resources.console16x16.GetHicon().ToInt32());
Win32.SendMessage(Win32.GetConsoleWindow(), 0x0080/*WM_SETICON*/, 1/*ICON_LARGE*/, global::BizHawk.MultiClient.Properties.Resources.console32x32.GetHicon().ToInt32()); Win32.SendMessage(Win32.GetConsoleWindow(), 0x0080/*WM_SETICON*/, 1/*ICON_LARGE*/, Properties.Resources.console32x32.GetHicon().ToInt32());
hasConsole = true; hasConsole = true;
} }
else else
@ -190,20 +185,10 @@ namespace BizHawk.MultiClient
if (attachedConsole) if (attachedConsole)
{ {
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("use cmd /c {0} to get more sensible console behaviour", System.IO.Path.GetFileName(PathManager.GetBasePathAbsolute())); Console.WriteLine("use cmd /c {0} to get more sensible console behaviour", Path.GetFileName(PathManager.GetBasePathAbsolute()));
} }
} }
static void DotNetRewireConout()
{
Stream cstm = Console.OpenStandardOutput();
var cstw = new StreamWriter(cstm) { AutoFlush = true };
Console.SetOut(cstw);
Console.SetError(cstw);
}
static void ReleaseConsole() static void ReleaseConsole()
{ {
if (!hasConsole) if (!hasConsole)
@ -255,7 +240,7 @@ namespace BizHawk.MultiClient
logStream = new LogStream(); logStream = new LogStream();
Log.HACK_LOG_STREAM = logStream; Log.HACK_LOG_STREAM = logStream;
var sout = new StreamWriter(logStream) { AutoFlush = true }; var sout = new StreamWriter(logStream) { AutoFlush = true };
sbLog = new StringBuilder(); //not using this right now new StringBuilder(); //not using this right now
Console.SetOut(sout); Console.SetOut(sout);
window = new LogWindow(); window = new LogWindow();
window.Show(); window.Show();

View File

@ -1,9 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing; using System.Drawing;
using System.Linq;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
@ -13,10 +10,7 @@ namespace BizHawk.MultiClient
{ {
public partial class LogWindow : Form public partial class LogWindow : Form
{ {
int defaultWidth; private readonly List<string> Lines = new List<string>();
int defaultHeight;
List<string> Lines = new List<string>();
public LogWindow() public LogWindow()
{ {
@ -45,7 +39,6 @@ namespace BizHawk.MultiClient
} }
} }
StringBuilder sbLog = new StringBuilder();
public void Append(string str) public void Append(string str)
{ {
var ss = str.Split('\n'); var ss = str.Split('\n');
@ -73,17 +66,14 @@ namespace BizHawk.MultiClient
private void LogWindow_Load(object sender, EventArgs e) private void LogWindow_Load(object sender, EventArgs e)
{ {
defaultWidth = this.Size.Width; //Save these first so that the user can restore to its original size
defaultHeight = this.Size.Height;
if (Global.Config.LogWindowSaveWindowPosition) if (Global.Config.LogWindowSaveWindowPosition)
{ {
if (Global.Config.LogWindowSaveWindowPosition && Global.Config.LogWindowWndx >= 0 && Global.Config.LogWindowWndy >= 0) if (Global.Config.LogWindowSaveWindowPosition && Global.Config.LogWindowWndx >= 0 && Global.Config.LogWindowWndy >= 0)
this.Location = new Point(Global.Config.LogWindowWndx, Global.Config.LogWindowWndy); Location = new Point(Global.Config.LogWindowWndx, Global.Config.LogWindowWndy);
if (Global.Config.LogWindowWidth >= 0 && Global.Config.LogWindowHeight >= 0) if (Global.Config.LogWindowWidth >= 0 && Global.Config.LogWindowHeight >= 0)
{ {
this.Size = new System.Drawing.Size(Global.Config.LogWindowWidth, Global.Config.LogWindowHeight); Size = new Size(Global.Config.LogWindowWidth, Global.Config.LogWindowHeight);
} }
} }
} }
@ -92,10 +82,10 @@ namespace BizHawk.MultiClient
{ {
if (Global.Config.LogWindowSaveWindowPosition) if (Global.Config.LogWindowSaveWindowPosition)
{ {
Global.Config.LogWindowWndx = this.Location.X; Global.Config.LogWindowWndx = Location.X;
Global.Config.LogWindowWndy = this.Location.Y; Global.Config.LogWindowWndy = Location.Y;
Global.Config.LogWindowWidth = this.Right - this.Left; Global.Config.LogWindowWidth = Right - Left;
Global.Config.LogWindowHeight = this.Bottom - this.Top; Global.Config.LogWindowHeight = Bottom - Top;
} }
} }

View File

@ -1924,7 +1924,7 @@ namespace BizHawk.MultiClient
//---------------------------------------------------- //----------------------------------------------------
public void savestate_saveslot(object lua_input) public void savestate_saveslot(object lua_input)
{ {
int x = 0; int x;
try //adelikat: This crap might not be necessary, need to test for a more elegant solution try //adelikat: This crap might not be necessary, need to test for a more elegant solution
{ {
@ -1943,7 +1943,7 @@ namespace BizHawk.MultiClient
public void savestate_loadslot(object lua_input) public void savestate_loadslot(object lua_input)
{ {
int x = 0; int x;
try //adelikat: This crap might not be necessary, need to test for a more elegant solution try //adelikat: This crap might not be necessary, need to test for a more elegant solution
{ {
@ -1962,7 +1962,7 @@ namespace BizHawk.MultiClient
public void savestate_save(object lua_input) public void savestate_save(object lua_input)
{ {
if (lua_input.GetType() == typeof(string)) if (lua_input is string)
{ {
string path = lua_input.ToString(); string path = lua_input.ToString();
var writer = new StreamWriter(path); var writer = new StreamWriter(path);
@ -1972,7 +1972,7 @@ namespace BizHawk.MultiClient
public void savestate_load(object lua_input) public void savestate_load(object lua_input)
{ {
if (lua_input.GetType() == typeof(string)) if (lua_input is string)
{ {
Global.MainForm.LoadStateFile(lua_input.ToString(), Path.GetFileName(lua_input.ToString()), true); Global.MainForm.LoadStateFile(lua_input.ToString(), Path.GetFileName(lua_input.ToString()), true);
} }
@ -2136,7 +2136,7 @@ namespace BizHawk.MultiClient
foreach (var button in buttons.Keys) foreach (var button in buttons.Keys)
{ {
bool invert = false; bool invert = false;
bool? theValue = null; bool? theValue;
string theValueStr = buttons[button].ToString(); string theValueStr = buttons[button].ToString();
if (!String.IsNullOrWhiteSpace(theValueStr)) if (!String.IsNullOrWhiteSpace(theValueStr))
@ -2187,7 +2187,7 @@ namespace BizHawk.MultiClient
Global.ForceOffAdaptor.SetSticky("P" + controller + " " + button, true); Global.ForceOffAdaptor.SetSticky("P" + controller + " " + button, true);
} }
} }
else if (theValue == null) else
{ {
//Turn everything off //Turn everything off
if (controller == null) if (controller == null)

View File

@ -1,8 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO; using System.IO;
using System.Windows.Forms; using System.Windows.Forms;
@ -29,8 +25,7 @@ namespace BizHawk.MultiClient
Global.MovieSession.Movie.WriteMovie(); Global.MovieSession.Movie.WriteMovie();
} }
Global.MovieSession = new MovieSession(); Global.MovieSession = new MovieSession {Movie = m};
Global.MovieSession.Movie = m;
RewireInputChain(); RewireInputChain();
if (!record) if (!record)
@ -66,21 +61,21 @@ namespace BizHawk.MultiClient
if (Global.MovieSession.Movie.IsPlaying) if (Global.MovieSession.Movie.IsPlaying)
{ {
Text = DisplayNameForSystem(Global.Game.System) + " - " + Global.Game.Name + " - " + Path.GetFileName(Global.MovieSession.Movie.Filename); Text = DisplayNameForSystem(Global.Game.System) + " - " + Global.Game.Name + " - " + Path.GetFileName(Global.MovieSession.Movie.Filename);
PlayRecordStatus.Image = BizHawk.MultiClient.Properties.Resources.Play; PlayRecordStatus.Image = Properties.Resources.Play;
PlayRecordStatus.ToolTipText = "Movie is in playback mode"; PlayRecordStatus.ToolTipText = "Movie is in playback mode";
PlayRecordStatus.Visible = true; PlayRecordStatus.Visible = true;
} }
else if (Global.MovieSession.Movie.IsRecording) else if (Global.MovieSession.Movie.IsRecording)
{ {
Text = DisplayNameForSystem(Global.Game.System) + " - " + Global.Game.Name + " - " + Path.GetFileName(Global.MovieSession.Movie.Filename); Text = DisplayNameForSystem(Global.Game.System) + " - " + Global.Game.Name + " - " + Path.GetFileName(Global.MovieSession.Movie.Filename);
PlayRecordStatus.Image = BizHawk.MultiClient.Properties.Resources.RecordHS; PlayRecordStatus.Image = Properties.Resources.RecordHS;
PlayRecordStatus.ToolTipText = "Movie is in record mode"; PlayRecordStatus.ToolTipText = "Movie is in record mode";
PlayRecordStatus.Visible = true; PlayRecordStatus.Visible = true;
} }
else if (!Global.MovieSession.Movie.IsActive) else if (!Global.MovieSession.Movie.IsActive)
{ {
Text = DisplayNameForSystem(Global.Game.System) + " - " + Global.Game.Name; Text = DisplayNameForSystem(Global.Game.System) + " - " + Global.Game.Name;
PlayRecordStatus.Image = BizHawk.MultiClient.Properties.Resources.Blank; PlayRecordStatus.Image = Properties.Resources.Blank;
PlayRecordStatus.ToolTipText = "No movie is active"; PlayRecordStatus.ToolTipText = "No movie is active";
PlayRecordStatus.Visible = false; PlayRecordStatus.Visible = false;
} }
@ -89,7 +84,7 @@ namespace BizHawk.MultiClient
public void PlayMovie() public void PlayMovie()
{ {
PlayMovie p = new PlayMovie(); PlayMovie p = new PlayMovie();
DialogResult d = p.ShowDialog(); p.ShowDialog();
} }
public void RecordMovie() public void RecordMovie()
@ -103,7 +98,7 @@ namespace BizHawk.MultiClient
"is currently BETA-status. We appreciate your help in testing Bizhawk. " + "is currently BETA-status. We appreciate your help in testing Bizhawk. " +
"You can record a movie on this core if you'd like to, but expect to " + "You can record a movie on this core if you'd like to, but expect to " +
"encounter bugs and sync problems. Continue?", "BizHawk", MessageBoxButtons.YesNo); "encounter bugs and sync problems. Continue?", "BizHawk", MessageBoxButtons.YesNo);
if (result != System.Windows.Forms.DialogResult.Yes) if (result != DialogResult.Yes)
return; return;
} }
RecordMovie r = new RecordMovie(); RecordMovie r = new RecordMovie();
@ -338,11 +333,10 @@ namespace BizHawk.MultiClient
//On movie load, these need to be set based on the contents of the movie file //On movie load, these need to be set based on the contents of the movie file
private void SetSyncDependentSettings() private void SetSyncDependentSettings()
{ {
string str = "";
switch (Global.Emulator.SystemId) switch (Global.Emulator.SystemId)
{ {
case "Coleco": case "Coleco":
str = Global.MovieSession.Movie.Header.GetHeaderLine(MovieHeader.SKIPBIOS); string str = Global.MovieSession.Movie.Header.GetHeaderLine(MovieHeader.SKIPBIOS);
if (!String.IsNullOrWhiteSpace(str)) if (!String.IsNullOrWhiteSpace(str))
{ {
if (str.ToLower() == "true") if (str.ToLower() == "true")

View File

@ -1,11 +1,11 @@
using System; using System;
using System.Linq;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.IO; using System.IO;
using System.Windows.Forms; using System.Windows.Forms;
using System.Diagnostics;
using BizHawk.Core; using BizHawk.Core;
using BizHawk.DiscSystem; using BizHawk.DiscSystem;
using BizHawk.Emulation.Consoles.Sega; using BizHawk.Emulation.Consoles.Sega;
@ -14,7 +14,6 @@ using BizHawk.Emulation.Consoles.Calculator;
using BizHawk.Emulation.Consoles.Nintendo; using BizHawk.Emulation.Consoles.Nintendo;
using BizHawk.Emulation.Consoles.Nintendo.SNES; using BizHawk.Emulation.Consoles.Nintendo.SNES;
using BizHawk.Emulation.Consoles.Coleco; using BizHawk.Emulation.Consoles.Coleco;
using BizHawk.MultiClient.tools;
using System.Collections.Generic; using System.Collections.Generic;
using BizHawk.Emulation.Consoles.Intellivision; using BizHawk.Emulation.Consoles.Intellivision;
using BizHawk.Emulation.Consoles.GB; using BizHawk.Emulation.Consoles.GB;
@ -30,11 +29,7 @@ namespace BizHawk.MultiClient
public static bool INTERIM = true; public static bool INTERIM = true;
public const string EMUVERSION = "Version " + VersionInfo.MAINVERSION; public const string EMUVERSION = "Version " + VersionInfo.MAINVERSION;
public const string RELEASEDATE = "March 23, 2013"; public const string RELEASEDATE = "March 23, 2013";
private Control renderTarget;
private RetainedViewportPanel retainedPanel;
public string CurrentlyOpenRom; public string CurrentlyOpenRom;
SavestateManager StateSlots = new SavestateManager();
public bool PauseAVI = false; public bool PauseAVI = false;
public bool PressFrameAdvance = false; public bool PressFrameAdvance = false;
public bool PressRewind = false; public bool PressRewind = false;
@ -43,36 +38,46 @@ namespace BizHawk.MultiClient
public bool RestoreReadWriteOnStop = false; public bool RestoreReadWriteOnStop = false;
public bool UpdateFrame = false; public bool UpdateFrame = false;
public bool NeedsReboot = false; public bool NeedsReboot = false;
private Control renderTarget;
private RetainedViewportPanel retainedPanel;
private readonly SavestateManager StateSlots = new SavestateManager();
private readonly Dictionary<string, string> SNES_prepared = new Dictionary<string, string>();
//avi/wav state //avi/wav state
IVideoWriter CurrAviWriter = null; IVideoWriter CurrAviWriter;
ISoundProvider AviSoundInput = null; ISoundProvider AviSoundInput;
/// <summary> /// <summary>
/// an audio proxy used for dumping /// an audio proxy used for dumping
/// </summary> /// </summary>
Emulation.Sound.MetaspuSoundProvider DumpProxy = null; Emulation.Sound.MetaspuSoundProvider DumpProxy;
/// <summary>audio timekeeping for video dumping</summary> /// <summary>audio timekeeping for video dumping</summary>
long SoundRemainder = 0; private long SoundRemainder;
int avwriter_resizew; private int avwriter_resizew;
int avwriter_resizeh; private int avwriter_resizeh;
//runloop control //runloop control
bool exit;
bool runloop_frameProgress;
DateTime FrameAdvanceTimestamp = DateTime.MinValue;
public bool EmulatorPaused { get; private set; } public bool EmulatorPaused { get; private set; }
public EventWaitHandle MainWait; public EventWaitHandle MainWait;
int runloop_fps;
int runloop_last_fps;
bool runloop_frameadvance;
DateTime runloop_second;
bool runloop_last_ff;
Throttle throttle; private bool exit;
bool unthrottled = false; private bool runloop_frameProgress;
private DateTime FrameAdvanceTimestamp = DateTime.MinValue;
private int runloop_fps;
private int runloop_last_fps;
private bool runloop_frameadvance;
private DateTime runloop_second;
private bool runloop_last_ff;
private readonly Throttle throttle;
private bool unthrottled;
//For handling automatic pausing when entering the menu //For handling automatic pausing when entering the menu
private bool wasPaused = false; private bool wasPaused;
private bool didMenuPause = false; private bool didMenuPause;
private bool InFullscreen;
private Point _windowed_location;
//tool dialogs //tool dialogs
public RamWatch RamWatch1 = new RamWatch(); public RamWatch RamWatch1 = new RamWatch();
@ -98,7 +103,7 @@ namespace BizHawk.MultiClient
/// <summary> /// <summary>
/// number of frames to autodump /// number of frames to autodump
/// </summary> /// </summary>
int autoDumpLength = 0; int autoDumpLength;
static MainForm() static MainForm()
{ {
@ -108,10 +113,9 @@ namespace BizHawk.MultiClient
public MainForm(string[] args) public MainForm(string[] args)
{ {
Global.MovieSession = new MovieSession(); Global.MovieSession = new MovieSession {Movie = new Movie()};
Global.MovieSession.Movie = new Movie();
MainWait = new AutoResetEvent(false); MainWait = new AutoResetEvent(false);
Icon = BizHawk.MultiClient.Properties.Resources.logo; Icon = Properties.Resources.logo;
InitializeComponent(); InitializeComponent();
Global.Game = GameInfo.GetNullGame(); Global.Game = GameInfo.GetNullGame();
if (Global.Config.ShowLogWindow) if (Global.Config.ShowLogWindow)
@ -123,7 +127,7 @@ namespace BizHawk.MultiClient
throttle = new Throttle(); throttle = new Throttle();
DiscSystem.FFMpeg.FFMpegPath = PathManager.MakeProgramRelativePath(Global.Config.FFMpegPath); FFMpeg.FFMpegPath = PathManager.MakeProgramRelativePath(Global.Config.FFMpegPath);
Global.CheatList = new CheatList(); Global.CheatList = new CheatList();
UpdateStatusSlots(); UpdateStatusSlots();
@ -325,7 +329,7 @@ namespace BizHawk.MultiClient
} }
if (Global.Config.MainWndx >= 0 && Global.Config.MainWndy >= 0 && Global.Config.SaveWindowPosition) if (Global.Config.MainWndx >= 0 && Global.Config.MainWndy >= 0 && Global.Config.SaveWindowPosition)
this.Location = new Point(Global.Config.MainWndx, Global.Config.MainWndy); Location = new Point(Global.Config.MainWndx, Global.Config.MainWndy);
if (Global.Config.DisplayStatusBar == false) if (Global.Config.DisplayStatusBar == false)
StatusSlot0.Visible = false; StatusSlot0.Visible = false;
@ -367,7 +371,6 @@ namespace BizHawk.MultiClient
} }
//contains a mapping: profilename->exepath ; or null if the exe wasnt available //contains a mapping: profilename->exepath ; or null if the exe wasnt available
Dictionary<string, string> SNES_prepared = new Dictionary<string, string>();
string SNES_Prepare(string profile) string SNES_Prepare(string profile)
{ {
SNES_Check(profile); SNES_Check(profile);
@ -381,7 +384,7 @@ namespace BizHawk.MultiClient
{ {
if (SNES_prepared.ContainsKey(profile)) return; if (SNES_prepared.ContainsKey(profile)) return;
string bits = "32"; const string bits = "32";
//disabled til it works //disabled til it works
//if (Win32.Is64BitOperatingSystem) //if (Win32.Is64BitOperatingSystem)
@ -456,12 +459,8 @@ namespace BizHawk.MultiClient
Global.DisplayManager.Suspend(); Global.DisplayManager.Suspend();
#if WINDOWS #if WINDOWS
bool gdi = Global.Config.DisplayGDI; bool gdi = Global.Config.DisplayGDI || Global.Direct3D == null;
if (Global.Direct3D == null)
gdi = true;
#endif #endif
if (renderTarget != null) if (renderTarget != null)
{ {
renderTarget.Dispose(); renderTarget.Dispose();
@ -623,13 +622,13 @@ namespace BizHawk.MultiClient
{ {
if (EmulatorPaused) if (EmulatorPaused)
{ {
PauseStrip.Image = BizHawk.MultiClient.Properties.Resources.Pause; PauseStrip.Image = Properties.Resources.Pause;
PauseStrip.Visible = true; PauseStrip.Visible = true;
PauseStrip.ToolTipText = "Emulator Paused"; PauseStrip.ToolTipText = "Emulator Paused";
} }
else else
{ {
PauseStrip.Image = BizHawk.MultiClient.Properties.Resources.Blank; PauseStrip.Image = Properties.Resources.Blank;
PauseStrip.Visible = false; PauseStrip.Visible = false;
PauseStrip.ToolTipText = ""; PauseStrip.ToolTipText = "";
} }
@ -813,8 +812,7 @@ namespace BizHawk.MultiClient
} }
Global.SMSControls = smsControls; Global.SMSControls = smsControls;
var asmsControls = new AutofireController(SMS.SmsController); var asmsControls = new AutofireController(SMS.SmsController) {Autofire = true};
asmsControls.Autofire = true;
asmsControls.BindMulti("Reset", Global.Config.SMSConsoleButtons.Reset); asmsControls.BindMulti("Reset", Global.Config.SMSConsoleButtons.Reset);
asmsControls.BindMulti("Pause", Global.Config.SMSConsoleButtons.Pause); asmsControls.BindMulti("Pause", Global.Config.SMSConsoleButtons.Pause);
for (int i = 0; i < 2; i++) for (int i = 0; i < 2; i++)
@ -843,8 +841,7 @@ namespace BizHawk.MultiClient
} }
Global.PCEControls = pceControls; Global.PCEControls = pceControls;
var apceControls = new AutofireController(PCEngine.PCEngineController); var apceControls = new AutofireController(PCEngine.PCEngineController) {Autofire = true};
apceControls.Autofire = true;
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++)
{ {
apceControls.BindMulti("P" + (i + 1) + " Up", Global.Config.PCEAutoController[i].Up); apceControls.BindMulti("P" + (i + 1) + " Up", Global.Config.PCEAutoController[i].Up);
@ -882,8 +879,7 @@ namespace BizHawk.MultiClient
Global.SNESControls = snesControls; Global.SNESControls = snesControls;
var asnesControls = new AutofireController(LibsnesCore.SNESController); var asnesControls = new AutofireController(LibsnesCore.SNESController) {Autofire = true};
asnesControls.Autofire = true;
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
asnesControls.BindMulti("P" + (i + 1) + " Up", Global.Config.SNESAutoController[i].Up); asnesControls.BindMulti("P" + (i + 1) + " Up", Global.Config.SNESAutoController[i].Up);
@ -922,8 +918,7 @@ namespace BizHawk.MultiClient
Global.NESControls = nesControls; Global.NESControls = nesControls;
var anesControls = new AutofireController(NES.NESController); var anesControls = new AutofireController(NES.NESController) {Autofire = true};
anesControls.Autofire = true;
for (int i = 0; i < 2 /*TODO*/; i++) for (int i = 0; i < 2 /*TODO*/; i++)
{ {
@ -950,8 +945,7 @@ namespace BizHawk.MultiClient
gbControls.BindMulti("Power", Global.Config.GBController[0].Power); gbControls.BindMulti("Power", Global.Config.GBController[0].Power);
Global.GBControls = gbControls; Global.GBControls = gbControls;
var agbControls = new AutofireController(Gameboy.GbController); var agbControls = new AutofireController(Gameboy.GbController) {Autofire = true};
agbControls.Autofire = true;
agbControls.BindMulti("Up", Global.Config.GBAutoController[0].Up); agbControls.BindMulti("Up", Global.Config.GBAutoController[0].Up);
agbControls.BindMulti("Down", Global.Config.GBAutoController[0].Down); agbControls.BindMulti("Down", Global.Config.GBAutoController[0].Down);
agbControls.BindMulti("Left", Global.Config.GBAutoController[0].Left); agbControls.BindMulti("Left", Global.Config.GBAutoController[0].Left);
@ -1465,7 +1459,6 @@ namespace BizHawk.MultiClient
private void FormDragDrop(object sender, DragEventArgs e) private void FormDragDrop(object sender, DragEventArgs e)
{ {
string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);
bool isLua = false; bool isLua = false;
foreach (string path in filePaths) foreach (string path in filePaths)
{ {
@ -1648,8 +1641,8 @@ namespace BizHawk.MultiClient
void NESSpeicalMenuAdd(string name, string button, string msg) void NESSpeicalMenuAdd(string name, string button, string msg)
{ {
nESSpeicalToolStripMenuItem.Visible = true; nESSpeicalToolStripMenuItem.Visible = true;
nESSpeicalToolStripMenuItem.DropDownItems.Add(name, null, delegate(object sender, EventArgs e) nESSpeicalToolStripMenuItem.DropDownItems.Add(name, null, delegate
{ {
if (Global.Emulator.ControllerDefinition.BoolButtons.Contains(button)) if (Global.Emulator.ControllerDefinition.BoolButtons.Contains(button))
{ {
if (!Global.MovieSession.Movie.IsPlaying || Global.MovieSession.Movie.IsFinished) if (!Global.MovieSession.Movie.IsPlaying || Global.MovieSession.Movie.IsFinished)
@ -1768,9 +1761,7 @@ namespace BizHawk.MultiClient
void RewireInputChain() void RewireInputChain()
{ {
Global.ControllerInputCoalescer = new ControllerInputCoalescer(); Global.ControllerInputCoalescer = new ControllerInputCoalescer {Type = Global.ActiveController.Type};
Global.ControllerInputCoalescer.Type = Global.ActiveController.Type;
Global.OrControllerAdapter.Source = Global.ActiveController; Global.OrControllerAdapter.Source = Global.ActiveController;
Global.OrControllerAdapter.SourceOr = Global.AutoFireController; Global.OrControllerAdapter.SourceOr = Global.AutoFireController;
@ -1801,7 +1792,7 @@ namespace BizHawk.MultiClient
if (path == null) return false; if (path == null) return false;
using (var file = new HawkFile()) using (var file = new HawkFile())
{ {
string[] romExtensions = new string[] { "SMS", "SMC", "SFC", "PCE", "SGX", "GG", "SG", "BIN", "GEN", "MD", "SMD", "GB", "NES", "FDS", "ROM", "INT", "GBC", "UNF", "A78", "CRT", "COL" }; string[] romExtensions = new[] { "SMS", "SMC", "SFC", "PCE", "SGX", "GG", "SG", "BIN", "GEN", "MD", "SMD", "GB", "NES", "FDS", "ROM", "INT", "GBC", "UNF", "A78", "CRT", "COL" };
//lets not use this unless we need to //lets not use this unless we need to
//file.NonArchiveExtensions = romExtensions; //file.NonArchiveExtensions = romExtensions;
@ -1870,20 +1861,14 @@ namespace BizHawk.MultiClient
// In the future we need to do something smarter, possibly including simply asking the user // In the future we need to do something smarter, possibly including simply asking the user
// what system the game is for. // what system the game is for.
if (BizHawk.Emulation.Consoles.PSX.Octoshock.CheckIsPSX(disc)) if (Emulation.Consoles.PSX.Octoshock.CheckIsPSX(disc))
{ {
game = new GameInfo(); game = new GameInfo {System = "PSX", Name = Path.GetFileNameWithoutExtension(file.Name), Hash = hash};
game.System = "PSX";
game.Name = Path.GetFileNameWithoutExtension(file.Name);
game.Hash = hash;
disc.Dispose(); disc.Dispose();
} }
else else
{ {
game = new GameInfo(); game = new GameInfo {System = "PCECD", Name = Path.GetFileNameWithoutExtension(file.Name), Hash = hash};
game.System = "PCECD";
game.Name = Path.GetFileNameWithoutExtension(file.Name);
game.Hash = hash;
} }
} }
@ -1891,7 +1876,7 @@ namespace BizHawk.MultiClient
{ {
case "PSX": case "PSX":
{ {
var psx = new BizHawk.Emulation.Consoles.PSX.Octoshock(nextComm); var psx = new Emulation.Consoles.PSX.Octoshock(nextComm);
nextEmulator = psx; nextEmulator = psx;
psx.LoadCuePath(file.CanonicalFullPath); psx.LoadCuePath(file.CanonicalFullPath);
nextEmulator.CoreComm.RomStatusDetails = "PSX etc."; nextEmulator.CoreComm.RomStatusDetails = "PSX etc.";
@ -2003,11 +1988,13 @@ namespace BizHawk.MultiClient
} }
} }
NES nes = new NES(nextComm, game, rom.FileData, bios); NES nes = new NES(nextComm, game, rom.FileData, bios)
nes.SoundOn = Global.Config.SoundEnabled; {
nes.NTSC_FirstDrawLine = Global.Config.NTSC_NESTopLine; SoundOn = Global.Config.SoundEnabled,
nes.NTSC_LastDrawLine = Global.Config.NTSC_NESBottomLine; NTSC_FirstDrawLine = Global.Config.NTSC_NESTopLine,
nes.PAL_FirstDrawLine = Global.Config.PAL_NESTopLine; NTSC_LastDrawLine = Global.Config.NTSC_NESBottomLine,
PAL_FirstDrawLine = Global.Config.PAL_NESTopLine
};
nes.NTSC_LastDrawLine = Global.Config.PAL_NESBottomLine; nes.NTSC_LastDrawLine = Global.Config.PAL_NESBottomLine;
nes.SetClipLeftAndRight(Global.Config.NESClipLeftAndRight); nes.SetClipLeftAndRight(Global.Config.NESClipLeftAndRight);
nextEmulator = nes; nextEmulator = nes;
@ -2169,7 +2156,7 @@ namespace BizHawk.MultiClient
} }
string gamedbpath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "EMU7800.csv"); string gamedbpath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "EMU7800.csv");
var a78 = new BizHawk.Emulation.Atari7800(nextComm, game, rom.RomData, NTSC_BIOS7800, PAL_BIOS7800, HighScoreBIOS, gamedbpath); var a78 = new Atari7800(nextComm, game, rom.RomData, NTSC_BIOS7800, PAL_BIOS7800, HighScoreBIOS, gamedbpath);
nextEmulator = a78; nextEmulator = a78;
break; break;
case "C64": case "C64":
@ -2341,52 +2328,52 @@ namespace BizHawk.MultiClient
private void UpdateDumpIcon() private void UpdateDumpIcon()
{ {
DumpStatus.Image = BizHawk.MultiClient.Properties.Resources.Blank; DumpStatus.Image = Properties.Resources.Blank;
DumpStatus.ToolTipText = ""; DumpStatus.ToolTipText = "";
if (Global.Emulator == null) return; if (Global.Emulator == null) return;
if (Global.Game == null) return; if (Global.Game == null) return;
var status = Global.Game.Status; var status = Global.Game.Status;
string annotation = ""; string annotation;
if (status == RomStatus.BadDump) if (status == RomStatus.BadDump)
{ {
DumpStatus.Image = BizHawk.MultiClient.Properties.Resources.ExclamationRed; DumpStatus.Image = Properties.Resources.ExclamationRed;
annotation = "Warning: Bad ROM Dump"; annotation = "Warning: Bad ROM Dump";
} }
else if (status == RomStatus.Overdump) else if (status == RomStatus.Overdump)
{ {
DumpStatus.Image = BizHawk.MultiClient.Properties.Resources.ExclamationRed; DumpStatus.Image = Properties.Resources.ExclamationRed;
annotation = "Warning: Overdump"; annotation = "Warning: Overdump";
} }
else if (status == RomStatus.NotInDatabase) else if (status == RomStatus.NotInDatabase)
{ {
DumpStatus.Image = BizHawk.MultiClient.Properties.Resources.RetroQuestion; DumpStatus.Image = Properties.Resources.RetroQuestion;
annotation = "Warning: Unknown ROM"; annotation = "Warning: Unknown ROM";
} }
else if (status == RomStatus.TranslatedRom) else if (status == RomStatus.TranslatedRom)
{ {
DumpStatus.Image = BizHawk.MultiClient.Properties.Resources.Translation; DumpStatus.Image = Properties.Resources.Translation;
annotation = "Translated ROM"; annotation = "Translated ROM";
} }
else if (status == RomStatus.Homebrew) else if (status == RomStatus.Homebrew)
{ {
DumpStatus.Image = BizHawk.MultiClient.Properties.Resources.HomeBrew; DumpStatus.Image = Properties.Resources.HomeBrew;
annotation = "Homebrew ROM"; annotation = "Homebrew ROM";
} }
else if (Global.Game.Status == RomStatus.Hack) else if (Global.Game.Status == RomStatus.Hack)
{ {
DumpStatus.Image = BizHawk.MultiClient.Properties.Resources.Hack; DumpStatus.Image = Properties.Resources.Hack;
annotation = "Hacked ROM"; annotation = "Hacked ROM";
} }
else if (Global.Game.Status == RomStatus.Unknown) else if (Global.Game.Status == RomStatus.Unknown)
{ {
DumpStatus.Image = BizHawk.MultiClient.Properties.Resources.Hack; DumpStatus.Image = Properties.Resources.Hack;
annotation = "Warning: ROM of Unknown Character"; annotation = "Warning: ROM of Unknown Character";
} }
else else
{ {
DumpStatus.Image = BizHawk.MultiClient.Properties.Resources.GreenCheck; DumpStatus.Image = Properties.Resources.GreenCheck;
annotation = "Verified good dump"; annotation = "Verified good dump";
} }
if (!string.IsNullOrEmpty(Global.Emulator.CoreComm.RomStatusAnnotation)) if (!string.IsNullOrEmpty(Global.Emulator.CoreComm.RomStatusAnnotation))
@ -2423,15 +2410,15 @@ namespace BizHawk.MultiClient
string path = PathManager.SaveRamPath(Global.Game); string path = PathManager.SaveRamPath(Global.Game);
var f = new FileInfo(path); var f = new FileInfo(path);
if (f.Directory.Exists == false) if (f.Directory != null && f.Directory.Exists == false)
f.Directory.Create(); f.Directory.Create();
//Make backup first //Make backup first
if (Global.Config.BackupSaveram && f.Exists == true) if (Global.Config.BackupSaveram && f.Exists)
{ {
string backup = path + ".bak"; string backup = path + ".bak";
var backupFile = new FileInfo(backup); var backupFile = new FileInfo(backup);
if (backupFile.Exists == true) if (backupFile.Exists)
backupFile.Delete(); backupFile.Delete();
f.CopyTo(backup); f.CopyTo(backup);
} }
@ -2463,14 +2450,14 @@ namespace BizHawk.MultiClient
get get
{ {
//the main form gets input //the main form gets input
if (Form.ActiveForm == this) return true; if (ActiveForm == this) return true;
//modals that need to capture input for binding purposes get input, of course //modals that need to capture input for binding purposes get input, of course
if (Form.ActiveForm is HotkeyWindow) return true; if (ActiveForm is HotkeyWindow) return true;
if (Form.ActiveForm is ControllerConfig) return true; if (ActiveForm is ControllerConfig) return true;
if (Form.ActiveForm is TAStudio) return true; if (ActiveForm is TAStudio) return true;
//if no form is active on this process, then the background input setting applies //if no form is active on this process, then the background input setting applies
if (Form.ActiveForm == null && Global.Config.AcceptBackgroundInput) return true; if (ActiveForm == null && Global.Config.AcceptBackgroundInput) return true;
return false; return false;
} }
@ -2542,10 +2529,7 @@ namespace BizHawk.MultiClient
handled = false; handled = false;
if (ie.EventType == Input.InputEventType.Press) if (ie.EventType == Input.InputEventType.Press)
{ {
foreach (var trigger in triggers) handled = triggers.Aggregate(handled, (current, trigger) => current | CheckHotkey(trigger));
{
handled |= CheckHotkey(trigger);
}
} }
//hotkeys which arent handled as actions get coalesced as pollable virtual client buttons //hotkeys which arent handled as actions get coalesced as pollable virtual client buttons
@ -2562,10 +2546,7 @@ namespace BizHawk.MultiClient
handled = false; handled = false;
if (ie.EventType == Input.InputEventType.Press) if (ie.EventType == Input.InputEventType.Press)
{ {
foreach (var trigger in triggers) handled = triggers.Aggregate(handled, (current, trigger) => current | CheckHotkey(trigger));
{
handled |= CheckHotkey(trigger);
}
} }
//hotkeys which arent handled as actions get coalesced as pollable virtual client buttons //hotkeys which arent handled as actions get coalesced as pollable virtual client buttons
@ -2579,10 +2560,7 @@ namespace BizHawk.MultiClient
handled = false; handled = false;
if (ie.EventType == Input.InputEventType.Press) if (ie.EventType == Input.InputEventType.Press)
{ {
foreach (var trigger in triggers) handled = triggers.Aggregate(handled, (current, trigger) => current | CheckHotkey(trigger));
{
handled |= CheckHotkey(trigger);
}
} }
//hotkeys which arent handled as actions get coalesced as pollable virtual client buttons //hotkeys which arent handled as actions get coalesced as pollable virtual client buttons
@ -2925,7 +2903,7 @@ namespace BizHawk.MultiClient
Global.MovieSession.Movie.SwitchToPlay(); Global.MovieSession.Movie.SwitchToPlay();
} }
} }
if (UpdateFrame == true) if (UpdateFrame)
{ {
runFrame = true; runFrame = true;
if (Global.MovieSession.Movie.IsRecording) if (Global.MovieSession.Movie.IsRecording)
@ -3120,7 +3098,7 @@ namespace BizHawk.MultiClient
{ {
using (var img = Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage()) using (var img = Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage())
{ {
System.Windows.Forms.Clipboard.SetImage(img); Clipboard.SetImage(img);
} }
Global.OSD.AddMessage("Screenshot saved to clipboard."); Global.OSD.AddMessage("Screenshot saved to clipboard.");
} }
@ -3141,7 +3119,7 @@ namespace BizHawk.MultiClient
public void TakeScreenshot(string path) public void TakeScreenshot(string path)
{ {
var fi = new FileInfo(path); var fi = new FileInfo(path);
if (fi.Directory.Exists == false) if (fi.Directory != null && fi.Directory.Exists == false)
fi.Directory.Create(); fi.Directory.Create();
using (var img = Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage()) using (var img = Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage())
{ {
@ -3155,15 +3133,15 @@ namespace BizHawk.MultiClient
string path = PathManager.SaveStatePrefix(Global.Game) + "." + name + ".State"; string path = PathManager.SaveStatePrefix(Global.Game) + "." + name + ".State";
var file = new FileInfo(path); var file = new FileInfo(path);
if (file.Directory.Exists == false) if (file.Directory != null && file.Directory.Exists == false)
file.Directory.Create(); file.Directory.Create();
//Make backup first //Make backup first
if (Global.Config.BackupSavestates && file.Exists == true) if (Global.Config.BackupSavestates && file.Exists)
{ {
string backup = path + ".bak"; string backup = path + ".bak";
var backupFile = new FileInfo(backup); var backupFile = new FileInfo(backup);
if (backupFile.Exists == true) if (backupFile.Exists)
backupFile.Delete(); backupFile.Delete();
file.CopyTo(backup); file.CopyTo(backup);
} }
@ -3202,7 +3180,7 @@ namespace BizHawk.MultiClient
sfd.InitialDirectory = path; sfd.InitialDirectory = path;
sfd.FileName = PathManager.SaveStatePrefix(Global.Game) + "." + "QuickSave0.State"; sfd.FileName = PathManager.SaveStatePrefix(Global.Game) + "." + "QuickSave0.State";
var file = new FileInfo(path); var file = new FileInfo(path);
if (file.Directory.Exists == false) if (file.Directory != null && file.Directory.Exists == false)
file.Directory.Create(); file.Directory.Create();
Global.Sound.StopSound(); Global.Sound.StopSound();
@ -3263,10 +3241,12 @@ namespace BizHawk.MultiClient
private void LoadStateAs() private void LoadStateAs()
{ {
if (IsNullEmulator()) return; if (IsNullEmulator()) return;
var ofd = new OpenFileDialog(); var ofd = new OpenFileDialog
ofd.InitialDirectory = PathManager.GetSaveStatePath(Global.Game); {
ofd.Filter = "Save States (*.State)|*.State|All Files|*.*"; InitialDirectory = PathManager.GetSaveStatePath(Global.Game),
ofd.RestoreDirectory = true; Filter = "Save States (*.State)|*.State|All Files|*.*",
RestoreDirectory = true
};
Global.Sound.StopSound(); Global.Sound.StopSound();
var result = ofd.ShowDialog(); var result = ofd.ShowDialog();
@ -3288,7 +3268,7 @@ namespace BizHawk.MultiClient
private void UpdateAutoLoadRecentRom() private void UpdateAutoLoadRecentRom()
{ {
if (Global.Config.AutoLoadMostRecentRom == true) if (Global.Config.AutoLoadMostRecentRom)
{ {
autoloadMostRecentToolStripMenuItem.Checked = false; autoloadMostRecentToolStripMenuItem.Checked = false;
Global.Config.AutoLoadMostRecentRom = false; Global.Config.AutoLoadMostRecentRom = false;
@ -3302,7 +3282,7 @@ namespace BizHawk.MultiClient
private void UpdateAutoLoadRecentMovie() private void UpdateAutoLoadRecentMovie()
{ {
if (Global.Config.AutoLoadMostRecentMovie == true) if (Global.Config.AutoLoadMostRecentMovie)
{ {
autoloadMostRecentToolStripMenuItem1.Checked = false; autoloadMostRecentToolStripMenuItem1.Checked = false;
Global.Config.AutoLoadMostRecentMovie = false; Global.Config.AutoLoadMostRecentMovie = false;
@ -3516,14 +3496,11 @@ namespace BizHawk.MultiClient
} }
} }
private bool InFullscreen = false;
private Point WindowedLocation;
public void ToggleFullscreen() public void ToggleFullscreen()
{ {
if (InFullscreen == false) if (InFullscreen == false)
{ {
WindowedLocation = Location; _windowed_location = Location;
FormBorderStyle = FormBorderStyle.None; FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized; WindowState = FormWindowState.Maximized;
if (Global.Config.ShowMenuInFullscreen) if (Global.Config.ShowMenuInFullscreen)
@ -3541,7 +3518,7 @@ namespace BizHawk.MultiClient
WindowState = FormWindowState.Normal; WindowState = FormWindowState.Normal;
MainMenuStrip.Visible = true; MainMenuStrip.Visible = true;
StatusSlot0.Visible = Global.Config.DisplayStatusBar; StatusSlot0.Visible = Global.Config.DisplayStatusBar;
Location = WindowedLocation; Location = _windowed_location;
PerformLayout(); PerformLayout();
FrameBufferResized(); FrameBufferResized();
InFullscreen = false; InFullscreen = false;
@ -3562,7 +3539,7 @@ namespace BizHawk.MultiClient
protected override bool ProcessDialogChar(char charCode) protected override bool ProcessDialogChar(char charCode)
{ {
//this is necessary to trap alt+char combinations so that only our hotkey system gets them //this is necessary to trap alt+char combinations so that only our hotkey system gets them
if ((Control.ModifierKeys & Keys.Alt) != 0) if ((ModifierKeys & Keys.Alt) != 0)
return true; return true;
else return base.ProcessDialogChar(charCode); else return base.ProcessDialogChar(charCode);
} }
@ -3570,11 +3547,7 @@ namespace BizHawk.MultiClient
//sends a simulation of a plain alt key keystroke //sends a simulation of a plain alt key keystroke
void SendPlainAltKey(int lparam) void SendPlainAltKey(int lparam)
{ {
Message m = new Message(); Message m = new Message {WParam = new IntPtr(0xF100), LParam = new IntPtr(lparam), Msg = 0x0112, HWnd = Handle};
m.WParam = new IntPtr(0xF100); //SC_KEYMENU
m.LParam = new IntPtr(lparam);
m.Msg = 0x0112; //WM_SYSCOMMAND
m.HWnd = Handle;
base.WndProc(ref m); base.WndProc(ref m);
} }
@ -3599,11 +3572,10 @@ namespace BizHawk.MultiClient
return str; return str;
} }
int LastOpenRomFilter = 0; int LastOpenRomFilter;
private void OpenROM() private void OpenROM()
{ {
var ofd = new OpenFileDialog(); var ofd = new OpenFileDialog {InitialDirectory = PathManager.GetRomsPath(Global.Emulator.SystemId)};
ofd.InitialDirectory = PathManager.GetRomsPath(Global.Emulator.SystemId);
//"Rom Files|*.NES;*.SMS;*.GG;*.SG;*.PCE;*.SGX;*.GB;*.BIN;*.SMD;*.ROM;*.ZIP;*.7z|NES (*.NES)|*.NES|Master System|*.SMS;*.GG;*.SG;*.ZIP;*.7z|PC Engine|*.PCE;*.SGX;*.ZIP;*.7z|Gameboy|*.GB;*.ZIP;*.7z|TI-83|*.rom|Archive Files|*.zip;*.7z|Savestate|*.state|All Files|*.*"; //"Rom Files|*.NES;*.SMS;*.GG;*.SG;*.PCE;*.SGX;*.GB;*.BIN;*.SMD;*.ROM;*.ZIP;*.7z|NES (*.NES)|*.NES|Master System|*.SMS;*.GG;*.SG;*.ZIP;*.7z|PC Engine|*.PCE;*.SGX;*.ZIP;*.7z|Gameboy|*.GB;*.ZIP;*.7z|TI-83|*.rom|Archive Files|*.zip;*.7z|Savestate|*.state|All Files|*.*";
//adelikat: ugly design for this, I know //adelikat: ugly design for this, I know
@ -3726,8 +3698,8 @@ namespace BizHawk.MultiClient
{ {
if (Global.Config.SaveWindowPosition) if (Global.Config.SaveWindowPosition)
{ {
Global.Config.MainWndx = this.Location.X; Global.Config.MainWndx = Location.X;
Global.Config.MainWndy = this.Location.Y; Global.Config.MainWndy = Location.Y;
} }
else else
{ {
@ -4081,9 +4053,10 @@ namespace BizHawk.MultiClient
IVideoWriter aw = null; IVideoWriter aw = null;
var writers = VideoWriterInventory.GetAllVideoWriters(); var writers = VideoWriterInventory.GetAllVideoWriters();
var video_writers = writers as IVideoWriter[] ?? writers.ToArray();
if (unattended) if (unattended)
{ {
foreach (var w in writers) foreach (var w in video_writers)
{ {
if (w.ShortName() == videowritername) if (w.ShortName() == videowritername)
{ {
@ -4094,10 +4067,10 @@ namespace BizHawk.MultiClient
} }
else else
{ {
aw = VideoWriterChooserForm.DoVideoWriterChoserDlg(writers, Global.MainForm, out avwriter_resizew, out avwriter_resizeh); aw = VideoWriterChooserForm.DoVideoWriterChoserDlg(video_writers, Global.MainForm, out avwriter_resizew, out avwriter_resizeh);
} }
foreach (var w in writers) foreach (var w in video_writers)
{ {
if (w != aw) if (w != aw)
w.Dispose(); w.Dispose();
@ -4174,7 +4147,7 @@ namespace BizHawk.MultiClient
//commit the avi writing last, in case there were any errors earlier //commit the avi writing last, in case there were any errors earlier
CurrAviWriter = aw; CurrAviWriter = aw;
Global.OSD.AddMessage("A/V capture started"); Global.OSD.AddMessage("A/V capture started");
AVIStatusLabel.Image = BizHawk.MultiClient.Properties.Resources.AVI; AVIStatusLabel.Image = Properties.Resources.AVI;
AVIStatusLabel.ToolTipText = "A/V capture in progress"; AVIStatusLabel.ToolTipText = "A/V capture in progress";
AVIStatusLabel.Visible = true; AVIStatusLabel.Visible = true;
@ -4207,7 +4180,7 @@ namespace BizHawk.MultiClient
CurrAviWriter.Dispose(); CurrAviWriter.Dispose();
CurrAviWriter = null; CurrAviWriter = null;
Global.OSD.AddMessage("A/V capture aborted"); Global.OSD.AddMessage("A/V capture aborted");
AVIStatusLabel.Image = BizHawk.MultiClient.Properties.Resources.Blank; AVIStatusLabel.Image = Properties.Resources.Blank;
AVIStatusLabel.ToolTipText = ""; AVIStatusLabel.ToolTipText = "";
AVIStatusLabel.Visible = false; AVIStatusLabel.Visible = false;
AviSoundInput = null; AviSoundInput = null;
@ -4228,7 +4201,7 @@ namespace BizHawk.MultiClient
CurrAviWriter.Dispose(); CurrAviWriter.Dispose();
CurrAviWriter = null; CurrAviWriter = null;
Global.OSD.AddMessage("A/V capture stopped"); Global.OSD.AddMessage("A/V capture stopped");
AVIStatusLabel.Image = BizHawk.MultiClient.Properties.Resources.Blank; AVIStatusLabel.Image = Properties.Resources.Blank;
AVIStatusLabel.ToolTipText = ""; AVIStatusLabel.ToolTipText = "";
AVIStatusLabel.Visible = false; AVIStatusLabel.Visible = false;
AviSoundInput = null; AviSoundInput = null;
@ -4287,7 +4260,7 @@ namespace BizHawk.MultiClient
} }
catch (Exception e) catch (Exception e)
{ {
MessageBox.Show("Video dumping died:\n\n" + e.ToString()); MessageBox.Show("Video dumping died:\n\n" + e);
AbortAVI(); AbortAVI();
} }
@ -4311,7 +4284,7 @@ namespace BizHawk.MultiClient
if (state.Exists == false) return; if (state.Exists == false) return;
if (backup.Exists == false) return; if (backup.Exists == false) return;
if (temp.Exists == true) temp.Delete(); if (temp.Exists) temp.Delete();
backup.CopyTo(path + ".bak.tmp"); backup.CopyTo(path + ".bak.tmp");
backup.Delete(); backup.Delete();
@ -4351,26 +4324,27 @@ namespace BizHawk.MultiClient
private void importMovieToolStripMenuItem_Click(object sender, EventArgs e) private void importMovieToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var ofd = new OpenFileDialog(); var ofd = new OpenFileDialog
ofd.InitialDirectory = PathManager.GetRomsPath(Global.Emulator.SystemId); {
ofd.Multiselect = true; InitialDirectory = PathManager.GetRomsPath(Global.Emulator.SystemId),
ofd.Filter = FormatFilter( Multiselect = true,
"Movie Files", "*.fm2;*.mc2;*.mcm;*.mmv;*.gmv;*.vbm;*.lsmv;*.fcm;*.fmv;*.vmv;*.nmv;*.smv;*.zmv;", Filter = FormatFilter(
"FCEUX", "*.fm2", "Movie Files", "*.fm2;*.mc2;*.mcm;*.mmv;*.gmv;*.vbm;*.lsmv;*.fcm;*.fmv;*.vmv;*.nmv;*.smv;*.zmv;",
"PCEjin/Mednafen", "*.mc2;*.mcm", "FCEUX", "*.fm2",
"Dega", "*.mmv", "PCEjin/Mednafen", "*.mc2;*.mcm",
"Gens", "*.gmv", "Dega", "*.mmv",
"Visual Boy Advance", "*.vbm", "Gens", "*.gmv",
"LSNES", "*.lsmv", "Visual Boy Advance", "*.vbm",
"FCEU", "*.fcm", "LSNES", "*.lsmv",
"Famtasia", "*.fmv", "FCEU", "*.fcm",
"VirtuaNES", "*.vmv", "Famtasia", "*.fmv",
"Nintendulator", "*.nmv", "VirtuaNES", "*.vmv",
"Snes9x", "*.smv", "Nintendulator", "*.nmv",
"ZSNES", "*.zmv", "Snes9x", "*.smv",
"All Files", "*.*"); "ZSNES", "*.zmv",
"All Files", "*.*"),
ofd.RestoreDirectory = false; RestoreDirectory = false
};
Global.Sound.StopSound(); Global.Sound.StopSound();
var result = ofd.ShowDialog(); var result = ofd.ShowDialog();
@ -4386,10 +4360,9 @@ namespace BizHawk.MultiClient
void ProcessMovieImport(string fn) void ProcessMovieImport(string fn)
{ {
var file = new FileInfo(fn);
string d = PathManager.MakeAbsolutePath(Global.Config.MoviesPath); string d = PathManager.MakeAbsolutePath(Global.Config.MoviesPath);
string errorMsg = ""; string errorMsg;
string warningMsg = ""; string warningMsg;
Movie m = MovieImport.ImportFile(fn, out errorMsg, out warningMsg); Movie m = MovieImport.ImportFile(fn, out errorMsg, out warningMsg);
if (errorMsg.Length > 0) if (errorMsg.Length > 0)
MessageBox.Show(errorMsg, "Conversion error", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(errorMsg, "Conversion error", MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -4457,7 +4430,6 @@ namespace BizHawk.MultiClient
if (num_images < 1 || frameskip < 1 || gifSpeed == 0) return false;//Exits if settings are bad if (num_images < 1 || frameskip < 1 || gifSpeed == 0) return false;//Exits if settings are bad
#region declare/insantiate variables #region declare/insantiate variables
List<Image> images = new List<Image>(); //Variable for holding all images for the gif animation List<Image> images = new List<Image>(); //Variable for holding all images for the gif animation
Image tempImage; //Holding the image in case it doesn't end up being added to the animation
// Such a scenario could be a frameskip setting of 2 and a gifSpeed setting of 3 // Such a scenario could be a frameskip setting of 2 and a gifSpeed setting of 3
// This would result in 1 of every 3 images being requested getting skipped. // This would result in 1 of every 3 images being requested getting skipped.
// My math might be wrong at this hour, but you get the point! // My math might be wrong at this hour, but you get the point!
@ -4471,7 +4443,7 @@ namespace BizHawk.MultiClient
images.Add(Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage()); images.Add(Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage());
while (images.Count < totalFrames) while (images.Count < totalFrames)
{ {
tempImage = Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage(); Image tempImage = Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage(); //Holding the image in case it doesn't end up being added to the animation
if (gifSpeed < 0) if (gifSpeed < 0)
for (speedTracker = 0; speedTracker > gifSpeed; speedTracker--) for (speedTracker = 0; speedTracker > gifSpeed; speedTracker--)
images.Add(tempImage); //If the speed of the animation is to be slowed down, then add that many copies images.Add(tempImage); //If the speed of the animation is to be slowed down, then add that many copies
@ -4505,9 +4477,8 @@ namespace BizHawk.MultiClient
#region make gif file #region make gif file
byte[] GifAnimation = { 33, 255, 11, 78, 69, 84, 83, 67, 65, 80, 69, 50, 46, 48, 3, 1, 0, 0, 0 }; byte[] GifAnimation = { 33, 255, 11, 78, 69, 84, 83, 67, 65, 80, 69, 50, 46, 48, 3, 1, 0, 0, 0 };
MemoryStream MS = new MemoryStream(); MemoryStream MS = new MemoryStream();
BinaryReader BR = new BinaryReader(MS);
var fi = new FileInfo(filename); var fi = new FileInfo(filename);
if (fi.Directory.Exists == false) if (fi.Directory != null && fi.Directory.Exists == false)
fi.Directory.Create(); fi.Directory.Create();
BinaryWriter BW = new BinaryWriter(new FileStream(filename, FileMode.Create)); BinaryWriter BW = new BinaryWriter(new FileStream(filename, FileMode.Create));
images[0].Save(MS, ImageFormat.Gif); images[0].Save(MS, ImageFormat.Gif);
@ -4554,44 +4525,6 @@ namespace BizHawk.MultiClient
#endregion #endregion
private void animatedGIFConfigToolStripMenuItem_Click(object sender, EventArgs e)
{
GifAnimator g = new GifAnimator();
g.Show();
}
private void makeAnimatedGIFToolStripMenuItem_Click(object sender, EventArgs e)
{
makeAnimatedGif();
}
private void makeAnimatedGif()
{
string path = String.Format(PathManager.ScreenshotPrefix(Global.Game) + "AGIF.{0:yyyy-MM-dd HH.mm.ss}.gif", DateTime.Now);
AnimatedGif(Global.Config.GifAnimatorNumFrames, Global.Config.GifAnimatorFrameSkip, Global.Config.GifAnimatorSpeed, Global.Config.GifAnimatorReversable, path);
}
private void makeAnimatedGif(string path)
{
AnimatedGif(Global.Config.GifAnimatorNumFrames, Global.Config.GifAnimatorFrameSkip, Global.Config.GifAnimatorSpeed, Global.Config.GifAnimatorReversable, path);
}
private void makeAnimatedGifAsToolStripMenuItem_Click(object sender, EventArgs e)
{
string path = String.Format(PathManager.ScreenshotPrefix(Global.Game) + "AGIF.{0:yyyy-MM-dd HH.mm.ss}.gif", DateTime.Now);
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = Path.GetDirectoryName(path);
sfd.FileName = Path.GetFileName(path);
sfd.Filter = "GIF File (*.gif)|*.gif";
Global.Sound.StopSound();
var result = sfd.ShowDialog();
Global.Sound.StartSound();
if (result != DialogResult.OK)
return;
makeAnimatedGif(sfd.FileName);
}
private void ShowConsole() private void ShowConsole()
{ {
LogConsole.ShowConsole(); LogConsole.ShowConsole();
@ -4680,7 +4613,7 @@ namespace BizHawk.MultiClient
private void IncreaseSpeed() private void IncreaseSpeed()
{ {
int oldp = Global.Config.SpeedPercent; int oldp = Global.Config.SpeedPercent;
int newp = 0; int newp;
if (oldp < 3) newp = 3; if (oldp < 3) newp = 3;
else if (oldp < 6) newp = 6; else if (oldp < 6) newp = 6;
else if (oldp < 12) newp = 12; else if (oldp < 12) newp = 12;
@ -4699,7 +4632,7 @@ namespace BizHawk.MultiClient
private void DecreaseSpeed() private void DecreaseSpeed()
{ {
int oldp = Global.Config.SpeedPercent; int oldp = Global.Config.SpeedPercent;
int newp = 0; int newp;
if (oldp > 800) newp = 800; if (oldp > 800) newp = 800;
else if (oldp > 400) newp = 400; else if (oldp > 400) newp = 400;
else if (oldp > 200) newp = 200; else if (oldp > 200) newp = 200;
@ -4876,11 +4809,6 @@ namespace BizHawk.MultiClient
Global.CoreComm.GG_HighlightActiveDisplayRegion = Global.Config.GGHighlightActiveDisplayRegion; Global.CoreComm.GG_HighlightActiveDisplayRegion = Global.Config.GGHighlightActiveDisplayRegion;
} }
private void loadConfigToolStripMenuItem_Click_1(object sender, EventArgs e)
{
}
private void saveMovieToolStripMenuItem_Click(object sender, EventArgs e) private void saveMovieToolStripMenuItem_Click(object sender, EventArgs e)
{ {
SaveMovie(); SaveMovie();
@ -4979,11 +4907,11 @@ namespace BizHawk.MultiClient
} }
if (Global.Emulator.CoreComm.DriveLED) if (Global.Emulator.CoreComm.DriveLED)
{ {
StatusBarLedLight.Image = BizHawk.MultiClient.Properties.Resources.LightOn; StatusBarLedLight.Image = Properties.Resources.LightOn;
} }
else else
{ {
StatusBarLedLight.Image = BizHawk.MultiClient.Properties.Resources.LightOff; StatusBarLedLight.Image = Properties.Resources.LightOff;
} }
} }
else else
@ -5066,15 +4994,15 @@ namespace BizHawk.MultiClient
{ {
default: default:
case 0: case 0:
KeyPriorityStatusBarLabel.Image = BizHawk.MultiClient.Properties.Resources.Both; KeyPriorityStatusBarLabel.Image = Properties.Resources.Both;
KeyPriorityStatusBarLabel.ToolTipText = "Key priority: Allow both hotkeys and controller buttons"; KeyPriorityStatusBarLabel.ToolTipText = "Key priority: Allow both hotkeys and controller buttons";
break; break;
case 1: case 1:
KeyPriorityStatusBarLabel.Image = BizHawk.MultiClient.Properties.Resources.GameController; KeyPriorityStatusBarLabel.Image = Properties.Resources.GameController;
KeyPriorityStatusBarLabel.ToolTipText = "Key priority: Controller buttons will override hotkeys"; KeyPriorityStatusBarLabel.ToolTipText = "Key priority: Controller buttons will override hotkeys";
break; break;
case 2: case 2:
KeyPriorityStatusBarLabel.Image = BizHawk.MultiClient.Properties.Resources.HotKeys; KeyPriorityStatusBarLabel.Image = Properties.Resources.HotKeys;
KeyPriorityStatusBarLabel.ToolTipText = "Key priority: Hotkeys will override controller buttons"; KeyPriorityStatusBarLabel.ToolTipText = "Key priority: Hotkeys will override controller buttons";
break; break;
} }

View File

@ -2,7 +2,7 @@
{ {
public class MruStack<T> public class MruStack<T>
{ {
private T[] store; private readonly T[] store;
private int count; private int count;
private int head; private int head;

View File

@ -104,7 +104,7 @@ namespace BizHawk.MultiClient
{ {
message += "\n\nInner Exception:\n\n" + e.InnerException; message += "\n\nInner Exception:\n\n" + e.InnerException;
} }
MessageBox.Show(e.ToString()); MessageBox.Show(message);
} }
#if WINDOWS #if WINDOWS
finally finally
@ -136,7 +136,7 @@ namespace BizHawk.MultiClient
//load missing assemblies by trying to find them in the dll directory //load missing assemblies by trying to find them in the dll directory
string dllname = new AssemblyName(args.Name).Name + ".dll"; string dllname = new AssemblyName(args.Name).Name + ".dll";
string directory = System.IO.Path.Combine(PathManager.GetExeDirectoryAbsolute(), "dll"); string directory = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "dll");
string fname = Path.Combine(directory, dllname); string fname = Path.Combine(directory, dllname);
if (!File.Exists(fname)) return null; if (!File.Exists(fname)) return null;
//it is important that we use LoadFile here and not load from a byte array; otherwise mixed (managed/unamanged) assemblies can't load //it is important that we use LoadFile here and not load from a byte array; otherwise mixed (managed/unamanged) assemblies can't load
@ -148,7 +148,7 @@ namespace BizHawk.MultiClient
public class SingleInstanceController : WindowsFormsApplicationBase public class SingleInstanceController : WindowsFormsApplicationBase
{ {
MainForm mf; MainForm mf;
string[] cmdArgs; readonly string[] cmdArgs;
public SingleInstanceController(string[] args) public SingleInstanceController(string[] args)
{ {
cmdArgs = args; cmdArgs = args;

View File

@ -1,13 +1,9 @@
using System; using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using sysdrawingfont=System.Drawing.Font; using sysdrawingfont=System.Drawing.Font;
using sysdrawing2d=System.Drawing.Drawing2D; using sysdrawing2d=System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
#if WINDOWS #if WINDOWS
using SlimDX; using SlimDX;
@ -57,7 +53,6 @@ namespace BizHawk.MultiClient
} }
else else
{ {
var currentTextureSize = Texture.GetLevelDescription(0);
if (imageWidth != width || imageHeight != height) if (imageWidth != width || imageHeight != height)
{ {
needsRecreating = true; needsRecreating = true;
@ -129,7 +124,7 @@ namespace BizHawk.MultiClient
void FastRenderAndPresent(DisplaySurface surface); void FastRenderAndPresent(DisplaySurface surface);
void Render(DisplaySurface surface); void Render(DisplaySurface surface);
void RenderOverlay(DisplaySurface surface); void RenderOverlay(DisplaySurface surface);
void Clear(System.Drawing.Color color); void Clear(Color color);
void Present(); void Present();
bool Resized { get; set; } bool Resized { get; set; }
Size NativeSize { get; } Size NativeSize { get; }
@ -143,10 +138,11 @@ namespace BizHawk.MultiClient
public class SysdrawingRenderPanel : IRenderer, IBlitter public class SysdrawingRenderPanel : IRenderer, IBlitter
{ {
sysdrawingfont MessageFont; private readonly sysdrawingfont MessageFont;
sysdrawingfont AlertFont; private readonly sysdrawingfont AlertFont;
DisplaySurface tempBuffer; private DisplaySurface tempBuffer;
Graphics g; private Graphics g;
private readonly SwappableDisplaySurfaceSet surfaceSet = new SwappableDisplaySurfaceSet();
public bool Resized { get; set; } public bool Resized { get; set; }
public void Dispose() { } public void Dispose() { }
@ -157,9 +153,8 @@ namespace BizHawk.MultiClient
lock (this) lock (this)
tempBuffer = surfaceSet.AllocateSurface(backingControl.Width, backingControl.Height, false); tempBuffer = surfaceSet.AllocateSurface(backingControl.Width, backingControl.Height, false);
RenderInternal(surface, false); RenderInternal(surface);
} }
SwappableDisplaySurfaceSet surfaceSet = new SwappableDisplaySurfaceSet();
class FontWrapper : IBlitterFont class FontWrapper : IBlitterFont
{ {
@ -167,7 +162,8 @@ namespace BizHawk.MultiClient
{ {
this.font = font; this.font = font;
} }
public sysdrawingfont font;
public readonly sysdrawingfont font;
} }
public Size NativeSize { get { return backingControl.ClientSize; } } public Size NativeSize { get { return backingControl.ClientSize; } }
@ -294,9 +290,9 @@ namespace BizHawk.MultiClient
public bool Resized { get; set; } public bool Resized { get; set; }
public string FPS { get; set; } public string FPS { get; set; }
public string MT { get; set; } public string MT { get; set; }
private Direct3D d3d; private readonly Direct3D d3d;
private Device Device; private Device _device;
private Control backingControl; private readonly Control backingControl;
public ImageTexture Texture; public ImageTexture Texture;
private Sprite Sprite; private Sprite Sprite;
private d3d9font MessageFont; private d3d9font MessageFont;
@ -308,7 +304,8 @@ namespace BizHawk.MultiClient
{ {
this.font = font; this.font = font;
} }
public d3d9font font;
public readonly d3d9font font;
} }
void IBlitter.Open() void IBlitter.Open()
@ -371,10 +368,10 @@ namespace BizHawk.MultiClient
Sprite = null; Sprite = null;
} }
if (Device != null) if (_device != null)
{ {
Device.Dispose(); _device.Dispose();
Device = null; _device = null;
} }
if (MessageFont != null) if (MessageFont != null)
@ -416,12 +413,12 @@ namespace BizHawk.MultiClient
{ {
flags = CreateFlags.HardwareVertexProcessing; flags = CreateFlags.HardwareVertexProcessing;
} }
Device = new Device(d3d, 0, DeviceType.Hardware, backingControl.Handle, flags, pp); _device = new Device(d3d, 0, DeviceType.Hardware, backingControl.Handle, flags, pp);
Sprite = new Sprite(Device); Sprite = new Sprite(_device);
Texture = new ImageTexture(Device); Texture = new ImageTexture(_device);
MessageFont = new d3d9font(Device, 16, 0, FontWeight.Bold, 1, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.Default | PitchAndFamily.DontCare, "Courier"); MessageFont = new d3d9font(_device, 16, 0, FontWeight.Bold, 1, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.Default | PitchAndFamily.DontCare, "Courier");
AlertFont = new d3d9font(Device, 16, 0, FontWeight.ExtraBold, 1, true, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.Default | PitchAndFamily.DontCare, "Courier"); AlertFont = new d3d9font(_device, 16, 0, FontWeight.ExtraBold, 1, true, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.Default | PitchAndFamily.DontCare, "Courier");
// NOTE: if you add ANY objects, like new fonts, textures, etc, to this method // NOTE: if you add ANY objects, like new fonts, textures, etc, to this method
// ALSO add dispose code in DestroyDevice() or you will be responsible for VRAM memory leaks. // ALSO add dispose code in DestroyDevice() or you will be responsible for VRAM memory leaks.
@ -429,11 +426,11 @@ namespace BizHawk.MultiClient
public void Render() public void Render()
{ {
if (Device == null || Resized || Vsync != VsyncRequested) if (_device == null || Resized || Vsync != VsyncRequested)
backingControl.Invoke(() => CreateDevice()); backingControl.Invoke(() => CreateDevice());
Resized = false; Resized = false;
Device.Clear(ClearFlags.Target, BackgroundColor, 1.0f, 0); _device.Clear(ClearFlags.Target, BackgroundColor, 1.0f, 0);
Present(); Present();
} }
@ -467,7 +464,7 @@ namespace BizHawk.MultiClient
if (Global.Sound != null) Global.Sound.StopSound(); if (Global.Sound != null) Global.Sound.StopSound();
do do
{ {
r = Device.TestCooperativeLevel(); r = _device.TestCooperativeLevel();
Thread.Sleep(100); Thread.Sleep(100);
} while (r == ResultCode.DeviceLost); } while (r == ResultCode.DeviceLost);
if (Global.Sound != null) Global.Sound.StartSound(); if (Global.Sound != null) Global.Sound.StartSound();
@ -481,14 +478,14 @@ namespace BizHawk.MultiClient
void RenderPrep() void RenderPrep()
{ {
if (Device == null || Resized || Vsync != VsyncRequested) if (_device == null || Resized || Vsync != VsyncRequested)
backingControl.Invoke(() => CreateDevice()); backingControl.Invoke(() => CreateDevice());
Resized = false; Resized = false;
} }
public void Clear(Color color) public void Clear(Color color)
{ {
Device.Clear(ClearFlags.Target, col(color), 0.0f, 0); _device.Clear(ClearFlags.Target, col(color), 0.0f, 0);
} }
private void RenderExec(DisplaySurface surface, bool overlay) private void RenderExec(DisplaySurface surface, bool overlay)
@ -502,32 +499,32 @@ namespace BizHawk.MultiClient
Texture.SetImage(surface, surface.Width, surface.Height); Texture.SetImage(surface, surface.Width, surface.Height);
if(!overlay) Device.Clear(ClearFlags.Target, BackgroundColor, 0.0f, 0); if(!overlay) _device.Clear(ClearFlags.Target, BackgroundColor, 0.0f, 0);
// figure out scaling factor // figure out scaling factor
float widthScale = (float)backingControl.Size.Width / surface.Width; float widthScale = (float)backingControl.Size.Width / surface.Width;
float heightScale = (float)backingControl.Size.Height / surface.Height; float heightScale = (float)backingControl.Size.Height / surface.Height;
float finalScale = Math.Min(widthScale, heightScale); float finalScale = Math.Min(widthScale, heightScale);
Device.BeginScene(); _device.BeginScene();
SpriteFlags flags = SpriteFlags.None; SpriteFlags flags = SpriteFlags.None;
if (overlay) flags |= SpriteFlags.AlphaBlend; if (overlay) flags |= SpriteFlags.AlphaBlend;
Sprite.Begin(flags); Sprite.Begin(flags);
if (Global.Config.DispBlurry) if (Global.Config.DispBlurry)
{ {
Device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Linear); _device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Linear);
Device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Linear); _device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Linear);
} }
else else
{ {
Device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Point); _device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Point);
Device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Point); _device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Point);
} }
Sprite.Transform = Matrix.Scaling(finalScale, finalScale, 0f); Sprite.Transform = Matrix.Scaling(finalScale, finalScale, 0f);
Sprite.Draw(Texture.Texture, new Rectangle(0, 0, surface.Width, surface.Height), new Vector3(surface.Width / 2f, surface.Height / 2f, 0), new Vector3(backingControl.Size.Width / 2f / finalScale, backingControl.Size.Height / 2f / finalScale, 0), Color.White); Sprite.Draw(Texture.Texture, new Rectangle(0, 0, surface.Width, surface.Height), new Vector3(surface.Width / 2f, surface.Height / 2f, 0), new Vector3(backingControl.Size.Width / 2f / finalScale, backingControl.Size.Height / 2f / finalScale, 0), Color.White);
Sprite.End(); Sprite.End();
Device.EndScene(); _device.EndScene();
} }
public void Present() public void Present()
@ -536,9 +533,9 @@ namespace BizHawk.MultiClient
RenderWrapper(_Present); RenderWrapper(_Present);
} }
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); private readonly System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
long stopwatchthrottle = System.Diagnostics.Stopwatch.Frequency / 50; private readonly long stopwatchthrottle = System.Diagnostics.Stopwatch.Frequency / 50;
long stopwatchtmr = 0; private long stopwatchtmr;
private void _Present() private void _Present()
{ {
// according to the internet, D3DPRESENT_DONOTWAIT is not terribly reliable // according to the internet, D3DPRESENT_DONOTWAIT is not terribly reliable
@ -555,7 +552,7 @@ namespace BizHawk.MultiClient
{ {
stopwatch.Restart(); stopwatch.Restart();
//Device.GetSwapChain(0).Present(SlimDX.Direct3D9.Present.DoNotWait); //Device.GetSwapChain(0).Present(SlimDX.Direct3D9.Present.DoNotWait);
Device.Present(SlimDX.Direct3D9.Present.None); _device.Present(SlimDX.Direct3D9.Present.None);
stopwatch.Stop(); stopwatch.Stop();
stopwatchtmr += stopwatch.ElapsedTicks; stopwatchtmr += stopwatch.ElapsedTicks;
//Console.WriteLine('.'); //Console.WriteLine('.');
@ -563,7 +560,7 @@ namespace BizHawk.MultiClient
} }
} }
else else
Device.Present(SlimDX.Direct3D9.Present.None); _device.Present(SlimDX.Direct3D9.Present.None);
} }
// not used anywhere? // not used anywhere?

View File

@ -4,32 +4,32 @@ namespace BizHawk.MultiClient
{ {
public partial class MainForm public partial class MainForm
{ {
MruStack<MemoryStream> RewindBuf = new MruStack<MemoryStream>(15000); private readonly MruStack<MemoryStream> RewindBuf = new MruStack<MemoryStream>(15000);
byte[] LastState; private byte[] LastState;
bool RewindImpossible = false; private bool RewindImpossible;
void CaptureRewindState() void CaptureRewindState()
{ {
if (RewindImpossible) if (RewindImpossible)
return; return;
if (LastState == null) if (LastState == null)
{ {
// This is the first frame. Capture the state, and put it in LastState for future deltas to be compared against. // This is the first frame. Capture the state, and put it in LastState for future deltas to be compared against.
LastState = Global.Emulator.SaveStateBinary(); LastState = Global.Emulator.SaveStateBinary();
if (LastState.Length > 0x100000) if (LastState.Length > 0x100000)
{ {
RewindImpossible = true; RewindImpossible = true;
LastState = null; LastState = null;
Global.OSD.AddMessage("Rewind Disabled: State too large."); Global.OSD.AddMessage("Rewind Disabled: State too large.");
Global.OSD.AddMessage("See 'Arcade Card Rewind Hack' in Emulation->PC Engine options."); Global.OSD.AddMessage("See 'Arcade Card Rewind Hack' in Emulation->PC Engine options.");
} }
return; return;
} }
// Otherwise, it's not the first frame, so build a delta. // Otherwise, it's not the first frame, so build a delta.
if (LastState.Length <= 0x10000) if (LastState.Length <= 0x10000)
CaptureRewindState64K(); CaptureRewindState64K();
else else
CaptureRewindStateLarge(); CaptureRewindStateLarge();
@ -197,7 +197,7 @@ namespace BizHawk.MultiClient
{ {
for (int i = 0; i < frames; i++) for (int i = 0; i < frames; i++)
{ {
if (RewindBuf.Count == 0 || (true == Global.MovieSession.Movie.Loaded && 0 == Global.MovieSession.Movie.Frames)) if (RewindBuf.Count == 0 || (Global.MovieSession.Movie.Loaded && 0 == Global.MovieSession.Movie.Frames))
{ {
return; return;
} }
@ -215,13 +215,13 @@ namespace BizHawk.MultiClient
public void ResetRewindBuffer() public void ResetRewindBuffer()
{ {
RewindBuf.Clear(); RewindBuf.Clear();
RewindImpossible = false; RewindImpossible = false;
LastState = null; LastState = null;
} }
public int RewindBufferCount() public int RewindBufferCount()
{ {
return RewindBuf.Count; return RewindBuf.Count;
} }
} }
} }

View File

@ -5,24 +5,20 @@ using SlimDX.DirectSound;
using SlimDX.Multimedia; using SlimDX.Multimedia;
#endif #endif
using BizHawk.Emulation.Consoles.Nintendo;
namespace BizHawk.MultiClient namespace BizHawk.MultiClient
{ {
#if WINDOWS #if WINDOWS
public class Sound : IDisposable public class Sound : IDisposable
{ {
private bool Muted = false;
private bool disposed = false;
private SecondarySoundBuffer DSoundBuffer;
private byte[] SoundBuffer;
private const int BufferSize = 4410 * 2 * 2; // 1/10th of a second, 2 bytes per sample, 2 channels;
//private int SoundBufferPosition; //TODO: use this
public bool needDiscard; public bool needDiscard;
private BufferedAsync semisync = new BufferedAsync(); private bool Muted;
private readonly bool disposed;
private SecondarySoundBuffer DSoundBuffer;
private readonly byte[] SoundBuffer;
private const int BufferSize = 4410 * 2 * 2; // 1/10th of a second, 2 bytes per sample, 2 channels;
//private int SoundBufferPosition; //TODO: use this
private readonly BufferedAsync semisync = new BufferedAsync();
private ISoundProvider asyncsoundProvider; private ISoundProvider asyncsoundProvider;
private ISyncSoundProvider syncsoundProvider; private ISyncSoundProvider syncsoundProvider;
@ -32,18 +28,23 @@ namespace BizHawk.MultiClient
{ {
device.SetCooperativeLevel(handle, CooperativeLevel.Priority); device.SetCooperativeLevel(handle, CooperativeLevel.Priority);
var format = new WaveFormat(); var format = new WaveFormat
format.SamplesPerSecond = 44100; {
format.BitsPerSample = 16; SamplesPerSecond = 44100,
format.Channels = 2; BitsPerSample = 16,
format.FormatTag = WaveFormatTag.Pcm; Channels = 2,
format.BlockAlignment = 4; FormatTag = WaveFormatTag.Pcm,
BlockAlignment = 4
};
format.AverageBytesPerSecond = format.SamplesPerSecond * format.Channels * (format.BitsPerSample / 8); format.AverageBytesPerSecond = format.SamplesPerSecond * format.Channels * (format.BitsPerSample / 8);
var desc = new SoundBufferDescription(); var desc = new SoundBufferDescription
desc.Format = format; {
desc.Flags = BufferFlags.GlobalFocus | BufferFlags.Software | BufferFlags.GetCurrentPosition2 | BufferFlags.ControlVolume; Format = format,
desc.SizeInBytes = BufferSize; Flags =
BufferFlags.GlobalFocus | BufferFlags.Software | BufferFlags.GetCurrentPosition2 | BufferFlags.ControlVolume,
SizeInBytes = BufferSize
};
DSoundBuffer = new SecondarySoundBuffer(device, desc); DSoundBuffer = new SecondarySoundBuffer(device, desc);
ChangeVolume(Global.Config.SoundVolume); ChangeVolume(Global.Config.SoundVolume);
} }
@ -158,7 +159,7 @@ namespace BizHawk.MultiClient
int samplesNeeded = SNDDXGetAudioSpace() * 2; int samplesNeeded = SNDDXGetAudioSpace() * 2;
short[] samples; short[] samples;
int samplesProvided = 0; int samplesProvided;
if (Muted) if (Muted)
@ -239,22 +240,10 @@ namespace BizHawk.MultiClient
/// </summary> /// </summary>
public void UpdateSoundSettings() public void UpdateSoundSettings()
{ {
int vol = Global.Config.SoundVolume;
if (!Global.Config.SoundEnabled || Global.Config.SoundVolume == 0) if (!Global.Config.SoundEnabled || Global.Config.SoundVolume == 0)
DSoundBuffer.Volume = -5000; DSoundBuffer.Volume = -5000;
else else
DSoundBuffer.Volume = 0 - ((100 - Global.Config.SoundVolume) * 15); DSoundBuffer.Volume = 0 - ((100 - Global.Config.SoundVolume) * 15);
/* //adelikat: I've been told this isn't TAS safe, so I'm disabling this speed hack
if (Global.Emulator is NES)
{
NES n = Global.Emulator as NES;
if (Global.Config.SoundEnabled == false)
n.SoundOn = false;
else
n.SoundOn = true;
}
*/
} }
} }
#else #else

View File

@ -1,7 +1,6 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
using System.IO;
//this throttle is nitsuja's fine-tuned techniques from desmume //this throttle is nitsuja's fine-tuned techniques from desmume
@ -36,7 +35,7 @@ namespace BizHawk.MultiClient
} }
public bool cfg_frameLimit public bool cfg_frameLimit
{ {
get get
{ {
if (Global.ClientControls["MaxTurbo"]) if (Global.ClientControls["MaxTurbo"])
{ {
@ -44,7 +43,7 @@ namespace BizHawk.MultiClient
} }
else else
{ {
return Global.Config.ClockThrottle; return Global.Config.ClockThrottle;
} }
} }
} }
@ -111,7 +110,7 @@ namespace BizHawk.MultiClient
SpeedThrottle(signal_paused); SpeedThrottle(signal_paused);
} }
if (cfg_autoframeskipenab && cfg_frameskiprate!=0) if (cfg_autoframeskipenab && cfg_frameskiprate != 0)
{ {
if (!signal_frameAdvance && !signal_continuousframeAdvancing) if (!signal_frameAdvance && !signal_continuousframeAdvancing)
{ {
@ -149,7 +148,7 @@ namespace BizHawk.MultiClient
{ {
ulong tmp; ulong tmp;
QueryPerformanceCounter(out tmp); QueryPerformanceCounter(out tmp);
return (ulong)tmp; return tmp;
} }
else else
{ {
@ -168,17 +167,14 @@ namespace BizHawk.MultiClient
[DllImport("kernel32.dll", SetLastError = true)] [DllImport("kernel32.dll", SetLastError = true)]
static extern bool QueryPerformanceFrequency(out ulong frequency); static extern bool QueryPerformanceFrequency(out ulong frequency);
[DllImport("winmm.dll", EntryPoint = "timeEndPeriod")]
static extern uint timeEndPeriod(uint uMilliseconds);
[DllImport("winmm.dll", EntryPoint = "timeBeginPeriod")] [DllImport("winmm.dll", EntryPoint = "timeBeginPeriod")]
static extern uint timeBeginPeriod(uint uMilliseconds); static extern uint timeBeginPeriod(uint uMilliseconds);
static int tmethod; static readonly int tmethod;
#endif #endif
static ulong afsfreq; static readonly ulong afsfreq;
static ulong tfreq; static readonly ulong tfreq;
static Throttle() static Throttle()
{ {
@ -196,13 +192,9 @@ namespace BizHawk.MultiClient
tfreq = afsfreq << 16; tfreq = afsfreq << 16;
} }
public Throttle()
{
}
public void SetCoreFps(double desired_fps) public void SetCoreFps(double desired_fps)
{ {
core_desiredfps = (ulong)(65536 * desired_fps); core_desiredfps = (ulong)(65536 * desired_fps);
int target_pct = pct; int target_pct = pct;
pct = -1; pct = -1;
SetSpeedPercent(target_pct); SetSpeedPercent(target_pct);
@ -217,7 +209,7 @@ namespace BizHawk.MultiClient
float fraction = percent / 100.0f; float fraction = percent / 100.0f;
desiredfps = (ulong)(core_desiredfps * fraction); desiredfps = (ulong)(core_desiredfps * fraction);
//Console.WriteLine("throttle set desiredfps " + desiredfps); //Console.WriteLine("throttle set desiredfps " + desiredfps);
desiredspf = 65536.0f / desiredfps; desiredspf = 65536.0f / desiredfps;
AutoFrameSkip_IgnorePreviousDelay(); AutoFrameSkip_IgnorePreviousDelay();
} }
@ -226,12 +218,12 @@ namespace BizHawk.MultiClient
float desiredspf; float desiredspf;
ulong ltime; ulong ltime;
ulong beginticks = 0, endticks = 0, preThrottleEndticks = 0; ulong beginticks, endticks, preThrottleEndticks;
float fSkipFrames = 0; float fSkipFrames;
float fSkipFramesError = 0; float fSkipFramesError;
int lastSkip = 0; int lastSkip;
float lastError = 0; float lastError;
float integral = 0; float integral;
public void AutoFrameSkip_IgnorePreviousDelay() public void AutoFrameSkip_IgnorePreviousDelay()
{ {
@ -357,8 +349,7 @@ namespace BizHawk.MultiClient
if ((ttime - ltime) < (tfreq / desiredfps)) if ((ttime - ltime) < (tfreq / desiredfps))
{ {
ulong sleepy; ulong sleepy = (tfreq / desiredfps) - (ttime - ltime);
sleepy = (tfreq / desiredfps) - (ttime - ltime);
sleepy *= 1000; sleepy *= 1000;
if (tfreq >= 65536) if (tfreq >= 65536)
sleepy /= afsfreq; sleepy /= afsfreq;
@ -366,8 +357,8 @@ namespace BizHawk.MultiClient
sleepy = 0; sleepy = 0;
if (sleepy >= 10 || paused) if (sleepy >= 10 || paused)
{ {
Thread.Sleep((int) (sleepy/2)); Thread.Sleep((int)(sleepy / 2));
// reduce it further beacuse Sleep usually sleeps for more than the amount we tell it to // reduce it further beacuse Sleep usually sleeps for more than the amount we tell it to
} }
else if (sleepy > 0) // spin for <1 millisecond waits else if (sleepy > 0) // spin for <1 millisecond waits
{ {