diff options
Diffstat (limited to 'src')
50 files changed, 7070 insertions, 0 deletions
diff --git a/src/BobberBar Private Fields.txt b/src/BobberBar Private Fields.txt new file mode 100644 index 00000000..2784f0e7 --- /dev/null +++ b/src/BobberBar Private Fields.txt @@ -0,0 +1,40 @@ +Single difficulty +Int32 motionType +Int32 whichFish +Single bobberPosition +Single bobberSpeed +Single bobberAcceleration +Single bobberTargetPosition +Single scale +Single everythingShakeTimer +Single floaterSinkerAcceleration +Single treasurePosition +Single treasureCatchLevel +Single treasureAppearTimer +Single treasureScale +Boolean bobberInBar +Boolean buttonPressed +Boolean flipBubble +Boolean fadeIn +Boolean fadeOut +Boolean treasure +Boolean treasureCaught +Boolean perfect +Boolean bossFish +Int32 bobberBarHeight +Int32 fishSize +Int32 fishQuality +Int32 minFishSize +Int32 maxFishSize +Int32 fishSizeReductionTimer +Int32 whichBobber +Microsoft.Xna.Framework.Vector2 barShake +Microsoft.Xna.Framework.Vector2 fishShake +Microsoft.Xna.Framework.Vector2 everythingShake +Microsoft.Xna.Framework.Vector2 treasureShake +Single reelRotation +StardewValley.BellsAndWhistles.SparklingText sparkleText +Single bobberBarPos +Single bobberBarSpeed +Single bobberBarAcceleration +Single distanceFromCatching
\ No newline at end of file diff --git a/src/Game1 Static Fields.txt b/src/Game1 Static Fields.txt new file mode 100644 index 00000000..4580f95f --- /dev/null +++ b/src/Game1 Static Fields.txt @@ -0,0 +1,329 @@ +Int32 pixelZoom +Int32 tileSize +System.String version +Microsoft.Xna.Framework.GraphicsDeviceManager graphics +Microsoft.Xna.Framework.Content.ContentManager content +Microsoft.Xna.Framework.Content.ContentManager temporaryContent +Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch +Microsoft.Xna.Framework.Input.GamePadState oldPadState +Single thumbStickSensitivity +Single runThreshold +Microsoft.Xna.Framework.Input.KeyboardState oldKBState +Microsoft.Xna.Framework.Input.MouseState oldMouseState +System.Collections.Generic.List`1[StardewValley.GameLocation] locations +StardewValley.GameLocation currentLocation +StardewValley.GameLocation locationAfterWarp +xTile.Display.IDisplayDevice mapDisplayDevice +StardewValley.Farmer player +StardewValley.Farmer serverHost +xTile.Dimensions.Rectangle viewport +Microsoft.Xna.Framework.Graphics.Texture2D objectSpriteSheet +Microsoft.Xna.Framework.Graphics.Texture2D toolSpriteSheet +Microsoft.Xna.Framework.Graphics.Texture2D cropSpriteSheet +Microsoft.Xna.Framework.Graphics.Texture2D mailboxTexture +Microsoft.Xna.Framework.Graphics.Texture2D emoteSpriteSheet +Microsoft.Xna.Framework.Graphics.Texture2D debrisSpriteSheet +Microsoft.Xna.Framework.Graphics.Texture2D toolIconBox +Microsoft.Xna.Framework.Graphics.Texture2D rainTexture +Microsoft.Xna.Framework.Graphics.Texture2D bigCraftableSpriteSheet +Microsoft.Xna.Framework.Graphics.Texture2D swordSwipe +Microsoft.Xna.Framework.Graphics.Texture2D swordSwipeDark +Microsoft.Xna.Framework.Graphics.Texture2D buffsIcons +Microsoft.Xna.Framework.Graphics.Texture2D daybg +Microsoft.Xna.Framework.Graphics.Texture2D nightbg +Microsoft.Xna.Framework.Graphics.Texture2D logoScreenTexture +Microsoft.Xna.Framework.Graphics.Texture2D tvStationTexture +Microsoft.Xna.Framework.Graphics.Texture2D cloud +Microsoft.Xna.Framework.Graphics.Texture2D menuTexture +Microsoft.Xna.Framework.Graphics.Texture2D lantern +Microsoft.Xna.Framework.Graphics.Texture2D windowLight +Microsoft.Xna.Framework.Graphics.Texture2D sconceLight +Microsoft.Xna.Framework.Graphics.Texture2D cauldronLight +Microsoft.Xna.Framework.Graphics.Texture2D shadowTexture +Microsoft.Xna.Framework.Graphics.Texture2D mouseCursors +Microsoft.Xna.Framework.Graphics.Texture2D indoorWindowLight +Microsoft.Xna.Framework.Graphics.Texture2D animations +Microsoft.Xna.Framework.Graphics.Texture2D titleScreenBG +Microsoft.Xna.Framework.Graphics.Texture2D logo +Microsoft.Xna.Framework.Graphics.RenderTarget2D lightmap +Microsoft.Xna.Framework.Graphics.Texture2D fadeToBlackRect +Microsoft.Xna.Framework.Graphics.Texture2D staminaRect +Microsoft.Xna.Framework.Graphics.Texture2D currentCoopTexture +Microsoft.Xna.Framework.Graphics.Texture2D currentBarnTexture +Microsoft.Xna.Framework.Graphics.Texture2D currentHouseTexture +Microsoft.Xna.Framework.Graphics.Texture2D greenhouseTexture +Microsoft.Xna.Framework.Graphics.Texture2D littleEffect +Microsoft.Xna.Framework.Graphics.SpriteFont dialogueFont +Microsoft.Xna.Framework.Graphics.SpriteFont smallFont +Microsoft.Xna.Framework.Graphics.SpriteFont borderFont +Microsoft.Xna.Framework.Graphics.SpriteFont tinyFont +Microsoft.Xna.Framework.Graphics.SpriteFont tinyFontBorder +Microsoft.Xna.Framework.Graphics.SpriteFont smoothFont +Single fadeToBlackAlpha +Single pickToolInterval +Single screenGlowAlpha +Single flashAlpha +Single starCropShimmerPause +Single noteBlockTimer +Single globalFadeSpeed +Boolean fadeToBlack +Boolean fadeIn +Boolean dialogueUp +Boolean dialogueTyping +Boolean pickingTool +Boolean isQuestion +Boolean nonWarpFade +Boolean particleRaining +Boolean newDay +Boolean inMine +Boolean isEating +Boolean menuUp +Boolean eventUp +Boolean viewportFreeze +Boolean eventOver +Boolean nameSelectUp +Boolean screenGlow +Boolean screenGlowHold +Boolean screenGlowUp +Boolean progressBar +Boolean isRaining +Boolean isSnowing +Boolean killScreen +Boolean coopDwellerBorn +Boolean messagePause +Boolean isDebrisWeather +Boolean boardingBus +Boolean listeningForKeyControlDefinitions +Boolean weddingToday +Boolean exitToTitle +Boolean debugMode +Boolean isLightning +Boolean displayHUD +Boolean displayFarmer +Boolean showKeyHelp +Boolean inputMode +Boolean shippingTax +Boolean dialogueButtonShrinking +Boolean jukeboxPlaying +Boolean drawLighting +Boolean bloomDay +Boolean quit +Boolean isChatting +Boolean globalFade +Boolean drawGrid +Boolean freezeControls +Boolean saveOnNewDay +Boolean panMode +Boolean showingEndOfNightStuff +Boolean wasRainingYesterday +Boolean hasLoadedGame +Boolean isActionAtCurrentCursorTile +Boolean isInspectionAtCurrentCursorTile +Boolean paused +Boolean lastCursorMotionWasMouse +System.String currentSeason +System.String debugOutput +System.String nextMusicTrack +System.String selectedItemsType +System.String nameSelectType +System.String messageAfterPause +System.String fertilizer +System.String samBandName +System.String elliottBookName +System.String slotResult +System.String keyHelpString +System.String debugInput +System.String loadingMessage +System.String errorMessage +System.Collections.Generic.Queue`1[System.String] currentObjectDialogue +System.Collections.Generic.Queue`1[System.String] mailbox +System.Collections.Generic.List`1[System.String] questionChoices +Int32 xLocationAfterWarp +Int32 yLocationAfterWarp +Int32 gameTimeInterval +Int32 currentQuestionChoice +Int32 currentDialogueCharacterIndex +Int32 dialogueTypingInterval +Int32 dayOfMonth +Int32 year +Int32 timeOfDay +Int32 numberOfSelectedItems +Int32 priceOfSelectedItem +Int32 currentWallpaper +Int32 farmerWallpaper +Int32 wallpaperPrice +Int32 currentFloor +Int32 FarmerFloor +Int32 floorPrice +Int32 dialogueWidth +Int32 countdownToWedding +Int32 menuChoice +Int32 tvStation +Int32 currentBillboard +Int32 facingDirectionAfterWarp +Int32 tmpTimeOfDay +Int32 percentageToWinStardewHero +Int32 mouseClickPolling +Int32 weatherIcon +Int32 hitShakeTimer +Int32 staminaShakeTimer +Int32 pauseThenDoFunctionTimer +Int32 weatherForTomorrow +Int32 currentSongIndex +Int32 cursorTileHintCheckTimer +Int32 timerUntilMouseFade +Int32 minecartHighScore +System.Collections.Generic.List`1[System.Int32] dealerCalicoJackTotal +Microsoft.Xna.Framework.Color morningColor +Microsoft.Xna.Framework.Color eveningColor +Microsoft.Xna.Framework.Color unselectedOptionColor +Microsoft.Xna.Framework.Color screenGlowColor +StardewValley.NPC currentSpeaker +System.Random random +System.Random recentMultiplayerRandom +System.Collections.Generic.Dictionary`2[System.Int32,System.String] objectInformation +System.Collections.Generic.Dictionary`2[System.Int32,System.String] bigCraftablesInformation +System.Collections.Generic.List`1[StardewValley.Object] shippingBin +StardewValley.Locations.MineShaft mine +System.Collections.Generic.List`1[StardewValley.HUDMessage] hudMessages +System.Collections.Generic.Dictionary`2[System.String,System.Boolean] eventConditions +System.Collections.Generic.Dictionary`2[System.String,System.String] NPCGiftTastes +Single musicPlayerVolume +Single pauseAccumulator +Single pauseTime +Single upPolling +Single downPolling +Single rightPolling +Single leftPolling +Single debrisSoundInterval +Single toolHold +Single windGust +Single dialogueButtonScale +Single creditsTimer +Single globalOutdoorLighting +Microsoft.Xna.Framework.Audio.Cue currentSong +Microsoft.Xna.Framework.Audio.AudioCategory musicCategory +Microsoft.Xna.Framework.Audio.AudioCategory soundCategory +Microsoft.Xna.Framework.PlayerIndex playerOneIndex +Microsoft.Xna.Framework.Audio.AudioEngine audioEngine +Microsoft.Xna.Framework.Audio.WaveBank waveBank +Microsoft.Xna.Framework.Audio.SoundBank soundBank +Microsoft.Xna.Framework.Vector2 shiny +Microsoft.Xna.Framework.Vector2 previousViewportPosition +Microsoft.Xna.Framework.Vector2 currentCursorTile +Microsoft.Xna.Framework.Vector2 lastCursorTile +StardewValley.RainDrop[] rainDrops +Double chanceToRainTomorrow +Microsoft.Xna.Framework.Audio.Cue fuseSound +Microsoft.Xna.Framework.Audio.Cue chargeUpSound +Microsoft.Xna.Framework.Audio.Cue wind +Double dailyLuck +System.Collections.Generic.List`1[StardewValley.WeatherDebris] debrisWeather +System.Collections.Generic.List`1[StardewValley.TemporaryAnimatedSprite] screenOverlayTempSprites +Byte gameMode +Byte multiplayerMode +System.Collections.Generic.IEnumerator`1[System.Int32] currentLoader +UInt64 uniqueIDForThisGame +StardewValley.LoadGameScreen loadGameScreen +StardewValley.Stats stats +Int32[] cropsOfTheWeek +StardewValley.Quests.Quest questOfTheDay +StardewValley.MoneyMadeScreen moneyMadeScreen +System.Collections.Generic.HashSet`1[StardewValley.LightSource] currentLightSources +Microsoft.Xna.Framework.Color ambientLight +Microsoft.Xna.Framework.Color outdoorLight +Microsoft.Xna.Framework.Color textColor +Microsoft.Xna.Framework.Color textShadowColor +StardewValley.Menus.IClickableMenu activeClickableMenu +StardewValley.Minigames.IMinigame currentMinigame +System.Collections.Generic.List`1[StardewValley.Menus.IClickableMenu] onScreenMenus +StardewValley.BloomComponent bloom +System.Collections.Generic.Dictionary`2[System.Int32,System.String] achievements +StardewValley.Object dishOfTheDay +StardewValley.Menus.BuffsDisplay buffsDisplay +StardewValley.Menus.DayTimeMoneyBox dayTimeMoneyBox +System.Collections.Generic.Dictionary`2[System.Int64,StardewValley.Farmer] otherFarmers +StardewValley.Network.Server server +StardewValley.Network.Client client +StardewValley.KeyboardDispatcher keyboardDispatcher +StardewValley.Background background +StardewValley.Events.FarmEvent farmEvent +afterFadeFunction afterFade +afterFadeFunction afterDialogues +afterFadeFunction afterViewport +afterFadeFunction viewportReachedTarget +afterFadeFunction afterPause +Microsoft.Xna.Framework.GameTime currentGameTime +System.Collections.Generic.List`1[StardewValley.DelayedAction] delayedActions +System.Collections.Generic.Stack`1[StardewValley.Menus.IClickableMenu] endOfNightMenus +StardewValley.Options options +StardewValley.Game1 game1 +Microsoft.Xna.Framework.Point lastMousePositionBeforeFade +Microsoft.Xna.Framework.Point viewportCenter +Microsoft.Xna.Framework.Vector2 viewportTarget +Single viewportSpeed +Int32 viewportHold +Boolean toggleFullScreen +Boolean isFullscreen +Boolean setToWindowedMode +Boolean setToFullscreen +System.String whereIsTodaysFest +Boolean farmerShouldPassOut +Microsoft.Xna.Framework.Vector2 currentViewportTarget +Microsoft.Xna.Framework.Vector2 viewportPositionLerp +Single screenGlowRate +Single screenGlowMax +Boolean haltAfterCheck +Int32 mouseCursor +Single mouseCursorTransparency +StardewValley.NPC objectDialoguePortraitPerson +Int32 defaultResolutionX +Int32 defaultResolutionY +Int32 smallestTileSize +Int32 up +Int32 right +Int32 down +Int32 left +Int32 spriteIndexForOveralls +Int32 colorToleranceForOveralls +Int32 spriteIndexForOverallsBorder +Int32 colorToloranceForOverallsBorder +Int32 dialogueBoxTileHeight +Int32 realMilliSecondsPerGameTenMinutes +Int32 rainDensity +Int32 millisecondsPerDialogueLetterType +Single pickToolDelay +Int32 defaultMinFishingBiteTime +Int32 defaultMaxFishingBiteTime +Int32 defaultMinFishingNibbleTime +Int32 defaultMaxFishingNibbleTime +Int32 minWallpaperPrice +Int32 maxWallpaperPrice +Int32 rainLoopLength +Int32 weather_sunny +Int32 weather_rain +Int32 weather_debris +Int32 weather_lightning +Int32 weather_festival +Int32 weather_snow +Int32 weather_wedding +Byte singlePlayer +Byte multiplayerClient +Byte multiplayerServer +Byte logoScreenGameMode +Byte titleScreenGameMode +Byte loadScreenGameMode +Byte newGameMode +Byte playingGameMode +Byte characterSelectMode +Byte loadingMode +Byte saveMode +Byte saveCompleteMode +Byte selectGameScreen +Byte creditsMode +Byte errorLogMode +Single keyPollingThreshold +Single toolHoldPerPowerupLevel +Single startingMusicVolume +Single thumbstickToMouseModifier +System.String NO_LETTER_MAIL
\ No newline at end of file diff --git a/src/StardewModdingAPI.sln b/src/StardewModdingAPI.sln new file mode 100644 index 00000000..087d0b36 --- /dev/null +++ b/src/StardewModdingAPI.sln @@ -0,0 +1,46 @@ +
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 14
+VisualStudioVersion = 14.0.25123.0
+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
+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
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/src/StardewModdingAPI/App.config b/src/StardewModdingAPI/App.config new file mode 100644 index 00000000..6664f1ed --- /dev/null +++ b/src/StardewModdingAPI/App.config @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="utf-8"?>
+
+<configuration>
+ <startup>
+ <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
+ </startup>
+ <runtime>
+ <loadFromRemoteSources enabled="true" />
+ </runtime>
+</configuration>
\ No newline at end of file diff --git a/src/StardewModdingAPI/Command.cs b/src/StardewModdingAPI/Command.cs new file mode 100644 index 00000000..4214b1a7 --- /dev/null +++ b/src/StardewModdingAPI/Command.cs @@ -0,0 +1,109 @@ +using System;
+using System.Collections.Generic;
+using StardewModdingAPI.Events;
+
+namespace StardewModdingAPI
+{
+ public class Command
+ {
+ internal static List<Command> RegisteredCommands = new List<Command>();
+ public string[] CalledArgs;
+ public string[] CommandArgs;
+ public string CommandDesc;
+
+ public string CommandName;
+
+ /// <summary>
+ /// Creates a Command from a Name, Description, and Arguments
+ /// </summary>
+ /// <param name="cname">Name</param>
+ /// <param name="cdesc">Description</param>
+ /// <param name="args">Arguments</param>
+ public Command(string cname, string cdesc, string[] args = null)
+ {
+ CommandName = cname;
+ CommandDesc = cdesc;
+ if (args == null)
+ args = new string[0];
+ CommandArgs = args;
+ }
+
+ public event EventHandler<EventArgsCommand> CommandFired;
+
+ /// <summary>
+ /// Calls the specified command. (It runs the command)
+ /// </summary>
+ /// <param name="input">The command to run</param>
+ public static void CallCommand(string input)
+ {
+ input = input.TrimEnd(' ');
+ var args = new string[0];
+ Command fnd;
+ if (input.Contains(" "))
+ {
+ args = input.Split(new[] {" "}, 2, StringSplitOptions.RemoveEmptyEntries);
+ fnd = FindCommand(args[0]);
+ args = args[1].Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);
+ }
+ else
+ {
+ fnd = FindCommand(input);
+ }
+
+ if (fnd != null)
+ {
+ fnd.CalledArgs = args;
+ fnd.Fire();
+ }
+ else
+ {
+ Log.AsyncR("Unknown Command");
+ }
+ }
+
+ /// <summary>
+ /// Registers a command to the list of commands properly
+ /// </summary>
+ /// <param name="command">Name of the command to register</param>
+ /// <param name="cdesc">Description</param>
+ /// <param name="args">Arguments (these are purely for viewing so that a user can see what an argument needs to be)</param>
+ /// <returns></returns>
+ public static Command RegisterCommand(string command, string cdesc, string[] args = null)
+ {
+ var c = new Command(command, cdesc, args);
+ if (RegisteredCommands.Contains(c))
+ {
+ Log.AsyncR($"Command already registered! [{c.CommandName}]");
+ return RegisteredCommands.Find(x => x.Equals(c));
+ }
+
+ RegisteredCommands.Add(c);
+ Log.Async("Registered command: " + command);
+
+ return c;
+ }
+
+ /// <summary>
+ /// Looks up a command in the list of registered commands. Returns null if it doesn't exist (I think)
+ /// </summary>
+ /// <param name="name">Name of command to find</param>
+ /// <returns></returns>
+ public static Command FindCommand(string name)
+ {
+ return RegisteredCommands.Find(x => x.CommandName.Equals(name));
+ }
+
+ /// <summary>
+ /// Runs a command. Fires it. Calls it. Any of those.
+ /// </summary>
+ public void Fire()
+ {
+ if (CommandFired == null)
+ {
+ Log.AsyncR("Command failed to fire because it's fire event is null: " + CommandName);
+ return;
+ }
+ CommandFired.Invoke(this, new EventArgsCommand(this));
+ }
+ }
+}
\ No newline at end of file diff --git a/src/StardewModdingAPI/Config.cs b/src/StardewModdingAPI/Config.cs new file mode 100644 index 00000000..c5b7beca --- /dev/null +++ b/src/StardewModdingAPI/Config.cs @@ -0,0 +1,176 @@ +/* + Copyright 2016 Zoey (Zoryn) +*/ + +using System; +using System.IO; +using System.Linq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace StardewModdingAPI +{ + public class Config + { + [JsonIgnore] + public virtual string ConfigLocation { get; protected internal set; } + + [JsonIgnore] + public virtual string ConfigDir => Path.GetDirectoryName(ConfigLocation); + + public virtual Config Instance<T>() where T : Config => Activator.CreateInstance<T>(); + + /// <summary> + /// Loads the config from the json blob on disk, updating and re-writing to the disk if needed. + /// </summary> + /// <typeparam name="T"></typeparam> + /// <returns></returns> + public virtual T LoadConfig<T>() where T : Config + { + if (string.IsNullOrEmpty(ConfigLocation)) + { + Log.AsyncR("A config tried to load without specifying a location on the disk."); + return null; + } + + T ret = null; + + if (!File.Exists(ConfigLocation)) + { + //no config exists, generate default values + var c = GenerateDefaultConfig<T>(); + c.ConfigLocation = ConfigLocation; + ret = c; + } + else + { + try + { + //try to load the config from a json blob on disk + var c = JsonConvert.DeserializeObject<T>(File.ReadAllText(ConfigLocation), new JsonSerializerSettings {ContractResolver = new JsonResolver()}); + + c.ConfigLocation = ConfigLocation; + + //update the config with default values if needed + ret = c.UpdateConfig<T>(); + + c = null; + } + catch (Exception ex) + { + Log.AsyncR($"Invalid JSON ({GetType().Name}): {ConfigLocation} \n{ex}"); + return GenerateDefaultConfig<T>(); + } + } + + ret.WriteConfig(); + return ret; + } + + /// <summary> + /// MUST be implemented in inheriting class! + /// </summary> + public virtual T GenerateDefaultConfig<T>() where T : Config + { + return null; + } + + /// <summary> + /// Merges a default-value config with the user-config on disk. + /// </summary> + /// <typeparam name="T"></typeparam> + /// <returns></returns> + public virtual T UpdateConfig<T>() where T : Config + { + try + { + //default config + var b = JObject.FromObject(Instance<T>().GenerateDefaultConfig<T>(), n |
