From 69bb8178d216d2d75d771114643d6749abdc7aea Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 4 Nov 2016 00:10:10 -0400 Subject: [PATCH] normalise inconsistent line endings --- .gitattributes | 2 + src/StardewModdingAPI.sln | 145 +- .../Inheritance/ItemStackChange.cs | 20 +- src/StardewModdingAPI/Inheritance/SGame.cs | 2678 ++++++++--------- src/StardewModdingAPI/Program.cs | 740 ++--- .../StardewModdingAPI.csproj | 512 ++-- src/StardewModdingAPI/packages.config | 10 +- src/TrainerMod/TrainerMod.cs | 1454 ++++----- src/TrainerMod/TrainerMod.csproj | 250 +- src/TrainerMod/packages.config | 6 +- 10 files changed, 2910 insertions(+), 2907 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..cd1acd35 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# normalise line endings +* text=auto diff --git a/src/StardewModdingAPI.sln b/src/StardewModdingAPI.sln index 9c999731..29c80e89 100644 --- a/src/StardewModdingAPI.sln +++ b/src/StardewModdingAPI.sln @@ -1,72 +1,73 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrainerMod", "TrainerMod\TrainerMod.csproj", "{28480467-1A48-46A7-99F8-236D95225359}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StardewModdingAPI", "StardewModdingAPI\StardewModdingAPI.csproj", "{F1A573B0-F436-472C-AE29-0B91EA6B9F8F}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "metadata", "metadata", "{86C452BE-D2D8-45B4-B63F-E329EB06CEDA}" - ProjectSection(SolutionItems) = preProject - ..\.gitignore = ..\.gitignore - ..\LICENSE = ..\LICENSE - ..\README.md = ..\README.md - ..\release-notes.md = ..\release-notes.md - EndProjectSection -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StardewModdingAPI.Installer", "StardewModdingAPI.Installer\StardewModdingAPI.Installer.csproj", "{443DDF81-6AAF-420A-A610-3459F37E5575}" - ProjectSection(ProjectDependencies) = postProject - {28480467-1A48-46A7-99F8-236D95225359} = {28480467-1A48-46A7-99F8-236D95225359} - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F} = {F1A573B0-F436-472C-AE29-0B91EA6B9F8F} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {28480467-1A48-46A7-99F8-236D95225359}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {28480467-1A48-46A7-99F8-236D95225359}.Debug|Any CPU.Build.0 = Debug|Any CPU - {28480467-1A48-46A7-99F8-236D95225359}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {28480467-1A48-46A7-99F8-236D95225359}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {28480467-1A48-46A7-99F8-236D95225359}.Debug|x86.ActiveCfg = Debug|Any CPU - {28480467-1A48-46A7-99F8-236D95225359}.Release|Any CPU.ActiveCfg = Release|Any CPU - {28480467-1A48-46A7-99F8-236D95225359}.Release|Any CPU.Build.0 = Release|Any CPU - {28480467-1A48-46A7-99F8-236D95225359}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {28480467-1A48-46A7-99F8-236D95225359}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {28480467-1A48-46A7-99F8-236D95225359}.Release|x86.ActiveCfg = Release|Any CPU - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|Mixed Platforms.Build.0 = Debug|x86 - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|x86.ActiveCfg = Debug|x86 - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|x86.Build.0 = Debug|x86 - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|Any CPU.Build.0 = Release|Any CPU - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|Mixed Platforms.ActiveCfg = Release|x86 - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|Mixed Platforms.Build.0 = Release|x86 - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|x86.ActiveCfg = Release|x86 - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|x86.Build.0 = Release|x86 - {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|Any CPU.Build.0 = Debug|Any CPU - {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|x86.ActiveCfg = Debug|Any CPU - {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|x86.Build.0 = Debug|Any CPU - {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|Any CPU.ActiveCfg = Release|Any CPU - {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|Any CPU.Build.0 = Release|Any CPU - {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|x86.ActiveCfg = Release|Any CPU - {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrainerMod", "TrainerMod\TrainerMod.csproj", "{28480467-1A48-46A7-99F8-236D95225359}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StardewModdingAPI", "StardewModdingAPI\StardewModdingAPI.csproj", "{F1A573B0-F436-472C-AE29-0B91EA6B9F8F}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "metadata", "metadata", "{86C452BE-D2D8-45B4-B63F-E329EB06CEDA}" + ProjectSection(SolutionItems) = preProject + ..\.gitattributes = ..\.gitattributes + ..\.gitignore = ..\.gitignore + ..\LICENSE = ..\LICENSE + ..\README.md = ..\README.md + ..\release-notes.md = ..\release-notes.md + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StardewModdingAPI.Installer", "StardewModdingAPI.Installer\StardewModdingAPI.Installer.csproj", "{443DDF81-6AAF-420A-A610-3459F37E5575}" + ProjectSection(ProjectDependencies) = postProject + {28480467-1A48-46A7-99F8-236D95225359} = {28480467-1A48-46A7-99F8-236D95225359} + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F} = {F1A573B0-F436-472C-AE29-0B91EA6B9F8F} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|Mixed Platforms = Debug|Mixed Platforms + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|Mixed Platforms = Release|Mixed Platforms + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {28480467-1A48-46A7-99F8-236D95225359}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28480467-1A48-46A7-99F8-236D95225359}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28480467-1A48-46A7-99F8-236D95225359}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {28480467-1A48-46A7-99F8-236D95225359}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {28480467-1A48-46A7-99F8-236D95225359}.Debug|x86.ActiveCfg = Debug|Any CPU + {28480467-1A48-46A7-99F8-236D95225359}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28480467-1A48-46A7-99F8-236D95225359}.Release|Any CPU.Build.0 = Release|Any CPU + {28480467-1A48-46A7-99F8-236D95225359}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {28480467-1A48-46A7-99F8-236D95225359}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {28480467-1A48-46A7-99F8-236D95225359}.Release|x86.ActiveCfg = Release|Any CPU + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|Mixed Platforms.Build.0 = Debug|x86 + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|x86.ActiveCfg = Debug|x86 + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|x86.Build.0 = Debug|x86 + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|Any CPU.Build.0 = Release|Any CPU + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|Mixed Platforms.ActiveCfg = Release|x86 + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|Mixed Platforms.Build.0 = Release|x86 + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|x86.ActiveCfg = Release|x86 + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Release|x86.Build.0 = Release|x86 + {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|Any CPU.Build.0 = Debug|Any CPU + {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|x86.ActiveCfg = Debug|Any CPU + {443DDF81-6AAF-420A-A610-3459F37E5575}.Debug|x86.Build.0 = Debug|Any CPU + {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|Any CPU.ActiveCfg = Release|Any CPU + {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|Any CPU.Build.0 = Release|Any CPU + {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|x86.ActiveCfg = Release|Any CPU + {443DDF81-6AAF-420A-A610-3459F37E5575}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/StardewModdingAPI/Inheritance/ItemStackChange.cs b/src/StardewModdingAPI/Inheritance/ItemStackChange.cs index 78775094..8abe3a76 100644 --- a/src/StardewModdingAPI/Inheritance/ItemStackChange.cs +++ b/src/StardewModdingAPI/Inheritance/ItemStackChange.cs @@ -1,11 +1,11 @@ -using StardewValley; - -namespace StardewModdingAPI.Inheritance -{ - public class ItemStackChange - { - public Item Item { get; set; } - public int StackChange { get; set; } - public ChangeType ChangeType { get; set; } - } +using StardewValley; + +namespace StardewModdingAPI.Inheritance +{ + public class ItemStackChange + { + public Item Item { get; set; } + public int StackChange { get; set; } + public ChangeType ChangeType { get; set; } + } } \ No newline at end of file diff --git a/src/StardewModdingAPI/Inheritance/SGame.cs b/src/StardewModdingAPI/Inheritance/SGame.cs index 26421136..808f0812 100644 --- a/src/StardewModdingAPI/Inheritance/SGame.cs +++ b/src/StardewModdingAPI/Inheritance/SGame.cs @@ -1,1340 +1,1340 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using Microsoft.Xna.Framework.Input; -using StardewModdingAPI.Events; -using StardewValley; -using StardewValley.BellsAndWhistles; -using StardewValley.Locations; -using StardewValley.Menus; -using StardewValley.Tools; -using xTile.Dimensions; -using Rectangle = Microsoft.Xna.Framework.Rectangle; - -namespace StardewModdingAPI.Inheritance -{ - /// - /// The 'SGame' class. - /// This summary, and many others, only exists because XML doc tags. - /// - public class SGame : Game1 - { - private bool FireLoadedGameEvent; - - /// - /// Gets a jagged array of all buttons pressed on the gamepad the prior frame. - /// - public Buttons[][] PreviouslyPressedButtons; - - internal SGame() - { - Instance = this; - FirstUpdate = true; - } - - /// - /// The current KeyboardState - /// - public KeyboardState KStateNow { get; private set; } - /// - /// The prior KeyboardState - /// - public KeyboardState KStatePrior { get; private set; } - - /// - /// The current MouseState - /// - public MouseState MStateNow { get; private set; } - - /// - /// The prior MouseState - /// - public MouseState MStatePrior { get; private set; } - - /// The current mouse position on the screen adjusted for the zoom level. - public Point MPositionNow { get; private set; } - - /// The previous mouse position on the screen adjusted for the zoom level. - public Point MPositionPrior { get; private set; } - - /// - /// All keys pressed on the current frame - /// - public Keys[] CurrentlyPressedKeys => KStateNow.GetPressedKeys(); - - /// - /// All keys pressed on the prior frame - /// - public Keys[] PreviouslyPressedKeys => KStatePrior.GetPressedKeys(); - - /// - /// All keys pressed on this frame except for the ones pressed on the prior frame - /// - public Keys[] FramePressedKeys => CurrentlyPressedKeys.Except(PreviouslyPressedKeys).ToArray(); - - /// - /// All keys pressed on the prior frame except for the ones pressed on the current frame - /// - public Keys[] FrameReleasedKeys => PreviouslyPressedKeys.Except(CurrentlyPressedKeys).ToArray(); - - /// - /// Whether or not a save was tagged as 'Loaded' the prior frame. - /// - public bool PreviouslyLoadedGame { get; private set; } - - /// - /// The list of GameLocations on the prior frame - /// - public int PreviousGameLocations { get; private set; } - - /// - /// The list of GameObjects on the prior frame - /// - public int PreviousLocationObjects { get; private set; } - - /// - /// The list of Items in the player's inventory on the prior frame - /// - public Dictionary PreviousItems { get; private set; } - - /// - /// The player's Combat level on the prior frame - /// - public int PreviousCombatLevel { get; private set; } - /// - /// The player's Farming level on the prior frame - /// - public int PreviousFarmingLevel { get; private set; } - /// - /// The player's Fishing level on the prior frame - /// - public int PreviousFishingLevel { get; private set; } - /// - /// The player's Foraging level on the prior frame - /// - public int PreviousForagingLevel { get; private set; } - /// - /// The player's Mining level on the prior frame - /// - public int PreviousMiningLevel { get; private set; } - /// - /// The player's Luck level on the prior frame - /// - public int PreviousLuckLevel { get; private set; } - - //Kill me now comments are so boring - - /// - /// The player's previous game location - /// - public GameLocation PreviousGameLocation { get; private set; } - - /// - /// The previous ActiveGameMenu in Game1 - /// - public IClickableMenu PreviousActiveMenu { get; private set; } - - /// - /// Indicates if the MenuClosed event was fired to prevent it from re-firing. - /// - internal bool WasMenuClosedInvoked = false; - - /// - /// The previous mine level - /// - public int PreviousMineLevel { get; private set; } - - /// - /// The previous TimeOfDay (Int32 between 600 and 2400?) - /// - public int PreviousTimeOfDay { get; private set; } - - /// - /// The previous DayOfMonth (Int32 between 1 and 28?) - /// - public int PreviousDayOfMonth { get; private set; } - - /// - /// The previous Season (String as follows: "winter", "spring", "summer", "fall") - /// - public string PreviousSeasonOfYear { get; private set; } - - /// - /// The previous Year - /// - public int PreviousYearOfGame { get; private set; } - - /// - /// The previous result of Game1.newDay - /// - public bool PreviousIsNewDay { get; private set; } - - /// - /// The previous 'Farmer' (Player) - /// - public Farmer PreviousFarmer { get; private set; } - - /// - /// The current index of the update tick. Recycles every 60th tick to 0. (Int32 between 0 and 59) - /// - public int CurrentUpdateTick { get; private set; } - - /// - /// Whether or not this update frame is the very first of the entire game - /// - public bool FirstUpdate { get; private set; } - - /// - /// The current RenderTarget in Game1 (Private field, uses reflection) - /// - public RenderTarget2D Screen - { - get { return typeof (Game1).GetBaseFieldValue(Program.gamePtr, "screen"); } - set { typeof (Game1).SetBaseFieldValue(this, "screen", value); } - } - - /// - /// The current Colour in Game1 (Private field, uses reflection) - /// - public Color BgColour - { - get { return (Color)typeof(Game1).GetBaseFieldValue(Program.gamePtr, "bgColor"); } - set { typeof(Game1).SetBaseFieldValue(this, "bgColor", value); } - } - - /// - /// Static accessor for an Instance of the class SGame - /// - public static SGame Instance { get; private set; } - - /// - /// The game's FPS. Re-determined every Draw update. - /// - public static float FramesPerSecond { get; private set; } - - /// - /// Whether or not we're in a pseudo 'debug' mode. Mostly for displaying information like FPS. - /// - public static bool Debug { get; private set; } - internal static Queue DebugMessageQueue { get; private set; } - - /// - /// The current player (equal to Farmer.Player) - /// - [Obsolete("Use Farmer.Player instead")] - public Farmer CurrentFarmer => player; - - /// - /// Gets ALL static fields that belong to 'Game1' - /// - public static FieldInfo[] GetStaticFields => typeof (Game1).GetFields(); - - /// - /// Whether or not a button was just pressed on the controller - /// - /// - /// - /// - /// - private bool WasButtonJustPressed(Buttons button, ButtonState buttonState, PlayerIndex stateIndex) - { - return buttonState == ButtonState.Pressed && !PreviouslyPressedButtons[(int) stateIndex].Contains(button); - } - - /// - /// Whether or not a button was just released on the controller - /// - /// - /// - /// - /// - private bool WasButtonJustReleased(Buttons button, ButtonState buttonState, PlayerIndex stateIndex) - { - return buttonState == ButtonState.Released && PreviouslyPressedButtons[(int) stateIndex].Contains(button); - } - - /// - /// Whether or not an analog button was just pressed on the controller - /// - /// - /// - /// - /// - private bool WasButtonJustPressed(Buttons button, float value, PlayerIndex stateIndex) - { - return WasButtonJustPressed(button, value > 0.2f ? ButtonState.Pressed : ButtonState.Released, stateIndex); - } - - /// - /// Whether or not an analog button was just released on the controller - /// - /// - /// - /// - /// - private bool WasButtonJustReleased(Buttons button, float value, PlayerIndex stateIndex) - { - return WasButtonJustReleased(button, value > 0.2f ? ButtonState.Pressed : ButtonState.Released, stateIndex); - } - - /// - /// Gets an array of all Buttons pressed on a joystick - /// - /// - /// - public Buttons[] GetButtonsDown(PlayerIndex index) - { - var state = GamePad.GetState(index); - var buttons = new List(); - if (state.IsConnected) - { - if (state.Buttons.A == ButtonState.Pressed) buttons.Add(Buttons.A); - if (state.Buttons.B == ButtonState.Pressed) buttons.Add(Buttons.B); - if (state.Buttons.Back == ButtonState.Pressed) buttons.Add(Buttons.Back); - if (state.Buttons.BigButton == ButtonState.Pressed) buttons.Add(Buttons.BigButton); - if (state.Buttons.LeftShoulder == ButtonState.Pressed) buttons.Add(Buttons.LeftShoulder); - if (state.Buttons.LeftStick == ButtonState.Pressed) buttons.Add(Buttons.LeftStick); - if (state.Buttons.RightShoulder == ButtonState.Pressed) buttons.Add(Buttons.RightShoulder); - if (state.Buttons.RightStick == ButtonState.Pressed) buttons.Add(Buttons.RightStick); - if (state.Buttons.Start == ButtonState.Pressed) buttons.Add(Buttons.Start); - if (state.Buttons.X == ButtonState.Pressed) buttons.Add(Buttons.X); - if (state.Buttons.Y == ButtonState.Pressed) buttons.Add(Buttons.Y); - if (state.DPad.Up == ButtonState.Pressed) buttons.Add(Buttons.DPadUp); - if (state.DPad.Down == ButtonState.Pressed) buttons.Add(Buttons.DPadDown); - if (state.DPad.Left == ButtonState.Pressed) buttons.Add(Buttons.DPadLeft); - if (state.DPad.Right == ButtonState.Pressed) buttons.Add(Buttons.DPadRight); - if (state.Triggers.Left > 0.2f) buttons.Add(Buttons.LeftTrigger); - if (state.Triggers.Right > 0.2f) buttons.Add(Buttons.RightTrigger); - } - return buttons.ToArray(); - } - - /// - /// Gets all buttons that were pressed on the current frame of a joystick - /// - /// - /// - public Buttons[] GetFramePressedButtons(PlayerIndex index) - { - var state = GamePad.GetState(index); - var buttons = new List(); - if (state.IsConnected) - { - if (WasButtonJustPressed(Buttons.A, state.Buttons.A, index)) buttons.Add(Buttons.A); - if (WasButtonJustPressed(Buttons.B, state.Buttons.B, index)) buttons.Add(Buttons.B); - if (WasButtonJustPressed(Buttons.Back, state.Buttons.Back, index)) buttons.Add(Buttons.Back); - if (WasButtonJustPressed(Buttons.BigButton, state.Buttons.BigButton, index)) buttons.Add(Buttons.BigButton); - if (WasButtonJustPressed(Buttons.LeftShoulder, state.Buttons.LeftShoulder, index)) buttons.Add(Buttons.LeftShoulder); - if (WasButtonJustPressed(Buttons.LeftStick, state.Buttons.LeftStick, index)) buttons.Add(Buttons.LeftStick); - if (WasButtonJustPressed(Buttons.RightShoulder, state.Buttons.RightShoulder, index)) buttons.Add(Buttons.RightShoulder); - if (WasButtonJustPressed(Buttons.RightStick, state.Buttons.RightStick, index)) buttons.Add(Buttons.RightStick); - if (WasButtonJustPressed(Buttons.Start, state.Buttons.Start, index)) buttons.Add(Buttons.Start); - if (WasButtonJustPressed(Buttons.X, state.Buttons.X, index)) buttons.Add(Buttons.X); - if (WasButtonJustPressed(Buttons.Y, state.Buttons.Y, index)) buttons.Add(Buttons.Y); - if (WasButtonJustPressed(Buttons.DPadUp, state.DPad.Up, index)) buttons.Add(Buttons.DPadUp); - if (WasButtonJustPressed(Buttons.DPadDown, state.DPad.Down, index)) buttons.Add(Buttons.DPadDown); - if (WasButtonJustPressed(Buttons.DPadLeft, state.DPad.Left, index)) buttons.Add(Buttons.DPadLeft); - if (WasButtonJustPressed(Buttons.DPadRight, state.DPad.Right, index)) buttons.Add(Buttons.DPadRight); - if (WasButtonJustPressed(Buttons.LeftTrigger, state.Triggers.Left, index)) buttons.Add(Buttons.LeftTrigger); - if (WasButtonJustPressed(Buttons.RightTrigger, state.Triggers.Right, index)) buttons.Add(Buttons.RightTrigger); - } - return buttons.ToArray(); - } - - /// - /// Gets all buttons that were released on the current frame of a joystick - /// - /// - /// - public Buttons[] GetFrameReleasedButtons(PlayerIndex index) - { - var state = GamePad.GetState(index); - var buttons = new List(); - if (state.IsConnected) - { - if (WasButtonJustReleased(Buttons.A, state.Buttons.A, index)) buttons.Add(Buttons.A); - if (WasButtonJustReleased(Buttons.B, state.Buttons.B, index)) buttons.Add(Buttons.B); - if (WasButtonJustReleased(Buttons.Back, state.Buttons.Back, index)) buttons.Add(Buttons.Back); - if (WasButtonJustReleased(Buttons.BigButton, state.Buttons.BigButton, index)) buttons.Add(Buttons.BigButton); - if (WasButtonJustReleased(Buttons.LeftShoulder, state.Buttons.LeftShoulder, index)) buttons.Add(Buttons.LeftShoulder); - if (WasButtonJustReleased(Buttons.LeftStick, state.Buttons.LeftStick, index)) buttons.Add(Buttons.LeftStick); - if (WasButtonJustReleased(Buttons.RightShoulder, state.Buttons.RightShoulder, index)) buttons.Add(Buttons.RightShoulder); - if (WasButtonJustReleased(Buttons.RightStick, state.Buttons.RightStick, index)) buttons.Add(Buttons.RightStick); - if (WasButtonJustReleased(Buttons.Start, state.Buttons.Start, index)) buttons.Add(Buttons.Start); - if (WasButtonJustReleased(Buttons.X, state.Buttons.X, index)) buttons.Add(Buttons.X); - if (WasButtonJustReleased(Buttons.Y, state.Buttons.Y, index)) buttons.Add(Buttons.Y); - if (WasButtonJustReleased(Buttons.DPadUp, state.DPad.Up, index)) buttons.Add(Buttons.DPadUp); - if (WasButtonJustReleased(Buttons.DPadDown, state.DPad.Down, index)) buttons.Add(Buttons.DPadDown); - if (WasButtonJustReleased(Buttons.DPadLeft, state.DPad.Left, index)) buttons.Add(Buttons.DPadLeft); - if (WasButtonJustReleased(Buttons.DPadRight, state.DPad.Right, index)) buttons.Add(Buttons.DPadRight); - if (WasButtonJustReleased(Buttons.LeftTrigger, state.Triggers.Left, index)) buttons.Add(Buttons.LeftTrigger); - if (WasButtonJustReleased(Buttons.RightTrigger, state.Triggers.Right, index)) buttons.Add(Buttons.RightTrigger); - } - return buttons.ToArray(); - } - - /// - /// - /// - public static MethodInfo DrawFarmBuildings = typeof (Game1).GetMethod("drawFarmBuildings", BindingFlags.NonPublic | BindingFlags.Instance); - - /// - /// - /// - public static MethodInfo DrawHUD = typeof (Game1).GetMethod("drawHUD", BindingFlags.NonPublic | BindingFlags.Instance); - - /// - /// - /// - public static MethodInfo DrawDialogueBox = typeof (Game1).GetMethod("drawDialogueBox", BindingFlags.NonPublic | BindingFlags.Instance); - - public static MethodInfo CheckForEscapeKeys = typeof (Game1).GetMethod("checkForEscapeKeys", BindingFlags.NonPublic | BindingFlags.Instance); - - public static MethodInfo UpdateControlInput = typeof(Game1).GetMethod("UpdateControlInput", BindingFlags.NonPublic | BindingFlags.Instance); - - public static MethodInfo UpdateCharacters = typeof(Game1).GetMethod("UpdateCharacters", BindingFlags.NonPublic | BindingFlags.Instance); - - public static MethodInfo UpdateLocations = typeof(Game1).GetMethod("UpdateLocations", BindingFlags.NonPublic | BindingFlags.Instance); - - public static MethodInfo getViewportCenter = typeof(Game1).GetMethod("getViewportCenter", BindingFlags.NonPublic | BindingFlags.Instance); - - public static MethodInfo UpdateTitleScreen = typeof(Game1).GetMethod("UpdateTitleScreen", BindingFlags.NonPublic | BindingFlags.Instance); - - public delegate void BaseBaseDraw(); - - /// - /// Whether or not the game's zoom level is 1.0f - /// - public bool ZoomLevelIsOne => options.zoomLevel.Equals(1.0f); - - /// - /// XNA Init Method - /// - protected override void Initialize() - { - Log.AsyncY("XNA Initialize"); - //ModItems = new Dictionary(); - DebugMessageQueue = new Queue(); - PreviouslyPressedButtons = new Buttons[4][]; - for (var i = 0; i < 4; ++i) PreviouslyPressedButtons[i] = new Buttons[0]; - - base.Initialize(); - GameEvents.InvokeInitialize(); - } - - /// - /// XNA LC Method - /// - protected override void LoadContent() - { - Log.AsyncY("XNA LoadContent"); - base.LoadContent(); - GameEvents.InvokeLoadContent(); - } - - /// - /// XNA Update Method - /// - /// - protected override void Update(GameTime gameTime) - { - QueueDebugMessage("FPS: " + FramesPerSecond); - UpdateEventCalls(); - - if (FramePressedKeys.Contains(Keys.F3)) - { - Debug = !Debug; - } - - try - { - base.Update(gameTime); - } - catch (Exception ex) - { - Log.AsyncR("An error occured in the base update loop: " + ex); - Console.ReadKey(); - } - - GameEvents.InvokeUpdateTick(); - if (FirstUpdate) - { - GameEvents.InvokeFirstUpdateTick(); - FirstUpdate = false; - } - - if (CurrentUpdateTick % 2 == 0) - GameEvents.InvokeSecondUpdateTick(); - - if (CurrentUpdateTick % 4 == 0) - GameEvents.InvokeFourthUpdateTick(); - - if (CurrentUpdateTick % 8 == 0) - GameEvents.InvokeEighthUpdateTick(); - - if (CurrentUpdateTick % 15 == 0) - GameEvents.InvokeQuarterSecondTick(); - - if (CurrentUpdateTick % 30 == 0) - GameEvents.InvokeHalfSecondTick(); - - if (CurrentUpdateTick % 60 == 0) - GameEvents.InvokeOneSecondTick(); - - CurrentUpdateTick += 1; - if (CurrentUpdateTick >= 60) - CurrentUpdateTick = 0; - - if (KStatePrior != KStateNow) - KStatePrior = KStateNow; - - for (var i = PlayerIndex.One; i <= PlayerIndex.Four; i++) - { - PreviouslyPressedButtons[(int) i] = GetButtonsDown(i); - } - } - - /// - /// XNA Draw Method - /// - /// - protected override void Draw(GameTime gameTime) - { - FramesPerSecond = 1 / (float) gameTime.ElapsedGameTime.TotalSeconds; - - if (Constants.EnableCompletelyOverridingBaseCalls) - { - #region Overridden Draw - - try - { - if (!ZoomLevelIsOne) - { - GraphicsDevice.SetRenderTarget(Screen); - } - - GraphicsDevice.Clear(BgColour); - if (options.showMenuBackground && activeClickableMenu != null && activeClickableMenu.showWithoutTransparencyIfOptionIsSet()) - { - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - activeClickableMenu.drawBackground(spriteBatch); - GraphicsEvents.InvokeOnPreRenderGuiEvent(null, EventArgs.Empty); - activeClickableMenu.draw(spriteBatch); - GraphicsEvents.InvokeOnPostRenderGuiEvent(null, EventArgs.Empty); - spriteBatch.End(); - if (!ZoomLevelIsOne) - { - GraphicsDevice.SetRenderTarget(null); - GraphicsDevice.Clear(BgColour); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); - spriteBatch.Draw(Screen, Vector2.Zero, Screen.Bounds, Color.White, 0f, Vector2.Zero, options.zoomLevel, SpriteEffects.None, 1f); - spriteBatch.End(); - } - return; - } - if (gameMode == 11) - { - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - spriteBatch.DrawString(smoothFont, "Stardew Valley has crashed...", new Vector2(16f, 16f), Color.HotPink); - spriteBatch.DrawString(smoothFont, "Please send the error report or a screenshot of this message to @ConcernedApe. (http://stardewvalley.net/contact/)", new Vector2(16f, 32f), new Color(0, 255, 0)); - spriteBatch.DrawString(smoothFont, parseText(errorMessage, smoothFont, graphics.GraphicsDevice.Viewport.Width), new Vector2(16f, 48f), Color.White); - spriteBatch.End(); - return; - } - if (currentMinigame != null) - { - currentMinigame.draw(spriteBatch); - if (globalFade && !menuUp && (!nameSelectUp || messagePause)) - { - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - spriteBatch.Draw(fadeToBlackRect, graphics.GraphicsDevice.Viewport.Bounds, Color.Black * ((gameMode == 0) ? (1f - fadeToBlackAlpha) : fadeToBlackAlpha)); - spriteBatch.End(); - } - if (!ZoomLevelIsOne) - { - GraphicsDevice.SetRenderTarget(null); - GraphicsDevice.Clear(BgColour); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); - spriteBatch.Draw(Screen, Vector2.Zero, Screen.Bounds, Color.White, 0f, Vector2.Zero, options.zoomLevel, SpriteEffects.None, 1f); - spriteBatch.End(); - } - return; - } - if (showingEndOfNightStuff) - { - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - activeClickableMenu?.draw(spriteBatch); - spriteBatch.End(); - if (!ZoomLevelIsOne) - { - GraphicsDevice.SetRenderTarget(null); - GraphicsDevice.Clear(BgColour); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); - spriteBatch.Draw(Screen, Vector2.Zero, Screen.Bounds, Color.White, 0f, Vector2.Zero, options.zoomLevel, SpriteEffects.None, 1f); - spriteBatch.End(); - } - return; - } - if (gameMode == 6) - { - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - string text = ""; - int num = 0; - while (num < gameTime.TotalGameTime.TotalMilliseconds % 999.0 / 333.0) - { - text += "."; - num++; - } - SpriteText.drawString(spriteBatch, "Loading" + text, 64, graphics.GraphicsDevice.Viewport.Height - 64, 999, -1, 999, 1f, 1f, false, 0, "Loading..."); - spriteBatch.End(); - if (!ZoomLevelIsOne) - { - GraphicsDevice.SetRenderTarget(null); - GraphicsDevice.Clear(BgColour); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); - spriteBatch.Draw(Screen, Vector2.Zero, Screen.Bounds, Color.White, 0f, Vector2.Zero, options.zoomLevel, SpriteEffects.None, 1f); - spriteBatch.End(); - } - return; - } - if (gameMode == 0) - { - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - } - else - { - if (drawLighting) - { - GraphicsDevice.SetRenderTarget(lightmap); - GraphicsDevice.Clear(Color.White * 0f); - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, null, null); - spriteBatch.Draw(staminaRect, lightmap.Bounds, currentLocation.name.Equals("UndergroundMine") ? mine.getLightingColor(gameTime) : ((!ambientLight.Equals(Color.White) && (!isRaining || !currentLocation.isOutdoors)) ? ambientLight : outdoorLight)); - for (int i = 0; i < currentLightSources.Count; i++) - { - if (Utility.isOnScreen(currentLightSources.ElementAt(i).position, (int) (currentLightSources.ElementAt(i).radius * tileSize * 4f))) - { - spriteBatch.Draw(currentLightSources.ElementAt(i).lightTexture, GlobalToLocal(viewport, currentLightSources.ElementAt(i).position) / options.lightingQuality, currentLightSources.ElementAt(i).lightTexture.Bounds, currentLightSources.ElementAt(i).color, 0f, new Vector2(currentLightSources.ElementAt(i).lightTexture.Bounds.Center.X, currentLightSources.ElementAt(i).lightTexture.Bounds.Center.Y), currentLightSources.ElementAt(i).radius / options.lightingQuality, SpriteEffects.None, 0.9f); - } - } - spriteBatch.End(); - GraphicsDevice.SetRenderTarget(ZoomLevelIsOne ? null : Screen); - } - if (bloomDay) - { - bloom?.BeginDraw(); - } - GraphicsDevice.Clear(BgColour); - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - GraphicsEvents.InvokeOnPreRenderEvent(null, EventArgs.Empty); - background?.draw(spriteBatch); - mapDisplayDevice.BeginScene(spriteBatch); - currentLocation.Map.GetLayer("Back").Draw(mapDisplayDevice, viewport, Location.Origin, false, pixelZoom); - currentLocation.drawWater(spriteBatch); - if (CurrentEvent == null) - { - using (List.Enumerator enumerator = currentLocation.characters.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - NPC current = enumerator.Current; - if (current != null && !current.swimming && !current.hideShadow && !current.IsMonster && !currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(current.getTileLocation())) - { - spriteBatch.Draw(shadowTexture, GlobalToLocal(viewport, current.position + new Vector2(current.sprite.spriteWidth * pixelZoom / 2f, current.GetBoundingBox().Height + (current.IsMonster ? 0 : (pixelZoom * 3)))), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), (pixelZoom + current.yJumpOffset / 40f) * current.scale, SpriteEffects.None, Math.Max(0f, current.getStandingY() / 10000f) - 1E-06f); - } - } - goto IL_B30; - } - } - foreach (NPC current2 in CurrentEvent.actors) - { - if (!current2.swimming && !current2.hideShadow && !currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(current2.getTileLocation())) - { - spriteBatch.Draw(shadowTexture, GlobalToLocal(viewport, current2.position + new Vector2(current2.sprite.spriteWidth * pixelZoom / 2f, current2.GetBoundingBox().Height + (current2.IsMonster ? 0 : (pixelZoom * 3)))), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), (pixelZoom + current2.yJumpOffset / 40f) * current2.scale, SpriteEffects.None, Math.Max(0f, current2.getStandingY() / 10000f) - 1E-06f); - } - } - IL_B30: - if (!player.swimming && !player.isRidingHorse() && !currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(player.getTileLocation())) - { - spriteBatch.Draw(shadowTexture, GlobalToLocal(player.position + new Vector2(32f, 24f)), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), 4f - (((player.running || player.usingTool) && player.FarmerSprite.indexInCurrentAnimation > 1) ? (Math.Abs(FarmerRenderer.featureYOffsetPerFrame[player.FarmerSprite.CurrentFrame]) * 0.5f) : 0f), SpriteEffects.None, 0f); - } - currentLocation.Map.GetLayer("Buildings").Draw(mapDisplayDevice, viewport, Location.Origin, false, pixelZoom); - mapDisplayDevice.EndScene(); - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - if (CurrentEvent == null) - { - using (List.Enumerator enumerator3 = currentLocation.characters.GetEnumerator()) - { - while (enumerator3.MoveNext()) - { - NPC current3 = enumerator3.Current; - if (current3 != null && !current3.swimming && !current3.hideShadow && currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(current3.getTileLocation())) - { - spriteBatch.Draw(shadowTexture, GlobalToLocal(viewport, current3.position + new Vector2(current3.sprite.spriteWidth * pixelZoom / 2f, current3.GetBoundingBox().Height + (current3.IsMonster ? 0 : (pixelZoom * 3)))), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), (pixelZoom + current3.yJumpOffset / 40f) * current3.scale, SpriteEffects.None, Math.Max(0f, current3.getStandingY() / 10000f) - 1E-06f); - } - } - goto IL_F5F; - } - } - foreach (NPC current4 in CurrentEvent.actors) - { - if (!current4.swimming && !current4.hideShadow && currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(current4.getTileLocation())) - { - spriteBatch.Draw(shadowTexture, GlobalToLocal(viewport, current4.position + new Vector2(current4.sprite.spriteWidth * pixelZoom / 2f, current4.GetBoundingBox().Height + (current4.IsMonster ? 0 : (pixelZoom * 3)))), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), (pixelZoom + current4.yJumpOffset / 40f) * current4.scale, SpriteEffects.None, Math.Max(0f, current4.getStandingY() / 10000f) - 1E-06f); - } - } - IL_F5F: - if (!player.swimming && !player.isRidingHorse() && currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(player.getTileLocation())) - { - spriteBatch.Draw(shadowTexture, GlobalToLocal(player.position + new Vector2(32f, 24f)), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), 4f - (((player.running || player.usingTool) && player.FarmerSprite.indexInCurrentAnimation > 1) ? (Math.Abs(FarmerRenderer.featureYOffsetPerFrame[player.FarmerSprite.CurrentFrame]) * 0.5f) : 0f), SpriteEffects.None, Math.Max(0.0001f, player.getStandingY() / 10000f + 0.00011f) - 0.0001f); - } - if (displayFarmer) - { - player.draw(spriteBatch); - } - if ((eventUp || killScreen) && !killScreen) - { - currentLocation.currentEvent?.draw(spriteBatch); - } - if (player.currentUpgrade != null && player.currentUpgrade.daysLeftTillUpgradeDone <= 3 && currentLocation.Name.Equals("Farm")) - { - spriteBatch.Draw(player.currentUpgrade.workerTexture, GlobalToLocal(viewport, player.currentUpgrade.positionOfCarpenter), player.currentUpgrade.getSourceRectangle(), Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, (player.currentUpgrade.positionOfCarpenter.Y + tileSize * 3 / 4) / 10000f); - } - currentLocation.draw(spriteBatch); - if (eventUp && currentLocation.currentEvent?.messageToScreen != null) - { - drawWithBorder(currentLocation.currentEvent.messageToScreen, Color.Black, Color.White, new Vector2(graphics.GraphicsDevice.Viewport.TitleSafeArea.Width / 2 - borderFont.MeasureString(currentLocation.currentEvent.messageToScreen).X / 2f, graphics.GraphicsDevice.Viewport.TitleSafeArea.Height - tileSize), 0f, 1f, 0.999f); - } - if (player.ActiveObject == null && (player.UsingTool || pickingTool) && player.CurrentTool != null && (!player.CurrentTool.Name.Equals("Seeds") || pickingTool)) - { - drawTool(player); - } - if (currentLocation.Name.Equals("Farm")) - { - DrawFarmBuildings.Invoke(Program.gamePtr, null); - } - if (tvStation >= 0) - { - spriteBatch.Draw(tvStationTexture, GlobalToLocal(viewport, new Vector2(6 * tileSize + tileSize / 4, 2 * tileSize + tileSize / 2)), new Rectangle(tvStation * 24, 0, 24, 15), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-08f); - } - if (panMode) - { - spriteBatch.Draw(fadeToBlackRect, new Rectangle((int) Math.Floor((getOldMouseX() + viewport.X) / (double) tileSize) * tileSize - viewport.X, (int) Math.Floor((getOldMouseY() + viewport.Y) / (double) tileSize) * tileSize - viewport.Y, tileSize, tileSize), Color.Lime * 0.75f); - foreach (Warp current5 in currentLocation.warps) - { - spriteBatch.Draw(fadeToBlackRect, new Rectangle(current5.X * tileSize - viewport.X, current5.Y * tileSize - viewport.Y, tileSize, tileSize), Color.Red * 0.75f); - } - } - mapDisplayDevice.BeginScene(spriteBatch); - currentLocation.Map.GetLayer("Front").Draw(mapDisplayDevice, viewport, Location.Origin, false, pixelZoom); - mapDisplayDevice.EndScene(); - currentLocation.drawAboveFrontLayer(spriteBatch); - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - if (currentLocation.Name.Equals("Farm") && stats.SeedsSown >= 200u) - { - spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(3 * tileSize + tileSize / 4, tileSize + tileSize / 3)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); - spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(4 * tileSize + tileSize, 2 * tileSize + tileSize)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); - spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(5 * tileSize, 2 * tileSize)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); - spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(3 * tileSize + tileSize / 2, 3 * tileSize)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); - spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(5 * tileSize - tileSize / 4, tileSize)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); - spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(4 * tileSize, 3 * tileSize + tileSize / 6)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); - spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(4 * tileSize + tileSize / 5, 2 * tileSize + tileSize / 3)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); - } - if (displayFarmer && player.ActiveObject != null && player.ActiveObject.bigCraftable && checkBigCraftableBoundariesForFrontLayer() && currentLocation.Map.GetLayer("Front").PickTile(new Location(player.getStandingX(), player.getStandingY()), viewport.Size) == null) - { - drawPlayerHeldObject(player); - } - else if (displayFarmer && player.ActiveObject != null && ((currentLocation.Map.GetLayer("Front").PickTile(new Location((int) player.position.X, (int) player.position.Y - tileSize * 3 / 5), viewport.Size) != null && !currentLocation.Map.GetLayer("Front").PickTile(new Location((int) player.position.X, (int) player.position.Y - tileSize * 3 / 5), viewport.Size).TileIndexProperties.ContainsKey("FrontAlways")) || (currentLocation.Map.GetLayer("Front").PickTile(new Location(player.GetBoundingBox().Right, (int) player.position.Y - tileSize * 3 / 5), viewport.Size) != null && !currentLocation.Map.GetLayer("Front").PickTile(new Location(player.GetBoundingBox().Right, (int) player.position.Y - tileSize * 3 / 5), viewport.Size).TileIndexProperties.ContainsKey("FrontAlways")))) - { - drawPlayerHeldObject(player); - } - if ((player.UsingTool || pickingTool) && player.CurrentTool != null && (!player.CurrentTool.Name.Equals("Seeds") || pickingTool) && currentLocation.Map.GetLayer("Front").PickTile(new Location(player.getStandingX(), (int) player.position.Y - tileSize * 3 / 5), viewport.Size) != null && currentLocation.Map.GetLayer("Front").PickTile(new Location(player.getStandingX(), player.getStandingY()), viewport.Size) == null) - { - drawTool(player); - } - if (currentLocation.Map.GetLayer("AlwaysFront") != null) - { - mapDisplayDevice.BeginScene(spriteBatch); - currentLocation.Map.GetLayer("AlwaysFront").Draw(mapDisplayDevice, viewport, Location.Origin, false, pixelZoom); - mapDisplayDevice.EndScene(); - } - if (toolHold > 400f && player.CurrentTool.UpgradeLevel >= 1 && player.canReleaseTool) - { - Color color = Color.White; - switch ((int) (toolHold / 600f) + 2) - { - case 1: - color = Tool.copperColor; - break; - case 2: - color = Tool.steelColor; - break; - case 3: - color = Tool.goldColor; - break; - case 4: - color = Tool.iridiumColor; - break; - } - spriteBatch.Draw(littleEffect, new Rectangle((int) player.getLocalPosition(viewport).X - 2, (int) player.getLocalPosition(viewport).Y - (player.CurrentTool.Name.Equals("Watering Can") ? 0 : tileSize) - 2, (int) (toolHold % 600f * 0.08f) + 4, tileSize / 8 + 4), Color.Black); - spriteBatch.Draw(littleEffect, new Rectangle((int) player.getLocalPosition(viewport).X, (int) player.getLocalPosition(viewport).Y - (player.CurrentTool.Name.Equals("Watering Can") ? 0 : tileSize), (int) (toolHold % 600f * 0.08f), tileSize / 8), color); - } - if (isDebrisWeather && currentLocation.IsOutdoors && !currentLocation.ignoreDebrisWeather && !currentLocation.Name.Equals("Desert") && viewport.X > -10) - { - foreach (WeatherDebris current6 in debrisWeather) - { - current6.draw(spriteBatch); - } - } - farmEvent?.draw(spriteBatch); - if (currentLocation.LightLevel > 0f && timeOfDay < 2000) - { - spriteBatch.Draw(fadeToBlackRect, graphics.GraphicsDevice.Viewport.Bounds, Color.Black * currentLocation.LightLevel); - } - if (screenGlow) - { - spriteBatch.Draw(fadeToBlackRect, graphics.GraphicsDevice.Viewport.Bounds, screenGlowColor * screenGlowAlpha); - } - currentLocation.drawAboveAlwaysFrontLayer(spriteBatch); - if (player.CurrentTool is FishingRod && ((player.CurrentTool as FishingRod).isTimingCast || (player.CurrentTool as FishingRod).castingChosenCountdown > 0f || (player.CurrentTool as FishingRod).fishCaught || (player.CurrentTool as FishingRod).showingTreasure)) - { - player.CurrentTool.draw(spriteBatch); - } - if (isRaining && currentLocation.IsOutdoors && !currentLocation.Name.Equals("Desert") && !(currentLocation is Summit) && (!eventUp || currentLocation.isTileOnMap(new Vector2(viewport.X / tileSize, viewport.Y / tileSize)))) - { - for (int j = 0; j < rainDrops.Length; j++) - { - spriteBatch.Draw(rainTexture, rainDrops[j].position, getSourceRectForStandardTileSheet(rainTexture, rainDrops[j].frame), Color.White); - } - } - - spriteBatch.End(); - - //base.Draw(gameTime); - - spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - if (eventUp && currentLocation.currentEvent != null) - { - foreach (NPC current7 in currentLocation.currentEvent.actors) - { - if (current7.isEmoting) - { - Vector2 localPosition = current7.getLocalPosition(viewport); - localPosition.Y -= tileSize * 2 + pixelZoom * 3; - if (current7.age == 2) - { - localPosition.Y += tileSize / 2; - } - else if (current7.gender == 1) - { - localPosition.Y += tileSize / 6; - } - spriteBatch.Draw(emoteSpriteSheet, localPosition, new Rectangle(current7.CurrentEmoteIndex * (tileSize / 4) % emoteSpriteSheet.Width, current7.CurrentEmoteIndex * (tileSize / 4) / emoteSpriteSheet.Width * (tileSize / 4), tileSize / 4, tileSize / 4), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, current7.getStandingY() / 10000f); - } - } - } - spriteBatch.End(); - if (drawLighting) - { - spriteBatch.Begin(SpriteSortMode.Deferred, new BlendState - { - ColorBlendFunction = BlendFunction.ReverseSubtract, - ColorDestinationBlend = Blend.One, - ColorSourceBlend = Blend.SourceColor - }, SamplerState.LinearClamp, null, null); - spriteBatch.Draw(lightmap, Vector2.Zero, lightmap.Bounds, Color.White, 0f, Vector2.Zero, options.lightingQuality, SpriteEffects.None, 1f); - if (isRaining && currentLocation.isOutdoors && !(currentLocation is Desert)) - { - spriteBatch.Draw(staminaRect, graphics.GraphicsDevice.Viewport.Bounds, Color.OrangeRed * 0.45f); - } - spriteBatch.End(); - } - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - if (drawGrid) - { - int num2 = -viewport.X % tileSize; - float num3 = -(float) viewport.Y % tileSize; - for (int k = num2; k < graphics.GraphicsDevice.Viewport.Width; k += tileSize) - { - spriteBatch.Draw(staminaRect, new Rectangle(k, (int) num3, 1, graphics.GraphicsDevice.Viewport.Height), Color.Red * 0.5f); - } - for (float num4 = num3; num4 < (float) graphics.GraphicsDevice.Viewport.Height; num4 += (float) tileSize) - { - spriteBatch.Draw(staminaRect, new Rectangle(num2, (int) num4, graphics.GraphicsDevice.Viewport.Width, 1), Color.Red * 0.5f); - } - } - if (currentBillboard != 0) - { - drawBillboard(); - } - - GraphicsEvents.InvokeOnPreRenderHudEventNoCheck(null, EventArgs.Empty); - if ((displayHUD || eventUp) && currentBillboard == 0 && gameMode == 3 && !freezeControls && !panMode) - { - GraphicsEvents.InvokeOnPreRenderHudEvent(null, EventArgs.Empty); - DrawHUD.Invoke(Program.gamePtr, null); - GraphicsEvents.InvokeOnPostRenderHudEvent(null, EventArgs.Empty); - } - else if (activeClickableMenu == null && farmEvent == null) - { - spriteBatch.Draw(mouseCursors, new Vector2(getOldMouseX(), getOldMouseY()), getSourceRectForStandardTileSheet(mouseCursors, 0, 16, 16), Color.White, 0f, Vector2.Zero, 4f + dialogueButtonScale / 150f, SpriteEffects.None, 1f); - } - GraphicsEvents.InvokeOnPostRenderHudEventNoCheck(null, EventArgs.Empty); - - if (hudMessages.Any() && (!eventUp || isFestival())) - { - for (int l = hudMessages.Count - 1; l >= 0; l--) - { - hudMessages[l].draw(spriteBatch, l); - } - } - } - farmEvent?.draw(spriteBatch); - if (dialogueUp && !nameSelectUp && !messagePause && !(activeClickableMenu is DialogueBox)) - { - DrawDialogueBox.Invoke(Program.gamePtr, null); - } - if (progressBar) - { - spriteBatch.Draw(fadeToBlackRect, new Rectangle((graphics.GraphicsDevice.Viewport.TitleSafeArea.Width - dialogueWidth) / 2, graphics.GraphicsDevice.Viewport.TitleSafeArea.Bottom - tileSize * 2, dialogueWidth, tileSize / 2), Color.LightGray); - spriteBatch.Draw(staminaRect, new Rectangle((graphics.GraphicsDevice.Viewport.TitleSafeArea.Width - dialogueWidth) / 2, graphics.GraphicsDevice.Viewport.TitleSafeArea.Bottom - tileSize * 2, (int) (pauseAccumulator / pauseTime * dialogueWidth), tileSize / 2), Color.DimGray); - } - if (eventUp) - { - currentLocation.currentEvent?.drawAfterMap(spriteBatch); - } - if (isRaining && currentLocation.isOutdoors && !(currentLocation is Desert)) - { - spriteBatch.Draw(staminaRect, graphics.GraphicsDevice.Viewport.Bounds, Color.Blue * 0.2f); - } - if ((fadeToBlack || globalFade) && !menuUp && (!nameSelectUp || messagePause)) - { - spriteBatch.Draw(fadeToBlackRect, graphics.GraphicsDevice.Viewport.Bounds, Color.Black * ((gameMode == 0) ? (1f - fadeToBlackAlpha) : fadeToBlackAlpha)); - } - else if (flashAlpha > 0f) - { - if (options.screenFlash) - { - spriteBatch.Draw(fadeToBlackRect, graphics.GraphicsDevice.Viewport.Bounds, Color.White * Math.Min(1f, flashAlpha)); - } - flashAlpha -= 0.1f; - } - if ((messagePause || globalFade) && dialogueUp) - { - DrawDialogueBox.Invoke(Program.gamePtr, null); - } - foreach (TemporaryAnimatedSprite current8 in screenOverlayTempSprites) - { - current8.draw(spriteBatch, true); - } - if (debugMode) - { - spriteBatch.DrawString(smallFont, string.Concat(new object[] - { - panMode ? ((getOldMouseX() + viewport.X) / tileSize + "," + (getOldMouseY() + viewport.Y) / tileSize) : string.Concat("aplayer: ", player.getStandingX() / tileSize, ", ", player.getStandingY() / tileSize), - Environment.NewLine, - "debugOutput: ", - debugOutput - }), new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y), Color.Red, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.9999999f); - } - /*if (inputMode) - { - spriteBatch.DrawString(smallFont, "Input: " + debugInput, new Vector2(tileSize, tileSize * 3), Color.Purple); - }*/ - if (showKeyHelp) - { - spriteBatch.DrawString(smallFont, keyHelpString, new Vector2(tileSize, viewport.Height - tileSize - (dialogueUp ? (tileSize * 3 + (isQuestion ? (questionChoices.Count * tileSize) : 0)) : 0) - smallFont.MeasureString(keyHelpString).Y), Color.LightGray, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.9999999f); - } - - GraphicsEvents.InvokeOnPreRenderGuiEventNoCheck(null, EventArgs.Empty); - if (activeClickableMenu != null) - { - GraphicsEvents.InvokeOnPreRenderGuiEvent(null, EventArgs.Empty); - activeClickableMenu.draw(spriteBatch); - GraphicsEvents.InvokeOnPostRenderGuiEvent(null, EventArgs.Empty); - } - else - { - farmEvent?.drawAboveEverything(spriteBatch); - } - GraphicsEvents.InvokeOnPostRenderGuiEventNoCheck(null, EventArgs.Empty); - - GraphicsEvents.InvokeOnPostRenderEvent(null, EventArgs.Empty); - spriteBatch.End(); - - GraphicsEvents.InvokeDrawInRenderTargetTick(); - - if (!ZoomLevelIsOne) - { - GraphicsDevice.SetRenderTarget(null); - GraphicsDevice.Clear(BgColour); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); - spriteBatch.Draw(Screen, Vector2.Zero, Screen.Bounds, Color.White, 0f, Vector2.Zero, options.zoomLevel, SpriteEffects.None, 1f); - spriteBatch.End(); - } - - GraphicsEvents.InvokeDrawTick(); - } - catch (Exception ex) - { - Log.Error("An error occured in the overridden draw loop: " + ex); - } - - #endregion - } - else - { - #region Base Draw Call - - try - { - base.Draw(gameTime); - } - catch (Exception ex) - { - Log.AsyncR("An error occured in the base draw loop: " + ex); - Console.ReadKey(); - } - - 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(); - - //Re-draw the HUD - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - activeClickableMenu?.draw(spriteBatch); - /* - if ((displayHUD || eventUp) && currentBillboard == 0 && gameMode == 3 && !freezeControls && !panMode) - typeof (Game1).GetMethod("drawHUD", BindingFlags.NonPublic | BindingFlags.Instance)?.Invoke(Program.gamePtr, null); - */ - spriteBatch.Draw(mouseCursors, new Vector2(getOldMouseX(), getOldMouseY()), getSourceRectForStandardTileSheet(mouseCursors, options.gamepadControls ? 44 : 0, 16, 16), Color.White, 0.0f, Vector2.Zero, pixelZoom + dialogueButtonScale / 150f, SpriteEffects.None, 1f); - - 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(); - } - } - - #endregion - } - - if (Debug) - { - spriteBatch.Begin(); - - int i = 0; - while (DebugMessageQueue.Any()) - { - string s = DebugMessageQueue.Dequeue(); - spriteBatch.DrawString(smoothFont, s, new Vector2(0, i * 14), Color.CornflowerBlue); - i++; - } - GraphicsEvents.InvokeDrawDebug(null, EventArgs.Empty); - - spriteBatch.End(); - } - else - { - DebugMessageQueue.Clear(); - } - } - - private void UpdateEventCalls() - { - KStateNow = Keyboard.GetState(); - - MStateNow = Mouse.GetState(); - MPositionNow = new Point(Game1.getMouseX(), Game1.getMouseY()); - - foreach (var k in FramePressedKeys) - ControlEvents.InvokeKeyPressed(k); - - foreach (var k in FrameReleasedKeys) - ControlEvents.InvokeKeyReleased(k); - - for (var i = PlayerIndex.One; i <= PlayerIndex.Four; i++) - { - var buttons = GetFramePressedButtons(i); - foreach (var b in buttons) - { - if (b == Buttons.LeftTrigger || b == Buttons.RightTrigger) - { - ControlEvents.InvokeTriggerPressed(i, b, b == Buttons.LeftTrigger ? GamePad.GetState(i).Triggers.Left : GamePad.GetState(i).Triggers.Right); - } - else - { - ControlEvents.InvokeButtonPressed(i, b); - } - } - } - - for (var i = PlayerIndex.One; i <= PlayerIndex.Four; i++) - { - foreach (var b in GetFrameReleasedButtons(i)) - { - if (b == Buttons.LeftTrigger || b == Buttons.RightTrigger) - { - ControlEvents.InvokeTriggerReleased(i, b, b == Buttons.LeftTrigger ? GamePad.GetState(i).Triggers.Left : GamePad.GetState(i).Triggers.Right); - } - else - { - ControlEvents.InvokeButtonReleased(i, b); - } - } - } - - - if (KStateNow != KStatePrior) - { - ControlEvents.InvokeKeyboardChanged(KStatePrior, KStateNow); - } - - if (MStateNow != MStatePrior) - { - ControlEvents.InvokeMouseChanged(MStatePrior, MStateNow, MPositionPrior, MPositionNow); - MStatePrior = MStateNow; - MPositionPrior = MPositionPrior; - } - - if (activeClickableMenu != null && activeClickableMenu != PreviousActiveMenu) - { - MenuEvents.InvokeMenuChanged(PreviousActiveMenu, activeClickableMenu); - PreviousActiveMenu = activeClickableMenu; - WasMenuClosedInvoked = false; - } - - if (!WasMenuClosedInvoked && PreviousActiveMenu != null && activeClickableMenu == null) - { - MenuEvents.InvokeMenuClosed(PreviousActiveMenu); - WasMenuClosedInvoked = true; - } - - if (locations.GetHash() != PreviousGameLocations) - { - LocationEvents.InvokeLocationsChanged(locations); - PreviousGameLocations = locations.GetHash(); - } - - if (currentLocation != PreviousGameLocation) - { - LocationEvents.InvokeCurrentLocationChanged(PreviousGameLocation, currentLocation); - PreviousGameLocation = currentLocation; - } - - if (player != null && player != PreviousFarmer) - { - PlayerEvents.InvokeFarmerChanged(PreviousFarmer, player); - PreviousFarmer = player; - } - - if (player != null && player.combatLevel != PreviousCombatLevel) - { - PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Combat, player.combatLevel); - PreviousCombatLevel = player.combatLevel; - } - - if (player != null && player.farmingLevel != PreviousFarmingLevel) - { - PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Farming, player.farmingLevel); - PreviousFarmingLevel = player.farmingLevel; - } - - if (player != null && player.fishingLevel != PreviousFishingLevel) - { - PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Fishing, player.fishingLevel); - PreviousFishingLevel = player.fishingLevel; - } - - if (player != null && player.foragingLevel != PreviousForagingLevel) - { - PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Foraging, player.foragingLevel); - PreviousForagingLevel = player.foragingLevel; - } - - if (player != null && player.miningLevel != PreviousMiningLevel) - { - PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Mining, player.miningLevel); - PreviousMiningLevel = player.miningLevel; - } - - if (player != null && player.luckLevel != PreviousLuckLevel) - { - PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Luck, player.luckLevel); - PreviousLuckLevel = player.luckLevel; - } - - List changedItems; - if (player != null && HasInventoryChanged(player.items, out changedItems)) - { - PlayerEvents.InvokeInventoryChanged(player.items, changedItems); - PreviousItems = player.items.Where(n => n != null).ToDictionary(n => n, n => n.Stack); - } - - var objectHash = currentLocation?.objects?.GetHash(); - if (objectHash != null && PreviousLocationObjects != objectHash) - { - LocationEvents.InvokeOnNewLocationObject(currentLocation.objects); - PreviousLocationObjects = objectHash ?? -1; - } - - if (timeOfDay != PreviousTimeOfDay) - { - TimeEvents.InvokeTimeOfDayChanged(PreviousTimeOfDay, timeOfDay); - PreviousTimeOfDay = timeOfDay; - } - - if (dayOfMonth != PreviousDayOfMonth) - { - TimeEvents.InvokeDayOfMonthChanged(PreviousDayOfMonth, dayOfMonth); - PreviousDayOfMonth = dayOfMonth; - } - - if (currentSeason != PreviousSeasonOfYear) - { - TimeEvents.InvokeSeasonOfYearChanged(PreviousSeasonOfYear, currentSeason); - PreviousSeasonOfYear = currentSeason; - } - - if (year != PreviousYearOfGame) - { - TimeEvents.InvokeYearOfGameChanged(PreviousYearOfGame, year); - PreviousYearOfGame = year; - } - - //NOTE THAT THIS MUST CHECK BEFORE SETTING IT TO TRUE BECAUSE OF SOME SILLY ISSUES - if (FireLoadedGameEvent) - { - PlayerEvents.InvokeLoadedGame(new EventArgsLoadedGameChanged(hasLoadedGame)); - FireLoadedGameEvent = false; - } - - if (hasLoadedGame != PreviouslyLoadedGame) - { - FireLoadedGameEvent = true; - PreviouslyLoadedGame = hasLoadedGame; - } - - if (mine != null && PreviousMineLevel != mine.mineLevel) - { - MineEvents.InvokeMineLevelChanged(PreviousMineLevel, mine.mineLevel); - PreviousMineLevel = mine.mineLevel; - } - - if (PreviousIsNewDay != newDay) - { - TimeEvents.InvokeOnNewDay(PreviousDayOfMonth, dayOfMonth, newDay); - PreviousIsNewDay = newDay; - } - } - - private bool HasInventoryChanged(List items, out List changedItems) - { - changedItems = new List(); - IEnumerable actualItems = items.Where(n => n != null).ToArray(); - foreach (var item in actualItems) - { - if (PreviousItems != null && PreviousItems.ContainsKey(item)) - { - if (PreviousItems[item] != item.Stack) - { - changedItems.Add(new ItemStackChange {Item = item, StackChange = item.Stack - PreviousItems[item], ChangeType = ChangeType.StackChange}); - } - } - else - { - changedItems.Add(new ItemStackChange {Item = item, StackChange = item.Stack, ChangeType = ChangeType.Added}); - } - } - - if (PreviousItems != null) - { - changedItems.AddRange(PreviousItems.Where(n => actualItems.All(i => i != n.Key)).Select(n => - new ItemStackChange {Item = n.Key, StackChange = -n.Key.Stack, ChangeType = ChangeType.Removed})); - } - - return changedItems.Any(); - } - - /// - /// Invokes a private, non-static method in Game1 via Reflection - /// - /// The name of the method - /// Any parameters needed - /// Whatever the method normally returns. Null if void. - [Obsolete("This is very slow. Cache the method info and then invoke it with InvokeMethodInfo().")] - public static object InvokeBasePrivateInstancedMethod(string name, params object[] parameters) - { - try - { - return typeof (Game1).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance).Invoke(Program.gamePtr, parameters); - } - catch - { - Log.AsyncR("Failed to call base method: " + name); - return null; - } - } - - /// - /// Invokes a given method info with the supplied parameters - /// - /// - /// - /// - public static object InvokeMethodInfo(MethodInfo mi, params object[] parameters) - { - try - { - return mi.Invoke(Program.gamePtr, parameters); - } - catch - { - Log.AsyncR("Failed to call base method: " + mi.Name); - return null; - } - } - - /// - /// Queue's a message to be drawn in Debug mode (F3) - /// - /// - public static bool QueueDebugMessage(string message) - { - if (!Debug) - return false; - - if (DebugMessageQueue.Count > 32) - return false; - - DebugMessageQueue.Enqueue(message); - return true; - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using StardewModdingAPI.Events; +using StardewValley; +using StardewValley.BellsAndWhistles; +using StardewValley.Locations; +using StardewValley.Menus; +using StardewValley.Tools; +using xTile.Dimensions; +using Rectangle = Microsoft.Xna.Framework.Rectangle; + +namespace StardewModdingAPI.Inheritance +{ + /// + /// The 'SGame' class. + /// This summary, and many others, only exists because XML doc tags. + /// + public class SGame : Game1 + { + private bool FireLoadedGameEvent; + + /// + /// Gets a jagged array of all buttons pressed on the gamepad the prior frame. + /// + public Buttons[][] PreviouslyPressedButtons; + + internal SGame() + { + Instance = this; + FirstUpdate = true; + } + + /// + /// The current KeyboardState + /// + public KeyboardState KStateNow { get; private set; } + /// + /// The prior KeyboardState + /// + public KeyboardState KStatePrior { get; private set; } + + /// + /// The current MouseState + /// + public MouseState MStateNow { get; private set; } + + /// + /// The prior MouseState + /// + public MouseState MStatePrior { get; private set; } + + /// The current mouse position on the screen adjusted for the zoom level. + public Point MPositionNow { get; private set; } + + /// The previous mouse position on the screen adjusted for the zoom level. + public Point MPositionPrior { get; private set; } + + /// + /// All keys pressed on the current frame + /// + public Keys[] CurrentlyPressedKeys => KStateNow.GetPressedKeys(); + + /// + /// All keys pressed on the prior frame + /// + public Keys[] PreviouslyPressedKeys => KStatePrior.GetPressedKeys(); + + /// + /// All keys pressed on this frame except for the ones pressed on the prior frame + /// + public Keys[] FramePressedKeys => CurrentlyPressedKeys.Except(PreviouslyPressedKeys).ToArray(); + + /// + /// All keys pressed on the prior frame except for the ones pressed on the current frame + /// + public Keys[] FrameReleasedKeys => PreviouslyPressedKeys.Except(CurrentlyPressedKeys).ToArray(); + + /// + /// Whether or not a save was tagged as 'Loaded' the prior frame. + /// + public bool PreviouslyLoadedGame { get; private set; } + + /// + /// The list of GameLocations on the prior frame + /// + public int PreviousGameLocations { get; private set; } + + /// + /// The list of GameObjects on the prior frame + /// + public int PreviousLocationObjects { get; private set; } + + /// + /// The list of Items in the player's inventory on the prior frame + /// + public Dictionary PreviousItems { get; private set; } + + /// + /// The player's Combat level on the prior frame + /// + public int PreviousCombatLevel { get; private set; } + /// + /// The player's Farming level on the prior frame + /// + public int PreviousFarmingLevel { get; private set; } + /// + /// The player's Fishing level on the prior frame + /// + public int PreviousFishingLevel { get; private set; } + /// + /// The player's Foraging level on the prior frame + /// + public int PreviousForagingLevel { get; private set; } + /// + /// The player's Mining level on the prior frame + /// + public int PreviousMiningLevel { get; private set; } + /// + /// The player's Luck level on the prior frame + /// + public int PreviousLuckLevel { get; private set; } + + //Kill me now comments are so boring + + /// + /// The player's previous game location + /// + public GameLocation PreviousGameLocation { get; private set; } + + /// + /// The previous ActiveGameMenu in Game1 + /// + public IClickableMenu PreviousActiveMenu { get; private set; } + + /// + /// Indicates if the MenuClosed event was fired to prevent it from re-firing. + /// + internal bool WasMenuClosedInvoked = false; + + /// + /// The previous mine level + /// + public int PreviousMineLevel { get; private set; } + + /// + /// The previous TimeOfDay (Int32 between 600 and 2400?) + /// + public int PreviousTimeOfDay { get; private set; } + + /// + /// The previous DayOfMonth (Int32 between 1 and 28?) + /// + public int PreviousDayOfMonth { get; private set; } + + /// + /// The previous Season (String as follows: "winter", "spring", "summer", "fall") + /// + public string PreviousSeasonOfYear { get; private set; } + + /// + /// The previous Year + /// + public int PreviousYearOfGame { get; private set; } + + /// + /// The previous result of Game1.newDay + /// + public bool PreviousIsNewDay { get; private set; } + + /// + /// The previous 'Farmer' (Player) + /// + public Farmer PreviousFarmer { get; private set; } + + /// + /// The current index of the update tick. Recycles every 60th tick to 0. (Int32 between 0 and 59) + /// + public int CurrentUpdateTick { get; private set; } + + /// + /// Whether or not this update frame is the very first of the entire game + /// + public bool FirstUpdate { get; private set; } + + /// + /// The current RenderTarget in Game1 (Private field, uses reflection) + /// + public RenderTarget2D Screen + { + get { return typeof (Game1).GetBaseFieldValue(Program.gamePtr, "screen"); } + set { typeof (Game1).SetBaseFieldValue(this, "screen", value); } + } + + /// + /// The current Colour in Game1 (Private field, uses reflection) + /// + public Color BgColour + { + get { return (Color)typeof(Game1).GetBaseFieldValue(Program.gamePtr, "bgColor"); } + set { typeof(Game1).SetBaseFieldValue(this, "bgColor", value); } + } + + /// + /// Static accessor for an Instance of the class SGame + /// + public static SGame Instance { get; private set; } + + /// + /// The game's FPS. Re-determined every Draw update. + /// + public static float FramesPerSecond { get; private set; } + + /// + /// Whether or not we're in a pseudo 'debug' mode. Mostly for displaying information like FPS. + /// + public static bool Debug { get; private set; } + internal static Queue DebugMessageQueue { get; private set; } + + /// + /// The current player (equal to Farmer.Player) + /// + [Obsolete("Use Farmer.Player instead")] + public Farmer CurrentFarmer => player; + + /// + /// Gets ALL static fields that belong to 'Game1' + /// + public static FieldInfo[] GetStaticFields => typeof (Game1).GetFields(); + + /// + /// Whether or not a button was just pressed on the controller + /// + /// + /// + /// + /// + private bool WasButtonJustPressed(Buttons button, ButtonState buttonState, PlayerIndex stateIndex) + { + return buttonState == ButtonState.Pressed && !PreviouslyPressedButtons[(int) stateIndex].Contains(button); + } + + /// + /// Whether or not a button was just released on the controller + /// + /// + /// + /// + /// + private bool WasButtonJustReleased(Buttons button, ButtonState buttonState, PlayerIndex stateIndex) + { + return buttonState == ButtonState.Released && PreviouslyPressedButtons[(int) stateIndex].Contains(button); + } + + /// + /// Whether or not an analog button was just pressed on the controller + /// + /// + /// + /// + /// + private bool WasButtonJustPressed(Buttons button, float value, PlayerIndex stateIndex) + { + return WasButtonJustPressed(button, value > 0.2f ? ButtonState.Pressed : ButtonState.Released, stateIndex); + } + + /// + /// Whether or not an analog button was just released on the controller + /// + /// + /// + /// + /// + private bool WasButtonJustReleased(Buttons button, float value, PlayerIndex stateIndex) + { + return WasButtonJustReleased(button, value > 0.2f ? ButtonState.Pressed : ButtonState.Released, stateIndex); + } + + /// + /// Gets an array of all Buttons pressed on a joystick + /// + /// + /// + public Buttons[] GetButtonsDown(PlayerIndex index) + { + var state = GamePad.GetState(index); + var buttons = new List(); + if (state.IsConnected) + { + if (state.Buttons.A == ButtonState.Pressed) buttons.Add(Buttons.A); + if (state.Buttons.B == ButtonState.Pressed) buttons.Add(Buttons.B); + if (state.Buttons.Back == ButtonState.Pressed) buttons.Add(Buttons.Back); + if (state.Buttons.BigButton == ButtonState.Pressed) buttons.Add(Buttons.BigButton); + if (state.Buttons.LeftShoulder == ButtonState.Pressed) buttons.Add(Buttons.LeftShoulder); + if (state.Buttons.LeftStick == ButtonState.Pressed) buttons.Add(Buttons.LeftStick); + if (state.Buttons.RightShoulder == ButtonState.Pressed) buttons.Add(Buttons.RightShoulder); + if (state.Buttons.RightStick == ButtonState.Pressed) buttons.Add(Buttons.RightStick); + if (state.Buttons.Start == ButtonState.Pressed) buttons.Add(Buttons.Start); + if (state.Buttons.X == ButtonState.Pressed) buttons.Add(Buttons.X); + if (state.Buttons.Y == ButtonState.Pressed) buttons.Add(Buttons.Y); + if (state.DPad.Up == ButtonState.Pressed) buttons.Add(Buttons.DPadUp); + if (state.DPad.Down == ButtonState.Pressed) buttons.Add(Buttons.DPadDown); + if (state.DPad.Left == ButtonState.Pressed) buttons.Add(Buttons.DPadLeft); + if (state.DPad.Right == ButtonState.Pressed) buttons.Add(Buttons.DPadRight); + if (state.Triggers.Left > 0.2f) buttons.Add(Buttons.LeftTrigger); + if (state.Triggers.Right > 0.2f) buttons.Add(Buttons.RightTrigger); + } + return buttons.ToArray(); + } + + /// + /// Gets all buttons that were pressed on the current frame of a joystick + /// + /// + /// + public Buttons[] GetFramePressedButtons(PlayerIndex index) + { + var state = GamePad.GetState(index); + var buttons = new List(); + if (state.IsConnected) + { + if (WasButtonJustPressed(Buttons.A, state.Buttons.A, index)) buttons.Add(Buttons.A); + if (WasButtonJustPressed(Buttons.B, state.Buttons.B, index)) buttons.Add(Buttons.B); + if (WasButtonJustPressed(Buttons.Back, state.Buttons.Back, index)) buttons.Add(Buttons.Back); + if (WasButtonJustPressed(Buttons.BigButton, state.Buttons.BigButton, index)) buttons.Add(Buttons.BigButton); + if (WasButtonJustPressed(Buttons.LeftShoulder, state.Buttons.LeftShoulder, index)) buttons.Add(Buttons.LeftShoulder); + if (WasButtonJustPressed(Buttons.LeftStick, state.Buttons.LeftStick, index)) buttons.Add(Buttons.LeftStick); + if (WasButtonJustPressed(Buttons.RightShoulder, state.Buttons.RightShoulder, index)) buttons.Add(Buttons.RightShoulder); + if (WasButtonJustPressed(Buttons.RightStick, state.Buttons.RightStick, index)) buttons.Add(Buttons.RightStick); + if (WasButtonJustPressed(Buttons.Start, state.Buttons.Start, index)) buttons.Add(Buttons.Start); + if (WasButtonJustPressed(Buttons.X, state.Buttons.X, index)) buttons.Add(Buttons.X); + if (WasButtonJustPressed(Buttons.Y, state.Buttons.Y, index)) buttons.Add(Buttons.Y); + if (WasButtonJustPressed(Buttons.DPadUp, state.DPad.Up, index)) buttons.Add(Buttons.DPadUp); + if (WasButtonJustPressed(Buttons.DPadDown, state.DPad.Down, index)) buttons.Add(Buttons.DPadDown); + if (WasButtonJustPressed(Buttons.DPadLeft, state.DPad.Left, index)) buttons.Add(Buttons.DPadLeft); + if (WasButtonJustPressed(Buttons.DPadRight, state.DPad.Right, index)) buttons.Add(Buttons.DPadRight); + if (WasButtonJustPressed(Buttons.LeftTrigger, state.Triggers.Left, index)) buttons.Add(Buttons.LeftTrigger); + if (WasButtonJustPressed(Buttons.RightTrigger, state.Triggers.Right, index)) buttons.Add(Buttons.RightTrigger); + } + return buttons.ToArray(); + } + + /// + /// Gets all buttons that were released on the current frame of a joystick + /// + /// + /// + public Buttons[] GetFrameReleasedButtons(PlayerIndex index) + { + var state = GamePad.GetState(index); + var buttons = new List(); + if (state.IsConnected) + { + if (WasButtonJustReleased(Buttons.A, state.Buttons.A, index)) buttons.Add(Buttons.A); + if (WasButtonJustReleased(Buttons.B, state.Buttons.B, index)) buttons.Add(Buttons.B); + if (WasButtonJustReleased(Buttons.Back, state.Buttons.Back, index)) buttons.Add(Buttons.Back); + if (WasButtonJustReleased(Buttons.BigButton, state.Buttons.BigButton, index)) buttons.Add(Buttons.BigButton); + if (WasButtonJustReleased(Buttons.LeftShoulder, state.Buttons.LeftShoulder, index)) buttons.Add(Buttons.LeftShoulder); + if (WasButtonJustReleased(Buttons.LeftStick, state.Buttons.LeftStick, index)) buttons.Add(Buttons.LeftStick); + if (WasButtonJustReleased(Buttons.RightShoulder, state.Buttons.RightShoulder, index)) buttons.Add(Buttons.RightShoulder); + if (WasButtonJustReleased(Buttons.RightStick, state.Buttons.RightStick, index)) buttons.Add(Buttons.RightStick); + if (WasButtonJustReleased(Buttons.Start, state.Buttons.Start, index)) buttons.Add(Buttons.Start); + if (WasButtonJustReleased(Buttons.X, state.Buttons.X, index)) buttons.Add(Buttons.X); + if (WasButtonJustReleased(Buttons.Y, state.Buttons.Y, index)) buttons.Add(Buttons.Y); + if (WasButtonJustReleased(Buttons.DPadUp, state.DPad.Up, index)) buttons.Add(Buttons.DPadUp); + if (WasButtonJustReleased(Buttons.DPadDown, state.DPad.Down, index)) buttons.Add(Buttons.DPadDown); + if (WasButtonJustReleased(Buttons.DPadLeft, state.DPad.Left, index)) buttons.Add(Buttons.DPadLeft); + if (WasButtonJustReleased(Buttons.DPadRight, state.DPad.Right, index)) buttons.Add(Buttons.DPadRight); + if (WasButtonJustReleased(Buttons.LeftTrigger, state.Triggers.Left, index)) buttons.Add(Buttons.LeftTrigger); + if (WasButtonJustReleased(Buttons.RightTrigger, state.Triggers.Right, index)) buttons.Add(Buttons.RightTrigger); + } + return buttons.ToArray(); + } + + /// + /// + /// + public static MethodInfo DrawFarmBuildings = typeof (Game1).GetMethod("drawFarmBuildings", BindingFlags.NonPublic | BindingFlags.Instance); + + /// + /// + /// + public static MethodInfo DrawHUD = typeof (Game1).GetMethod("drawHUD", BindingFlags.NonPublic | BindingFlags.Instance); + + /// + /// + /// + public static MethodInfo DrawDialogueBox = typeof (Game1).GetMethod("drawDialogueBox", BindingFlags.NonPublic | BindingFlags.Instance); + + public static MethodInfo CheckForEscapeKeys = typeof (Game1).GetMethod("checkForEscapeKeys", BindingFlags.NonPublic | BindingFlags.Instance); + + public static MethodInfo UpdateControlInput = typeof(Game1).GetMethod("UpdateControlInput", BindingFlags.NonPublic | BindingFlags.Instance); + + public static MethodInfo UpdateCharacters = typeof(Game1).GetMethod("UpdateCharacters", BindingFlags.NonPublic | BindingFlags.Instance); + + public static MethodInfo UpdateLocations = typeof(Game1).GetMethod("UpdateLocations", BindingFlags.NonPublic | BindingFlags.Instance); + + public static MethodInfo getViewportCenter = typeof(Game1).GetMethod("getViewportCenter", BindingFlags.NonPublic | BindingFlags.Instance); + + public static MethodInfo UpdateTitleScreen = typeof(Game1).GetMethod("UpdateTitleScreen", BindingFlags.NonPublic | BindingFlags.Instance); + + public delegate void BaseBaseDraw(); + + /// + /// Whether or not the game's zoom level is 1.0f + /// + public bool ZoomLevelIsOne => options.zoomLevel.Equals(1.0f); + + /// + /// XNA Init Method + /// + protected override void Initialize() + { + Log.AsyncY("XNA Initialize"); + //ModItems = new Dictionary(); + DebugMessageQueue = new Queue(); + PreviouslyPressedButtons = new Buttons[4][]; + for (var i = 0; i < 4; ++i) PreviouslyPressedButtons[i] = new Buttons[0]; + + base.Initialize(); + GameEvents.InvokeInitialize(); + } + + /// + /// XNA LC Method + /// + protected override void LoadContent() + { + Log.AsyncY("XNA LoadContent"); + base.LoadContent(); + GameEvents.InvokeLoadContent(); + } + + /// + /// XNA Update Method + /// + /// + protected override void Update(GameTime gameTime) + { + QueueDebugMessage("FPS: " + FramesPerSecond); + UpdateEventCalls(); + + if (FramePressedKeys.Contains(Keys.F3)) + { + Debug = !Debug; + } + + try + { + base.Update(gameTime); + } + catch (Exception ex) + { + Log.AsyncR("An error occured in the base update loop: " + ex); + Console.ReadKey(); + } + + GameEvents.InvokeUpdateTick(); + if (FirstUpdate) + { + GameEvents.InvokeFirstUpdateTick(); + FirstUpdate = false; + } + + if (CurrentUpdateTick % 2 == 0) + GameEvents.InvokeSecondUpdateTick(); + + if (CurrentUpdateTick % 4 == 0) + GameEvents.InvokeFourthUpdateTick(); + + if (CurrentUpdateTick % 8 == 0) + GameEvents.InvokeEighthUpdateTick(); + + if (CurrentUpdateTick % 15 == 0) + GameEvents.InvokeQuarterSecondTick(); + + if (CurrentUpdateTick % 30 == 0) + GameEvents.InvokeHalfSecondTick(); + + if (CurrentUpdateTick % 60 == 0) + GameEvents.InvokeOneSecondTick(); + + CurrentUpdateTick += 1; + if (CurrentUpdateTick >= 60) + CurrentUpdateTick = 0; + + if (KStatePrior != KStateNow) + KStatePrior = KStateNow; + + for (var i = PlayerIndex.One; i <= PlayerIndex.Four; i++) + { + PreviouslyPressedButtons[(int) i] = GetButtonsDown(i); + } + } + + /// + /// XNA Draw Method + /// + /// + protected override void Draw(GameTime gameTime) + { + FramesPerSecond = 1 / (float) gameTime.ElapsedGameTime.TotalSeconds; + + if (Constants.EnableCompletelyOverridingBaseCalls) + { + #region Overridden Draw + + try + { + if (!ZoomLevelIsOne) + { + GraphicsDevice.SetRenderTarget(Screen); + } + + GraphicsDevice.Clear(BgColour); + if (options.showMenuBackground && activeClickableMenu != null && activeClickableMenu.showWithoutTransparencyIfOptionIsSet()) + { + spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + activeClickableMenu.drawBackground(spriteBatch); + GraphicsEvents.InvokeOnPreRenderGuiEvent(null, EventArgs.Empty); + activeClickableMenu.draw(spriteBatch); + GraphicsEvents.InvokeOnPostRenderGuiEvent(null, EventArgs.Empty); + spriteBatch.End(); + if (!ZoomLevelIsOne) + { + GraphicsDevice.SetRenderTarget(null); + GraphicsDevice.Clear(BgColour); + spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); + spriteBatch.Draw(Screen, Vector2.Zero, Screen.Bounds, Color.White, 0f, Vector2.Zero, options.zoomLevel, SpriteEffects.None, 1f); + spriteBatch.End(); + } + return; + } + if (gameMode == 11) + { + spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + spriteBatch.DrawString(smoothFont, "Stardew Valley has crashed...", new Vector2(16f, 16f), Color.HotPink); + spriteBatch.DrawString(smoothFont, "Please send the error report or a screenshot of this message to @ConcernedApe. (http://stardewvalley.net/contact/)", new Vector2(16f, 32f), new Color(0, 255, 0)); + spriteBatch.DrawString(smoothFont, parseText(errorMessage, smoothFont, graphics.GraphicsDevice.Viewport.Width), new Vector2(16f, 48f), Color.White); + spriteBatch.End(); + return; + } + if (currentMinigame != null) + { + currentMinigame.draw(spriteBatch); + if (globalFade && !menuUp && (!nameSelectUp || messagePause)) + { + spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + spriteBatch.Draw(fadeToBlackRect, graphics.GraphicsDevice.Viewport.Bounds, Color.Black * ((gameMode == 0) ? (1f - fadeToBlackAlpha) : fadeToBlackAlpha)); + spriteBatch.End(); + } + if (!ZoomLevelIsOne) + { + GraphicsDevice.SetRenderTarget(null); + GraphicsDevice.Clear(BgColour); + spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); + spriteBatch.Draw(Screen, Vector2.Zero, Screen.Bounds, Color.White, 0f, Vector2.Zero, options.zoomLevel, SpriteEffects.None, 1f); + spriteBatch.End(); + } + return; + } + if (showingEndOfNightStuff) + { + spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + activeClickableMenu?.draw(spriteBatch); + spriteBatch.End(); + if (!ZoomLevelIsOne) + { + GraphicsDevice.SetRenderTarget(null); + GraphicsDevice.Clear(BgColour); + spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); + spriteBatch.Draw(Screen, Vector2.Zero, Screen.Bounds, Color.White, 0f, Vector2.Zero, options.zoomLevel, SpriteEffects.None, 1f); + spriteBatch.End(); + } + return; + } + if (gameMode == 6) + { + spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + string text = ""; + int num = 0; + while (num < gameTime.TotalGameTime.TotalMilliseconds % 999.0 / 333.0) + { + text += "."; + num++; + } + SpriteText.drawString(spriteBatch, "Loading" + text, 64, graphics.GraphicsDevice.Viewport.Height - 64, 999, -1, 999, 1f, 1f, false, 0, "Loading..."); + spriteBatch.End(); + if (!ZoomLevelIsOne) + { + GraphicsDevice.SetRenderTarget(null); + GraphicsDevice.Clear(BgColour); + spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); + spriteBatch.Draw(Screen, Vector2.Zero, Screen.Bounds, Color.White, 0f, Vector2.Zero, options.zoomLevel, SpriteEffects.None, 1f); + spriteBatch.End(); + } + return; + } + if (gameMode == 0) + { + spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + } + else + { + if (drawLighting) + { + GraphicsDevice.SetRenderTarget(lightmap); + GraphicsDevice.Clear(Color.White * 0f); + spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, null, null); + spriteBatch.Draw(staminaRect, lightmap.Bounds, currentLocation.name.Equals("UndergroundMine") ? mine.getLightingColor(gameTime) : ((!ambientLight.Equals(Color.White) && (!isRaining || !currentLocation.isOutdoors)) ? ambientLight : outdoorLight)); + for (int i = 0; i < currentLightSources.Count; i++) + { + if (Utility.isOnScreen(currentLightSources.ElementAt(i).position, (int) (currentLightSources.ElementAt(i).radius * tileSize * 4f))) + { + spriteBatch.Draw(currentLightSources.ElementAt(i).lightTexture, GlobalToLocal(viewport, currentLightSources.ElementAt(i).position) / options.lightingQuality, currentLightSources.ElementAt(i).lightTexture.Bounds, currentLightSources.ElementAt(i).color, 0f, new Vector2(currentLightSources.ElementAt(i).lightTexture.Bounds.Center.X, currentLightSources.ElementAt(i).lightTexture.Bounds.Center.Y), currentLightSources.ElementAt(i).radius / options.lightingQuality, SpriteEffects.None, 0.9f); + } + } + spriteBatch.End(); + GraphicsDevice.SetRenderTarget(ZoomLevelIsOne ? null : Screen); + } + if (bloomDay) + { + bloom?.BeginDraw(); + } + GraphicsDevice.Clear(BgColour); + spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + GraphicsEvents.InvokeOnPreRenderEvent(null, EventArgs.Empty); + background?.draw(spriteBatch); + mapDisplayDevice.BeginScene(spriteBatch); + currentLocation.Map.GetLayer("Back").Draw(mapDisplayDevice, viewport, Location.Origin, false, pixelZoom); + currentLocation.drawWater(spriteBatch); + if (CurrentEvent == null) + { + using (List.Enumerator enumerator = currentLocation.characters.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + NPC current = enumerator.Current; + if (current != null && !current.swimming && !current.hideShadow && !current.IsMonster && !currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(current.getTileLocation())) + { + spriteBatch.Draw(shadowTexture, GlobalToLocal(viewport, current.position + new Vector2(current.sprite.spriteWidth * pixelZoom / 2f, current.GetBoundingBox().Height + (current.IsMonster ? 0 : (pixelZoom * 3)))), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), (pixelZoom + current.yJumpOffset / 40f) * current.scale, SpriteEffects.None, Math.Max(0f, current.getStandingY() / 10000f) - 1E-06f); + } + } + goto IL_B30; + } + } + foreach (NPC current2 in CurrentEvent.actors) + { + if (!current2.swimming && !current2.hideShadow && !currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(current2.getTileLocation())) + { + spriteBatch.Draw(shadowTexture, GlobalToLocal(viewport, current2.position + new Vector2(current2.sprite.spriteWidth * pixelZoom / 2f, current2.GetBoundingBox().Height + (current2.IsMonster ? 0 : (pixelZoom * 3)))), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), (pixelZoom + current2.yJumpOffset / 40f) * current2.scale, SpriteEffects.None, Math.Max(0f, current2.getStandingY() / 10000f) - 1E-06f); + } + } + IL_B30: + if (!player.swimming && !player.isRidingHorse() && !currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(player.getTileLocation())) + { + spriteBatch.Draw(shadowTexture, GlobalToLocal(player.position + new Vector2(32f, 24f)), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), 4f - (((player.running || player.usingTool) && player.FarmerSprite.indexInCurrentAnimation > 1) ? (Math.Abs(FarmerRenderer.featureYOffsetPerFrame[player.FarmerSprite.CurrentFrame]) * 0.5f) : 0f), SpriteEffects.None, 0f); + } + currentLocation.Map.GetLayer("Buildings").Draw(mapDisplayDevice, viewport, Location.Origin, false, pixelZoom); + mapDisplayDevice.EndScene(); + spriteBatch.End(); + spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + if (CurrentEvent == null) + { + using (List.Enumerator enumerator3 = currentLocation.characters.GetEnumerator()) + { + while (enumerator3.MoveNext()) + { + NPC current3 = enumerator3.Current; + if (current3 != null && !current3.swimming && !current3.hideShadow && currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(current3.getTileLocation())) + { + spriteBatch.Draw(shadowTexture, GlobalToLocal(viewport, current3.position + new Vector2(current3.sprite.spriteWidth * pixelZoom / 2f, current3.GetBoundingBox().Height + (current3.IsMonster ? 0 : (pixelZoom * 3)))), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), (pixelZoom + current3.yJumpOffset / 40f) * current3.scale, SpriteEffects.None, Math.Max(0f, current3.getStandingY() / 10000f) - 1E-06f); + } + } + goto IL_F5F; + } + } + foreach (NPC current4 in CurrentEvent.actors) + { + if (!current4.swimming && !current4.hideShadow && currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(current4.getTileLocation())) + { + spriteBatch.Draw(shadowTexture, GlobalToLocal(viewport, current4.position + new Vector2(current4.sprite.spriteWidth * pixelZoom / 2f, current4.GetBoundingBox().Height + (current4.IsMonster ? 0 : (pixelZoom * 3)))), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), (pixelZoom + current4.yJumpOffset / 40f) * current4.scale, SpriteEffects.None, Math.Max(0f, current4.getStandingY() / 10000f) - 1E-06f); + } + } + IL_F5F: + if (!player.swimming && !player.isRidingHorse() && currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(player.getTileLocation())) + { + spriteBatch.Draw(shadowTexture, GlobalToLocal(player.position + new Vector2(32f, 24f)), shadowTexture.Bounds, Color.White, 0f, new Vector2(shadowTexture.Bounds.Center.X, shadowTexture.Bounds.Center.Y), 4f - (((player.running || player.usingTool) && player.FarmerSprite.indexInCurrentAnimation > 1) ? (Math.Abs(FarmerRenderer.featureYOffsetPerFrame[player.FarmerSprite.CurrentFrame]) * 0.5f) : 0f), SpriteEffects.None, Math.Max(0.0001f, player.getStandingY() / 10000f + 0.00011f) - 0.0001f); + } + if (displayFarmer) + { + player.draw(spriteBatch); + } + if ((eventUp || killScreen) && !killScreen) + { + currentLocation.currentEvent?.draw(spriteBatch); + } + if (player.currentUpgrade != null && player.currentUpgrade.daysLeftTillUpgradeDone <= 3 && currentLocation.Name.Equals("Farm")) + { + spriteBatch.Draw(player.currentUpgrade.workerTexture, GlobalToLocal(viewport, player.currentUpgrade.positionOfCarpenter), player.currentUpgrade.getSourceRectangle(), Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, (player.currentUpgrade.positionOfCarpenter.Y + tileSize * 3 / 4) / 10000f); + } + currentLocation.draw(spriteBatch); + if (eventUp && currentLocation.currentEvent?.messageToScreen != null) + { + drawWithBorder(currentLocation.currentEvent.messageToScreen, Color.Black, Color.White, new Vector2(graphics.GraphicsDevice.Viewport.TitleSafeArea.Width / 2 - borderFont.MeasureString(currentLocation.currentEvent.messageToScreen).X / 2f, graphics.GraphicsDevice.Viewport.TitleSafeArea.Height - tileSize), 0f, 1f, 0.999f); + } + if (player.ActiveObject == null && (player.UsingTool || pickingTool) && player.CurrentTool != null && (!player.CurrentTool.Name.Equals("Seeds") || pickingTool)) + { + drawTool(player); + } + if (currentLocation.Name.Equals("Farm")) + { + DrawFarmBuildings.Invoke(Program.gamePtr, null); + } + if (tvStation >= 0) + { + spriteBatch.Draw(tvStationTexture, GlobalToLocal(viewport, new Vector2(6 * tileSize + tileSize / 4, 2 * tileSize + tileSize / 2)), new Rectangle(tvStation * 24, 0, 24, 15), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-08f); + } + if (panMode) + { + spriteBatch.Draw(fadeToBlackRect, new Rectangle((int) Math.Floor((getOldMouseX() + viewport.X) / (double) tileSize) * tileSize - viewport.X, (int) Math.Floor((getOldMouseY() + viewport.Y) / (double) tileSize) * tileSize - viewport.Y, tileSize, tileSize), Color.Lime * 0.75f); + foreach (Warp current5 in currentLocation.warps) + { + spriteBatch.Draw(fadeToBlackRect, new Rectangle(current5.X * tileSize - viewport.X, current5.Y * tileSize - viewport.Y, tileSize, tileSize), Color.Red * 0.75f); + } + } + mapDisplayDevice.BeginScene(spriteBatch); + currentLocation.Map.GetLayer("Front").Draw(mapDisplayDevice, viewport, Location.Origin, false, pixelZoom); + mapDisplayDevice.EndScene(); + currentLocation.drawAboveFrontLayer(spriteBatch); + spriteBatch.End(); + spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + if (currentLocation.Name.Equals("Farm") && stats.SeedsSown >= 200u) + { + spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(3 * tileSize + tileSize / 4, tileSize + tileSize / 3)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); + spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(4 * tileSize + tileSize, 2 * tileSize + tileSize)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); + spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(5 * tileSize, 2 * tileSize)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); + spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(3 * tileSize + tileSize / 2, 3 * tileSize)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); + spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(5 * tileSize - tileSize / 4, tileSize)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); + spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(4 * tileSize, 3 * tileSize + tileSize / 6)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); + spriteBatch.Draw(debrisSpriteSheet, GlobalToLocal(viewport, new Vector2(4 * tileSize + tileSize / 5, 2 * tileSize + tileSize / 3)), getSourceRectForStandardTileSheet(debrisSpriteSheet, 16), Color.White); + } + if (displayFarmer && player.ActiveObject != null && player.ActiveObject.bigCraftable && checkBigCraftableBoundariesForFrontLayer() && currentLocation.Map.GetLayer("Front").PickTile(new Location(player.getStandingX(), player.getStandingY()), viewport.Size) == null) + { + drawPlayerHeldObject(player); + } + else if (displayFarmer && player.ActiveObject != null && ((currentLocation.Map.GetLayer("Front").PickTile(new Location((int) player.position.X, (int) player.position.Y - tileSize * 3 / 5), viewport.Size) != null && !currentLocation.Map.GetLayer("Front").PickTile(new Location((int) player.position.X, (int) player.position.Y - tileSize * 3 / 5), viewport.Size).TileIndexProperties.ContainsKey("FrontAlways")) || (currentLocation.Map.GetLayer("Front").PickTile(new Location(player.GetBoundingBox().Right, (int) player.position.Y - tileSize * 3 / 5), viewport.Size) != null && !currentLocation.Map.GetLayer("Front").PickTile(new Location(player.GetBoundingBox().Right, (int) player.position.Y - tileSize * 3 / 5), viewport.Size).TileIndexProperties.ContainsKey("FrontAlways")))) + { + drawPlayerHeldObject(player); + } + if ((player.UsingTool || pickingTool) && player.CurrentTool != null && (!player.CurrentTool.Name.Equals("Seeds") || pickingTool) && currentLocation.Map.GetLayer("Front").PickTile(new Location(player.getStandingX(), (int) player.position.Y - tileSize * 3 / 5), viewport.Size) != null && currentLocation.Map.GetLayer("Front").PickTile(new Location(player.getStandingX(), player.getStandingY()), viewport.Size) == null) + { + drawTool(player); + } + if (currentLocation.Map.GetLayer("AlwaysFront") != null) + { + mapDisplayDevice.BeginScene(spriteBatch); + currentLocation.Map.GetLayer("AlwaysFront").Draw(mapDisplayDevice, viewport, Location.Origin, false, pixelZoom); + mapDisplayDevice.EndScene(); + } + if (toolHold > 400f && player.CurrentTool.UpgradeLevel >= 1 && player.canReleaseTool) + { + Color color = Color.White; + switch ((int) (toolHold / 600f) + 2) + { + case 1: + color = Tool.copperColor; + break; + case 2: + color = Tool.steelColor; + break; + case 3: + color = Tool.goldColor; + break; + case 4: + color = Tool.iridiumColor; + break; + } + spriteBatch.Draw(littleEffect, new Rectangle((int) player.getLocalPosition(viewport).X - 2, (int) player.getLocalPosition(viewport).Y - (player.CurrentTool.Name.Equals("Watering Can") ? 0 : tileSize) - 2, (int) (toolHold % 600f * 0.08f) + 4, tileSize / 8 + 4), Color.Black); + spriteBatch.Draw(littleEffect, new Rectangle((int) player.getLocalPosition(viewport).X, (int) player.getLocalPosition(viewport).Y - (player.CurrentTool.Name.Equals("Watering Can") ? 0 : tileSize), (int) (toolHold % 600f * 0.08f), tileSize / 8), color); + } + if (isDebrisWeather && currentLocation.IsOutdoors && !currentLocation.ignoreDebrisWeather && !currentLocation.Name.Equals("Desert") && viewport.X > -10) + { + foreach (WeatherDebris current6 in debrisWeather) + { + current6.draw(spriteBatch); + } + } + farmEvent?.draw(spriteBatch); + if (currentLocation.LightLevel > 0f && timeOfDay < 2000) + { + spriteBatch.Draw(fadeToBlackRect, graphics.GraphicsDevice.Viewport.Bounds, Color.Black * currentLocation.LightLevel); + } + if (screenGlow) + { + spriteBatch.Draw(fadeToBlackRect, graphics.GraphicsDevice.Viewport.Bounds, screenGlowColor * screenGlowAlpha); + } + currentLocation.drawAboveAlwaysFrontLayer(spriteBatch); + if (player.CurrentTool is FishingRod && ((player.CurrentTool as FishingRod).isTimingCast || (player.CurrentTool as FishingRod).castingChosenCountdown > 0f || (player.CurrentTool as FishingRod).fishCaught || (player.CurrentTool as FishingRod).showingTreasure)) + { + player.CurrentTool.draw(spriteBatch); + } + if (isRaining && currentLocation.IsOutdoors && !currentLocation.Name.Equals("Desert") && !(currentLocation is Summit) && (!eventUp || currentLocation.isTileOnMap(new Vector2(viewport.X / tileSize, viewport.Y / tileSize)))) + { + for (int j = 0; j < rainDrops.Length; j++) + { + spriteBatch.Draw(rainTexture, rainDrops[j].position, getSourceRectForStandardTileSheet(rainTexture, rainDrops[j].frame), Color.White); + } + } + + spriteBatch.End(); + + //base.Draw(gameTime); + + spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + if (eventUp && currentLocation.currentEvent != null) + { + foreach (NPC current7 in currentLocation.currentEvent.actors) + { + if (current7.isEmoting) + { + Vector2 localPosition = current7.getLocalPosition(viewport); + localPosition.Y -= tileSize * 2 + pixelZoom * 3; + if (current7.age == 2) + { + localPosition.Y += tileSize / 2; + } + else if (current7.gender == 1) + { + localPosition.Y += tileSize / 6; + } + spriteBatch.Draw(emoteSpriteSheet, localPosition, new Rectangle(current7.CurrentEmoteIndex * (tileSize / 4) % emoteSpriteSheet.Width, current7.CurrentEmoteIndex * (tileSize / 4) / emoteSpriteSheet.Width * (tileSize / 4), tileSize / 4, tileSize / 4), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, current7.getStandingY() / 10000f); + } + } + } + spriteBatch.End(); + if (drawLighting) + { + spriteBatch.Begin(SpriteSortMode.Deferred, new BlendState + { + ColorBlendFunction = BlendFunction.ReverseSubtract, + ColorDestinationBlend = Blend.One, + ColorSourceBlend = Blend.SourceColor + }, SamplerState.LinearClamp, null, null); + spriteBatch.Draw(lightmap, Vector2.Zero, lightmap.Bounds, Color.White, 0f, Vector2.Zero, options.lightingQuality, SpriteEffects.None, 1f); + if (isRaining && currentLocation.isOutdoors && !(currentLocation is Desert)) + { + spriteBatch.Draw(staminaRect, graphics.GraphicsDevice.Viewport.Bounds, Color.OrangeRed * 0.45f); + } + spriteBatch.End(); + } + spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + if (drawGrid) + { + int num2 = -viewport.X % tileSize; + float num3 = -(float) viewport.Y % tileSize; + for (int k = num2; k < graphics.GraphicsDevice.Viewport.Width; k += tileSize) + { + spriteBatch.Draw(staminaRect, new Rectangle(k, (int) num3, 1, graphics.GraphicsDevice.Viewport.Height), Color.Red * 0.5f); + } + for (float num4 = num3; num4 < (float) graphics.GraphicsDevice.Viewport.Height; num4 += (float) tileSize) + { + spriteBatch.Draw(staminaRect, new Rectangle(num2, (int) num4, graphics.GraphicsDevice.Viewport.Width, 1), Color.Red * 0.5f); + } + } + if (currentBillboard != 0) + { + drawBillboard(); + } + + GraphicsEvents.InvokeOnPreRenderHudEventNoCheck(null, EventArgs.Empty); + if ((displayHUD || eventUp) && currentBillboard == 0 && gameMode == 3 && !freezeControls && !panMode) + { + GraphicsEvents.InvokeOnPreRenderHudEvent(null, EventArgs.Empty); + DrawHUD.Invoke(Program.gamePtr, null); + GraphicsEvents.InvokeOnPostRenderHudEvent(null, EventArgs.Empty); + } + else if (activeClickableMenu == null && farmEvent == null) + { + spriteBatch.Draw(mouseCursors, new Vector2(getOldMouseX(), getOldMouseY()), getSourceRectForStandardTileSheet(mouseCursors, 0, 16, 16), Color.White, 0f, Vector2.Zero, 4f + dialogueButtonScale / 150f, SpriteEffects.None, 1f); + } + GraphicsEvents.InvokeOnPostRenderHudEventNoCheck(null, EventArgs.Empty); + + if (hudMessages.Any() && (!eventUp || isFestival())) + { + for (int l = hudMessages.Count - 1; l >= 0; l--) + { + hudMessages[l].draw(spriteBatch, l); + } + } + } + farmEvent?.draw(spriteBatch); + if (dialogueUp && !nameSelectUp && !messagePause && !(activeClickableMenu is DialogueBox)) + { + DrawDialogueBox.Invoke(Program.gamePtr, null); + } + if (progressBar) + { + spriteBatch.Draw(fadeToBlackRect, new Rectangle((graphics.GraphicsDevice.Viewport.TitleSafeArea.Width - dialogueWidth) / 2, graphics.GraphicsDevice.Viewport.TitleSafeArea.Bottom - tileSize * 2, dialogueWidth, tileSize / 2), Color.LightGray); + spriteBatch.Draw(staminaRect, new Rectangle((graphics.GraphicsDevice.Viewport.TitleSafeArea.Width - dialogueWidth) / 2, graphics.GraphicsDevice.Viewport.TitleSafeArea.Bottom - tileSize * 2, (int) (pauseAccumulator / pauseTime * dialogueWidth), tileSize / 2), Color.DimGray); + } + if (eventUp) + { + currentLocation.currentEvent?.drawAfterMap(spriteBatch); + } + if (isRaining && currentLocation.isOutdoors && !(currentLocation is Desert)) + { + spriteBatch.Draw(staminaRect, graphics.GraphicsDevice.Viewport.Bounds, Color.Blue * 0.2f); + } + if ((fadeToBlack || globalFade) && !menuUp && (!nameSelectUp || messagePause)) + { + spriteBatch.Draw(fadeToBlackRect, graphics.GraphicsDevice.Viewport.Bounds, Color.Black * ((gameMode == 0) ? (1f - fadeToBlackAlpha) : fadeToBlackAlpha)); + } + else if (flashAlpha > 0f) + { + if (options.screenFlash) + { + spriteBatch.Draw(fadeToBlackRect, graphics.GraphicsDevice.Viewport.Bounds, Color.White * Math.Min(1f, flashAlpha)); + } + flashAlpha -= 0.1f; + } + if ((messagePause || globalFade) && dialogueUp) + { + DrawDialogueBox.Invoke(Program.gamePtr, null); + } + foreach (TemporaryAnimatedSprite current8 in screenOverlayTempSprites) + { + current8.draw(spriteBatch, true); + } + if (debugMode) + { + spriteBatch.DrawString(smallFont, string.Concat(new object[] + { + panMode ? ((getOldMouseX() + viewport.X) / tileSize + "," + (getOldMouseY() + viewport.Y) / tileSize) : string.Concat("aplayer: ", player.getStandingX() / tileSize, ", ", player.getStandingY() / tileSize), + Environment.NewLine, + "debugOutput: ", + debugOutput + }), new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y), Color.Red, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.9999999f); + } + /*if (inputMode) + { + spriteBatch.DrawString(smallFont, "Input: " + debugInput, new Vector2(tileSize, tileSize * 3), Color.Purple); + }*/ + if (showKeyHelp) + { + spriteBatch.DrawString(smallFont, keyHelpString, new Vector2(tileSize, viewport.Height - tileSize - (dialogueUp ? (tileSize * 3 + (isQuestion ? (questionChoices.Count * tileSize) : 0)) : 0) - smallFont.MeasureString(keyHelpString).Y), Color.LightGray, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.9999999f); + } + + GraphicsEvents.InvokeOnPreRenderGuiEventNoCheck(null, EventArgs.Empty); + if (activeClickableMenu != null) + { + GraphicsEvents.InvokeOnPreRenderGuiEvent(null, EventArgs.Empty); + activeClickableMenu.draw(spriteBatch); + GraphicsEvents.InvokeOnPostRenderGuiEvent(null, EventArgs.Empty); + } + else + { + farmEvent?.drawAboveEverything(spriteBatch); + } + GraphicsEvents.InvokeOnPostRenderGuiEventNoCheck(null, EventArgs.Empty); + + GraphicsEvents.InvokeOnPostRenderEvent(null, EventArgs.Empty); + spriteBatch.End(); + + GraphicsEvents.InvokeDrawInRenderTargetTick(); + + if (!ZoomLevelIsOne) + { + GraphicsDevice.SetRenderTarget(null); + GraphicsDevice.Clear(BgColour); + spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); + spriteBatch.Draw(Screen, Vector2.Zero, Screen.Bounds, Color.White, 0f, Vector2.Zero, options.zoomLevel, SpriteEffects.None, 1f); + spriteBatch.End(); + } + + GraphicsEvents.InvokeDrawTick(); + } + catch (Exception ex) + { + Log.Error("An error occured in the overridden draw loop: " + ex); + } + + #endregion + } + else + { + #region Base Draw Call + + try + { + base.Draw(gameTime); + } + catch (Exception ex) + { + Log.AsyncR("An error occured in the base draw loop: " + ex); + Console.ReadKey(); + } + + 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(); + + //Re-draw the HUD + spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + activeClickableMenu?.draw(spriteBatch); + /* + if ((displayHUD || eventUp) && currentBillboard == 0 && gameMode == 3 && !freezeControls && !panMode) + typeof (Game1).GetMethod("drawHUD", BindingFlags.NonPublic | BindingFlags.Instance)?.Invoke(Program.gamePtr, null); + */ + spriteBatch.Draw(mouseCursors, new Vector2(getOldMouseX(), getOldMouseY()), getSourceRectForStandardTileSheet(mouseCursors, options.gamepadControls ? 44 : 0, 16, 16), Color.White, 0.0f, Vector2.Zero, pixelZoom + dialogueButtonScale / 150f, SpriteEffects.None, 1f); + + 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(); + } + } + + #endregion + } + + if (Debug) + { + spriteBatch.Begin(); + + int i = 0; + while (DebugMessageQueue.Any()) + { + string s = DebugMessageQueue.Dequeue(); + spriteBatch.DrawString(smoothFont, s, new Vector2(0, i * 14), Color.CornflowerBlue); + i++; + } + GraphicsEvents.InvokeDrawDebug(null, EventArgs.Empty); + + spriteBatch.End(); + } + else + { + DebugMessageQueue.Clear(); + } + } + + private void UpdateEventCalls() + { + KStateNow = Keyboard.GetState(); + + MStateNow = Mouse.GetState(); + MPositionNow = new Point(Game1.getMouseX(), Game1.getMouseY()); + + foreach (var k in FramePressedKeys) + ControlEvents.InvokeKeyPressed(k); + + foreach (var k in FrameReleasedKeys) + ControlEvents.InvokeKeyReleased(k); + + for (var i = PlayerIndex.One; i <= PlayerIndex.Four; i++) + { + var buttons = GetFramePressedButtons(i); + foreach (var b in buttons) + { + if (b == Buttons.LeftTrigger || b == Buttons.RightTrigger) + { + ControlEvents.InvokeTriggerPressed(i, b, b == Buttons.LeftTrigger ? GamePad.GetState(i).Triggers.Left : GamePad.GetState(i).Triggers.Right); + } + else + { + ControlEvents.InvokeButtonPressed(i, b); + } + } + } + + for (var i = PlayerIndex.One; i <= PlayerIndex.Four; i++) + { + foreach (var b in GetFrameReleasedButtons(i)) + { + if (b == Buttons.LeftTrigger || b == Buttons.RightTrigger) + { + ControlEvents.InvokeTriggerReleased(i, b, b == Buttons.LeftTrigger ? GamePad.GetState(i).Triggers.Left : GamePad.GetState(i).Triggers.Right); + } + else + { + ControlEvents.InvokeButtonReleased(i, b); + } + } + } + + + if (KStateNow != KStatePrior) + { + ControlEvents.InvokeKeyboardChanged(KStatePrior, KStateNow); + } + + if (MStateNow != MStatePrior) + { + ControlEvents.InvokeMouseChanged(MStatePrior, MStateNow, MPositionPrior, MPositionNow); + MStatePrior = MStateNow; + MPositionPrior = MPositionPrior; + } + + if (activeClickableMenu != null && activeClickableMenu != PreviousActiveMenu) + { + MenuEvents.InvokeMenuChanged(PreviousActiveMenu, activeClickableMenu); + PreviousActiveMenu = activeClickableMenu; + WasMenuClosedInvoked = false; + } + + if (!WasMenuClosedInvoked && PreviousActiveMenu != null && activeClickableMenu == null) + { + MenuEvents.InvokeMenuClosed(PreviousActiveMenu); + WasMenuClosedInvoked = true; + } + + if (locations.GetHash() != PreviousGameLocations) + { + LocationEvents.InvokeLocationsChanged(locations); + PreviousGameLocations = locations.GetHash(); + } + + if (currentLocation != PreviousGameLocation) + { + LocationEvents.InvokeCurrentLocationChanged(PreviousGameLocation, currentLocation); + PreviousGameLocation = currentLocation; + } + + if (player != null && player != PreviousFarmer) + { + PlayerEvents.InvokeFarmerChanged(PreviousFarmer, player); + PreviousFarmer = player; + } + + if (player != null && player.combatLevel != PreviousCombatLevel) + { + PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Combat, player.combatLevel); + PreviousCombatLevel = player.combatLevel; + } + + if (player != null && player.farmingLevel != PreviousFarmingLevel) + { + PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Farming, player.farmingLevel); + PreviousFarmingLevel = player.farmingLevel; + } + + if (player != null && player.fishingLevel != PreviousFishingLevel) + { + PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Fishing, player.fishingLevel); + PreviousFishingLevel = player.fishingLevel; + } + + if (player != null && player.foragingLevel != PreviousForagingLevel) + { + PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Foraging, player.foragingLevel); + PreviousForagingLevel = player.foragingLevel; + } + + if (player != null && player.miningLevel != PreviousMiningLevel) + { + PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Mining, player.miningLevel); + PreviousMiningLevel = player.miningLevel; + } + + if (player != null && player.luckLevel != PreviousLuckLevel) + { + PlayerEvents.InvokeLeveledUp(EventArgsLevelUp.LevelType.Luck, player.luckLevel); + PreviousLuckLevel = player.luckLevel; + } + + List changedItems; + if (player != null && HasInventoryChanged(player.items, out changedItems)) + { + PlayerEvents.InvokeInventoryChanged(player.items, changedItems); + PreviousItems = player.items.Where(n => n != null).ToDictionary(n => n, n => n.Stack); + } + + var objectHash = currentLocation?.objects?.GetHash(); + if (objectHash != null && PreviousLocationObjects != objectHash) + { + LocationEvents.InvokeOnNewLocationObject(currentLocation.objects); + PreviousLocationObjects = objectHash ?? -1; + } + + if (timeOfDay != PreviousTimeOfDay) + { + TimeEvents.InvokeTimeOfDayChanged(PreviousTimeOfDay, timeOfDay); + PreviousTimeOfDay = timeOfDay; + } + + if (dayOfMonth != PreviousDayOfMonth) + { + TimeEvents.InvokeDayOfMonthChanged(PreviousDayOfMonth, dayOfMonth); + PreviousDayOfMonth = dayOfMonth; + } + + if (currentSeason != PreviousSeasonOfYear) + { + TimeEvents.InvokeSeasonOfYearChanged(PreviousSeasonOfYear, currentSeason); + PreviousSeasonOfYear = currentSeason; + } + + if (year != PreviousYearOfGame) + { + TimeEvents.InvokeYearOfGameChanged(PreviousYearOfGame, year); + PreviousYearOfGame = year; + } + + //NOTE THAT THIS MUST CHECK BEFORE SETTING IT TO TRUE BECAUSE OF SOME SILLY ISSUES + if (FireLoadedGameEvent) + { + PlayerEvents.InvokeLoadedGame(new EventArgsLoadedGameChanged(hasLoadedGame)); + FireLoadedGameEvent = false; + } + + if (hasLoadedGame != PreviouslyLoadedGame) + { + FireLoadedGameEvent = true; + PreviouslyLoadedGame = hasLoadedGame; + } + + if (mine != null && PreviousMineLevel != mine.mineLevel) + { + MineEvents.InvokeMineLevelChanged(PreviousMineLevel, mine.mineLevel); + PreviousMineLevel = mine.mineLevel; + } + + if (PreviousIsNewDay != newDay) + { + TimeEvents.InvokeOnNewDay(PreviousDayOfMonth, dayOfMonth, newDay); + PreviousIsNewDay = newDay; + } + } + + private bool HasInventoryChanged(List items, out List changedItems) + { + changedItems = new List(); + IEnumerable actualItems = items.Where(n => n != null).ToArray(); + foreach (var item in actualItems) + { + if (PreviousItems != null && PreviousItems.ContainsKey(item)) + { + if (PreviousItems[item] != item.Stack) + { + changedItems.Add(new ItemStackChange {Item = item, StackChange = item.Stack - PreviousItems[item], ChangeType = ChangeType.StackChange}); + } + } + else + { + changedItems.Add(new ItemStackChange {Item = item, StackChange = item.Stack, ChangeType = ChangeType.Added}); + } + } + + if (PreviousItems != null) + { + changedItems.AddRange(PreviousItems.Where(n => actualItems.All(i => i != n.Key)).Select(n => + new ItemStackChange {Item = n.Key, StackChange = -n.Key.Stack, ChangeType = ChangeType.Removed})); + } + + return changedItems.Any(); + } + + /// + /// Invokes a private, non-static method in Game1 via Reflection + /// + /// The name of the method + /// Any parameters needed + /// Whatever the method normally returns. Null if void. + [Obsolete("This is very slow. Cache the method info and then invoke it with InvokeMethodInfo().")] + public static object InvokeBasePrivateInstancedMethod(string name, params object[] parameters) + { + try + { + return typeof (Game1).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance).Invoke(Program.gamePtr, parameters); + } + catch + { + Log.AsyncR("Failed to call base method: " + name); + return null; + } + } + + /// + /// Invokes a given method info with the supplied parameters + /// + /// + /// + /// + public static object InvokeMethodInfo(MethodInfo mi, params object[] parameters) + { + try + { + return mi.Invoke(Program.gamePtr, parameters); + } + catch + { + Log.AsyncR("Failed to call base method: " + mi.Name); + return null; + } + } + + /// + /// Queue's a message to be drawn in Debug mode (F3) + /// + /// + public static bool QueueDebugMessage(string message) + { + if (!Debug) + return false; + + if (DebugMessageQueue.Count > 32) + return false; + + DebugMessageQueue.Enqueue(message); + return true; + } + } } \ No newline at end of file diff --git a/src/StardewModdingAPI/Program.cs b/src/StardewModdingAPI/Program.cs index e2576e40..2908de8f 100644 --- a/src/StardewModdingAPI/Program.cs +++ b/src/StardewModdingAPI/Program.cs @@ -1,370 +1,370 @@ -using System; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Threading; -#if SMAPI_FOR_WINDOWS -using System.Windows.Forms; -#endif -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using StardewModdingAPI.Events; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Inheritance; -using StardewValley; - -namespace StardewModdingAPI -{ - public class Program - { - /// The full path to the Stardew Valley executable. - private static readonly string GameExecutablePath = File.Exists(Path.Combine(Constants.ExecutionPath, "StardewValley.exe")) - ? Path.Combine(Constants.ExecutionPath, "StardewValley.exe") // Linux or Mac - : Path.Combine(Constants.ExecutionPath, "Stardew Valley.exe"); // Windows - - /// The full path to the folder containing mods. - private static readonly string ModPath = Path.Combine(Constants.ExecutionPath, "Mods"); - - public static SGame gamePtr; - public static bool ready; - - public static Assembly StardewAssembly; - public static Type StardewProgramType; - public static FieldInfo StardewGameInfo; - - public static Thread gameThread; - public static Thread consoleInputThread; - - public static Texture2D DebugPixel { get; private set; } - - // ReSharper disable once PossibleNullReferenceException - public static int BuildType => (int)StardewProgramType.GetField("buildType", BindingFlags.Public | BindingFlags.Static).GetValue(null); - - ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - /// - /// Main method holding the API execution - /// - /// - private static void Main(string[] args) - { - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); - - try - { - Log.AsyncY($"SMAPI {Constants.Version}"); - Log.AsyncY($"Stardew Valley {Game1.version} on {Environment.OSVersion}"); - Program.CheckForUpdateAsync(); - Program.ConfigureUI(); - Program.CreateDirectories(); - Program.StartGame(); - } - catch (Exception e) - { - // Catch and display all exceptions. - Console.WriteLine(e); - Console.ReadKey(); - Log.AsyncR("Critical error: " + e); - } - - Log.AsyncY("The API will now terminate. Press any key to continue..."); - Console.ReadKey(); - } - - /// - /// Set up the console properties - /// - private static void ConfigureUI() - { - Console.Title = Constants.ConsoleTitle; -#if DEBUG - Console.Title += " - DEBUG IS NOT FALSE, AUTHOUR NEEDS TO REUPLOAD THIS VERSION"; -#endif - } - - /// Create and verify the SMAPI directories. - private static void CreateDirectories() - { - Log.AsyncY("Validating file paths..."); - VerifyPath(ModPath); - VerifyPath(Constants.LogDir); - if (!File.Exists(GameExecutablePath)) - throw new FileNotFoundException($"Could not find executable: {GameExecutablePath}"); - } - - /// Asynchronously check for a new version of SMAPI, and print a message to the console if an update is available. - private static void CheckForUpdateAsync() - { - new Thread(() => - { - try - { - GitRelease release = UpdateHelper.GetLatestVersionAsync(Constants.GitHubRepository).Result; - Version latestVersion = new Version(release.Tag); - if (latestVersion.CompareTo(Constants.Version) > 0) - Log.AsyncColour($"You can update SMAPI from version {Constants.Version} to {latestVersion}", ConsoleColor.Magenta); - } - catch (Exception ex) - { - Log.Debug($"Couldn't check for a new version of SMAPI. This won't affect your game, but you may not be notified of new versions if this keeps happening.\n{ex}"); - } - }).Start(); - } - - /// - /// Load Stardev Valley and control features, and launch the game. - /// - private static void StartGame() - { - // Load in the assembly - ignores security - Log.AsyncY("Initializing SDV Assembly..."); - StardewAssembly = Assembly.UnsafeLoadFrom(GameExecutablePath); - StardewProgramType = StardewAssembly.GetType("StardewValley.Program", true); - StardewGameInfo = StardewProgramType.GetField("gamePtr"); - - // Change the game's version - Log.AsyncY("Injecting New SDV Version..."); - Game1.version += $"-Z_MODDED | SMAPI {Constants.Version}"; - - // add error interceptors -#if SMAPI_FOR_WINDOWS - Application.ThreadException += Log.Application_ThreadException; - Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); -#endif - AppDomain.CurrentDomain.UnhandledException += Log.CurrentDomain_UnhandledException; - - // initialise game - try - { - Log.AsyncY("Initializing SDV..."); - gamePtr = new SGame(); - - // hook events - gamePtr.Exiting += (sender, e) => ready = false; - gamePtr.Window.ClientSizeChanged += GraphicsEvents.InvokeResize; - - // patch graphics - Log.AsyncY("Patching SDV Graphics Profile..."); - Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef; - - // load mods - LoadMods(); - - // initialise - StardewGameInfo.SetValue(StardewProgramType, gamePtr); - Log.AsyncY("Applying Final SDV Tweaks..."); - gamePtr.IsMouseVisible = false; - gamePtr.Window.Title = "Stardew Valley - Version " + Game1.version; - } - catch (Exception ex) - { - Log.AsyncR("Game failed to initialise: " + ex); - return; - } - - // initialise after game launches - new Thread(() => - { - // Wait for the game to load up - while (!ready) Thread.Sleep(1000); - - // Create definition to listen for input - Log.AsyncY("Initializing Console Input Thread..."); - consoleInputThread = new Thread(ConsoleInputThread); - - // The only command in the API (at least it should be, for now) - Command.RegisterCommand("help", "Lists all commands | 'help ' returns command description").CommandFired += help_CommandFired; - - // Subscribe to events - ControlEvents.KeyPressed += Events_KeyPressed; - GameEvents.LoadContent += Events_LoadContent; - - // Game's in memory now, send the event - Log.AsyncY("Game Loaded"); - GameEvents.InvokeGameLoaded(); - - // Listen for command line input - Log.AsyncY("Type 'help' for help, or 'help ' for a command's usage"); - consoleInputThread.Start(); - while (ready) - Thread.Sleep(1000 / 10); // Check if the game is still running 10 times a second - - // Abort the thread, we're closing - if (consoleInputThread != null && consoleInputThread.ThreadState == ThreadState.Running) - consoleInputThread.Abort(); - - Log.AsyncY("Game Execution Finished"); - Log.AsyncY("Shutting Down..."); - Thread.Sleep(100); - Environment.Exit(0); - }).Start(); - - // Start game loop - Log.AsyncY("Starting SDV..."); - try - { - ready = true; - gamePtr.Run(); - } - catch (Exception ex) - { - ready = false; - Log.AsyncR("Game failed to start: " + ex); - } - } - - /// Create a directory path if it doesn't exist. - /// The directory path. - private static void VerifyPath(string path) - { - try - { - if (!Directory.Exists(path)) - Directory.CreateDirectory(path); - } - catch (Exception ex) - { - Log.AsyncR("Could not create a path: " + path + "\n\n" + ex); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - public static void LoadMods() - { - Log.AsyncY("LOADING MODS"); - foreach (string directory in Directory.GetDirectories(ModPath)) - { - foreach (string manifestPath in Directory.GetFiles(directory, "manifest.json")) - { - if (manifestPath.Contains("StardewInjector")) - continue; - - // read manifest - Log.AsyncG($"Found Manifest: {manifestPath}"); - Manifest manifest = new Manifest(); - try - { - // read manifest text - string json = File.ReadAllText(manifestPath); - if (string.IsNullOrEmpty(json)) - { - Log.AsyncR($"Failed to read mod manifest '{manifestPath}'. Manifest is empty!"); - continue; - } - - // deserialise manifest - manifest = manifest.InitializeConfig(manifestPath); - if (string.IsNullOrEmpty(manifest.EntryDll)) - { - Log.AsyncR($"Failed to read mod manifest '{manifestPath}'. EntryDll is empty!"); - continue; - } - } - catch (Exception ex) - { - Log.AsyncR($"Failed to read mod manifest '{manifestPath}'. Exception details:\n" + ex); - continue; - } - - string targDir = Path.GetDirectoryName(manifestPath); - string psDir = Path.Combine(targDir, "psconfigs"); - Log.AsyncY($"Created psconfigs directory @{psDir}"); - try - { - if (manifest.PerSaveConfigs) - { - if (!Directory.Exists(psDir)) - { - Directory.CreateDirectory(psDir); - Log.AsyncY($"Created psconfigs directory @{psDir}"); - } - - if (!Directory.Exists(psDir)) - { - Log.AsyncR($"Failed to create psconfigs directory '{psDir}'. No exception occured."); - continue; - } - } - } - catch (Exception ex) - { - Log.AsyncR($"Failed to create psconfigs directory '{targDir}'. Exception details:\n" + ex); - continue; - } - string targDll = string.Empty; - try - { - targDll = Path.Combine(targDir, manifest.EntryDll); - if (!File.Exists(targDll)) - { - Log.AsyncR($"Failed to load mod '{manifest.EntryDll}'. File {targDll} does not exist!"); - continue; - } - - Assembly modAssembly = Assembly.UnsafeLoadFrom(targDll); - if (modAssembly.DefinedTypes.Count(x => x.BaseType == typeof(Mod)) > 0) - { - Log.AsyncY("Loading Mod DLL..."); - TypeInfo tar = modAssembly.DefinedTypes.First(x => x.BaseType == typeof(Mod)); - Mod modEntry = (Mod)modAssembly.CreateInstance(tar.ToString()); - if (modEntry != null) - { - modEntry.PathOnDisk = targDir; - modEntry.Manifest = manifest; - Log.AsyncG($"LOADED MOD: {modEntry.Manifest.Name} by {modEntry.Manifest.Author} - Version {modEntry.Manifest.Version} | Description: {modEntry.Manifest.Description} (@ {targDll})"); - Constants.ModsLoaded += 1; - modEntry.Entry(); - } - } - else - Log.AsyncR("Invalid Mod DLL"); - } - catch (Exception ex) - { - Log.AsyncR($"Failed to load mod '{targDll}'. Exception details:\n" + ex); - } - } - } - - Log.AsyncG($"LOADED {Constants.ModsLoaded} MODS"); - Console.Title = Constants.ConsoleTitle; - } - - public static void ConsoleInputThread() - { - while (true) - { - Command.CallCommand(Console.ReadLine()); - } - } - - private static void Events_LoadContent(object o, EventArgs e) - { - Log.AsyncY("Initializing Debug Assets..."); - DebugPixel = new Texture2D(Game1.graphics.GraphicsDevice, 1, 1); - DebugPixel.SetData(new[] { Color.White }); - } - - private static void Events_KeyPressed(object o, EventArgsKeyPressed e) - { - } - - private static void help_CommandFired(object o, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - var fnd = Command.FindCommand(e.Command.CalledArgs[0]); - if (fnd == null) - Log.AsyncR("The command specified could not be found"); - else - { - Log.AsyncY(fnd.CommandArgs.Length > 0 ? $"{fnd.CommandName}: {fnd.CommandDesc} - {fnd.CommandArgs.ToSingular()}" : $"{fnd.CommandName}: {fnd.CommandDesc}"); - } - } - else - Log.AsyncY("Commands: " + Command.RegisteredCommands.Select(x => x.CommandName).ToSingular()); - } - } -} +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading; +#if SMAPI_FOR_WINDOWS +using System.Windows.Forms; +#endif +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using StardewModdingAPI.Events; +using StardewModdingAPI.Framework; +using StardewModdingAPI.Inheritance; +using StardewValley; + +namespace StardewModdingAPI +{ + public class Program + { + /// The full path to the Stardew Valley executable. + private static readonly string GameExecutablePath = File.Exists(Path.Combine(Constants.ExecutionPath, "StardewValley.exe")) + ? Path.Combine(Constants.ExecutionPath, "StardewValley.exe") // Linux or Mac + : Path.Combine(Constants.ExecutionPath, "Stardew Valley.exe"); // Windows + + /// The full path to the folder containing mods. + private static readonly string ModPath = Path.Combine(Constants.ExecutionPath, "Mods"); + + public static SGame gamePtr; + public static bool ready; + + public static Assembly StardewAssembly; + public static Type StardewProgramType; + public static FieldInfo StardewGameInfo; + + public static Thread gameThread; + public static Thread consoleInputThread; + + public static Texture2D DebugPixel { get; private set; } + + // ReSharper disable once PossibleNullReferenceException + public static int BuildType => (int)StardewProgramType.GetField("buildType", BindingFlags.Public | BindingFlags.Static).GetValue(null); + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /// + /// Main method holding the API execution + /// + /// + private static void Main(string[] args) + { + Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); + + try + { + Log.AsyncY($"SMAPI {Constants.Version}"); + Log.AsyncY($"Stardew Valley {Game1.version} on {Environment.OSVersion}"); + Program.CheckForUpdateAsync(); + Program.ConfigureUI(); + Program.CreateDirectories(); + Program.StartGame(); + } + catch (Exception e) + { + // Catch and display all exceptions. + Console.WriteLine(e); + Console.ReadKey(); + Log.AsyncR("Critical error: " + e); + } + + Log.AsyncY("The API will now terminate. Press any key to continue..."); + Console.ReadKey(); + } + + /// + /// Set up the console properties + /// + private static void ConfigureUI() + { + Console.Title = Constants.ConsoleTitle; +#if DEBUG + Console.Title += " - DEBUG IS NOT FALSE, AUTHOUR NEEDS TO REUPLOAD THIS VERSION"; +#endif + } + + /// Create and verify the SMAPI directories. + private static void CreateDirectories() + { + Log.AsyncY("Validating file paths..."); + VerifyPath(ModPath); + VerifyPath(Constants.LogDir); + if (!File.Exists(GameExecutablePath)) + throw new FileNotFoundException($"Could not find executable: {GameExecutablePath}"); + } + + /// Asynchronously check for a new version of SMAPI, and print a message to the console if an update is available. + private static void CheckForUpdateAsync() + { + new Thread(() => + { + try + { + GitRelease release = UpdateHelper.GetLatestVersionAsync(Constants.GitHubRepository).Result; + Version latestVersion = new Version(release.Tag); + if (latestVersion.CompareTo(Constants.Version) > 0) + Log.AsyncColour($"You can update SMAPI from version {Constants.Version} to {latestVersion}", ConsoleColor.Magenta); + } + catch (Exception ex) + { + Log.Debug($"Couldn't check for a new version of SMAPI. This won't affect your game, but you may not be notified of new versions if this keeps happening.\n{ex}"); + } + }).Start(); + } + + /// + /// Load Stardev Valley and control features, and launch the game. + /// + private static void StartGame() + { + // Load in the assembly - ignores security + Log.AsyncY("Initializing SDV Assembly..."); + StardewAssembly = Assembly.UnsafeLoadFrom(GameExecutablePath); + StardewProgramType = StardewAssembly.GetType("StardewValley.Program", true); + StardewGameInfo = StardewProgramType.GetField("gamePtr"); + + // Change the game's version + Log.AsyncY("Injecting New SDV Version..."); + Game1.version += $"-Z_MODDED | SMAPI {Constants.Version}"; + + // add error interceptors +#if SMAPI_FOR_WINDOWS + Application.ThreadException += Log.Application_ThreadException; + Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); +#endif + AppDomain.CurrentDomain.UnhandledException += Log.CurrentDomain_UnhandledException; + + // initialise game + try + { + Log.AsyncY("Initializing SDV..."); + gamePtr = new SGame(); + + // hook events + gamePtr.Exiting += (sender, e) => ready = false; + gamePtr.Window.ClientSizeChanged += GraphicsEvents.InvokeResize; + + // patch graphics + Log.AsyncY("Patching SDV Graphics Profile..."); + Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef; + + // load mods + LoadMods(); + + // initialise + StardewGameInfo.SetValue(StardewProgramType, gamePtr); + Log.AsyncY("Applying Final SDV Tweaks..."); + gamePtr.IsMouseVisible = false; + gamePtr.Window.Title = "Stardew Valley - Version " + Game1.version; + } + catch (Exception ex) + { + Log.AsyncR("Game failed to initialise: " + ex); + return; + } + + // initialise after game launches + new Thread(() => + { + // Wait for the game to load up + while (!ready) Thread.Sleep(1000); + + // Create definition to listen for input + Log.AsyncY("Initializing Console Input Thread..."); + consoleInputThread = new Thread(ConsoleInputThread); + + // The only command in the API (at least it should be, for now) + Command.RegisterCommand("help", "Lists all commands | 'help ' returns command description").CommandFired += help_CommandFired; + + // Subscribe to events + ControlEvents.KeyPressed += Events_KeyPressed; + GameEvents.LoadContent += Events_LoadContent; + + // Game's in memory now, send the event + Log.AsyncY("Game Loaded"); + GameEvents.InvokeGameLoaded(); + + // Listen for command line input + Log.AsyncY("Type 'help' for help, or 'help ' for a command's usage"); + consoleInputThread.Start(); + while (ready) + Thread.Sleep(1000 / 10); // Check if the game is still running 10 times a second + + // Abort the thread, we're closing + if (consoleInputThread != null && consoleInputThread.ThreadState == ThreadState.Running) + consoleInputThread.Abort(); + + Log.AsyncY("Game Execution Finished"); + Log.AsyncY("Shutting Down..."); + Thread.Sleep(100); + Environment.Exit(0); + }).Start(); + + // Start game loop + Log.AsyncY("Starting SDV..."); + try + { + ready = true; + gamePtr.Run(); + } + catch (Exception ex) + { + ready = false; + Log.AsyncR("Game failed to start: " + ex); + } + } + + /// Create a directory path if it doesn't exist. + /// The directory path. + private static void VerifyPath(string path) + { + try + { + if (!Directory.Exists(path)) + Directory.CreateDirectory(path); + } + catch (Exception ex) + { + Log.AsyncR("Could not create a path: " + path + "\n\n" + ex); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public static void LoadMods() + { + Log.AsyncY("LOADING MODS"); + foreach (string directory in Directory.GetDirectories(ModPath)) + { + foreach (string manifestPath in Directory.GetFiles(directory, "manifest.json")) + { + if (manifestPath.Contains("StardewInjector")) + continue; + + // read manifest + Log.AsyncG($"Found Manifest: {manifestPath}"); + Manifest manifest = new Manifest(); + try + { + // read manifest text + string json = File.ReadAllText(manifestPath); + if (string.IsNullOrEmpty(json)) + { + Log.AsyncR($"Failed to read mod manifest '{manifestPath}'. Manifest is empty!"); + continue; + } + + // deserialise manifest + manifest = manifest.InitializeConfig(manifestPath); + if (string.IsNullOrEmpty(manifest.EntryDll)) + { + Log.AsyncR($"Failed to read mod manifest '{manifestPath}'. EntryDll is empty!"); + continue; + } + } + catch (Exception ex) + { + Log.AsyncR($"Failed to read mod manifest '{manifestPath}'. Exception details:\n" + ex); + continue; + } + + string targDir = Path.GetDirectoryName(manifestPath); + string psDir = Path.Combine(targDir, "psconfigs"); + Log.AsyncY($"Created psconfigs directory @{psDir}"); + try + { + if (manifest.PerSaveConfigs) + { + if (!Directory.Exists(psDir)) + { + Directory.CreateDirectory(psDir); + Log.AsyncY($"Created psconfigs directory @{psDir}"); + } + + if (!Directory.Exists(psDir)) + { + Log.AsyncR($"Failed to create psconfigs directory '{psDir}'. No exception occured."); + continue; + } + } + } + catch (Exception ex) + { + Log.AsyncR($"Failed to create psconfigs directory '{targDir}'. Exception details:\n" + ex); + continue; + } + string targDll = string.Empty; + try + { + targDll = Path.Combine(targDir, manifest.EntryDll); + if (!File.Exists(targDll)) + { + Log.AsyncR($"Failed to load mod '{manifest.EntryDll}'. File {targDll} does not exist!"); + continue; + } + + Assembly modAssembly = Assembly.UnsafeLoadFrom(targDll); + if (modAssembly.DefinedTypes.Count(x => x.BaseType == typeof(Mod)) > 0) + { + Log.AsyncY("Loading Mod DLL..."); + TypeInfo tar = modAssembly.DefinedTypes.First(x => x.BaseType == typeof(Mod)); + Mod modEntry = (Mod)modAssembly.CreateInstance(tar.ToString()); + if (modEntry != null) + { + modEntry.PathOnDisk = targDir; + modEntry.Manifest = manifest; + Log.AsyncG($"LOADED MOD: {modEntry.Manifest.Name} by {modEntry.Manifest.Author} - Version {modEntry.Manifest.Version} | Description: {modEntry.Manifest.Description} (@ {targDll})"); + Constants.ModsLoaded += 1; + modEntry.Entry(); + } + } + else + Log.AsyncR("Invalid Mod DLL"); + } + catch (Exception ex) + { + Log.AsyncR($"Failed to load mod '{targDll}'. Exception details:\n" + ex); + } + } + } + + Log.AsyncG($"LOADED {Constants.ModsLoaded} MODS"); + Console.Title = Constants.ConsoleTitle; + } + + public static void ConsoleInputThread() + { + while (true) + { + Command.CallCommand(Console.ReadLine()); + } + } + + private static void Events_LoadContent(object o, EventArgs e) + { + Log.AsyncY("Initializing Debug Assets..."); + DebugPixel = new Texture2D(Game1.graphics.GraphicsDevice, 1, 1); + DebugPixel.SetData(new[] { Color.White }); + } + + private static void Events_KeyPressed(object o, EventArgsKeyPressed e) + { + } + + private static void help_CommandFired(object o, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + var fnd = Command.FindCommand(e.Command.CalledArgs[0]); + if (fnd == null) + Log.AsyncR("The command specified could not be found"); + else + { + Log.AsyncY(fnd.CommandArgs.Length > 0 ? $"{fnd.CommandName}: {fnd.CommandDesc} - {fnd.CommandArgs.ToSingular()}" : $"{fnd.CommandName}: {fnd.CommandDesc}"); + } + } + else + Log.AsyncY("Commands: " + Command.RegisteredCommands.Select(x => x.CommandName).ToSingular()); + } + } +} diff --git a/src/StardewModdingAPI/StardewModdingAPI.csproj b/src/StardewModdingAPI/StardewModdingAPI.csproj index b182bf4a..cf8c58cb 100644 --- a/src/StardewModdingAPI/StardewModdingAPI.csproj +++ b/src/StardewModdingAPI/StardewModdingAPI.csproj @@ -1,257 +1,257 @@ - - - - - Debug - AnyCPU - {F1A573B0-F436-472C-AE29-0B91EA6B9F8F} - Exe - Properties - StardewModdingAPI - StardewModdingAPI - v4.5 - 512 - false - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - true - - - AnyCPU - true - full - true - $(SolutionDir)\..\bin\Debug\SMAPI - TRACE;DEBUG - prompt - 4 - false - true - - - AnyCPU - pdbonly - true - $(SolutionDir)\..\bin\Release\SMAPI - TRACE - prompt - 4 - false - true - - - x86 - bin\Debug\ - false - DEBUG;TRACE - true - false - $(SolutionDir)\..\bin\Debug\SMAPI - bin\Debug\StardewModdingAPI.xml - true - 6 - - - x86 - bin\Release\ - false - $(SolutionDir)\..\bin\Release\SMAPI - bin\Release\StardewModdingAPI.xml - TRACE - true - true - 6 - pdbonly - true - - - icon.ico - - - StardewModdingAPI.Program - - - - $(HOME)/GOG Games/Stardew Valley/game - $(HOME)/.local/share/Steam/steamapps/common/Stardew Valley - - $(HOME)/Library/Application Support/Steam/steamapps/common/Stardew Valley/Contents/MacOS - - C:\Program Files (x86)\GalaxyClient\Games\Stardew Valley - C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley - - - - - $(DefineConstants);SMAPI_FOR_WINDOWS - - - - False - - - False - - - False - - - False - - - $(GamePath)\Stardew Valley.exe - False - - - $(GamePath)\xTile.dll - False - False - - - - - - $(DefineConstants);SMAPI_FOR_UNIX - - - - $(GamePath)\MonoGame.Framework.dll - False - False - - - $(GamePath)\StardewValley.exe - False - - - $(GamePath)\xTile.dll - False - - - - - - - ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll - True - - - - - - True - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - - - Designer - - - Always - - - - - - - Always - - - - - False - Microsoft .NET Framework 4.5 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 - false - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - + + + + + Debug + AnyCPU + {F1A573B0-F436-472C-AE29-0B91EA6B9F8F} + Exe + Properties + StardewModdingAPI + StardewModdingAPI + v4.5 + 512 + false + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + AnyCPU + true + full + true + $(SolutionDir)\..\bin\Debug\SMAPI + TRACE;DEBUG + prompt + 4 + false + true + + + AnyCPU + pdbonly + true + $(SolutionDir)\..\bin\Release\SMAPI + TRACE + prompt + 4 + false + true + + + x86 + bin\Debug\ + false + DEBUG;TRACE + true + false + $(SolutionDir)\..\bin\Debug\SMAPI + bin\Debug\StardewModdingAPI.xml + true + 6 + + + x86 + bin\Release\ + false + $(SolutionDir)\..\bin\Release\SMAPI + bin\Release\StardewModdingAPI.xml + TRACE + true + true + 6 + pdbonly + true + + + icon.ico + + + StardewModdingAPI.Program + + + + $(HOME)/GOG Games/Stardew Valley/game + $(HOME)/.local/share/Steam/steamapps/common/Stardew Valley + + $(HOME)/Library/Application Support/Steam/steamapps/common/Stardew Valley/Contents/MacOS + + C:\Program Files (x86)\GalaxyClient\Games\Stardew Valley + C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley + + + + + $(DefineConstants);SMAPI_FOR_WINDOWS + + + + False + + + False + + + False + + + False + + + $(GamePath)\Stardew Valley.exe + False + + + $(GamePath)\xTile.dll + False + False + + + + + + $(DefineConstants);SMAPI_FOR_UNIX + + + + $(GamePath)\MonoGame.Framework.dll + False + False + + + $(GamePath)\StardewValley.exe + False + + + $(GamePath)\xTile.dll + False + + + + + + + ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + True + + + + + + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Designer + + + Designer + + + Always + + + + + + + Always + + + + + False + Microsoft .NET Framework 4.5 %28x86 and x64%29 + true + + + False + .NET Framework 3.5 SP1 + false + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + + \ No newline at end of file diff --git a/src/StardewModdingAPI/packages.config b/src/StardewModdingAPI/packages.config index 03310458..0aec11c6 100644 --- a/src/StardewModdingAPI/packages.config +++ b/src/StardewModdingAPI/packages.config @@ -1,6 +1,6 @@ - - - - - + + + + + \ No newline at end of file diff --git a/src/TrainerMod/TrainerMod.cs b/src/TrainerMod/TrainerMod.cs index 94fd823b..224e70ad 100644 --- a/src/TrainerMod/TrainerMod.cs +++ b/src/TrainerMod/TrainerMod.cs @@ -1,728 +1,728 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.Xna.Framework; -using StardewModdingAPI; -using StardewModdingAPI.Events; -using StardewValley; -using StardewValley.Menus; -using StardewValley.Objects; -using StardewValley.Tools; -using Object = StardewValley.Object; - -namespace TrainerMod -{ - public class TrainerMod : Mod - { - public static int frozenTime; - public static bool infHealth, infStamina, infMoney, freezeTime; - - public override void Entry(params object[] objects) - { - RegisterCommands(); - GameEvents.UpdateTick += Events_UpdateTick; - } - - private static void Events_UpdateTick(object sender, EventArgs e) - { - if (Game1.player == null) - return; - - if (infHealth) - { - Game1.player.health = Game1.player.maxHealth; - } - if (infStamina) - { - Game1.player.stamina = Game1.player.MaxStamina; - } - if (infMoney) - { - Game1.player.money = 999999; - } - if (freezeTime) - { - Game1.timeOfDay = frozenTime; - } - } - - public static void RegisterCommands() - { - Command.RegisterCommand("types", "Lists all value types | types").CommandFired += types_CommandFired; - - Command.RegisterCommand("save", "Saves the game? Doesn't seem to work. | save").CommandFired += save_CommandFired; - Command.RegisterCommand("load", "Shows the load screen | load").CommandFired += load_CommandFired; - - Command.RegisterCommand("exit", "Closes the game | exit").CommandFired += exit_CommandFired; - Command.RegisterCommand("stop", "Closes the game | stop").CommandFired += exit_CommandFired; - - Command.RegisterCommand("player_setname", "Sets the player's name | player_setname ", new[] {"(player, pet, farm) (String) The target name"}).CommandFired += player_setName; - Command.RegisterCommand("player_setmoney", "Sets the player's money | player_setmoney |inf", new[] {"(Int32) The target money"}).CommandFired += player_setMoney; - Command.RegisterCommand("player_setstamina", "Sets the player's stamina | player_setstamina |inf", new[] {"(Int32) The target stamina"}).CommandFired += player_setStamina; - Command.RegisterCommand("player_setmaxstamina", "Sets the player's max stamina | player_setmaxstamina ", new[] {"(Int32) The target max stamina"}).CommandFired += player_setMaxStamina; - Command.RegisterCommand("player_sethealth", "Sets the player's health | player_sethealth |inf", new[] {"(Int32) The target health"}).CommandFired += player_setHealth; - Command.RegisterCommand("player_setmaxhealth", "Sets the player's max health | player_setmaxhealth ", new[] {"(Int32) The target max health"}).CommandFired += player_setMaxHealth; - Command.RegisterCommand("player_setimmunity", "Sets the player's immunity | player_setimmunity ", new[] {"(Int32) The target immunity"}).CommandFired += player_setImmunity; - - Command.RegisterCommand("player_setlevel", "Sets the player's specified skill to the specified value | player_setlevel ", new[] {"(luck, mining, combat, farming, fishing, foraging) (1-10) The target level"}).CommandFired += player_setLevel; - Command.RegisterCommand("player_setspeed", "Sets the player's speed to the specified value?", new[] {"(Int32) The target speed [0 is normal]"}).CommandFired += player_setSpeed; - Command.RegisterCommand("player_changecolour", "Sets the player's colour of the specified object | player_changecolor ", new[] {"(hair, eyes, pants) (r,g,b)"}).CommandFired += player_changeColour; - Command.RegisterCommand("player_changestyle", "Sets the player's style of the specified object | player_changecolor ", new[] {"(hair, shirt, skin, acc, shoe, swim, gender) (Int32)"}).CommandFired += player_changeStyle; - - Command.RegisterCommand("player_additem", "Gives the player an item | player_additem [count] [quality]", new[] {"(Int32) (Int32)[count] (Int32)[quality]"}).CommandFired += player_addItem; - Command.RegisterCommand("player_addmelee", "Gives the player a melee item | player_addmelee ", new[] {"?"}).CommandFired += player_addMelee; - Command.RegisterCommand("player_addring", "Gives the player a ring | player_addring ", new[] {"?"}).CommandFired += player_addRing; - - Command.RegisterCommand("out_items", "Outputs a list of items | out_items", new[] {""}).CommandFired += out_items; - Command.RegisterCommand("out_melee", "Outputs a list of melee weapons | out_melee", new[] {""}).CommandFired += out_melee; - Command.RegisterCommand("out_rings", "Outputs a list of rings | out_rings", new[] {""}).CommandFired += out_rings; - Command.RegisterCommand("newitem", "not to be used | newitem", new[] {""}).CommandFired += RegisterNewItem; - - Command.RegisterCommand("world_settime", "Sets the time to the specified value | world_settime ", new[] {"(Int32) The target time [06:00 AM is 600]"}).CommandFired += world_setTime; - Command.RegisterCommand("world_freezetime", "Freezes or thaws time | world_freezetime ", new[] {"(0 - 1) Whether or not to freeze time. 0 is thawed, 1 is frozen"}).CommandFired += world_freezeTime; - Command.RegisterCommand("world_setday", "Sets the day to the specified value | world_setday ", new[] {"(Int32) The target day [1-28]"}).CommandFired += world_setDay; - Command.RegisterCommand("world_setseason", "Sets the season to the specified value | world_setseason ", new[] {"(winter, spring, summer, fall) The target season"}).CommandFired += world_setSeason; - Command.RegisterCommand("world_downminelevel", "Goes down one mine level? | world_downminelevel", new[] {""}).CommandFired += world_downMineLevel; - Command.RegisterCommand("world_setminelevel", "Sets mine level? | world_setminelevel", new[] {"(Int32) The target level"}).CommandFired += world_setMineLevel; - } - - private static void types_CommandFired(object sender, EventArgsCommand e) - { - Log.AsyncY($"[Int32: {int.MinValue} - {int.MaxValue}], [Int64: {long.MinValue} - {long.MaxValue}], [String: \"raw text\"], [Colour: r,g,b (EG: 128, 32, 255)]"); - } - - private static void save_CommandFired(object sender, EventArgsCommand e) - { - SaveGame.Save(); - } - - private static void load_CommandFired(object sender, EventArgsCommand e) - { - Game1.hasLoadedGame = false; - Game1.activeClickableMenu = new LoadGameMenu(); - } - - private static void exit_CommandFired(object sender, EventArgsCommand e) - { - Program.gamePtr.Exit(); - Environment.Exit(0); - } - - private static void player_setName(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 1) - { - var obj = e.Command.CalledArgs[0]; - var objs = "player,pet,farm".Split(','); - if (objs.Contains(obj)) - { - switch (obj) - { - case "player": - Game1.player.Name = e.Command.CalledArgs[1]; - break; - case "pet": - Log.AsyncR("Pets cannot currently be renamed."); - break; - case "farm": - Game1.player.farmName = e.Command.CalledArgs[1]; - break; - } - } - else - { - Log.LogObjectInvalid(); - } - } - else - { - Log.LogObjectValueNotSpecified(); - } - } - - private static void player_setMoney(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0] == "inf") - { - infMoney = true; - } - else - { - infMoney = false; - var ou = 0; - if (int.TryParse(e.Command.CalledArgs[0], out ou)) - { - Game1.player.Money = ou; - Log.Async($"Set {Game1.player.Name}'s money to {Game1.player.Money}"); - } - else - { - Log.LogValueNotInt32(); - } - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void player_setStamina(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0] == "inf") - { - infStamina = true; - } - else - { - infStamina = false; - var ou = 0; - if (int.TryParse(e.Command.CalledArgs[0], out ou)) - { - Game1.player.Stamina = ou; - Log.Async($"Set {Game1.player.Name}'s stamina to {Game1.player.Stamina}"); - } - else - { - Log.LogValueNotInt32(); - } - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void player_setMaxStamina(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - var ou = 0; - if (int.TryParse(e.Command.CalledArgs[0], out ou)) - { - Game1.player.MaxStamina = ou; - Log.Async($"Set {Game1.player.Name}'s max stamina to {Game1.player.MaxStamina}"); - } - else - { - Log.LogValueNotInt32(); - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void player_setLevel(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 1) - { - var skill = e.Command.CalledArgs[0]; - var skills = "luck,mining,combat,farming,fishing,foraging".Split(','); - if (skills.Contains(skill)) - { - var ou = 0; - if (int.TryParse(e.Command.CalledArgs[1], out ou)) - { - switch (skill) - { - case "luck": - Game1.player.LuckLevel = ou; - break; - case "mining": - Game1.player.MiningLevel = ou; - break; - case "combat": - Game1.player.CombatLevel = ou; - break; - case "farming": - Game1.player.FarmingLevel = ou; - break; - case "fishing": - Game1.player.FishingLevel = ou; - break; - case "foraging": - Game1.player.ForagingLevel = ou; - break; - } - } - else - { - Log.LogValueNotInt32(); - } - } - else - { - Log.AsyncR(" is invalid"); - } - } - else - { - Log.AsyncR(" and must be specified"); - } - } - - private static void player_setSpeed(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0].IsInt32()) - { - Game1.player.addedSpeed = e.Command.CalledArgs[0].AsInt32(); - Log.Async($"Set {Game1.player.Name}'s added speed to {Game1.player.addedSpeed}"); - } - else - { - Log.LogValueNotInt32(); - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void player_changeColour(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 1) - { - var obj = e.Command.CalledArgs[0]; - var objs = "hair,eyes,pants".Split(','); - if (objs.Contains(obj)) - { - var cs = e.Command.CalledArgs[1].Split(new[] {','}, 3); - if (cs[0].IsInt32() && cs[1].IsInt32() && cs[2].IsInt32()) - { - var c = new Color(cs[0].AsInt32(), cs[1].AsInt32(), cs[2].AsInt32()); - switch (obj) - { - case "hair": - Game1.player.hairstyleColor = c; - break; - case "eyes": - Game1.player.changeEyeColor(c); - break; - case "pants": - Game1.player.pantsColor = c; - break; - } - } - else - { - Log.AsyncR(" is invalid"); - } - } - else - { - Log.LogObjectInvalid(); - } - } - else - { - Log.AsyncR(" and must be specified"); - } - } - - private static void player_changeStyle(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 1) - { - var obj = e.Command.CalledArgs[0]; - var objs = "hair,shirt,skin,acc,shoe,swim,gender".Split(','); - if (objs.Contains(obj)) - { - if (e.Command.CalledArgs[1].IsInt32()) - { - var i = e.Command.CalledArgs[1].AsInt32(); - switch (obj) - { - case "hair": - Game1.player.changeHairStyle(i); - break; - case "shirt": - Game1.player.changeShirt(i); - break; - case "acc": - Game1.player.changeAccessory(i); - break; - case "skin": - Game1.player.changeSkinColor(i); - break; - case "shoe": - Game1.player.changeShoeColor(i); - break; - case "swim": - if (i == 0) - Game1.player.changeOutOfSwimSuit(); - else if (i == 1) - Game1.player.changeIntoSwimsuit(); - else - Log.AsyncR(" must be 0 or 1 for this "); - break; - case "gender": - if (i == 0) - Game1.player.changeGender(true); - else if (i == 1) - Game1.player.changeGender(false); - else - Log.AsyncR(" must be 0 or 1 for this "); - break; - } - } - else - { - Log.LogValueInvalid(); - } - } - else - { - Log.LogObjectInvalid(); - } - } - else - { - Log.LogObjectValueNotSpecified(); - } - } - - private static void world_freezeTime(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0].IsInt32()) - { - if (e.Command.CalledArgs[0].AsInt32() == 0 || e.Command.CalledArgs[0].AsInt32() == 1) - { - freezeTime = e.Command.CalledArgs[0].AsInt32() == 1; - frozenTime = freezeTime ? Game1.timeOfDay : 0; - Log.AsyncY("Time is now " + (freezeTime ? "frozen" : "thawed")); - } - else - { - Log.AsyncR(" should be 0 or 1"); - } - } - else - { - Log.LogValueNotInt32(); - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void world_setTime(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0].IsInt32()) - { - if (e.Command.CalledArgs[0].AsInt32() <= 2600 && e.Command.CalledArgs[0].AsInt32() >= 600) - { - Game1.timeOfDay = e.Command.CalledArgs[0].AsInt32(); - frozenTime = freezeTime ? Game1.timeOfDay : 0; - Log.AsyncY("Time set to: " + Game1.timeOfDay); - } - else - { - Log.AsyncR(" should be between 600 and 2600 (06:00 AM - 02:00 AM [NEXT DAY])"); - } - } - else - { - Log.LogValueNotInt32(); - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void world_setDay(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0].IsInt32()) - { - if (e.Command.CalledArgs[0].AsInt32() <= 28 && e.Command.CalledArgs[0].AsInt32() > 0) - { - Game1.dayOfMonth = e.Command.CalledArgs[0].AsInt32(); - } - else - { - Log.AsyncY(" must be between 1 and 28"); - } - } - else - { - Log.LogValueNotInt32(); - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void world_setSeason(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - var obj = e.Command.CalledArgs[0]; - var objs = "winter,spring,summer,fall".Split(','); - if (objs.Contains(obj)) - { - Game1.currentSeason = obj; - } - else - { - Log.LogValueInvalid(); - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void player_setHealth(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0] == "inf") - { - infHealth = true; - } - else - { - infHealth = false; - if (e.Command.CalledArgs[0].IsInt32()) - { - Game1.player.health = e.Command.CalledArgs[0].AsInt32(); - } - else - { - Log.LogValueNotInt32(); - } - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void player_setMaxHealth(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0].IsInt32()) - { - Game1.player.maxHealth = e.Command.CalledArgs[0].AsInt32(); - } - else - { - Log.LogValueNotInt32(); - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void player_setImmunity(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0].IsInt32()) - { - Game1.player.immunity = e.Command.CalledArgs[0].AsInt32(); - } - else - { - Log.LogValueNotInt32(); - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void player_addItem(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0].IsInt32()) - { - var count = 1; - var quality = 0; - if (e.Command.CalledArgs.Length > 1) - { - Console.WriteLine(e.Command.CalledArgs[1]); - if (e.Command.CalledArgs[1].IsInt32()) - { - count = e.Command.CalledArgs[1].AsInt32(); - } - else - { - Log.AsyncR("[count] is invalid"); - return; - } - - if (e.Command.CalledArgs.Length > 2) - { - if (e.Command.CalledArgs[2].IsInt32()) - { - quality = e.Command.CalledArgs[2].AsInt32(); - } - else - { - Log.AsyncR("[quality] is invalid"); - return; - } - } - } - - var o = new Object(e.Command.CalledArgs[0].AsInt32(), count) {quality = quality}; - - Game1.player.addItemByMenuIfNecessary(o); - } - else - { - Log.AsyncR(" is invalid"); - } - } - else - { - Log.LogObjectValueNotSpecified(); - } - } - - private static void player_addMelee(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0].IsInt32()) - { - var toAdd = new MeleeWeapon(e.Command.CalledArgs[0].AsInt32()); - Game1.player.addItemByMenuIfNecessary(toAdd); - Log.Async($"Given {toAdd.Name} to {Game1.player.Name}"); - } - else - { - Log.AsyncR(" is invalid"); - } - } - else - { - Log.LogObjectValueNotSpecified(); - } - } - - private static void player_addRing(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0].IsInt32()) - { - var toAdd = new Ring(e.Command.CalledArgs[0].AsInt32()); - Game1.player.addItemByMenuIfNecessary(toAdd); - Log.Async($"Given {toAdd.Name} to {Game1.player.Name}"); - } - else - { - Log.AsyncR(" is invalid"); - } - } - else - { - Log.LogObjectValueNotSpecified(); - } - } - - private static void out_items(object sender, EventArgsCommand e) - { - for (var i = 0; i < 1000; i++) - { - try - { - Item it = new Object(i, 1); - if (it.Name != "Error Item") - Console.WriteLine(i + "| " + it.Name); - } - catch - { - } - } - } - - private static void out_melee(object sender, EventArgsCommand e) - { - var d = Game1.content.Load>("Data\\weapons"); - Console.Write("DATA\\WEAPONS: "); - foreach (var v in d) - { - Console.WriteLine(v.Key + " | " + v.Value); - } - } - - private static void out_rings(object sender, EventArgsCommand e) - { - for (var i = 0; i < 100; i++) - { - try - { - Item it = new Ring(i); - if (it.Name != "Error Item") - Console.WriteLine(i + "| " + it.Name); - } - catch - { - } - } - } - - private static void world_downMineLevel(object sender, EventArgsCommand e) - { - Game1.nextMineLevel(); - } - - private static void world_setMineLevel(object sender, EventArgsCommand e) - { - if (e.Command.CalledArgs.Length > 0) - { - if (e.Command.CalledArgs[0].IsInt32()) - { - Game1.enterMine(true, e.Command.CalledArgs[0].AsInt32(), ""); - } - else - { - Log.LogValueNotInt32(); - } - } - else - { - Log.LogValueNotSpecified(); - } - } - - private static void blank_command(object sender, EventArgsCommand e) - { - } - - private static void RegisterNewItem(object sender, EventArgsCommand e) - { - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.Xna.Framework; +using StardewModdingAPI; +using StardewModdingAPI.Events; +using StardewValley; +using StardewValley.Menus; +using StardewValley.Objects; +using StardewValley.Tools; +using Object = StardewValley.Object; + +namespace TrainerMod +{ + public class TrainerMod : Mod + { + public static int frozenTime; + public static bool infHealth, infStamina, infMoney, freezeTime; + + public override void Entry(params object[] objects) + { + RegisterCommands(); + GameEvents.UpdateTick += Events_UpdateTick; + } + + private static void Events_UpdateTick(object sender, EventArgs e) + { + if (Game1.player == null) + return; + + if (infHealth) + { + Game1.player.health = Game1.player.maxHealth; + } + if (infStamina) + { + Game1.player.stamina = Game1.player.MaxStamina; + } + if (infMoney) + { + Game1.player.money = 999999; + } + if (freezeTime) + { + Game1.timeOfDay = frozenTime; + } + } + + public static void RegisterCommands() + { + Command.RegisterCommand("types", "Lists all value types | types").CommandFired += types_CommandFired; + + Command.RegisterCommand("save", "Saves the game? Doesn't seem to work. | save").CommandFired += save_CommandFired; + Command.RegisterCommand("load", "Shows the load screen | load").CommandFired += load_CommandFired; + + Command.RegisterCommand("exit", "Closes the game | exit").CommandFired += exit_CommandFired; + Command.RegisterCommand("stop", "Closes the game | stop").CommandFired += exit_CommandFired; + + Command.RegisterCommand("player_setname", "Sets the player's name | player_setname ", new[] {"(player, pet, farm) (String) The target name"}).CommandFired += player_setName; + Command.RegisterCommand("player_setmoney", "Sets the player's money | player_setmoney |inf", new[] {"(Int32) The target money"}).CommandFired += player_setMoney; + Command.RegisterCommand("player_setstamina", "Sets the player's stamina | player_setstamina |inf", new[] {"(Int32) The target stamina"}).CommandFired += player_setStamina; + Command.RegisterCommand("player_setmaxstamina", "Sets the player's max stamina | player_setmaxstamina ", new[] {"(Int32) The target max stamina"}).CommandFired += player_setMaxStamina; + Command.RegisterCommand("player_sethealth", "Sets the player's health | player_sethealth |inf", new[] {"(Int32) The target health"}).CommandFired += player_setHealth; + Command.RegisterCommand("player_setmaxhealth", "Sets the player's max health | player_setmaxhealth ", new[] {"(Int32) The target max health"}).CommandFired += player_setMaxHealth; + Command.RegisterCommand("player_setimmunity", "Sets the player's immunity | player_setimmunity ", new[] {"(Int32) The target immunity"}).CommandFired += player_setImmunity; + + Command.RegisterCommand("player_setlevel", "Sets the player's specified skill to the specified value | player_setlevel ", new[] {"(luck, mining, combat, farming, fishing, foraging) (1-10) The target level"}).CommandFired += player_setLevel; + Command.RegisterCommand("player_setspeed", "Sets the player's speed to the specified value?", new[] {"(Int32) The target speed [0 is normal]"}).CommandFired += player_setSpeed; + Command.RegisterCommand("player_changecolour", "Sets the player's colour of the specified object | player_changecolor ", new[] {"(hair, eyes, pants) (r,g,b)"}).CommandFired += player_changeColour; + Command.RegisterCommand("player_changestyle", "Sets the player's style of the specified object | player_changecolor ", new[] {"(hair, shirt, skin, acc, shoe, swim, gender) (Int32)"}).CommandFired += player_changeStyle; + + Command.RegisterCommand("player_additem", "Gives the player an item | player_additem [count] [quality]", new[] {"(Int32) (Int32)[count] (Int32)[quality]"}).CommandFired += player_addItem; + Command.RegisterCommand("player_addmelee", "Gives the player a melee item | player_addmelee ", new[] {"?"}).CommandFired += player_addMelee; + Command.RegisterCommand("player_addring", "Gives the player a ring | player_addring ", new[] {"?"}).CommandFired += player_addRing; + + Command.RegisterCommand("out_items", "Outputs a list of items | out_items", new[] {""}).CommandFired += out_items; + Command.RegisterCommand("out_melee", "Outputs a list of melee weapons | out_melee", new[] {""}).CommandFired += out_melee; + Command.RegisterCommand("out_rings", "Outputs a list of rings | out_rings", new[] {""}).CommandFired += out_rings; + Command.RegisterCommand("newitem", "not to be used | newitem", new[] {""}).CommandFired += RegisterNewItem; + + Command.RegisterCommand("world_settime", "Sets the time to the specified value | world_settime ", new[] {"(Int32) The target time [06:00 AM is 600]"}).CommandFired += world_setTime; + Command.RegisterCommand("world_freezetime", "Freezes or thaws time | world_freezetime ", new[] {"(0 - 1) Whether or not to freeze time. 0 is thawed, 1 is frozen"}).CommandFired += world_freezeTime; + Command.RegisterCommand("world_setday", "Sets the day to the specified value | world_setday ", new[] {"(Int32) The target day [1-28]"}).CommandFired += world_setDay; + Command.RegisterCommand("world_setseason", "Sets the season to the specified value | world_setseason ", new[] {"(winter, spring, summer, fall) The target season"}).CommandFired += world_setSeason; + Command.RegisterCommand("world_downminelevel", "Goes down one mine level? | world_downminelevel", new[] {""}).CommandFired += world_downMineLevel; + Command.RegisterCommand("world_setminelevel", "Sets mine level? | world_setminelevel", new[] {"(Int32) The target level"}).CommandFired += world_setMineLevel; + } + + private static void types_CommandFired(object sender, EventArgsCommand e) + { + Log.AsyncY($"[Int32: {int.MinValue} - {int.MaxValue}], [Int64: {long.MinValue} - {long.MaxValue}], [String: \"raw text\"], [Colour: r,g,b (EG: 128, 32, 255)]"); + } + + private static void save_CommandFired(object sender, EventArgsCommand e) + { + SaveGame.Save(); + } + + private static void load_CommandFired(object sender, EventArgsCommand e) + { + Game1.hasLoadedGame = false; + Game1.activeClickableMenu = new LoadGameMenu(); + } + + private static void exit_CommandFired(object sender, EventArgsCommand e) + { + Program.gamePtr.Exit(); + Environment.Exit(0); + } + + private static void player_setName(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 1) + { + var obj = e.Command.CalledArgs[0]; + var objs = "player,pet,farm".Split(','); + if (objs.Contains(obj)) + { + switch (obj) + { + case "player": + Game1.player.Name = e.Command.CalledArgs[1]; + break; + case "pet": + Log.AsyncR("Pets cannot currently be renamed."); + break; + case "farm": + Game1.player.farmName = e.Command.CalledArgs[1]; + break; + } + } + else + { + Log.LogObjectInvalid(); + } + } + else + { + Log.LogObjectValueNotSpecified(); + } + } + + private static void player_setMoney(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0] == "inf") + { + infMoney = true; + } + else + { + infMoney = false; + var ou = 0; + if (int.TryParse(e.Command.CalledArgs[0], out ou)) + { + Game1.player.Money = ou; + Log.Async($"Set {Game1.player.Name}'s money to {Game1.player.Money}"); + } + else + { + Log.LogValueNotInt32(); + } + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void player_setStamina(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0] == "inf") + { + infStamina = true; + } + else + { + infStamina = false; + var ou = 0; + if (int.TryParse(e.Command.CalledArgs[0], out ou)) + { + Game1.player.Stamina = ou; + Log.Async($"Set {Game1.player.Name}'s stamina to {Game1.player.Stamina}"); + } + else + { + Log.LogValueNotInt32(); + } + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void player_setMaxStamina(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + var ou = 0; + if (int.TryParse(e.Command.CalledArgs[0], out ou)) + { + Game1.player.MaxStamina = ou; + Log.Async($"Set {Game1.player.Name}'s max stamina to {Game1.player.MaxStamina}"); + } + else + { + Log.LogValueNotInt32(); + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void player_setLevel(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 1) + { + var skill = e.Command.CalledArgs[0]; + var skills = "luck,mining,combat,farming,fishing,foraging".Split(','); + if (skills.Contains(skill)) + { + var ou = 0; + if (int.TryParse(e.Command.CalledArgs[1], out ou)) + { + switch (skill) + { + case "luck": + Game1.player.LuckLevel = ou; + break; + case "mining": + Game1.player.MiningLevel = ou; + break; + case "combat": + Game1.player.CombatLevel = ou; + break; + case "farming": + Game1.player.FarmingLevel = ou; + break; + case "fishing": + Game1.player.FishingLevel = ou; + break; + case "foraging": + Game1.player.ForagingLevel = ou; + break; + } + } + else + { + Log.LogValueNotInt32(); + } + } + else + { + Log.AsyncR(" is invalid"); + } + } + else + { + Log.AsyncR(" and must be specified"); + } + } + + private static void player_setSpeed(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0].IsInt32()) + { + Game1.player.addedSpeed = e.Command.CalledArgs[0].AsInt32(); + Log.Async($"Set {Game1.player.Name}'s added speed to {Game1.player.addedSpeed}"); + } + else + { + Log.LogValueNotInt32(); + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void player_changeColour(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 1) + { + var obj = e.Command.CalledArgs[0]; + var objs = "hair,eyes,pants".Split(','); + if (objs.Contains(obj)) + { + var cs = e.Command.CalledArgs[1].Split(new[] {','}, 3); + if (cs[0].IsInt32() && cs[1].IsInt32() && cs[2].IsInt32()) + { + var c = new Color(cs[0].AsInt32(), cs[1].AsInt32(), cs[2].AsInt32()); + switch (obj) + { + case "hair": + Game1.player.hairstyleColor = c; + break; + case "eyes": + Game1.player.changeEyeColor(c); + break; + case "pants": + Game1.player.pantsColor = c; + break; + } + } + else + { + Log.AsyncR(" is invalid"); + } + } + else + { + Log.LogObjectInvalid(); + } + } + else + { + Log.AsyncR(" and must be specified"); + } + } + + private static void player_changeStyle(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 1) + { + var obj = e.Command.CalledArgs[0]; + var objs = "hair,shirt,skin,acc,shoe,swim,gender".Split(','); + if (objs.Contains(obj)) + { + if (e.Command.CalledArgs[1].IsInt32()) + { + var i = e.Command.CalledArgs[1].AsInt32(); + switch (obj) + { + case "hair": + Game1.player.changeHairStyle(i); + break; + case "shirt": + Game1.player.changeShirt(i); + break; + case "acc": + Game1.player.changeAccessory(i); + break; + case "skin": + Game1.player.changeSkinColor(i); + break; + case "shoe": + Game1.player.changeShoeColor(i); + break; + case "swim": + if (i == 0) + Game1.player.changeOutOfSwimSuit(); + else if (i == 1) + Game1.player.changeIntoSwimsuit(); + else + Log.AsyncR(" must be 0 or 1 for this "); + break; + case "gender": + if (i == 0) + Game1.player.changeGender(true); + else if (i == 1) + Game1.player.changeGender(false); + else + Log.AsyncR(" must be 0 or 1 for this "); + break; + } + } + else + { + Log.LogValueInvalid(); + } + } + else + { + Log.LogObjectInvalid(); + } + } + else + { + Log.LogObjectValueNotSpecified(); + } + } + + private static void world_freezeTime(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0].IsInt32()) + { + if (e.Command.CalledArgs[0].AsInt32() == 0 || e.Command.CalledArgs[0].AsInt32() == 1) + { + freezeTime = e.Command.CalledArgs[0].AsInt32() == 1; + frozenTime = freezeTime ? Game1.timeOfDay : 0; + Log.AsyncY("Time is now " + (freezeTime ? "frozen" : "thawed")); + } + else + { + Log.AsyncR(" should be 0 or 1"); + } + } + else + { + Log.LogValueNotInt32(); + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void world_setTime(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0].IsInt32()) + { + if (e.Command.CalledArgs[0].AsInt32() <= 2600 && e.Command.CalledArgs[0].AsInt32() >= 600) + { + Game1.timeOfDay = e.Command.CalledArgs[0].AsInt32(); + frozenTime = freezeTime ? Game1.timeOfDay : 0; + Log.AsyncY("Time set to: " + Game1.timeOfDay); + } + else + { + Log.AsyncR(" should be between 600 and 2600 (06:00 AM - 02:00 AM [NEXT DAY])"); + } + } + else + { + Log.LogValueNotInt32(); + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void world_setDay(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0].IsInt32()) + { + if (e.Command.CalledArgs[0].AsInt32() <= 28 && e.Command.CalledArgs[0].AsInt32() > 0) + { + Game1.dayOfMonth = e.Command.CalledArgs[0].AsInt32(); + } + else + { + Log.AsyncY(" must be between 1 and 28"); + } + } + else + { + Log.LogValueNotInt32(); + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void world_setSeason(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + var obj = e.Command.CalledArgs[0]; + var objs = "winter,spring,summer,fall".Split(','); + if (objs.Contains(obj)) + { + Game1.currentSeason = obj; + } + else + { + Log.LogValueInvalid(); + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void player_setHealth(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0] == "inf") + { + infHealth = true; + } + else + { + infHealth = false; + if (e.Command.CalledArgs[0].IsInt32()) + { + Game1.player.health = e.Command.CalledArgs[0].AsInt32(); + } + else + { + Log.LogValueNotInt32(); + } + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void player_setMaxHealth(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0].IsInt32()) + { + Game1.player.maxHealth = e.Command.CalledArgs[0].AsInt32(); + } + else + { + Log.LogValueNotInt32(); + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void player_setImmunity(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0].IsInt32()) + { + Game1.player.immunity = e.Command.CalledArgs[0].AsInt32(); + } + else + { + Log.LogValueNotInt32(); + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void player_addItem(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0].IsInt32()) + { + var count = 1; + var quality = 0; + if (e.Command.CalledArgs.Length > 1) + { + Console.WriteLine(e.Command.CalledArgs[1]); + if (e.Command.CalledArgs[1].IsInt32()) + { + count = e.Command.CalledArgs[1].AsInt32(); + } + else + { + Log.AsyncR("[count] is invalid"); + return; + } + + if (e.Command.CalledArgs.Length > 2) + { + if (e.Command.CalledArgs[2].IsInt32()) + { + quality = e.Command.CalledArgs[2].AsInt32(); + } + else + { + Log.AsyncR("[quality] is invalid"); + return; + } + } + } + + var o = new Object(e.Command.CalledArgs[0].AsInt32(), count) {quality = quality}; + + Game1.player.addItemByMenuIfNecessary(o); + } + else + { + Log.AsyncR(" is invalid"); + } + } + else + { + Log.LogObjectValueNotSpecified(); + } + } + + private static void player_addMelee(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0].IsInt32()) + { + var toAdd = new MeleeWeapon(e.Command.CalledArgs[0].AsInt32()); + Game1.player.addItemByMenuIfNecessary(toAdd); + Log.Async($"Given {toAdd.Name} to {Game1.player.Name}"); + } + else + { + Log.AsyncR(" is invalid"); + } + } + else + { + Log.LogObjectValueNotSpecified(); + } + } + + private static void player_addRing(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0].IsInt32()) + { + var toAdd = new Ring(e.Command.CalledArgs[0].AsInt32()); + Game1.player.addItemByMenuIfNecessary(toAdd); + Log.Async($"Given {toAdd.Name} to {Game1.player.Name}"); + } + else + { + Log.AsyncR(" is invalid"); + } + } + else + { + Log.LogObjectValueNotSpecified(); + } + } + + private static void out_items(object sender, EventArgsCommand e) + { + for (var i = 0; i < 1000; i++) + { + try + { + Item it = new Object(i, 1); + if (it.Name != "Error Item") + Console.WriteLine(i + "| " + it.Name); + } + catch + { + } + } + } + + private static void out_melee(object sender, EventArgsCommand e) + { + var d = Game1.content.Load>("Data\\weapons"); + Console.Write("DATA\\WEAPONS: "); + foreach (var v in d) + { + Console.WriteLine(v.Key + " | " + v.Value); + } + } + + private static void out_rings(object sender, EventArgsCommand e) + { + for (var i = 0; i < 100; i++) + { + try + { + Item it = new Ring(i); + if (it.Name != "Error Item") + Console.WriteLine(i + "| " + it.Name); + } + catch + { + } + } + } + + private static void world_downMineLevel(object sender, EventArgsCommand e) + { + Game1.nextMineLevel(); + } + + private static void world_setMineLevel(object sender, EventArgsCommand e) + { + if (e.Command.CalledArgs.Length > 0) + { + if (e.Command.CalledArgs[0].IsInt32()) + { + Game1.enterMine(true, e.Command.CalledArgs[0].AsInt32(), ""); + } + else + { + Log.LogValueNotInt32(); + } + } + else + { + Log.LogValueNotSpecified(); + } + } + + private static void blank_command(object sender, EventArgsCommand e) + { + } + + private static void RegisterNewItem(object sender, EventArgsCommand e) + { + } + } } \ No newline at end of file diff --git a/src/TrainerMod/TrainerMod.csproj b/src/TrainerMod/TrainerMod.csproj index 2bb92768..9bc2c5ab 100644 --- a/src/TrainerMod/TrainerMod.csproj +++ b/src/TrainerMod/TrainerMod.csproj @@ -1,126 +1,126 @@ - - - - - Debug - AnyCPU - {28480467-1A48-46A7-99F8-236D95225359} - Library - Properties - TrainerMod - TrainerMod - v4.5 - 512 - - - true - full - true - $(SolutionDir)\..\bin\Debug\Mods\TrainerMod\ - DEBUG;TRACE - prompt - 4 - x86 - false - 6 - true - - - pdbonly - true - $(SolutionDir)\..\bin\Release\Mods\TrainerMod\ - TRACE - prompt - 4 - false - 6 - true - x86 - - - - $(HOME)/GOG Games/Stardew Valley/game - $(HOME)/.local/share/Steam/steamapps/common/Stardew Valley - - $(HOME)/Library/Application Support/Steam/steamapps/common/Stardew Valley/Contents/MacOS - - C:\Program Files (x86)\GalaxyClient\Games\Stardew Valley - C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley - - - - - - False - - - False - - - $(GamePath)\Stardew Valley.exe - False - - - $(GamePath)\xTile.dll - False - False - - - - - - - $(GamePath)\MonoGame.Framework.dll - False - False - - - $(GamePath)\StardewValley.exe - False - - - $(GamePath)\xTile.dll - False - - - - - - - ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll - True - - - - - - - - - - - - - - - {f1a573b0-f436-472c-ae29-0b91ea6b9f8f} - StardewModdingAPI - False - - - - - PreserveNewest - - - - - - - - - - - - + + + + + Debug + AnyCPU + {28480467-1A48-46A7-99F8-236D95225359} + Library + Properties + TrainerMod + TrainerMod + v4.5 + 512 + + + true + full + true + $(SolutionDir)\..\bin\Debug\Mods\TrainerMod\ + DEBUG;TRACE + prompt + 4 + x86 + false + 6 + true + + + pdbonly + true + $(SolutionDir)\..\bin\Release\Mods\TrainerMod\ + TRACE + prompt + 4 + false + 6 + true + x86 + + + + $(HOME)/GOG Games/Stardew Valley/game + $(HOME)/.local/share/Steam/steamapps/common/Stardew Valley + + $(HOME)/Library/Application Support/Steam/steamapps/common/Stardew Valley/Contents/MacOS + + C:\Program Files (x86)\GalaxyClient\Games\Stardew Valley + C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley + + + + + + False + + + False + + + $(GamePath)\Stardew Valley.exe + False + + + $(GamePath)\xTile.dll + False + False + + + + + + + $(GamePath)\MonoGame.Framework.dll + False + False + + + $(GamePath)\StardewValley.exe + False + + + $(GamePath)\xTile.dll + False + + + + + + + ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + True + + + + + + + + + + + + + + + {f1a573b0-f436-472c-ae29-0b91ea6b9f8f} + StardewModdingAPI + False + + + + + PreserveNewest + + + + + + + + + + + + \ No newline at end of file diff --git a/src/TrainerMod/packages.config b/src/TrainerMod/packages.config index adc92baf..75e68e71 100644 --- a/src/TrainerMod/packages.config +++ b/src/TrainerMod/packages.config @@ -1,4 +1,4 @@ - - - + + + \ No newline at end of file