From 36fb605a7c5262a04e2752c55ae97093d26c1a73 Mon Sep 17 00:00:00 2001 From: Zoryn Aaron Date: Sat, 26 Mar 2016 21:50:47 -0400 Subject: uhhhhhh. async logging. an event i think. something or other. mid-update commit. --- StardewModdingAPI/Constants.cs | 11 +- StardewModdingAPI/Events/EventArgs.cs | 10 ++ StardewModdingAPI/Events/Graphics.cs | 8 +- StardewModdingAPI/Events/Mine.cs | 6 +- StardewModdingAPI/Inheritance/SGame.cs | 55 +++++++-- StardewModdingAPI/Log.cs | 181 ----------------------------- StardewModdingAPI/Program.cs | 40 ++++--- StardewModdingAPI/StardewModdingAPI.csproj | 2 +- 8 files changed, 99 insertions(+), 214 deletions(-) delete mode 100644 StardewModdingAPI/Log.cs (limited to 'StardewModdingAPI') diff --git a/StardewModdingAPI/Constants.cs b/StardewModdingAPI/Constants.cs index a29e5fa8..109f22f8 100644 --- a/StardewModdingAPI/Constants.cs +++ b/StardewModdingAPI/Constants.cs @@ -42,13 +42,20 @@ namespace StardewModdingAPI /// Path for log files to be output to. /// %LocalAppData%//StardewValley//ErrorLogs /// - public static string LogPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "StardewValley", "ErrorLogs"); + public static string LogDir => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "StardewValley", "ErrorLogs"); + public static string LogPath => Path.Combine(LogDir, "MODDED_ProgramLog.Log_LATEST.txt"); - public static readonly Version Version = new Version(0, 39, 2, "Alpha"); + public static readonly Version Version = new Version(0, 39, 3, "Alpha"); /// /// Not quite "constant", but it makes more sense for it to be here, at least for now /// public static int ModsLoaded = 0; + + /// + /// Whether or not to enable the Render Target drawing code offered by ClxS + /// Do not mark as 'const' or else 'if' checks will complain that the expression is always true in ReSharper + /// + public static bool EnableDrawingIntoRenderTarget => true; } } diff --git a/StardewModdingAPI/Events/EventArgs.cs b/StardewModdingAPI/Events/EventArgs.cs index a6de3597..59fa1bbd 100644 --- a/StardewModdingAPI/Events/EventArgs.cs +++ b/StardewModdingAPI/Events/EventArgs.cs @@ -108,6 +108,16 @@ namespace StardewModdingAPI.Events } public List NewLocations { get; private set; } } + public class EventArgsMineLevelChanged : EventArgs + { + public EventArgsMineLevelChanged(int previousMineLevel, int currentMineLevel) + { + PreviousMineLevel = previousMineLevel; + CurrentMineLevel = currentMineLevel; + } + public int PreviousMineLevel { get; private set; } + public int CurrentMineLevel { get; private set; } + } public class EventArgsLocationObjectsChanged : EventArgs { diff --git a/StardewModdingAPI/Events/Graphics.cs b/StardewModdingAPI/Events/Graphics.cs index 87ee845b..db963924 100644 --- a/StardewModdingAPI/Events/Graphics.cs +++ b/StardewModdingAPI/Events/Graphics.cs @@ -6,6 +6,7 @@ namespace StardewModdingAPI.Events { public static event EventHandler Resize = delegate { }; public static event EventHandler DrawTick = delegate { }; + public static event EventHandler DrawInRenderTargetTick = delegate { }; public static void InvokeDrawTick() { @@ -15,10 +16,15 @@ namespace StardewModdingAPI.Events } catch (Exception ex) { - Log.Error("An exception occured in XNA DrawTick: " + ex); + Log.Error("An exception occured in a Mod's DrawTick: " + ex); } } + public static void InvokeDrawInRenderTargetTick() + { + DrawInRenderTargetTick.Invoke(null, EventArgs.Empty); + } + public static void InvokeResize(object sender, EventArgs e) { Resize.Invoke(sender, e); diff --git a/StardewModdingAPI/Events/Mine.cs b/StardewModdingAPI/Events/Mine.cs index 2f4e9ba7..f48e9574 100644 --- a/StardewModdingAPI/Events/Mine.cs +++ b/StardewModdingAPI/Events/Mine.cs @@ -4,11 +4,11 @@ namespace StardewModdingAPI.Events { public static class MineEvents { - public static event EventHandler MineLevelChanged = delegate { }; + public static event EventHandler MineLevelChanged = delegate { }; - public static void InvokeLocationsChanged(int currentMineLevel) + public static void InvokeMineLevelChanged(int previousMinelevel, int currentMineLevel) { - + MineLevelChanged.Invoke(null, new EventArgsMineLevelChanged(previousMinelevel, currentMineLevel)); } } } diff --git a/StardewModdingAPI/Inheritance/SGame.cs b/StardewModdingAPI/Inheritance/SGame.cs index da6260be..ce2488d5 100644 --- a/StardewModdingAPI/Inheritance/SGame.cs +++ b/StardewModdingAPI/Inheritance/SGame.cs @@ -32,15 +32,10 @@ namespace StardewModdingAPI.Inheritance public Keys[] CurrentlyPressedKeys => KStateNow.GetPressedKeys(); public Keys[] PreviouslyPressedKeys => KStatePrior.GetPressedKeys(); - public Keys[] FramePressedKeys - { - get { return CurrentlyPressedKeys.Except(PreviouslyPressedKeys).ToArray(); } - } - public Keys[] FrameReleasedKeys - { - get { return PreviouslyPressedKeys.Except(CurrentlyPressedKeys).ToArray(); } - } - + public Keys[] FramePressedKeys => CurrentlyPressedKeys.Except(PreviouslyPressedKeys).ToArray(); + + public Keys[] FrameReleasedKeys => PreviouslyPressedKeys.Except(CurrentlyPressedKeys).ToArray(); + public Buttons[][] PreviouslyPressedButtons; private bool WasButtonJustPressed(Buttons button, ButtonState buttonState, PlayerIndex stateIndex) @@ -161,6 +156,8 @@ namespace StardewModdingAPI.Inheritance public GameLocation PreviousGameLocation { get; private set; } public IClickableMenu PreviousActiveMenu { get; private set; } + public int PreviousMineLevel { get; private set; } + public Int32 PreviousTimeOfDay { get; private set; } public Int32 PreviousDayOfMonth { get; private set; } public String PreviousSeasonOfYear { get; private set; } @@ -282,6 +279,40 @@ namespace StardewModdingAPI.Inheritance GraphicsEvents.InvokeDrawTick(); + if (Constants.EnableDrawingIntoRenderTarget) + { + if (!options.zoomLevel.Equals(1.0f)) + { + if (Screen.RenderTargetUsage == RenderTargetUsage.DiscardContents) + { + Screen = new RenderTarget2D(graphics.GraphicsDevice, Math.Min(4096, (int) (Window.ClientBounds.Width * (1.0 / options.zoomLevel))), + Math.Min(4096, (int) (Window.ClientBounds.Height * (1.0 / options.zoomLevel))), + false, SurfaceFormat.Color, DepthFormat.Depth16, 1, RenderTargetUsage.PreserveContents); + } + GraphicsDevice.SetRenderTarget(Screen); + } + + // Not beginning the batch due to inconsistancies with the standard draw tick... + //spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + + GraphicsEvents.InvokeDrawInRenderTargetTick(); + + //spriteBatch.End(); + + if (!options.zoomLevel.Equals(1.0f)) + { + GraphicsDevice.SetRenderTarget(null); + spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); + spriteBatch.Draw(Screen, Vector2.Zero, Screen.Bounds, Color.White, 0.0f, Vector2.Zero, options.zoomLevel, SpriteEffects.None, 1f); + spriteBatch.End(); + } + + //Re-draw the mouse + spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + spriteBatch.Draw(mouseCursors, new Vector2(getMouseX(), getMouseY()), getSourceRectForStandardTileSheet(mouseCursors, mouseCursor, 16, 16), Color.White * mouseCursorTransparency, 0.0f, Vector2.Zero, pixelZoom + dialogueButtonScale / 150f, SpriteEffects.None, 1f); + spriteBatch.End(); + } + if (Debug) { spriteBatch.Begin(); @@ -490,6 +521,12 @@ namespace StardewModdingAPI.Inheritance FireLoadedGameEvent = true; PreviouslyLoadedGame = hasLoadedGame; } + + if (mine != null && PreviousMineLevel != mine.mineLevel) + { + MineEvents.InvokeMineLevelChanged(PreviousMineLevel, mine.mineLevel); + PreviousMineLevel = mine.mineLevel; + } } private bool HasInventoryChanged(List items, out List changedItems) diff --git a/StardewModdingAPI/Log.cs b/StardewModdingAPI/Log.cs deleted file mode 100644 index 6c338edc..00000000 --- a/StardewModdingAPI/Log.cs +++ /dev/null @@ -1,181 +0,0 @@ -using System; -using System.IO; -using System.Threading; - -namespace StardewModdingAPI -{ - - /// - /// Class to organize logging calls. - /// - public class Log - { - private static StreamWriter _logStream; - private static string _logPath; - - /// - /// Set up the logging stream - /// - /// - public static void Initialize(string logPath) - { - _logPath = logPath; - var logFile = string.Format("{0}\\MODDED_ProgramLog.Log_LATEST.txt", logPath); - try - { - _logStream = new StreamWriter(logFile, false); - } - catch (Exception) - { - // TODO: not use general exception - Error("Could not initialize LogStream - Logging is disabled"); - } - } - - private static void PrintLog(object message, bool disableLogging) - { - string logOutput = $"[{DateTime.Now.ToLongTimeString()}] {message?.ToString()}"; - Console.WriteLine(logOutput); - - if (_logStream != null && !disableLogging) - { - _logStream.WriteLine(logOutput); - _logStream.Flush(); - } - } - - /// - /// Print provided parameters to the console/file as applicable - /// - /// Desired message - /// When true, writes to ONLY console and not the log file. - /// Deprecated. Does nothing. - private static void PrintLog(object message, bool disableLogging, params object[] values) - { - PrintLog(message, disableLogging); - } - - /// - /// Successful message to display to console and logging. - /// - /// - /// Deprecated. Do not use. - public static void Success(object message, params object[] values) - { - Console.ForegroundColor = ConsoleColor.Green; - PrintLog(message?.ToString(), false); - Console.ForegroundColor = ConsoleColor.Gray; - } - - /// - /// Generic comment to display to console and logging. - /// - /// - /// Deprecated. Do not use. - public static void Verbose(object message, params object[] values) - { - Console.ForegroundColor = ConsoleColor.Gray; - PrintLog(message?.ToString(), false); - Console.ForegroundColor = ConsoleColor.Gray; - } - - /// - /// Additional comment to display to console and logging. - /// - /// - /// Deprecated. Do not use. - public static void Comment(object message, params object[] values) - { - Console.ForegroundColor = ConsoleColor.Yellow; - PrintLog(message?.ToString(), false); - Console.ForegroundColor = ConsoleColor.Gray; - } - - /// - /// Message for only console. Does not appear in logging. - /// - /// - /// Deprecated. Do not use. - public static void Info(object message, params object[] values) - { - Console.ForegroundColor = ConsoleColor.Gray; - PrintLog(message?.ToString(), true); - Console.ForegroundColor = ConsoleColor.Gray; - } - - /// - /// Important message indicating an error. - /// - /// - /// Deprecated. Do not use. - public static void Error(object message, params object[] values) - { - Console.ForegroundColor = ConsoleColor.Red; - PrintLog(message?.ToString(), false); - Console.ForegroundColor = ConsoleColor.Gray; - } - - /// - /// A message displayed only while in DEBUG mode - /// - /// - /// Deprecated. Do not use. - public static void Debug(object message, params object[] values) - { -#if DEBUG - Console.ForegroundColor = ConsoleColor.Yellow; - Log.PrintLog(message.ToString(), false); - Console.ForegroundColor = ConsoleColor.Gray; -#endif - } - - /// - /// Catch unhandled exception from the application - /// - /// Should be moved out of here if we do more than just log the exception. - public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) - { - Console.WriteLine("An exception has been caught"); - File.WriteAllText(_logPath + "\\MODDED_ErrorLog.Log_" + DateTime.UtcNow.Ticks + ".txt", e.ExceptionObject.ToString()); - } - - /// - /// Catch thread exception from the application - /// - /// Should be moved out of here if we do more than just log the exception. - public static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) - { - Console.WriteLine("A thread exception has been caught"); - File.WriteAllText(_logPath + "\\MODDED_ErrorLog.Log_" + Extensions.Random.Next(100000000, 999999999) + ".txt", e.Exception.ToString()); - } - - // I'm including the following for now because they have a lot of references with different uses. - // They should be removed since they do not provide any insight into actual problems, and other log methods should be used. - - public static void LogValueNotSpecified() - { - Error(" must be specified"); - } - - public static void LogObjectValueNotSpecified() - { - Error(" and must be specified"); - } - - public static void LogValueInvalid() - { - Error(" is invalid"); - } - - public static void LogObjectInvalid() - { - Error(" is invalid"); - } - - public static void LogValueNotInt32() - { - Error(" must be a whole number (Int32)"); - } - - } -} diff --git a/StardewModdingAPI/Program.cs b/StardewModdingAPI/Program.cs index 4d1d23d1..05da664c 100644 --- a/StardewModdingAPI/Program.cs +++ b/StardewModdingAPI/Program.cs @@ -59,6 +59,8 @@ namespace StardewModdingAPI catch (Exception e) { // Catch and display all exceptions. + Console.WriteLine(e); + Console.ReadKey(); Log.Error("Critical error: " + e); } @@ -99,9 +101,7 @@ namespace StardewModdingAPI //Checks that all defined modpaths exist as directories _modPaths.ForEach(path => VerifyPath(path)); //_modContentPaths.ForEach(path => VerifyPath(path)); - VerifyPath(Constants.LogPath); - - Log.Initialize(Constants.LogPath); + VerifyPath(Constants.LogDir); if (!File.Exists(Constants.ExecutionPath + "\\Stardew Valley.exe")) { @@ -267,7 +267,7 @@ namespace StardewModdingAPI string t = File.ReadAllText(s); if (string.IsNullOrEmpty(t)) { - Log.Error("Failed to read mod manifest '{0}'. Manifest is empty!", s); + Log.Error($"Failed to read mod manifest '{s}'. Manifest is empty!"); continue; } @@ -275,41 +275,47 @@ namespace StardewModdingAPI if (string.IsNullOrEmpty(manifest.EntryDll)) { - Log.Error("Failed to read mod manifest '{0}'. EntryDll is empty!", s); + Log.Error($"Failed to read mod manifest '{s}'. EntryDll is empty!"); continue; } } catch (Exception ex) { - Log.Error("Failed to read mod manifest '{0}'. Exception details:\n" + ex, s); + Log.Error($"Failed to read mod manifest '{s}'. Exception details:\n" + ex); continue; } + string targDir = Path.GetDirectoryName(s); + string psDir = Path.Combine(targDir, "psconfigs"); + Log.Info($"Created psconfigs directory @{psDir}"); try { if (manifest.PerSaveConfigs) { - if (!Directory.Exists(Path.GetDirectoryName(s))) - Directory.CreateDirectory(Path.GetDirectoryName(s)); + if (!Directory.Exists(psDir)) + { + Directory.CreateDirectory(psDir); + Log.Info($"Created psconfigs directory @{psDir}"); + } - if (!Directory.Exists(Path.GetDirectoryName(s))) + if (!Directory.Exists(psDir)) { - Log.Error("Failed to create psconfigs directory '{0}'. No exception occured.", Path.GetDirectoryName(s)); + Log.Error($"Failed to create psconfigs directory '{psDir}'. No exception occured."); continue; } } } catch (Exception ex) { - Log.Error("Failed to create psconfigs directory '{0}'. Exception details:\n" + ex, Path.GetDirectoryName(s)); + Log.Error($"Failed to create psconfigs directory '{targDir}'. Exception details:\n" + ex); continue; } string targDll = string.Empty; try { - targDll = Path.Combine(Path.GetDirectoryName(s), manifest.EntryDll); + targDll = Path.Combine(targDir, manifest.EntryDll); if (!File.Exists(targDll)) { - Log.Error("Failed to load mod '{0}'. File {1} does not exist!", manifest.EntryDll, targDll); + Log.Error($"Failed to load mod '{manifest.EntryDll}'. File {targDll} does not exist!"); continue; } @@ -320,9 +326,9 @@ namespace StardewModdingAPI Log.Verbose("Loading Mod DLL..."); TypeInfo tar = mod.DefinedTypes.First(x => x.BaseType == typeof (Mod)); Mod m = (Mod) mod.CreateInstance(tar.ToString()); - m.PathOnDisk = Path.GetDirectoryName(s); + m.PathOnDisk = targDir; m.Manifest = manifest; - Log.Success("LOADED MOD: {0} by {1} - Version {2} | Description: {3} (@ {4})", m.Manifest.Name, m.Manifest.Authour, m.Manifest.Version, m.Manifest.Description, targDll); + Log.Success($"LOADED MOD: {m.Manifest.Name} by {m.Manifest.Authour} - Version {m.Manifest.Version} | Description: {m.Manifest.Description} (@ {targDll})"); Constants.ModsLoaded += 1; m.Entry(); } @@ -333,12 +339,12 @@ namespace StardewModdingAPI } catch (Exception ex) { - Log.Error("Failed to load mod '{0}'. Exception details:\n" + ex, targDll); + Log.Error($"Failed to load mod '{targDll}'. Exception details:\n" + ex); } } } } - Log.Success("LOADED {0} MODS", Constants.ModsLoaded); + Log.Success($"LOADED {Constants.ModsLoaded} MODS"); Console.Title = Constants.ConsoleTitle; } diff --git a/StardewModdingAPI/StardewModdingAPI.csproj b/StardewModdingAPI/StardewModdingAPI.csproj index 76ebd86c..d60e2544 100644 --- a/StardewModdingAPI/StardewModdingAPI.csproj +++ b/StardewModdingAPI/StardewModdingAPI.csproj @@ -152,7 +152,7 @@ - + -- cgit