Transportation for ContentPatcher MOD, Renamed Namespace, Disabled Compatible Check.
Some of the mod without transportation may works now
This commit is contained in:
parent
589d48a969
commit
46b21d1d3a
|
@ -31,8 +31,8 @@
|
||||||
<WarningLevel>4</WarningLevel>
|
<WarningLevel>4</WarningLevel>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Reference Include="Mod">
|
<Reference Include="StardewModdingAPI">
|
||||||
<HintPath>..\assemblies\Mod.dll</HintPath>
|
<HintPath>..\assemblies\StardewModdingAPI.dll</HintPath>
|
||||||
</Reference>
|
</Reference>
|
||||||
<Reference Include="StardewValley">
|
<Reference Include="StardewValley">
|
||||||
<HintPath>..\assemblies\StardewValley.dll</HintPath>
|
<HintPath>..\assemblies\StardewValley.dll</HintPath>
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
@ -12,5 +12,6 @@ namespace AutoFish
|
||||||
public bool autoHit { get; set; } = true;
|
public bool autoHit { get; set; } = true;
|
||||||
public bool fastBite { get; set; } = false;
|
public bool fastBite { get; set; } = false;
|
||||||
public bool catchTreasure { get; set; } = true;
|
public bool catchTreasure { get; set; } = true;
|
||||||
|
public bool autoPlay { get; set; } = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,6 +25,12 @@ namespace AutoFish
|
||||||
public override List<OptionsElement> GetConfigMenuItems()
|
public override List<OptionsElement> GetConfigMenuItems()
|
||||||
{
|
{
|
||||||
List<OptionsElement> options = new List<OptionsElement>();
|
List<OptionsElement> options = new List<OptionsElement>();
|
||||||
|
ModOptionsCheckbox _optionsCheckboxPlay = new ModOptionsCheckbox("自动钓鱼", 0x8765, delegate (bool value) {
|
||||||
|
this.Config.autoPlay = value;
|
||||||
|
this.Helper.WriteConfig<ModConfig>(this.Config);
|
||||||
|
}, -1, -1);
|
||||||
|
_optionsCheckboxPlay.isChecked = this.Config.autoPlay;
|
||||||
|
options.Add(_optionsCheckboxPlay);
|
||||||
ModOptionsCheckbox _optionsCheckboxAutoHit = new ModOptionsCheckbox("自动起钩", 0x8765, delegate (bool value) {
|
ModOptionsCheckbox _optionsCheckboxAutoHit = new ModOptionsCheckbox("自动起钩", 0x8765, delegate (bool value) {
|
||||||
this.Config.autoHit = value;
|
this.Config.autoHit = value;
|
||||||
this.Helper.WriteConfig<ModConfig>(this.Config);
|
this.Helper.WriteConfig<ModConfig>(this.Config);
|
||||||
|
@ -43,12 +49,6 @@ namespace AutoFish
|
||||||
}, -1, -1);
|
}, -1, -1);
|
||||||
_optionsCheckboxFastBite.isChecked = this.Config.fastBite;
|
_optionsCheckboxFastBite.isChecked = this.Config.fastBite;
|
||||||
options.Add(_optionsCheckboxFastBite);
|
options.Add(_optionsCheckboxFastBite);
|
||||||
ModOptionsCheckbox _optionsCheckboxCatchTreasure = new ModOptionsCheckbox("钓取宝箱", 0x8765, delegate (bool value) {
|
|
||||||
this.Config.catchTreasure = value;
|
|
||||||
this.Helper.WriteConfig<ModConfig>(this.Config);
|
|
||||||
}, -1, -1);
|
|
||||||
_optionsCheckboxCatchTreasure.isChecked = this.Config.catchTreasure;
|
|
||||||
options.Add(_optionsCheckboxCatchTreasure);
|
|
||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -71,7 +71,7 @@ namespace AutoFish
|
||||||
currentTool.castingPower = 1;
|
currentTool.castingPower = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Game1.activeClickableMenu is BobberBar) // 自动小游戏
|
if (this.Config.autoPlay && Game1.activeClickableMenu is BobberBar) // 自动小游戏
|
||||||
{
|
{
|
||||||
BobberBar bar = Game1.activeClickableMenu as BobberBar;
|
BobberBar bar = Game1.activeClickableMenu as BobberBar;
|
||||||
float barPos = this.Helper.Reflection.GetField<float>(bar, "bobberBarPos").GetValue();
|
float barPos = this.Helper.Reflection.GetField<float>(bar, "bobberBarPos").GetValue();
|
||||||
|
|
|
@ -33,8 +33,8 @@
|
||||||
<LangVersion>7.2</LangVersion>
|
<LangVersion>7.2</LangVersion>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Reference Include="Mod">
|
<Reference Include="StardewModdingAPI">
|
||||||
<HintPath>..\assemblies\Mod.dll</HintPath>
|
<HintPath>..\assemblies\StardewModdingAPI.dll</HintPath>
|
||||||
</Reference>
|
</Reference>
|
||||||
<Reference Include="StardewValley">
|
<Reference Include="StardewValley">
|
||||||
<HintPath>..\assemblies\StardewValley.dll</HintPath>
|
<HintPath>..\assemblies\StardewValley.dll</HintPath>
|
||||||
|
|
|
@ -0,0 +1,345 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using Microsoft.Xna.Framework.Graphics;
|
||||||
|
using Pathoschild.Stardew.Common.UI;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
using StardewValley;
|
||||||
|
using StardewValley.Locations;
|
||||||
|
using StardewValley.Menus;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common
|
||||||
|
{
|
||||||
|
/// <summary>Provides common utility methods for interacting with the game code shared by my various mods.</summary>
|
||||||
|
internal static class CommonHelper
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>A blank pixel which can be colorised and stretched to draw geometric shapes.</summary>
|
||||||
|
private static readonly Lazy<Texture2D> LazyPixel = new Lazy<Texture2D>(() =>
|
||||||
|
{
|
||||||
|
Texture2D pixel = new Texture2D(Game1.graphics.GraphicsDevice, 1, 1);
|
||||||
|
pixel.SetData(new[] { Color.White });
|
||||||
|
return pixel;
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>A blank pixel which can be colorised and stretched to draw geometric shapes.</summary>
|
||||||
|
public static Texture2D Pixel => CommonHelper.LazyPixel.Value;
|
||||||
|
|
||||||
|
/// <summary>The width of the horizontal and vertical scroll edges (between the origin position and start of content padding).</summary>
|
||||||
|
public static readonly Vector2 ScrollEdgeSize = new Vector2(CommonSprites.Scroll.TopLeft.Width * Game1.pixelZoom, CommonSprites.Scroll.TopLeft.Height * Game1.pixelZoom);
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/****
|
||||||
|
** Game
|
||||||
|
****/
|
||||||
|
/// <summary>Get all game locations.</summary>
|
||||||
|
public static IEnumerable<GameLocation> GetLocations()
|
||||||
|
{
|
||||||
|
return Game1.locations
|
||||||
|
.Concat(
|
||||||
|
from location in Game1.locations.OfType<BuildableGameLocation>()
|
||||||
|
from building in location.buildings
|
||||||
|
where building.indoors.Value != null
|
||||||
|
select building.indoors.Value
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Fonts
|
||||||
|
****/
|
||||||
|
/// <summary>Get the dimensions of a space character.</summary>
|
||||||
|
/// <param name="font">The font to measure.</param>
|
||||||
|
public static float GetSpaceWidth(SpriteFont font)
|
||||||
|
{
|
||||||
|
return font.MeasureString("A B").X - font.MeasureString("AB").X;
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** UI
|
||||||
|
****/
|
||||||
|
/// <summary>Draw a pretty hover box for the given text.</summary>
|
||||||
|
/// <param name="spriteBatch">The sprite batch being drawn.</param>
|
||||||
|
/// <param name="label">The text to display.</param>
|
||||||
|
/// <param name="position">The position at which to draw the text.</param>
|
||||||
|
/// <param name="wrapWidth">The maximum width to display.</param>
|
||||||
|
public static Vector2 DrawHoverBox(SpriteBatch spriteBatch, string label, in Vector2 position, float wrapWidth)
|
||||||
|
{
|
||||||
|
const int paddingSize = 27;
|
||||||
|
const int gutterSize = 20;
|
||||||
|
|
||||||
|
Vector2 labelSize = spriteBatch.DrawTextBlock(Game1.smallFont, label, position + new Vector2(gutterSize), wrapWidth); // draw text to get wrapped text dimensions
|
||||||
|
IClickableMenu.drawTextureBox(spriteBatch, Game1.menuTexture, new Rectangle(0, 256, 60, 60), (int)position.X, (int)position.Y, (int)labelSize.X + paddingSize + gutterSize, (int)labelSize.Y + paddingSize, Color.White);
|
||||||
|
spriteBatch.DrawTextBlock(Game1.smallFont, label, position + new Vector2(gutterSize), wrapWidth); // draw again over texture box
|
||||||
|
|
||||||
|
return labelSize + new Vector2(paddingSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Draw a button background.</summary>
|
||||||
|
/// <param name="spriteBatch">The sprite batch to which to draw.</param>
|
||||||
|
/// <param name="position">The top-left pixel coordinate at which to draw the button.</param>
|
||||||
|
/// <param name="contentSize">The button content's pixel size.</param>
|
||||||
|
/// <param name="contentPos">The pixel position at which the content begins.</param>
|
||||||
|
/// <param name="bounds">The button's outer bounds.</param>
|
||||||
|
/// <param name="padding">The padding between the content and border.</param>
|
||||||
|
public static void DrawButton(SpriteBatch spriteBatch, in Vector2 position, in Vector2 contentSize, out Vector2 contentPos, out Rectangle bounds, int padding = 0)
|
||||||
|
{
|
||||||
|
CommonHelper.DrawContentBox(
|
||||||
|
spriteBatch: spriteBatch,
|
||||||
|
texture: CommonSprites.Button.Sheet,
|
||||||
|
background: CommonSprites.Button.Background,
|
||||||
|
top: CommonSprites.Button.Top,
|
||||||
|
right: CommonSprites.Button.Right,
|
||||||
|
bottom: CommonSprites.Button.Bottom,
|
||||||
|
left: CommonSprites.Button.Left,
|
||||||
|
topLeft: CommonSprites.Button.TopLeft,
|
||||||
|
topRight: CommonSprites.Button.TopRight,
|
||||||
|
bottomRight: CommonSprites.Button.BottomRight,
|
||||||
|
bottomLeft: CommonSprites.Button.BottomLeft,
|
||||||
|
position: position,
|
||||||
|
contentSize: contentSize,
|
||||||
|
contentPos: out contentPos,
|
||||||
|
bounds: out bounds,
|
||||||
|
padding: padding
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Draw a scroll background.</summary>
|
||||||
|
/// <param name="spriteBatch">The sprite batch to which to draw.</param>
|
||||||
|
/// <param name="position">The top-left pixel coordinate at which to draw the scroll.</param>
|
||||||
|
/// <param name="contentSize">The scroll content's pixel size.</param>
|
||||||
|
/// <param name="contentPos">The pixel position at which the content begins.</param>
|
||||||
|
/// <param name="bounds">The scroll's outer bounds.</param>
|
||||||
|
/// <param name="padding">The padding between the content and border.</param>
|
||||||
|
public static void DrawScroll(SpriteBatch spriteBatch, in Vector2 position, in Vector2 contentSize, out Vector2 contentPos, out Rectangle bounds, int padding = 5)
|
||||||
|
{
|
||||||
|
CommonHelper.DrawContentBox(
|
||||||
|
spriteBatch: spriteBatch,
|
||||||
|
texture: CommonSprites.Scroll.Sheet,
|
||||||
|
background: in CommonSprites.Scroll.Background,
|
||||||
|
top: CommonSprites.Scroll.Top,
|
||||||
|
right: CommonSprites.Scroll.Right,
|
||||||
|
bottom: CommonSprites.Scroll.Bottom,
|
||||||
|
left: CommonSprites.Scroll.Left,
|
||||||
|
topLeft: CommonSprites.Scroll.TopLeft,
|
||||||
|
topRight: CommonSprites.Scroll.TopRight,
|
||||||
|
bottomRight: CommonSprites.Scroll.BottomRight,
|
||||||
|
bottomLeft: CommonSprites.Scroll.BottomLeft,
|
||||||
|
position: position,
|
||||||
|
contentSize: contentSize,
|
||||||
|
contentPos: out contentPos,
|
||||||
|
bounds: out bounds,
|
||||||
|
padding: padding
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Draw a generic content box like a scroll or button.</summary>
|
||||||
|
/// <param name="spriteBatch">The sprite batch to which to draw.</param>
|
||||||
|
/// <param name="texture">The texture to draw.</param>
|
||||||
|
/// <param name="background">The source rectangle for the background.</param>
|
||||||
|
/// <param name="top">The source rectangle for the top border.</param>
|
||||||
|
/// <param name="right">The source rectangle for the right border.</param>
|
||||||
|
/// <param name="bottom">The source rectangle for the bottom border.</param>
|
||||||
|
/// <param name="left">The source rectangle for the left border.</param>
|
||||||
|
/// <param name="topLeft">The source rectangle for the top-left corner.</param>
|
||||||
|
/// <param name="topRight">The source rectangle for the top-right corner.</param>
|
||||||
|
/// <param name="bottomRight">The source rectangle for the bottom-right corner.</param>
|
||||||
|
/// <param name="bottomLeft">The source rectangle for the bottom-left corner.</param>
|
||||||
|
/// <param name="position">The top-left pixel coordinate at which to draw the button.</param>
|
||||||
|
/// <param name="contentSize">The button content's pixel size.</param>
|
||||||
|
/// <param name="contentPos">The pixel position at which the content begins.</param>
|
||||||
|
/// <param name="bounds">The box's outer bounds.</param>
|
||||||
|
/// <param name="padding">The padding between the content and border.</param>
|
||||||
|
public static void DrawContentBox(SpriteBatch spriteBatch, Texture2D texture, in Rectangle background, in Rectangle top, in Rectangle right, in Rectangle bottom, in Rectangle left, in Rectangle topLeft, in Rectangle topRight, in Rectangle bottomRight, in Rectangle bottomLeft, in Vector2 position, in Vector2 contentSize, out Vector2 contentPos, out Rectangle bounds, int padding)
|
||||||
|
{
|
||||||
|
int cornerWidth = topLeft.Width * Game1.pixelZoom;
|
||||||
|
int cornerHeight = topLeft.Height * Game1.pixelZoom;
|
||||||
|
int innerWidth = (int)(contentSize.X + padding * 2);
|
||||||
|
int innerHeight = (int)(contentSize.Y + padding * 2);
|
||||||
|
int outerWidth = innerWidth + cornerWidth * 2;
|
||||||
|
int outerHeight = innerHeight + cornerHeight * 2;
|
||||||
|
int x = (int)position.X;
|
||||||
|
int y = (int)position.Y;
|
||||||
|
|
||||||
|
// draw scroll background
|
||||||
|
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth, y + cornerHeight, innerWidth, innerHeight), background, Color.White);
|
||||||
|
|
||||||
|
// draw borders
|
||||||
|
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth, y, innerWidth, cornerHeight), top, Color.White);
|
||||||
|
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth, y + cornerHeight + innerHeight, innerWidth, cornerHeight), bottom, Color.White);
|
||||||
|
spriteBatch.Draw(texture, new Rectangle(x, y + cornerHeight, cornerWidth, innerHeight), left, Color.White);
|
||||||
|
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth + innerWidth, y + cornerHeight, cornerWidth, innerHeight), right, Color.White);
|
||||||
|
|
||||||
|
// draw corners
|
||||||
|
spriteBatch.Draw(texture, new Rectangle(x, y, cornerWidth, cornerHeight), topLeft, Color.White);
|
||||||
|
spriteBatch.Draw(texture, new Rectangle(x, y + cornerHeight + innerHeight, cornerWidth, cornerHeight), bottomLeft, Color.White);
|
||||||
|
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth + innerWidth, y, cornerWidth, cornerHeight), topRight, Color.White);
|
||||||
|
spriteBatch.Draw(texture, new Rectangle(x + cornerWidth + innerWidth, y + cornerHeight + innerHeight, cornerWidth, cornerHeight), bottomRight, Color.White);
|
||||||
|
|
||||||
|
// set out params
|
||||||
|
contentPos = new Vector2(x + cornerWidth + padding, y + cornerHeight + padding);
|
||||||
|
bounds = new Rectangle(x, y, outerWidth, outerHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Show an informational message to the player.</summary>
|
||||||
|
/// <param name="message">The message to show.</param>
|
||||||
|
/// <param name="duration">The number of milliseconds during which to keep the message on the screen before it fades (or <c>null</c> for the default time).</param>
|
||||||
|
public static void ShowInfoMessage(string message, int? duration = null)
|
||||||
|
{
|
||||||
|
Game1.addHUDMessage(new HUDMessage(message, 3) { noIcon = true, timeLeft = duration ?? HUDMessage.defaultTime });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Show an error message to the player.</summary>
|
||||||
|
/// <param name="message">The message to show.</param>
|
||||||
|
public static void ShowErrorMessage(string message)
|
||||||
|
{
|
||||||
|
Game1.addHUDMessage(new HUDMessage(message, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Drawing
|
||||||
|
****/
|
||||||
|
/// <summary>Draw a sprite to the screen.</summary>
|
||||||
|
/// <param name="batch">The sprite batch.</param>
|
||||||
|
/// <param name="x">The X-position at which to start the line.</param>
|
||||||
|
/// <param name="y">The X-position at which to start the line.</param>
|
||||||
|
/// <param name="size">The line dimensions.</param>
|
||||||
|
/// <param name="color">The color to tint the sprite.</param>
|
||||||
|
public static void DrawLine(this SpriteBatch batch, float x, float y, in Vector2 size, in Color? color = null)
|
||||||
|
{
|
||||||
|
batch.Draw(CommonHelper.Pixel, new Rectangle((int)x, (int)y, (int)size.X, (int)size.Y), color ?? Color.White);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Draw a block of text to the screen with the specified wrap width.</summary>
|
||||||
|
/// <param name="batch">The sprite batch.</param>
|
||||||
|
/// <param name="font">The sprite font.</param>
|
||||||
|
/// <param name="text">The block of text to write.</param>
|
||||||
|
/// <param name="position">The position at which to draw the text.</param>
|
||||||
|
/// <param name="wrapWidth">The width at which to wrap the text.</param>
|
||||||
|
/// <param name="color">The text color.</param>
|
||||||
|
/// <param name="bold">Whether to draw bold text.</param>
|
||||||
|
/// <param name="scale">The font scale.</param>
|
||||||
|
/// <returns>Returns the text dimensions.</returns>
|
||||||
|
public static Vector2 DrawTextBlock(this SpriteBatch batch, SpriteFont font, string text, in Vector2 position, float wrapWidth, in Color? color = null, bool bold = false, float scale = 1)
|
||||||
|
{
|
||||||
|
if (text == null)
|
||||||
|
return new Vector2(0, 0);
|
||||||
|
|
||||||
|
// get word list
|
||||||
|
List<string> words = new List<string>();
|
||||||
|
foreach (string word in text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
|
||||||
|
{
|
||||||
|
// split on newlines
|
||||||
|
string wordPart = word;
|
||||||
|
int newlineIndex;
|
||||||
|
while ((newlineIndex = wordPart.IndexOf(Environment.NewLine, StringComparison.InvariantCulture)) >= 0)
|
||||||
|
{
|
||||||
|
if (newlineIndex == 0)
|
||||||
|
{
|
||||||
|
words.Add(Environment.NewLine);
|
||||||
|
wordPart = wordPart.Substring(Environment.NewLine.Length);
|
||||||
|
}
|
||||||
|
else if (newlineIndex > 0)
|
||||||
|
{
|
||||||
|
words.Add(wordPart.Substring(0, newlineIndex));
|
||||||
|
words.Add(Environment.NewLine);
|
||||||
|
wordPart = wordPart.Substring(newlineIndex + Environment.NewLine.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// add remaining word (after newline split)
|
||||||
|
if (wordPart.Length > 0)
|
||||||
|
words.Add(wordPart);
|
||||||
|
}
|
||||||
|
|
||||||
|
// track draw values
|
||||||
|
float xOffset = 0;
|
||||||
|
float yOffset = 0;
|
||||||
|
float lineHeight = font.MeasureString("ABC").Y * scale;
|
||||||
|
float spaceWidth = CommonHelper.GetSpaceWidth(font) * scale;
|
||||||
|
float blockWidth = 0;
|
||||||
|
float blockHeight = lineHeight;
|
||||||
|
foreach (string word in words)
|
||||||
|
{
|
||||||
|
// check wrap width
|
||||||
|
float wordWidth = font.MeasureString(word).X * scale;
|
||||||
|
if (word == Environment.NewLine || ((wordWidth + xOffset) > wrapWidth && (int)xOffset != 0))
|
||||||
|
{
|
||||||
|
xOffset = 0;
|
||||||
|
yOffset += lineHeight;
|
||||||
|
blockHeight += lineHeight;
|
||||||
|
}
|
||||||
|
if (word == Environment.NewLine)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
// draw text
|
||||||
|
Vector2 wordPosition = new Vector2(position.X + xOffset, position.Y + yOffset);
|
||||||
|
if (bold)
|
||||||
|
Utility.drawBoldText(batch, word, font, wordPosition, color ?? Color.Black, scale);
|
||||||
|
else
|
||||||
|
batch.DrawString(font, word, wordPosition, color ?? Color.Black, 0, Vector2.Zero, scale, SpriteEffects.None, 1);
|
||||||
|
|
||||||
|
// update draw values
|
||||||
|
if (xOffset + wordWidth > blockWidth)
|
||||||
|
blockWidth = xOffset + wordWidth;
|
||||||
|
xOffset += wordWidth + spaceWidth;
|
||||||
|
}
|
||||||
|
|
||||||
|
// return text position & dimensions
|
||||||
|
return new Vector2(blockWidth, blockHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Error handling
|
||||||
|
****/
|
||||||
|
/// <summary>Intercept errors thrown by the action.</summary>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
/// <param name="verb">The verb describing where the error occurred (e.g. "looking that up"). This is displayed on the screen, so it should be simple and avoid characters that might not be available in the sprite font.</param>
|
||||||
|
/// <param name="action">The action to invoke.</param>
|
||||||
|
/// <param name="onError">A callback invoked if an error is intercepted.</param>
|
||||||
|
public static void InterceptErrors(this IMonitor monitor, string verb, Action action, Action<Exception> onError = null)
|
||||||
|
{
|
||||||
|
monitor.InterceptErrors(verb, null, action, onError);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Intercept errors thrown by the action.</summary>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
/// <param name="verb">The verb describing where the error occurred (e.g. "looking that up"). This is displayed on the screen, so it should be simple and avoid characters that might not be available in the sprite font.</param>
|
||||||
|
/// <param name="detailedVerb">A more detailed form of <see cref="verb"/> if applicable. This is displayed in the log, so it can be more technical and isn't constrained by the sprite font.</param>
|
||||||
|
/// <param name="action">The action to invoke.</param>
|
||||||
|
/// <param name="onError">A callback invoked if an error is intercepted.</param>
|
||||||
|
public static void InterceptErrors(this IMonitor monitor, string verb, string detailedVerb, Action action, Action<Exception> onError = null)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
action();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
monitor.InterceptError(ex, verb, detailedVerb);
|
||||||
|
onError?.Invoke(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Log an error and warn the user.</summary>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
/// <param name="ex">The exception to handle.</param>
|
||||||
|
/// <param name="verb">The verb describing where the error occurred (e.g. "looking that up"). This is displayed on the screen, so it should be simple and avoid characters that might not be available in the sprite font.</param>
|
||||||
|
/// <param name="detailedVerb">A more detailed form of <see cref="verb"/> if applicable. This is displayed in the log, so it can be more technical and isn't constrained by the sprite font.</param>
|
||||||
|
public static void InterceptError(this IMonitor monitor, Exception ex, string verb, string detailedVerb = null)
|
||||||
|
{
|
||||||
|
detailedVerb = detailedVerb ?? verb;
|
||||||
|
monitor.Log($"Something went wrong {detailedVerb}:\n{ex}", LogLevel.Error);
|
||||||
|
CommonHelper.ShowErrorMessage($"Huh. Something went wrong {verb}. The error log has the technical details.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,93 @@
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using StardewModdingAPI.Utilities;
|
||||||
|
using StardewValley;
|
||||||
|
using SObject = StardewValley.Object;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.DataParsers
|
||||||
|
{
|
||||||
|
/// <summary>Analyses crop data for a tile.</summary>
|
||||||
|
internal class CropDataParser
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The crop.</summary>
|
||||||
|
public Crop Crop { get; }
|
||||||
|
|
||||||
|
/// <summary>The seasons in which the crop grows.</summary>
|
||||||
|
public string[] Seasons { get; }
|
||||||
|
|
||||||
|
/// <summary>The phase index in <see cref="StardewValley.Crop.phaseDays"/> when the crop can be harvested.</summary>
|
||||||
|
public int HarvestablePhase { get; }
|
||||||
|
|
||||||
|
/// <summary>The number of days needed between planting and first harvest.</summary>
|
||||||
|
public int DaysToFirstHarvest { get; }
|
||||||
|
|
||||||
|
/// <summary>The number of days needed between harvests, after the first harvest.</summary>
|
||||||
|
public int DaysToSubsequentHarvest { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the crop can be harvested multiple times.</summary>
|
||||||
|
public bool HasMultipleHarvests { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the crop is ready to harvest now.</summary>
|
||||||
|
public bool CanHarvestNow { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="crop">The crop.</param>
|
||||||
|
public CropDataParser(Crop crop)
|
||||||
|
{
|
||||||
|
this.Crop = crop;
|
||||||
|
if (crop != null)
|
||||||
|
{
|
||||||
|
this.Seasons = crop.seasonsToGrowIn.ToArray();
|
||||||
|
this.HasMultipleHarvests = crop.regrowAfterHarvest.Value == -1;
|
||||||
|
this.HarvestablePhase = crop.phaseDays.Count - 1;
|
||||||
|
this.CanHarvestNow = (crop.currentPhase.Value >= this.HarvestablePhase) && (!crop.fullyGrown.Value || crop.dayOfCurrentPhase.Value <= 0);
|
||||||
|
this.DaysToFirstHarvest = crop.phaseDays.Take(crop.phaseDays.Count - 1).Sum(); // ignore harvestable phase
|
||||||
|
this.DaysToSubsequentHarvest = crop.regrowAfterHarvest.Value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the date when the crop will next be ready to harvest.</summary>
|
||||||
|
public SDate GetNextHarvest()
|
||||||
|
{
|
||||||
|
// get crop
|
||||||
|
Crop crop = this.Crop;
|
||||||
|
if (crop == null)
|
||||||
|
throw new InvalidOperationException("Can't get the harvest date because there's no crop.");
|
||||||
|
|
||||||
|
// ready now
|
||||||
|
if (this.CanHarvestNow)
|
||||||
|
return SDate.Now();
|
||||||
|
|
||||||
|
// growing: days until next harvest
|
||||||
|
if (!crop.fullyGrown.Value)
|
||||||
|
{
|
||||||
|
int daysUntilLastPhase = this.DaysToFirstHarvest - this.Crop.dayOfCurrentPhase.Value - crop.phaseDays.Take(crop.currentPhase.Value).Sum();
|
||||||
|
return SDate.Now().AddDays(daysUntilLastPhase);
|
||||||
|
}
|
||||||
|
|
||||||
|
// regrowable crop harvested today
|
||||||
|
if (crop.dayOfCurrentPhase.Value >= crop.regrowAfterHarvest.Value)
|
||||||
|
return SDate.Now().AddDays(crop.regrowAfterHarvest.Value);
|
||||||
|
|
||||||
|
// regrowable crop
|
||||||
|
// dayOfCurrentPhase decreases to 0 when fully grown, where <=0 is harvestable
|
||||||
|
return SDate.Now().AddDays(crop.dayOfCurrentPhase.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get a sample item acquired by harvesting the crop.</summary>
|
||||||
|
public Item GetSampleDrop()
|
||||||
|
{
|
||||||
|
if (this.Crop == null)
|
||||||
|
throw new InvalidOperationException("Can't get a sample drop because there's no crop.");
|
||||||
|
|
||||||
|
return new SObject(this.Crop.indexOfHarvest.Value, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,44 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.Automate
|
||||||
|
{
|
||||||
|
/// <summary>Handles the logic for integrating with the Automate mod.</summary>
|
||||||
|
internal class AutomateIntegration : BaseIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The mod's public API.</summary>
|
||||||
|
private readonly IAutomateApi ModApi;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
public AutomateIntegration(IModRegistry modRegistry, IMonitor monitor)
|
||||||
|
: base("Automate", "Pathoschild.Automate", "1.11.0", modRegistry, monitor)
|
||||||
|
{
|
||||||
|
if (!this.IsLoaded)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// get mod API
|
||||||
|
this.ModApi = this.GetValidatedApi<IAutomateApi>();
|
||||||
|
this.IsLoaded = this.ModApi != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the status of machines in a tile area. This is a specialised API for Data Layers and similar mods.</summary>
|
||||||
|
/// <param name="location">The location for which to display data.</param>
|
||||||
|
/// <param name="tileArea">The tile area for which to display data.</param>
|
||||||
|
public IDictionary<Vector2, int> GetMachineStates(GameLocation location, Rectangle tileArea)
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
return this.ModApi.GetMachineStates(location, tileArea);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.Automate
|
||||||
|
{
|
||||||
|
/// <summary>The API provided by the Automate mod.</summary>
|
||||||
|
public interface IAutomateApi
|
||||||
|
{
|
||||||
|
/// <summary>Get the status of machines in a tile area. This is a specialised API for Data Layers and similar mods.</summary>
|
||||||
|
/// <param name="location">The location for which to display data.</param>
|
||||||
|
/// <param name="tileArea">The tile area for which to display data.</param>
|
||||||
|
IDictionary<Vector2, int> GetMachineStates(GameLocation location, Rectangle tileArea);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,82 @@
|
||||||
|
using System;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations
|
||||||
|
{
|
||||||
|
/// <summary>The base implementation for a mod integration.</summary>
|
||||||
|
internal abstract class BaseIntegration : IModIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The mod's unique ID.</summary>
|
||||||
|
protected string ModID { get; }
|
||||||
|
|
||||||
|
/// <summary>An API for fetching metadata about loaded mods.</summary>
|
||||||
|
protected IModRegistry ModRegistry { get; }
|
||||||
|
|
||||||
|
/// <summary>Encapsulates monitoring and logging.</summary>
|
||||||
|
protected IMonitor Monitor { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>A human-readable name for the mod.</summary>
|
||||||
|
public string Label { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the mod is available.</summary>
|
||||||
|
public bool IsLoaded { get; protected set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="label">A human-readable name for the mod.</param>
|
||||||
|
/// <param name="modID">The mod's unique ID.</param>
|
||||||
|
/// <param name="minVersion">The minimum version of the mod that's supported.</param>
|
||||||
|
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
protected BaseIntegration(string label, string modID, string minVersion, IModRegistry modRegistry, IMonitor monitor)
|
||||||
|
{
|
||||||
|
// init
|
||||||
|
this.Label = label;
|
||||||
|
this.ModID = modID;
|
||||||
|
this.ModRegistry = modRegistry;
|
||||||
|
this.Monitor = monitor;
|
||||||
|
|
||||||
|
// validate mod
|
||||||
|
IManifest manifest = modRegistry.Get(this.ModID)?.Manifest;
|
||||||
|
if (manifest == null)
|
||||||
|
return;
|
||||||
|
if (manifest.Version.IsOlderThan(minVersion))
|
||||||
|
{
|
||||||
|
monitor.Log($"Detected {label} {manifest.Version}, but need {minVersion} or later. Disabled integration with this mod.", LogLevel.Warn);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.IsLoaded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get an API for the mod, and show a message if it can't be loaded.</summary>
|
||||||
|
/// <typeparam name="TInterface">The API type.</typeparam>
|
||||||
|
protected TInterface GetValidatedApi<TInterface>() where TInterface : class
|
||||||
|
{
|
||||||
|
TInterface api = this.ModRegistry.GetApi<TInterface>(this.ModID);
|
||||||
|
if (api == null)
|
||||||
|
{
|
||||||
|
this.Monitor.Log($"Detected {this.Label}, but couldn't fetch its API. Disabled integration with this mod.", LogLevel.Warn);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return api;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Assert that the integration is loaded.</summary>
|
||||||
|
/// <exception cref="InvalidOperationException">The integration isn't loaded.</exception>
|
||||||
|
protected void AssertLoaded()
|
||||||
|
{
|
||||||
|
if (!this.IsLoaded)
|
||||||
|
throw new InvalidOperationException($"The {this.Label} integration isn't loaded.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,40 @@
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.BetterJunimos
|
||||||
|
{
|
||||||
|
/// <summary>Handles the logic for integrating with the Better Junimos mod.</summary>
|
||||||
|
internal class BetterJunimosIntegration : BaseIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The mod's public API.</summary>
|
||||||
|
private readonly IBetterJunimosApi ModApi;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The Junimo Hut coverage radius.</summary>
|
||||||
|
public int MaxRadius { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
public BetterJunimosIntegration(IModRegistry modRegistry, IMonitor monitor)
|
||||||
|
: base("Better Junimos", "hawkfalcon.BetterJunimos", "0.5.0", modRegistry, monitor)
|
||||||
|
{
|
||||||
|
if (!this.IsLoaded)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// get mod API
|
||||||
|
this.ModApi = this.GetValidatedApi<IBetterJunimosApi>();
|
||||||
|
this.IsLoaded = this.ModApi != null;
|
||||||
|
this.MaxRadius = this.ModApi?.GetJunimoHutMaxRadius() ?? 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.BetterJunimos
|
||||||
|
{
|
||||||
|
/// <summary>The API provided by the Better Junimos mod.</summary>
|
||||||
|
public interface IBetterJunimosApi
|
||||||
|
{
|
||||||
|
/// <summary>Get the maximum radius for Junimo Huts.</summary>
|
||||||
|
int GetJunimoHutMaxRadius();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.BetterSprinklers
|
||||||
|
{
|
||||||
|
/// <summary>Handles the logic for integrating with the Better Sprinklers mod.</summary>
|
||||||
|
internal class BetterSprinklersIntegration : BaseIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The mod's public API.</summary>
|
||||||
|
private readonly IBetterSprinklersApi ModApi;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The maximum possible sprinkler radius.</summary>
|
||||||
|
public int MaxRadius { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
public BetterSprinklersIntegration(IModRegistry modRegistry, IMonitor monitor)
|
||||||
|
: base("Better Sprinklers", "Speeder.BetterSprinklers", "2.3.1-unofficial.6-pathoschild", modRegistry, monitor)
|
||||||
|
{
|
||||||
|
if (!this.IsLoaded)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// get mod API
|
||||||
|
this.ModApi = this.GetValidatedApi<IBetterSprinklersApi>();
|
||||||
|
this.IsLoaded = this.ModApi != null;
|
||||||
|
this.MaxRadius = this.ModApi?.GetMaxGridSize() ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the configured Sprinkler tiles relative to (0, 0).</summary>
|
||||||
|
public IDictionary<int, Vector2[]> GetSprinklerTiles()
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
return this.ModApi.GetSprinklerCoverage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.BetterSprinklers
|
||||||
|
{
|
||||||
|
/// <summary>The API provided by the Better Sprinklers mod.</summary>
|
||||||
|
public interface IBetterSprinklersApi
|
||||||
|
{
|
||||||
|
/// <summary>Get the maximum supported coverage width or height.</summary>
|
||||||
|
int GetMaxGridSize();
|
||||||
|
|
||||||
|
/// <summary>Get the relative tile coverage by supported sprinkler ID.</summary>
|
||||||
|
IDictionary<int, Vector2[]> GetSprinklerCoverage();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,48 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.Cobalt
|
||||||
|
{
|
||||||
|
/// <summary>Handles the logic for integrating with the Cobalt mod.</summary>
|
||||||
|
internal class CobaltIntegration : BaseIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The mod's public API.</summary>
|
||||||
|
private readonly ICobaltApi ModApi;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
public CobaltIntegration(IModRegistry modRegistry, IMonitor monitor)
|
||||||
|
: base("Cobalt", "spacechase0.Cobalt", "1.1", modRegistry, monitor)
|
||||||
|
{
|
||||||
|
if (!this.IsLoaded)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// get mod API
|
||||||
|
this.ModApi = this.GetValidatedApi<ICobaltApi>();
|
||||||
|
this.IsLoaded = this.ModApi != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the cobalt sprinkler's object ID.</summary>
|
||||||
|
public int GetSprinklerId()
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
return this.ModApi.GetSprinklerId();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the configured Sprinkler tiles relative to (0, 0).</summary>
|
||||||
|
public IEnumerable<Vector2> GetSprinklerTiles()
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
return this.ModApi.GetSprinklerCoverage(Vector2.Zero);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.Cobalt
|
||||||
|
{
|
||||||
|
/// <summary>The API provided by the Cobalt mod.</summary>
|
||||||
|
public interface ICobaltApi
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get the cobalt sprinkler's object ID.</summary>
|
||||||
|
int GetSprinklerId();
|
||||||
|
|
||||||
|
/// <summary>Get the cobalt sprinkler coverage.</summary>
|
||||||
|
/// <param name="origin">The tile position containing the sprinkler.</param>
|
||||||
|
IEnumerable<Vector2> GetSprinklerCoverage(Vector2 origin);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
using System;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using Microsoft.Xna.Framework.Graphics;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
using StardewValley;
|
||||||
|
using SObject = StardewValley.Object;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.CustomFarmingRedux
|
||||||
|
{
|
||||||
|
/// <summary>Handles the logic for integrating with the Custom Farming Redux mod.</summary>
|
||||||
|
internal class CustomFarmingReduxIntegration : BaseIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The mod's public API.</summary>
|
||||||
|
private readonly ICustomFarmingApi ModApi;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
public CustomFarmingReduxIntegration(IModRegistry modRegistry, IMonitor monitor)
|
||||||
|
: base("Custom Farming Redux", "Platonymous.CustomFarming", "2.8.5", modRegistry, monitor)
|
||||||
|
{
|
||||||
|
if (!this.IsLoaded)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// get mod API
|
||||||
|
this.ModApi = this.GetValidatedApi<ICustomFarmingApi>();
|
||||||
|
this.IsLoaded = this.ModApi != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the sprite info for a custom object, or <c>null</c> if the object isn't custom.</summary>
|
||||||
|
/// <param name="obj">The custom object.</param>
|
||||||
|
public SpriteInfo GetSprite(SObject obj)
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
|
||||||
|
Tuple<Item, Texture2D, Rectangle, Color> data = this.ModApi.getRealItemAndTexture(obj);
|
||||||
|
return data != null
|
||||||
|
? new SpriteInfo(data.Item2, data.Item3)
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
using System;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using Microsoft.Xna.Framework.Graphics;
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.CustomFarmingRedux
|
||||||
|
{
|
||||||
|
/// <summary>The API provided by the Custom Farming Redux mod.</summary>
|
||||||
|
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "The naming convention is defined by the Custom Farming Redux mod.")]
|
||||||
|
public interface ICustomFarmingApi
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get metadata for a custom machine and draw metadata for an object.</summary>
|
||||||
|
/// <param name="dummy">The item that would be replaced by the custom item.</param>
|
||||||
|
Tuple<Item, Texture2D, Rectangle, Color> getRealItemAndTexture(StardewValley.Object dummy);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
using StardewModdingAPI;
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.FarmExpansion
|
||||||
|
{
|
||||||
|
/// <summary>Handles the logic for integrating with the Farm Expansion mod.</summary>
|
||||||
|
internal class FarmExpansionIntegration : BaseIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The mod's public API.</summary>
|
||||||
|
private readonly IFarmExpansionApi ModApi;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
public FarmExpansionIntegration(IModRegistry modRegistry, IMonitor monitor)
|
||||||
|
: base("Farm Expansion", "Advize.FarmExpansion", "3.3", modRegistry, monitor)
|
||||||
|
{
|
||||||
|
if (!this.IsLoaded)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// get mod API
|
||||||
|
this.ModApi = this.GetValidatedApi<IFarmExpansionApi>();
|
||||||
|
this.IsLoaded = this.ModApi != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Add a blueprint to all future carpenter menus for the farm area.</summary>
|
||||||
|
/// <param name="blueprint">The blueprint to add.</param>
|
||||||
|
public void AddFarmBluePrint(BluePrint blueprint)
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
this.ModApi.AddFarmBluePrint(blueprint);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Add a blueprint to all future carpenter menus for the expansion area.</summary>
|
||||||
|
/// <param name="blueprint">The blueprint to add.</param>
|
||||||
|
public void AddExpansionBluePrint(BluePrint blueprint)
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
this.ModApi.AddExpansionBluePrint(blueprint);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.FarmExpansion
|
||||||
|
{
|
||||||
|
/// <summary>The API provided by the Farm Expansion mod.</summary>
|
||||||
|
public interface IFarmExpansionApi
|
||||||
|
{
|
||||||
|
/// <summary>Add a blueprint to all future carpenter menus for the farm area.</summary>
|
||||||
|
/// <param name="blueprint">The blueprint to add.</param>
|
||||||
|
void AddFarmBluePrint(BluePrint blueprint);
|
||||||
|
|
||||||
|
/// <summary>Add a blueprint to all future carpenter menus for the expansion area.</summary>
|
||||||
|
/// <param name="blueprint">The blueprint to add.</param>
|
||||||
|
void AddExpansionBluePrint(BluePrint blueprint);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations
|
||||||
|
{
|
||||||
|
/// <summary>Handles integration with a given mod.</summary>
|
||||||
|
internal interface IModIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>A human-readable name for the mod.</summary>
|
||||||
|
string Label { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the mod is available.</summary>
|
||||||
|
bool IsLoaded { get; }
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.LineSprinklers
|
||||||
|
{
|
||||||
|
/// <summary>The API provided by the Line Sprinklers mod.</summary>
|
||||||
|
public interface ILineSprinklersApi
|
||||||
|
{
|
||||||
|
/// <summary>Get the maximum supported coverage width or height.</summary>
|
||||||
|
int GetMaxGridSize();
|
||||||
|
|
||||||
|
/// <summary>Get the relative tile coverage by supported sprinkler ID.</summary>
|
||||||
|
IDictionary<int, Vector2[]> GetSprinklerCoverage();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.LineSprinklers
|
||||||
|
{
|
||||||
|
/// <summary>Handles the logic for integrating with the Line Sprinklers mod.</summary>
|
||||||
|
internal class LineSprinklersIntegration : BaseIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The mod's public API.</summary>
|
||||||
|
private readonly ILineSprinklersApi ModApi;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The maximum possible sprinkler radius.</summary>
|
||||||
|
public int MaxRadius { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
public LineSprinklersIntegration(IModRegistry modRegistry, IMonitor monitor)
|
||||||
|
: base("Line Sprinklers", "hootless.LineSprinklers", "1.1.0", modRegistry, monitor)
|
||||||
|
{
|
||||||
|
if (!this.IsLoaded)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// get mod API
|
||||||
|
this.ModApi = this.GetValidatedApi<ILineSprinklersApi>();
|
||||||
|
this.IsLoaded = this.ModApi != null;
|
||||||
|
this.MaxRadius = this.ModApi?.GetMaxGridSize() ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the configured Sprinkler tiles relative to (0, 0).</summary>
|
||||||
|
public IDictionary<int, Vector2[]> GetSprinklerTiles()
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
return this.ModApi.GetSprinklerCoverage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
using StardewModdingAPI;
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.PelicanFiber
|
||||||
|
{
|
||||||
|
/// <summary>Handles the logic for integrating with the Pelican Fiber mod.</summary>
|
||||||
|
internal class PelicanFiberIntegration : BaseIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The full type name of the Pelican Fiber mod's build menu.</summary>
|
||||||
|
private readonly string MenuTypeName = "PelicanFiber.Framework.ConstructionMenu";
|
||||||
|
|
||||||
|
/// <summary>An API for accessing private code.</summary>
|
||||||
|
private readonly IReflectionHelper Reflection;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
|
||||||
|
/// <param name="reflection">An API for accessing private code.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
public PelicanFiberIntegration(IModRegistry modRegistry, IReflectionHelper reflection, IMonitor monitor)
|
||||||
|
: base("Pelican Fiber", "jwdred.PelicanFiber", "3.0.2", modRegistry, monitor)
|
||||||
|
{
|
||||||
|
this.Reflection = reflection;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get whether the Pelican Fiber build menu is open.</summary>
|
||||||
|
public bool IsBuildMenuOpen()
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
return Game1.activeClickableMenu?.GetType().FullName == this.MenuTypeName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the selected blueprint from the Pelican Fiber build menu, if it's open.</summary>
|
||||||
|
public BluePrint GetBuildMenuBlueprint()
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
if (!this.IsBuildMenuOpen())
|
||||||
|
return null;
|
||||||
|
|
||||||
|
return this.Reflection.GetProperty<BluePrint>(Game1.activeClickableMenu, "CurrentBlueprint").GetValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.PrismaticTools
|
||||||
|
{
|
||||||
|
/// <summary>The API provided by the Prismatic Tools mod.</summary>
|
||||||
|
public interface IPrismaticToolsApi
|
||||||
|
{
|
||||||
|
/// <summary>Whether prismatic sprinklers also act as scarecrows.</summary>
|
||||||
|
bool ArePrismaticSprinklersScarecrows { get; }
|
||||||
|
|
||||||
|
/// <summary>The prismatic sprinkler object ID.</summary>
|
||||||
|
int SprinklerIndex { get; }
|
||||||
|
|
||||||
|
/// <summary>Get the relative tile coverage for a prismatic sprinkler.</summary>
|
||||||
|
/// <param name="origin">The sprinkler tile.</param>
|
||||||
|
IEnumerable<Vector2> GetSprinklerCoverage(Vector2 origin);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,55 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.PrismaticTools
|
||||||
|
{
|
||||||
|
/// <summary>Handles the logic for integrating with the Prismatic Tools mod.</summary>
|
||||||
|
internal class PrismaticToolsIntegration : BaseIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The mod's public API.</summary>
|
||||||
|
private readonly IPrismaticToolsApi ModApi;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
public PrismaticToolsIntegration(IModRegistry modRegistry, IMonitor monitor)
|
||||||
|
: base("Prismatic Tools", "stokastic.PrismaticTools", "1.3.0", modRegistry, monitor)
|
||||||
|
{
|
||||||
|
if (!this.IsLoaded)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// get mod API
|
||||||
|
this.ModApi = this.GetValidatedApi<IPrismaticToolsApi>();
|
||||||
|
this.IsLoaded = this.ModApi != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get whether prismatic sprinklers also act as scarecrows.</summary>
|
||||||
|
public bool ArePrismaticSprinklersScarecrows()
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
return this.ModApi.ArePrismaticSprinklersScarecrows;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the prismatic sprinkler object ID.</summary>
|
||||||
|
public int GetSprinklerID()
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
return this.ModApi.SprinklerIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the relative tile coverage for a prismatic sprinkler.</summary>
|
||||||
|
public IEnumerable<Vector2> GetSprinklerCoverage()
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
return this.ModApi.GetSprinklerCoverage(Vector2.Zero);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.SimpleSprinkler
|
||||||
|
{
|
||||||
|
/// <summary>The API provided by the Simple Sprinkler mod.</summary>
|
||||||
|
public interface ISimplerSprinklerApi
|
||||||
|
{
|
||||||
|
/// <summary>Get the relative tile coverage for supported sprinkler IDs (additive to the game's default coverage).</summary>
|
||||||
|
IDictionary<int, Vector2[]> GetNewSprinklerCoverage();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,41 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Integrations.SimpleSprinkler
|
||||||
|
{
|
||||||
|
/// <summary>Handles the logic for integrating with the Simple Sprinkler mod.</summary>
|
||||||
|
internal class SimpleSprinklerIntegration : BaseIntegration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The mod's public API.</summary>
|
||||||
|
private readonly ISimplerSprinklerApi ModApi;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="modRegistry">An API for fetching metadata about loaded mods.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
public SimpleSprinklerIntegration(IModRegistry modRegistry, IMonitor monitor)
|
||||||
|
: base("Simple Sprinklers", "tZed.SimpleSprinkler", "1.6.0", modRegistry, monitor)
|
||||||
|
{
|
||||||
|
if (!this.IsLoaded)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// get mod API
|
||||||
|
this.ModApi = this.GetValidatedApi<ISimplerSprinklerApi>();
|
||||||
|
this.IsLoaded = this.ModApi != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the Sprinkler tiles relative to (0, 0), additive to the game's default sprinkler coverage.</summary>
|
||||||
|
public IDictionary<int, Vector2[]> GetNewSprinklerTiles()
|
||||||
|
{
|
||||||
|
this.AssertLoaded();
|
||||||
|
return this.ModApi.GetNewSprinklerCoverage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,86 @@
|
||||||
|
using System;
|
||||||
|
using System.Diagnostics.Contracts;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common
|
||||||
|
{
|
||||||
|
/// <summary>Provides utilities for normalising file paths.</summary>
|
||||||
|
/// <remarks>This class is duplicated from <c>StardewModdingAPI.Toolkit.Utilities</c>.</remarks>
|
||||||
|
internal static class PathUtilities
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The possible directory separator characters in a file path.</summary>
|
||||||
|
private static readonly char[] PossiblePathSeparators = new[] { '/', '\\', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }.Distinct().ToArray();
|
||||||
|
|
||||||
|
/// <summary>The preferred directory separator chaeacter in an asset key.</summary>
|
||||||
|
private static readonly string PreferredPathSeparator = Path.DirectorySeparatorChar.ToString();
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get the segments from a path (e.g. <c>/usr/bin/boop</c> => <c>usr</c>, <c>bin</c>, and <c>boop</c>).</summary>
|
||||||
|
/// <param name="path">The path to split.</param>
|
||||||
|
/// <param name="limit">The number of segments to match. Any additional segments will be merged into the last returned part.</param>
|
||||||
|
public static string[] GetSegments(string path, int? limit = null)
|
||||||
|
{
|
||||||
|
return limit.HasValue
|
||||||
|
? path.Split(PathUtilities.PossiblePathSeparators, limit.Value, StringSplitOptions.RemoveEmptyEntries)
|
||||||
|
: path.Split(PathUtilities.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Normalise path separators in a file path.</summary>
|
||||||
|
/// <param name="path">The file path to normalise.</param>
|
||||||
|
[Pure]
|
||||||
|
public static string NormalisePathSeparators(string path)
|
||||||
|
{
|
||||||
|
string[] parts = PathUtilities.GetSegments(path);
|
||||||
|
string normalised = string.Join(PathUtilities.PreferredPathSeparator, parts);
|
||||||
|
if (path.StartsWith(PathUtilities.PreferredPathSeparator))
|
||||||
|
normalised = PathUtilities.PreferredPathSeparator + normalised; // keep root slash
|
||||||
|
return normalised;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get a directory or file path relative to a given source path.</summary>
|
||||||
|
/// <param name="sourceDir">The source folder path.</param>
|
||||||
|
/// <param name="targetPath">The target folder or file path.</param>
|
||||||
|
[Pure]
|
||||||
|
public static string GetRelativePath(string sourceDir, string targetPath)
|
||||||
|
{
|
||||||
|
// convert to URIs
|
||||||
|
Uri from = new Uri(sourceDir.TrimEnd(PathUtilities.PossiblePathSeparators) + "/");
|
||||||
|
Uri to = new Uri(targetPath.TrimEnd(PathUtilities.PossiblePathSeparators) + "/");
|
||||||
|
if (from.Scheme != to.Scheme)
|
||||||
|
throw new InvalidOperationException($"Can't get path for '{targetPath}' relative to '{sourceDir}'.");
|
||||||
|
|
||||||
|
// get relative path
|
||||||
|
string relative = PathUtilities.NormalisePathSeparators(Uri.UnescapeDataString(from.MakeRelativeUri(to).ToString()));
|
||||||
|
if (relative == "")
|
||||||
|
relative = "./";
|
||||||
|
return relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get whether a path is relative and doesn't try to climb out of its containing folder (e.g. doesn't contain <c>../</c>).</summary>
|
||||||
|
/// <param name="path">The path to check.</param>
|
||||||
|
public static bool IsSafeRelativePath(string path)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(path))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
return
|
||||||
|
!Path.IsPathRooted(path)
|
||||||
|
&& PathUtilities.GetSegments(path).All(segment => segment.Trim() != "..");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get whether a string is a valid 'slug', containing only basic characters that are safe in all contexts (e.g. filenames, URLs, etc).</summary>
|
||||||
|
/// <param name="str">The string to check.</param>
|
||||||
|
public static bool IsSlug(string str)
|
||||||
|
{
|
||||||
|
return !Regex.IsMatch(str, "[^a-z0-9_.-]", RegexOptions.IgnoreCase);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using Microsoft.Xna.Framework.Graphics;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common
|
||||||
|
{
|
||||||
|
/// <summary>Represents a single sprite in a spritesheet.</summary>
|
||||||
|
internal class SpriteInfo
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The spritesheet texture.</summary>
|
||||||
|
public Texture2D Spritesheet { get; }
|
||||||
|
|
||||||
|
/// <summary>The area in the spritesheet containing the sprite.</summary>
|
||||||
|
public Rectangle SourceRectangle { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="spritesheet">The spritesheet texture.</param>
|
||||||
|
/// <param name="sourceRectangle">The area in the spritesheet containing the sprite.</param>
|
||||||
|
public SpriteInfo(Texture2D spritesheet, Rectangle sourceRectangle)
|
||||||
|
{
|
||||||
|
this.Spritesheet = spritesheet;
|
||||||
|
this.SourceRectangle = sourceRectangle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,153 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Converters;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common
|
||||||
|
{
|
||||||
|
/// <summary>A variant of <see cref="StringEnumConverter"/> which represents arrays in JSON as a comma-delimited string.</summary>
|
||||||
|
internal class StringEnumArrayConverter : StringEnumConverter
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>Whether to return null values for missing data instead of an empty array.</summary>
|
||||||
|
public bool AllowNull { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get whether this instance can convert the specified object type.</summary>
|
||||||
|
/// <param name="type">The object type.</param>
|
||||||
|
public override bool CanConvert(Type type)
|
||||||
|
{
|
||||||
|
if (!type.IsArray)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
Type elementType = this.GetElementType(type);
|
||||||
|
return elementType != null && base.CanConvert(elementType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Read a JSON representation.</summary>
|
||||||
|
/// <param name="reader">The JSON reader from which to read.</param>
|
||||||
|
/// <param name="valueType">The value type.</param>
|
||||||
|
/// <param name="rawValue">The raw value of the object being read.</param>
|
||||||
|
/// <param name="serializer">The calling serializer.</param>
|
||||||
|
public override object ReadJson(JsonReader reader, Type valueType, object rawValue, JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
// get element type
|
||||||
|
Type elementType = this.GetElementType(valueType);
|
||||||
|
if (elementType == null)
|
||||||
|
throw new InvalidOperationException("Couldn't extract enum array element type."); // should never happen since we validate in CanConvert
|
||||||
|
|
||||||
|
// parse
|
||||||
|
switch (reader.TokenType)
|
||||||
|
{
|
||||||
|
case JsonToken.Null:
|
||||||
|
return this.GetNullOrEmptyArray(elementType);
|
||||||
|
|
||||||
|
case JsonToken.StartArray:
|
||||||
|
{
|
||||||
|
string[] elements = JArray.Load(reader).Values<string>().ToArray();
|
||||||
|
object[] parsed = elements.Select(raw => this.ParseOne(raw, elementType)).ToArray();
|
||||||
|
return this.Cast(parsed, elementType);
|
||||||
|
}
|
||||||
|
|
||||||
|
case JsonToken.String:
|
||||||
|
{
|
||||||
|
string value = (string)JToken.Load(reader);
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(value))
|
||||||
|
return this.GetNullOrEmptyArray(elementType);
|
||||||
|
|
||||||
|
object[] parsed = this.ParseMany(value, elementType).ToArray();
|
||||||
|
return this.Cast(parsed, elementType);
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
return base.ReadJson(reader, valueType, rawValue, serializer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Write a JSON representation.</summary>
|
||||||
|
/// <param name="writer">The JSON writer to which to write.</param>
|
||||||
|
/// <param name="value">The value.</param>
|
||||||
|
/// <param name="serializer">The calling serializer.</param>
|
||||||
|
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
if (value == null)
|
||||||
|
writer.WriteNull();
|
||||||
|
else if (value is IEnumerable list)
|
||||||
|
{
|
||||||
|
string[] array = (from object element in list where element != null select element.ToString()).ToArray();
|
||||||
|
writer.WriteValue(string.Join(", ", array));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
base.WriteJson(writer, value, serializer);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get the underlying array element type (bypassing <see cref="Nullable"/> if necessary).</summary>
|
||||||
|
/// <param name="type">The array type.</param>
|
||||||
|
private Type GetElementType(Type type)
|
||||||
|
{
|
||||||
|
if (!type.IsArray)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
type = type.GetElementType();
|
||||||
|
if (type == null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
type = Nullable.GetUnderlyingType(type) ?? type;
|
||||||
|
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Parse a string into individual values.</summary>
|
||||||
|
/// <param name="input">The input string.</param>
|
||||||
|
/// <param name="elementType">The enum type.</param>
|
||||||
|
private IEnumerable<object> ParseMany(string input, Type elementType)
|
||||||
|
{
|
||||||
|
string[] values = input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
foreach (string value in values)
|
||||||
|
yield return this.ParseOne(value, elementType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Parse a string into one value.</summary>
|
||||||
|
/// <param name="input">The input string.</param>
|
||||||
|
/// <param name="elementType">The enum type.</param>
|
||||||
|
private object ParseOne(string input, Type elementType)
|
||||||
|
{
|
||||||
|
return Enum.Parse(elementType, input, ignoreCase: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get <c>null</c> or an empty array, depending on the value of <see cref="AllowNull"/>.</summary>
|
||||||
|
/// <param name="elementType">The enum type.</param>
|
||||||
|
private Array GetNullOrEmptyArray(Type elementType)
|
||||||
|
{
|
||||||
|
return this.AllowNull
|
||||||
|
? null
|
||||||
|
: Array.CreateInstance(elementType, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Create an array of elements with the given type.</summary>
|
||||||
|
/// <param name="elements">The array elements.</param>
|
||||||
|
/// <param name="elementType">The array element type.</param>
|
||||||
|
private Array Cast(object[] elements, Type elementType)
|
||||||
|
{
|
||||||
|
if (elements == null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
Array result = Array.CreateInstance(elementType, elements.Length);
|
||||||
|
Array.Copy(elements, result, result.Length);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,126 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using StardewValley;
|
||||||
|
using xTile.Layers;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common
|
||||||
|
{
|
||||||
|
/// <summary>Provides extension methods for working with tiles.</summary>
|
||||||
|
internal static class TileHelper
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/****
|
||||||
|
** Location
|
||||||
|
****/
|
||||||
|
/// <summary>Get the tile coordinates in the game location.</summary>
|
||||||
|
/// <param name="location">The game location to search.</param>
|
||||||
|
public static IEnumerable<Vector2> GetTiles(this GameLocation location)
|
||||||
|
{
|
||||||
|
if (location?.Map?.Layers == null)
|
||||||
|
return Enumerable.Empty<Vector2>();
|
||||||
|
|
||||||
|
Layer layer = location.Map.Layers[0];
|
||||||
|
return TileHelper.GetTiles(0, 0, layer.LayerWidth, layer.LayerHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Rectangle
|
||||||
|
****/
|
||||||
|
/// <summary>Get the tile coordinates in the tile area.</summary>
|
||||||
|
/// <param name="area">The tile area to search.</param>
|
||||||
|
public static IEnumerable<Vector2> GetTiles(this Rectangle area)
|
||||||
|
{
|
||||||
|
return TileHelper.GetTiles(area.X, area.Y, area.Width, area.Height);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Expand a rectangle equally in all directions.</summary>
|
||||||
|
/// <param name="area">The rectangle to expand.</param>
|
||||||
|
/// <param name="distance">The number of tiles to add in each direction.</param>
|
||||||
|
public static Rectangle Expand(this Rectangle area, int distance)
|
||||||
|
{
|
||||||
|
return new Rectangle(area.X - distance, area.Y - distance, area.Width + distance * 2, area.Height + distance * 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Tiles
|
||||||
|
****/
|
||||||
|
/// <summary>Get the eight tiles surrounding the given tile.</summary>
|
||||||
|
/// <param name="tile">The center tile.</param>
|
||||||
|
public static IEnumerable<Vector2> GetSurroundingTiles(this Vector2 tile)
|
||||||
|
{
|
||||||
|
return Utility.getSurroundingTileLocationsArray(tile);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the tiles surrounding the given tile area.</summary>
|
||||||
|
/// <param name="area">The center tile area.</param>
|
||||||
|
public static IEnumerable<Vector2> GetSurroundingTiles(this Rectangle area)
|
||||||
|
{
|
||||||
|
for (int x = area.X - 1; x <= area.X + area.Width; x++)
|
||||||
|
{
|
||||||
|
for (int y = area.Y - 1; y <= area.Y + area.Height; y++)
|
||||||
|
{
|
||||||
|
if (!area.Contains(x, y))
|
||||||
|
yield return new Vector2(x, y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the four tiles adjacent to the given tile.</summary>
|
||||||
|
/// <param name="tile">The center tile.</param>
|
||||||
|
public static IEnumerable<Vector2> GetAdjacentTiles(this Vector2 tile)
|
||||||
|
{
|
||||||
|
return Utility.getAdjacentTileLocationsArray(tile);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get a rectangular grid of tiles.</summary>
|
||||||
|
/// <param name="x">The X coordinate of the top-left tile.</param>
|
||||||
|
/// <param name="y">The Y coordinate of the top-left tile.</param>
|
||||||
|
/// <param name="width">The grid width.</param>
|
||||||
|
/// <param name="height">The grid height.</param>
|
||||||
|
public static IEnumerable<Vector2> GetTiles(int x, int y, int width, int height)
|
||||||
|
{
|
||||||
|
for (int curX = x, maxX = x + width - 1; curX <= maxX; curX++)
|
||||||
|
{
|
||||||
|
for (int curY = y, maxY = y + height - 1; curY <= maxY; curY++)
|
||||||
|
yield return new Vector2(curX, curY);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get all tiles which are on-screen.</summary>
|
||||||
|
public static IEnumerable<Vector2> GetVisibleTiles()
|
||||||
|
{
|
||||||
|
return TileHelper.GetVisibleArea().GetTiles();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the tile area visible on-screen.</summary>
|
||||||
|
public static Rectangle GetVisibleArea()
|
||||||
|
{
|
||||||
|
return new Rectangle(
|
||||||
|
x: Game1.viewport.X / Game1.tileSize,
|
||||||
|
y: Game1.viewport.Y / Game1.tileSize,
|
||||||
|
width: (int)(Game1.viewport.Width / (decimal)Game1.tileSize) + 2, // extend off-screen slightly to avoid edges popping in
|
||||||
|
height: (int)(Game1.viewport.Height / (decimal)Game1.tileSize) + 2
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Cursor
|
||||||
|
****/
|
||||||
|
/// <summary>Get the tile under the player's cursor (not restricted to the player's grab tile range).</summary>
|
||||||
|
public static Vector2 GetTileFromCursor()
|
||||||
|
{
|
||||||
|
return TileHelper.GetTileFromScreenPosition(Game1.getMouseX(), Game1.getMouseY());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the tile at the pixel coordinate relative to the top-left corner of the screen.</summary>
|
||||||
|
/// <param name="x">The pixel X coordinate.</param>
|
||||||
|
/// <param name="y">The pixel Y coordinate.</param>
|
||||||
|
public static Vector2 GetTileFromScreenPosition(float x, float y)
|
||||||
|
{
|
||||||
|
return new Vector2((int)((Game1.viewport.X + x) / Game1.tileSize), (int)((Game1.viewport.Y + y) / Game1.tileSize));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,214 @@
|
||||||
|
using System;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using Microsoft.Xna.Framework.Graphics;
|
||||||
|
using Microsoft.Xna.Framework.Input;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
using StardewModdingAPI.Events;
|
||||||
|
using StardewValley;
|
||||||
|
using Rectangle = xTile.Dimensions.Rectangle;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.UI
|
||||||
|
{
|
||||||
|
/// <summary>An interface which supports user interaction and overlays the active menu (if any).</summary>
|
||||||
|
internal abstract class BaseOverlay : IDisposable
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The SMAPI events available for mods.</summary>
|
||||||
|
private readonly IModEvents Events;
|
||||||
|
|
||||||
|
/// <summary>An API for checking and changing input state.</summary>
|
||||||
|
protected readonly IInputHelper InputHelper;
|
||||||
|
|
||||||
|
/// <summary>The last viewport bounds.</summary>
|
||||||
|
private Rectangle LastViewport;
|
||||||
|
|
||||||
|
/// <summary>Indicates whether to keep the overlay active. If <c>null</c>, the overlay is kept until explicitly disposed.</summary>
|
||||||
|
private readonly Func<bool> KeepAliveCheck;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Release all resources.</summary>
|
||||||
|
public virtual void Dispose()
|
||||||
|
{
|
||||||
|
this.Events.Display.Rendered -= this.OnRendered;
|
||||||
|
this.Events.GameLoop.UpdateTicked -= this.OnUpdateTicked;
|
||||||
|
this.Events.Input.ButtonPressed -= this.OnButtonPressed;
|
||||||
|
this.Events.Input.CursorMoved -= this.OnCursorMoved;
|
||||||
|
this.Events.Input.MouseWheelScrolled -= this.OnMouseWheelScrolled;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Protected methods
|
||||||
|
*********/
|
||||||
|
/****
|
||||||
|
** Implementation
|
||||||
|
****/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="events">The SMAPI events available for mods.</param>
|
||||||
|
/// <param name="inputHelper">An API for checking and changing input state.</param>
|
||||||
|
/// <param name="keepAlive">Indicates whether to keep the overlay active. If <c>null</c>, the overlay is kept until explicitly disposed.</param>
|
||||||
|
protected BaseOverlay(IModEvents events, IInputHelper inputHelper, Func<bool> keepAlive = null)
|
||||||
|
{
|
||||||
|
this.Events = events;
|
||||||
|
this.InputHelper = inputHelper;
|
||||||
|
this.KeepAliveCheck = keepAlive;
|
||||||
|
this.LastViewport = new Rectangle(Game1.viewport.X, Game1.viewport.Y, Game1.viewport.Width, Game1.viewport.Height);
|
||||||
|
|
||||||
|
events.Display.Rendered += this.OnRendered;
|
||||||
|
events.GameLoop.UpdateTicked += this.OnUpdateTicked;
|
||||||
|
events.Input.ButtonPressed += this.OnButtonPressed;
|
||||||
|
events.Input.CursorMoved += this.OnCursorMoved;
|
||||||
|
events.Input.MouseWheelScrolled += this.OnMouseWheelScrolled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Draw the overlay to the screen.</summary>
|
||||||
|
/// <param name="batch">The sprite batch being drawn.</param>
|
||||||
|
protected virtual void Draw(SpriteBatch batch) { }
|
||||||
|
|
||||||
|
/// <summary>The method invoked when the player left-clicks.</summary>
|
||||||
|
/// <param name="x">The X-position of the cursor.</param>
|
||||||
|
/// <param name="y">The Y-position of the cursor.</param>
|
||||||
|
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
|
||||||
|
protected virtual bool ReceiveLeftClick(int x, int y)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The method invoked when the player presses a button.</summary>
|
||||||
|
/// <param name="input">The button that was pressed.</param>
|
||||||
|
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
|
||||||
|
protected virtual bool ReceiveButtonPress(SButton input)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The method invoked when the player uses the mouse scroll wheel.</summary>
|
||||||
|
/// <param name="amount">The scroll amount.</param>
|
||||||
|
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
|
||||||
|
protected virtual bool ReceiveScrollWheelAction(int amount)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The method invoked when the cursor is hovered.</summary>
|
||||||
|
/// <param name="x">The cursor's X position.</param>
|
||||||
|
/// <param name="y">The cursor's Y position.</param>
|
||||||
|
/// <returns>Whether the event has been handled and shouldn't be propagated further.</returns>
|
||||||
|
protected virtual bool ReceiveCursorHover(int x, int y)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The method invoked when the player resizes the game windoww.</summary>
|
||||||
|
/// <param name="oldBounds">The previous game window bounds.</param>
|
||||||
|
/// <param name="newBounds">The new game window bounds.</param>
|
||||||
|
protected virtual void ReceiveGameWindowResized(Rectangle oldBounds, Rectangle newBounds) { }
|
||||||
|
|
||||||
|
/// <summary>Draw the mouse cursor.</summary>
|
||||||
|
/// <remarks>Derived from <see cref="StardewValley.Menus.IClickableMenu.drawMouse"/>.</remarks>
|
||||||
|
protected void DrawCursor()
|
||||||
|
{
|
||||||
|
if (Game1.options.hardwareCursor)
|
||||||
|
return;
|
||||||
|
Game1.spriteBatch.Draw(Game1.mouseCursors, new Vector2(Game1.getMouseX(), Game1.getMouseY()), Game1.getSourceRectForStandardTileSheet(Game1.mouseCursors, Game1.options.SnappyMenus ? 44 : 0, 16, 16), Color.White * Game1.mouseCursorTransparency, 0.0f, Vector2.Zero, Game1.pixelZoom + Game1.dialogueButtonScale / 150f, SpriteEffects.None, 1f);
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Event listeners
|
||||||
|
****/
|
||||||
|
/// <summary>The method called when the game finishes drawing components to the screen.</summary>
|
||||||
|
/// <param name="sender">The source of the event.</param>
|
||||||
|
/// <param name="e">The event arguments.</param>
|
||||||
|
private void OnRendered(object sender, RenderedEventArgs e)
|
||||||
|
{
|
||||||
|
this.Draw(Game1.spriteBatch);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The method called once per event tick.</summary>
|
||||||
|
/// <param name="sender">The source of the event.</param>
|
||||||
|
/// <param name="e">The event arguments.</param>
|
||||||
|
private void OnUpdateTicked(object sender, UpdateTickedEventArgs e)
|
||||||
|
{
|
||||||
|
// detect end of life
|
||||||
|
if (this.KeepAliveCheck != null && !this.KeepAliveCheck())
|
||||||
|
{
|
||||||
|
this.Dispose();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// trigger window resize event
|
||||||
|
Rectangle newViewport = Game1.viewport;
|
||||||
|
if (this.LastViewport.Width != newViewport.Width || this.LastViewport.Height != newViewport.Height)
|
||||||
|
{
|
||||||
|
newViewport = new Rectangle(newViewport.X, newViewport.Y, newViewport.Width, newViewport.Height);
|
||||||
|
this.ReceiveGameWindowResized(this.LastViewport, newViewport);
|
||||||
|
this.LastViewport = newViewport;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The method invoked when the player presses a key.</summary>
|
||||||
|
/// <param name="sender">The source of the event.</param>
|
||||||
|
/// <param name="e">The event arguments.</param>
|
||||||
|
private void OnButtonPressed(object sender, ButtonPressedEventArgs e)
|
||||||
|
{
|
||||||
|
bool handled = e.Button == SButton.MouseLeft || e.Button.IsUseToolButton()
|
||||||
|
? this.ReceiveLeftClick(Game1.getMouseX(), Game1.getMouseY())
|
||||||
|
: this.ReceiveButtonPress(e.Button);
|
||||||
|
|
||||||
|
if (handled)
|
||||||
|
this.InputHelper.Suppress(e.Button);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The method invoked when the mouse wheel is scrolled.</summary>
|
||||||
|
/// <param name="sender">The source of the event.</param>
|
||||||
|
/// <param name="e">The event arguments.</param>
|
||||||
|
private void OnMouseWheelScrolled(object sender, MouseWheelScrolledEventArgs e)
|
||||||
|
{
|
||||||
|
bool scrollHandled = this.ReceiveScrollWheelAction(e.Delta);
|
||||||
|
if (scrollHandled)
|
||||||
|
{
|
||||||
|
MouseState cur = Game1.oldMouseState;
|
||||||
|
Game1.oldMouseState = new MouseState(
|
||||||
|
x: cur.X,
|
||||||
|
y: cur.Y,
|
||||||
|
scrollWheel: e.NewValue,
|
||||||
|
leftButton: cur.LeftButton,
|
||||||
|
middleButton: cur.MiddleButton,
|
||||||
|
rightButton: cur.RightButton,
|
||||||
|
xButton1: cur.XButton1,
|
||||||
|
xButton2: cur.XButton2
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The method invoked when the in-game cursor is moved.</summary>
|
||||||
|
/// <param name="sender">The source of the event.</param>
|
||||||
|
/// <param name="e">The event arguments.</param>
|
||||||
|
private void OnCursorMoved(object sender, CursorMovedEventArgs e)
|
||||||
|
{
|
||||||
|
int x = (int)e.NewPosition.ScreenPixels.X;
|
||||||
|
int y = (int)e.NewPosition.ScreenPixels.Y;
|
||||||
|
|
||||||
|
bool hoverHandled = this.ReceiveCursorHover(x, y);
|
||||||
|
if (hoverHandled)
|
||||||
|
{
|
||||||
|
MouseState cur = Game1.oldMouseState;
|
||||||
|
Game1.oldMouseState = new MouseState(
|
||||||
|
x: x,
|
||||||
|
y: y,
|
||||||
|
scrollWheel: cur.ScrollWheelValue,
|
||||||
|
leftButton: cur.LeftButton,
|
||||||
|
middleButton: cur.MiddleButton,
|
||||||
|
rightButton: cur.RightButton,
|
||||||
|
xButton1: cur.XButton1,
|
||||||
|
xButton2: cur.XButton2
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,79 @@
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using Microsoft.Xna.Framework.Graphics;
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.UI
|
||||||
|
{
|
||||||
|
/// <summary>Simplifies access to the game's sprite sheets.</summary>
|
||||||
|
/// <remarks>Each sprite is represented by a rectangle, which specifies the coordinates and dimensions of the image in the sprite sheet.</remarks>
|
||||||
|
internal static class CommonSprites
|
||||||
|
{
|
||||||
|
/// <summary>Sprites used to draw a button.</summary>
|
||||||
|
public static class Button
|
||||||
|
{
|
||||||
|
/// <summary>The sprite sheet containing the icon sprites.</summary>
|
||||||
|
public static Texture2D Sheet => Game1.mouseCursors;
|
||||||
|
|
||||||
|
/// <summary>The legend background.</summary>
|
||||||
|
public static readonly Rectangle Background = new Rectangle(297, 364, 1, 1);
|
||||||
|
|
||||||
|
/// <summary>The top border.</summary>
|
||||||
|
public static readonly Rectangle Top = new Rectangle(279, 284, 1, 4);
|
||||||
|
|
||||||
|
/// <summary>The bottom border.</summary>
|
||||||
|
public static readonly Rectangle Bottom = new Rectangle(279, 296, 1, 4);
|
||||||
|
|
||||||
|
/// <summary>The left border.</summary>
|
||||||
|
public static readonly Rectangle Left = new Rectangle(274, 289, 4, 1);
|
||||||
|
|
||||||
|
/// <summary>The right border.</summary>
|
||||||
|
public static readonly Rectangle Right = new Rectangle(286, 289, 4, 1);
|
||||||
|
|
||||||
|
/// <summary>The top-left corner.</summary>
|
||||||
|
public static readonly Rectangle TopLeft = new Rectangle(274, 284, 4, 4);
|
||||||
|
|
||||||
|
/// <summary>The top-right corner.</summary>
|
||||||
|
public static readonly Rectangle TopRight = new Rectangle(286, 284, 4, 4);
|
||||||
|
|
||||||
|
/// <summary>The bottom-left corner.</summary>
|
||||||
|
public static readonly Rectangle BottomLeft = new Rectangle(274, 296, 4, 4);
|
||||||
|
|
||||||
|
/// <summary>The bottom-right corner.</summary>
|
||||||
|
public static readonly Rectangle BottomRight = new Rectangle(286, 296, 4, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sprites used to draw a scroll.</summary>
|
||||||
|
public static class Scroll
|
||||||
|
{
|
||||||
|
/// <summary>The sprite sheet containing the icon sprites.</summary>
|
||||||
|
public static Texture2D Sheet => Game1.mouseCursors;
|
||||||
|
|
||||||
|
/// <summary>The legend background.</summary>
|
||||||
|
public static readonly Rectangle Background = new Rectangle(334, 321, 1, 1);
|
||||||
|
|
||||||
|
/// <summary>The top border.</summary>
|
||||||
|
public static readonly Rectangle Top = new Rectangle(331, 318, 1, 2);
|
||||||
|
|
||||||
|
/// <summary>The bottom border.</summary>
|
||||||
|
public static readonly Rectangle Bottom = new Rectangle(327, 334, 1, 2);
|
||||||
|
|
||||||
|
/// <summary>The left border.</summary>
|
||||||
|
public static readonly Rectangle Left = new Rectangle(325, 320, 6, 1);
|
||||||
|
|
||||||
|
/// <summary>The right border.</summary>
|
||||||
|
public static readonly Rectangle Right = new Rectangle(344, 320, 6, 1);
|
||||||
|
|
||||||
|
/// <summary>The top-left corner.</summary>
|
||||||
|
public static readonly Rectangle TopLeft = new Rectangle(325, 318, 6, 2);
|
||||||
|
|
||||||
|
/// <summary>The top-right corner.</summary>
|
||||||
|
public static readonly Rectangle TopRight = new Rectangle(344, 318, 6, 2);
|
||||||
|
|
||||||
|
/// <summary>The bottom-left corner.</summary>
|
||||||
|
public static readonly Rectangle BottomLeft = new Rectangle(325, 334, 6, 2);
|
||||||
|
|
||||||
|
/// <summary>The bottom-right corner.</summary>
|
||||||
|
public static readonly Rectangle BottomRight = new Rectangle(344, 334, 6, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,141 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Utilities
|
||||||
|
{
|
||||||
|
/// <summary>A logical collection of values defined by restriction and exclusion values which may be infinite.</summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// <para>
|
||||||
|
/// Unlike a typical collection, a constraint set doesn't necessarily track the values it contains. For
|
||||||
|
/// example, a constraint set of <see cref="uint"/> values with one exclusion only stores one number but
|
||||||
|
/// logically contains <see cref="uint.MaxValue"/> elements.
|
||||||
|
/// </para>
|
||||||
|
///
|
||||||
|
/// <para>
|
||||||
|
/// A constraint set is defined by two inner sets: <see cref="ExcludeValues"/> contains values which are
|
||||||
|
/// explicitly not part of the set, and <see cref="RestrictToValues"/> contains values which are explicitly
|
||||||
|
/// part of the set. Crucially, an empty <see cref="RestrictToValues"/> means an unbounded set (i.e. it
|
||||||
|
/// contains all possible values). If a value is part of both <see cref="ExcludeValues"/> and
|
||||||
|
/// <see cref="RestrictToValues"/>, the exclusion takes priority.
|
||||||
|
/// </para>
|
||||||
|
/// </remarks>
|
||||||
|
internal class ConstraintSet<T>
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The specific values to contain (or empty to match any value).</summary>
|
||||||
|
public HashSet<T> RestrictToValues { get; }
|
||||||
|
|
||||||
|
/// <summary>The specific values to exclude.</summary>
|
||||||
|
public HashSet<T> ExcludeValues { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the constraint set matches a finite set of values.</summary>
|
||||||
|
public bool IsBounded => this.RestrictToValues.Count != 0;
|
||||||
|
|
||||||
|
/// <summary>Get whether the constraint set logically matches an infinite set of values.</summary>
|
||||||
|
public bool IsInfinite => !this.IsBounded;
|
||||||
|
|
||||||
|
/// <summary>Whether there are any constraints placed on the set of values.</summary>
|
||||||
|
public bool IsConstrained => this.RestrictToValues.Count != 0 || this.ExcludeValues.Count != 0;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
public ConstraintSet()
|
||||||
|
: this(EqualityComparer<T>.Default) { }
|
||||||
|
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="comparer">The equality comparer to use when comparing values in the set, or <see langword="null" /> to use the default implementation for the set type.</param>
|
||||||
|
public ConstraintSet(IEqualityComparer<T> comparer)
|
||||||
|
{
|
||||||
|
this.RestrictToValues = new HashSet<T>(comparer);
|
||||||
|
this.ExcludeValues = new HashSet<T>(comparer);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bound the constraint set by adding the given value to the set of allowed values. If the constraint set is unbounded, this makes it bounded.</summary>
|
||||||
|
/// <param name="value">The value.</param>
|
||||||
|
/// <returns>Returns <c>true</c> if the value was added; else <c>false</c> if it was already present.</returns>
|
||||||
|
public bool AddBound(T value)
|
||||||
|
{
|
||||||
|
return this.RestrictToValues.Add(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bound the constraint set by adding the given values to the set of allowed values. If the constraint set is unbounded, this makes it bounded.</summary>
|
||||||
|
/// <param name="values">The values.</param>
|
||||||
|
/// <returns>Returns <c>true</c> if any value was added; else <c>false</c> if all values were already present.</returns>
|
||||||
|
public bool AddBound(IEnumerable<T> values)
|
||||||
|
{
|
||||||
|
bool anyAdded = false;
|
||||||
|
foreach (T value in values)
|
||||||
|
{
|
||||||
|
if (this.RestrictToValues.Add(value))
|
||||||
|
anyAdded = true;
|
||||||
|
}
|
||||||
|
return anyAdded;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Add values to exclude.</summary>
|
||||||
|
/// <param name="value">The value to exclude.</param>
|
||||||
|
/// <returns>Returns <c>true</c> if the value was added; else <c>false</c> if it was already present.</returns>
|
||||||
|
public bool Exclude(T value)
|
||||||
|
{
|
||||||
|
return this.ExcludeValues.Add(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Add values to exclude.</summary>
|
||||||
|
/// <param name="values">The values to exclude.</param>
|
||||||
|
/// <returns>Returns <c>true</c> if any value was added; else <c>false</c> if all values were already present.</returns>
|
||||||
|
public bool Exclude(IEnumerable<T> values)
|
||||||
|
{
|
||||||
|
bool anyAdded = false;
|
||||||
|
foreach (T value in values)
|
||||||
|
{
|
||||||
|
if (this.ExcludeValues.Add(value))
|
||||||
|
anyAdded = true;
|
||||||
|
}
|
||||||
|
return anyAdded;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get whether this constraint allows some values that would be allowed by another.</summary>
|
||||||
|
/// <param name="other">The other </param>
|
||||||
|
public bool Intersects(ConstraintSet<T> other)
|
||||||
|
{
|
||||||
|
// If both sets are unbounded, they're guaranteed to intersect since exclude can't be unbounded.
|
||||||
|
if (this.IsInfinite && other.IsInfinite)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
// if either set is bounded, they can only intersect in the included subset.
|
||||||
|
if (this.IsBounded)
|
||||||
|
{
|
||||||
|
foreach (T value in this.RestrictToValues)
|
||||||
|
{
|
||||||
|
if (this.Allows(value) && other.Allows(value))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (other.IsBounded)
|
||||||
|
{
|
||||||
|
foreach (T value in other.RestrictToValues)
|
||||||
|
{
|
||||||
|
if (other.Allows(value) && this.Allows(value))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// else no intersection
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get whether the constraints allow the given value.</summary>
|
||||||
|
/// <param name="value">The value to match.</param>
|
||||||
|
public bool Allows(T value)
|
||||||
|
{
|
||||||
|
if (this.ExcludeValues.Contains(value))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return this.IsInfinite || this.RestrictToValues.Contains(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Utilities
|
||||||
|
{
|
||||||
|
/// <summary>An implementation of <see cref="Dictionary{TKey,TValue}"/> whose keys are guaranteed to use <see cref="StringComparer.InvariantCultureIgnoreCase"/>.</summary>
|
||||||
|
internal class InvariantDictionary<TValue> : Dictionary<string, TValue>
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
public InvariantDictionary()
|
||||||
|
: base(StringComparer.InvariantCultureIgnoreCase) { }
|
||||||
|
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="values">The values to add.</param>
|
||||||
|
public InvariantDictionary(IDictionary<string, TValue> values)
|
||||||
|
: base(values, StringComparer.InvariantCultureIgnoreCase) { }
|
||||||
|
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="values">The values to add.</param>
|
||||||
|
public InvariantDictionary(IEnumerable<KeyValuePair<string, TValue>> values)
|
||||||
|
: base(StringComparer.InvariantCultureIgnoreCase)
|
||||||
|
{
|
||||||
|
foreach (var entry in values)
|
||||||
|
this.Add(entry.Key, entry.Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,32 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Utilities
|
||||||
|
{
|
||||||
|
/// <summary>An implementation of <see cref="HashSet{T}"/> for strings which always uses <see cref="StringComparer.InvariantCultureIgnoreCase"/>.</summary>
|
||||||
|
internal class InvariantHashSet : HashSet<string>
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
public InvariantHashSet()
|
||||||
|
: base(StringComparer.InvariantCultureIgnoreCase) { }
|
||||||
|
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="values">The values to add.</param>
|
||||||
|
public InvariantHashSet(IEnumerable<string> values)
|
||||||
|
: base(values, StringComparer.InvariantCultureIgnoreCase) { }
|
||||||
|
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="value">The single value to add.</param>
|
||||||
|
public InvariantHashSet(string value)
|
||||||
|
: base(new[] { value }, StringComparer.InvariantCultureIgnoreCase) { }
|
||||||
|
|
||||||
|
/// <summary>Get a hashset for boolean true/false.</summary>
|
||||||
|
public static InvariantHashSet Boolean()
|
||||||
|
{
|
||||||
|
return new InvariantHashSet(new[] { "true", "false" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
namespace Pathoschild.Stardew.Common.Utilities
|
||||||
|
{
|
||||||
|
/// <summary>A comparer which considers two references equal if they point to the same instance.</summary>
|
||||||
|
/// <typeparam name="T">The value type.</typeparam>
|
||||||
|
internal class ObjectReferenceComparer<T> : IEqualityComparer<T>
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Determines whether the specified objects are equal.</summary>
|
||||||
|
/// <returns>true if the specified objects are equal; otherwise, false.</returns>
|
||||||
|
/// <param name="x">The first object to compare.</param>
|
||||||
|
/// <param name="y">The second object to compare.</param>
|
||||||
|
public bool Equals(T x, T y)
|
||||||
|
{
|
||||||
|
return object.ReferenceEquals(x, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get a hash code for the specified object.</summary>
|
||||||
|
/// <param name="obj">The value.</param>
|
||||||
|
public int GetHashCode(T obj)
|
||||||
|
{
|
||||||
|
return RuntimeHelpers.GetHashCode(obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,271 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||||
|
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||||
|
<PropertyGroup>
|
||||||
|
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||||
|
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||||
|
<ProjectGuid>{8E1D56B0-D640-4EB0-A703-E280C40A655D}</ProjectGuid>
|
||||||
|
<OutputType>Library</OutputType>
|
||||||
|
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||||
|
<RootNamespace>ContentPatcher</RootNamespace>
|
||||||
|
<AssemblyName>ContentPatcher</AssemblyName>
|
||||||
|
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
|
||||||
|
<FileAlignment>512</FileAlignment>
|
||||||
|
<Deterministic>true</Deterministic>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||||
|
<DebugSymbols>true</DebugSymbols>
|
||||||
|
<DebugType>full</DebugType>
|
||||||
|
<Optimize>false</Optimize>
|
||||||
|
<OutputPath>bin\Debug\</OutputPath>
|
||||||
|
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||||
|
<ErrorReport>prompt</ErrorReport>
|
||||||
|
<LangVersion>7.2</LangVersion>
|
||||||
|
<WarningLevel>4</WarningLevel>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||||
|
<DebugType>pdbonly</DebugType>
|
||||||
|
<Optimize>true</Optimize>
|
||||||
|
<OutputPath>bin\Release\</OutputPath>
|
||||||
|
<DefineConstants>TRACE</DefineConstants>
|
||||||
|
<ErrorReport>prompt</ErrorReport>
|
||||||
|
<WarningLevel>4</WarningLevel>
|
||||||
|
<LangVersion>7.2</LangVersion>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="StardewModdingAPI">
|
||||||
|
<HintPath>..\assemblies\StardewModdingAPI.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="StardewValley">
|
||||||
|
<HintPath>..\assemblies\StardewValley.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="BmFont, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\BmFont.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Google.Android.Vending.Expansion.Downloader, Version=2.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Google.Android.Vending.Expansion.Downloader.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Google.Android.Vending.Expansion.ZipFile, Version=2.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Google.Android.Vending.Expansion.ZipFile.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Google.Android.Vending.Licensing, Version=2.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Google.Android.Vending.Licensing.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Java.Interop, Version=0.1.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Java.Interop.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Microsoft.AppCenter, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Microsoft.AppCenter.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Microsoft.AppCenter.Analytics, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Microsoft.AppCenter.Analytics.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Microsoft.AppCenter.Analytics.Android.Bindings, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Microsoft.AppCenter.Analytics.Android.Bindings.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Microsoft.AppCenter.Android.Bindings, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Microsoft.AppCenter.Android.Bindings.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Microsoft.AppCenter.Crashes, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Microsoft.AppCenter.Crashes.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Microsoft.AppCenter.Crashes.Android.Bindings, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Microsoft.AppCenter.Crashes.Android.Bindings.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Mono.Android.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Mono.Security, Version=2.0.5.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Mono.Security.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="MonoGame.Framework, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\MonoGame.Framework.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e">
|
||||||
|
<HintPath>..\assemblies\mscorlib.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="System, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e">
|
||||||
|
<HintPath>..\assemblies\System.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="System.Xml, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e">
|
||||||
|
<HintPath>..\assemblies\System.Xml</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||||
|
<HintPath>..\assemblies\System.Net.Http</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="System.Runtime.Serialization, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e">
|
||||||
|
<HintPath>..\assemblies\System.Runtime.Serialization</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Xamarin.Android.Arch.Core.Common, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Xamarin.Android.Arch.Core.Common.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Xamarin.Android.Arch.Lifecycle.Common, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Xamarin.Android.Arch.Lifecycle.Common.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Xamarin.Android.Arch.Lifecycle.Runtime, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Xamarin.Android.Arch.Lifecycle.Runtime.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Xamarin.Android.Support.Annotations, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Xamarin.Android.Support.Annotations.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Xamarin.Android.Support.Compat, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Xamarin.Android.Support.Compat.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Xamarin.Android.Support.Core.UI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Xamarin.Android.Support.Core.UI.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Xamarin.Android.Support.Core.Utils, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Xamarin.Android.Support.Core.Utils.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Xamarin.Android.Support.Fragment, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Xamarin.Android.Support.Fragment.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Xamarin.Android.Support.Media.Compat, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Xamarin.Android.Support.Media.Compat.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="Xamarin.Android.Support.v4, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\Xamarin.Android.Support.v4.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="xTile, Version=1.0.7033.16602, Culture=neutral, processorArchitecture=MSIL">
|
||||||
|
<SpecificVersion>False</SpecificVersion>
|
||||||
|
<HintPath>..\assemblies\xTile.dll</HintPath>
|
||||||
|
</Reference>
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="Common\CommonHelper.cs" />
|
||||||
|
<Compile Include="Common\DataParsers\CropDataParser.cs" />
|
||||||
|
<Compile Include="Common\Integrations\Automate\AutomateIntegration.cs" />
|
||||||
|
<Compile Include="Common\Integrations\Automate\IAutomateApi.cs" />
|
||||||
|
<Compile Include="Common\Integrations\BaseIntegration.cs" />
|
||||||
|
<Compile Include="Common\Integrations\BetterJunimos\BetterJunimosIntegration.cs" />
|
||||||
|
<Compile Include="Common\Integrations\BetterJunimos\IBetterJunimosApi.cs" />
|
||||||
|
<Compile Include="Common\Integrations\BetterSprinklers\BetterSprinklersIntegration.cs" />
|
||||||
|
<Compile Include="Common\Integrations\BetterSprinklers\IBetterSprinklersApi.cs" />
|
||||||
|
<Compile Include="Common\Integrations\Cobalt\CobaltIntegration.cs" />
|
||||||
|
<Compile Include="Common\Integrations\Cobalt\ICobaltApi.cs" />
|
||||||
|
<Compile Include="Common\Integrations\CustomFarmingRedux\CustomFarmingReduxIntegration.cs" />
|
||||||
|
<Compile Include="Common\Integrations\CustomFarmingRedux\ICustomFarmingApi.cs" />
|
||||||
|
<Compile Include="Common\Integrations\FarmExpansion\FarmExpansionIntegration.cs" />
|
||||||
|
<Compile Include="Common\Integrations\FarmExpansion\IFarmExpansionApi.cs" />
|
||||||
|
<Compile Include="Common\Integrations\IModIntegration.cs" />
|
||||||
|
<Compile Include="Common\Integrations\LineSprinklers\ILineSprinklersApi.cs" />
|
||||||
|
<Compile Include="Common\Integrations\LineSprinklers\LineSprinklersIntegration.cs" />
|
||||||
|
<Compile Include="Common\Integrations\PelicanFiber\PelicanFiberIntegration.cs" />
|
||||||
|
<Compile Include="Common\Integrations\PrismaticTools\IPrismaticToolsApi.cs" />
|
||||||
|
<Compile Include="Common\Integrations\PrismaticTools\PrismaticToolsIntegration.cs" />
|
||||||
|
<Compile Include="Common\Integrations\SimpleSprinkler\ISimplerSprinklerApi.cs" />
|
||||||
|
<Compile Include="Common\Integrations\SimpleSprinkler\SimpleSprinklerIntegration.cs" />
|
||||||
|
<Compile Include="Common\PathUtilities.cs" />
|
||||||
|
<Compile Include="Common\SpriteInfo.cs" />
|
||||||
|
<Compile Include="Common\StringEnumArrayConverter.cs" />
|
||||||
|
<Compile Include="Common\TileHelper.cs" />
|
||||||
|
<Compile Include="Common\UI\BaseOverlay.cs" />
|
||||||
|
<Compile Include="Common\UI\CommonSprites.cs" />
|
||||||
|
<Compile Include="Common\Utilities\ConstraintSet.cs" />
|
||||||
|
<Compile Include="Common\Utilities\InvariantDictionary.cs" />
|
||||||
|
<Compile Include="Common\Utilities\InvariantHashSet.cs" />
|
||||||
|
<Compile Include="Common\Utilities\ObjectReferenceComparer.cs" />
|
||||||
|
<Compile Include="Framework\CaseInsensitiveExtensions.cs" />
|
||||||
|
<Compile Include="Framework\Commands\CommandHandler.cs" />
|
||||||
|
<Compile Include="Framework\Commands\PatchInfo.cs" />
|
||||||
|
<Compile Include="Framework\Conditions\Condition.cs" />
|
||||||
|
<Compile Include="Framework\Conditions\ConditionDictionary.cs" />
|
||||||
|
<Compile Include="Framework\Conditions\ConditionType.cs" />
|
||||||
|
<Compile Include="Framework\Conditions\PatchType.cs" />
|
||||||
|
<Compile Include="Framework\Conditions\TokenString.cs" />
|
||||||
|
<Compile Include="Framework\Conditions\Weather.cs" />
|
||||||
|
<Compile Include="Framework\ConfigFileHandler.cs" />
|
||||||
|
<Compile Include="Framework\ConfigModels\ConfigField.cs" />
|
||||||
|
<Compile Include="Framework\ConfigModels\ConfigSchemaFieldConfig.cs" />
|
||||||
|
<Compile Include="Framework\ConfigModels\ContentConfig.cs" />
|
||||||
|
<Compile Include="Framework\ConfigModels\DynamicTokenConfig.cs" />
|
||||||
|
<Compile Include="Framework\ConfigModels\ModConfig.cs" />
|
||||||
|
<Compile Include="Framework\ConfigModels\PatchConfig.cs" />
|
||||||
|
<Compile Include="Framework\Constants\FarmCaveType.cs" />
|
||||||
|
<Compile Include="Framework\Constants\FarmType.cs" />
|
||||||
|
<Compile Include="Framework\Constants\Gender.cs" />
|
||||||
|
<Compile Include="Framework\Constants\PetType.cs" />
|
||||||
|
<Compile Include="Framework\Constants\Profession.cs" />
|
||||||
|
<Compile Include="Framework\Constants\Skill.cs" />
|
||||||
|
<Compile Include="Framework\Constants\WalletItem.cs" />
|
||||||
|
<Compile Include="Framework\DebugOverlay.cs" />
|
||||||
|
<Compile Include="Framework\GenericTokenContext.cs" />
|
||||||
|
<Compile Include="Framework\Lexing\Lexer.cs" />
|
||||||
|
<Compile Include="Framework\Lexing\LexTokens\ILexToken.cs" />
|
||||||
|
<Compile Include="Framework\Lexing\LexTokens\LexBit.cs" />
|
||||||
|
<Compile Include="Framework\Lexing\LexTokens\LexBitType.cs" />
|
||||||
|
<Compile Include="Framework\Lexing\LexTokens\LexTokenInputArg.cs" />
|
||||||
|
<Compile Include="Framework\Lexing\LexTokens\LexTokenLiteral.cs" />
|
||||||
|
<Compile Include="Framework\Lexing\LexTokens\LexTokenPipe.cs" />
|
||||||
|
<Compile Include="Framework\Lexing\LexTokens\LexTokenToken.cs" />
|
||||||
|
<Compile Include="Framework\Lexing\LexTokens\LexTokenType.cs" />
|
||||||
|
<Compile Include="Framework\ManagedContentPack.cs" />
|
||||||
|
<Compile Include="Framework\Migrations\AggregateMigration.cs" />
|
||||||
|
<Compile Include="Framework\Migrations\BaseMigration.cs" />
|
||||||
|
<Compile Include="Framework\Migrations\IMigration.cs" />
|
||||||
|
<Compile Include="Framework\Migrations\Migration_1_3.cs" />
|
||||||
|
<Compile Include="Framework\Migrations\Migration_1_4.cs" />
|
||||||
|
<Compile Include="Framework\Migrations\Migration_1_5.cs" />
|
||||||
|
<Compile Include="Framework\Migrations\Migration_1_6.cs" />
|
||||||
|
<Compile Include="Framework\ModTokenContext.cs" />
|
||||||
|
<Compile Include="Framework\Patches\DisabledPatch.cs" />
|
||||||
|
<Compile Include="Framework\Patches\EditDataPatch.cs" />
|
||||||
|
<Compile Include="Framework\Patches\EditDataPatchField.cs" />
|
||||||
|
<Compile Include="Framework\Patches\EditDataPatchRecord.cs" />
|
||||||
|
<Compile Include="Framework\Patches\EditImagePatch.cs" />
|
||||||
|
<Compile Include="Framework\Patches\IPatch.cs" />
|
||||||
|
<Compile Include="Framework\Patches\LoadPatch.cs" />
|
||||||
|
<Compile Include="Framework\Patches\Patch.cs" />
|
||||||
|
<Compile Include="Framework\PatchManager.cs" />
|
||||||
|
<Compile Include="Framework\RawContentPack.cs" />
|
||||||
|
<Compile Include="Framework\TokenManager.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\DynamicToken.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\DynamicTokenValue.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\GenericToken.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\IContext.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ImmutableToken.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\IToken.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\TokenName.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ValueProviders\BaseValueProvider.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ValueProviders\ConditionTypeValueProvider.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ValueProviders\DynamicTokenValueProvider.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ValueProviders\HasFileValueProvider.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ValueProviders\HasProfessionValueProvider.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ValueProviders\HasWalletItemValueProvider.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ValueProviders\ImmutableValueProvider.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ValueProviders\IValueProvider.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ValueProviders\SkillLevelValueProvider.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ValueProviders\VillagerHeartsValueProvider.cs" />
|
||||||
|
<Compile Include="Framework\Tokens\ValueProviders\VillagerRelationshipValueProvider.cs" />
|
||||||
|
<Compile Include="Framework\Validators\BaseValidator.cs" />
|
||||||
|
<Compile Include="Framework\Validators\IAssetValidator.cs" />
|
||||||
|
<Compile Include="Framework\Validators\StardewValley_1_3_36_Validator.cs" />
|
||||||
|
<Compile Include="ModEntry.cs" />
|
||||||
|
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||||
|
</Project>
|
|
@ -0,0 +1,52 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework
|
||||||
|
{
|
||||||
|
/// <summary>Provides case-insensitive extension methods.</summary>
|
||||||
|
internal static class CaseInsensitiveExtensions
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get the set difference of two sequences, using the invariant culture and ignoring case.</summary>
|
||||||
|
/// <param name="source">The first sequence to compare.</param>
|
||||||
|
/// <param name="other">The second sequence to compare.</param>
|
||||||
|
/// <exception cref="ArgumentNullException"><paramref name="source" /> or <paramref name="other" /> is <see langword="null" />.</exception>
|
||||||
|
public static IEnumerable<string> ExceptIgnoreCase(this IEnumerable<string> source, IEnumerable<string> other)
|
||||||
|
{
|
||||||
|
return source.Except(other, StringComparer.InvariantCultureIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Group the elements of a sequence according to a specified key selector function, comparing the keys using the invariant culture and ignoring case.</summary>
|
||||||
|
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
|
||||||
|
/// <param name="source">The sequence whose elements to group.</param>
|
||||||
|
/// <param name="keySelector">A function to extract the key for each element.</param>
|
||||||
|
/// <exception cref="ArgumentNullException"><paramref name="source" /> or <paramref name="keySelector" /> is <see langword="null" />.</exception>
|
||||||
|
public static IEnumerable<IGrouping<string, TSource>> GroupByIgnoreCase<TSource>(this IEnumerable<TSource> source, Func<TSource, string> keySelector)
|
||||||
|
{
|
||||||
|
return source.GroupBy(keySelector, StringComparer.InvariantCultureIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sort the elements of a sequence in ascending order by using a specified comparer.</summary>
|
||||||
|
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
|
||||||
|
/// <param name="source">A sequence of values to order.</param>
|
||||||
|
/// <param name="keySelector">A function to extract a key from an element.</param>
|
||||||
|
/// <exception cref="ArgumentNullException"><paramref name="source" /> or <paramref name="keySelector" /> is <see langword="null" />.</exception>
|
||||||
|
public static IOrderedEnumerable<TSource> OrderByIgnoreCase<TSource>(this IEnumerable<TSource> source, Func<TSource, string> keySelector)
|
||||||
|
{
|
||||||
|
return source.OrderBy(keySelector, StringComparer.InvariantCultureIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Perform a subsequent ordering of the elements in a sequence in ascending order according to a key.</summary>
|
||||||
|
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
|
||||||
|
/// <param name="source">The sequence whose elements to group.</param>
|
||||||
|
/// <param name="keySelector">A function to extract the key for each element.</param>
|
||||||
|
/// <exception cref="ArgumentNullException"><paramref name="source" /> or <paramref name="keySelector" /> is <see langword="null" />.</exception>
|
||||||
|
public static IOrderedEnumerable<TSource> ThenByIgnoreCase<TSource>(this IOrderedEnumerable<TSource> source, Func<TSource, string> keySelector)
|
||||||
|
{
|
||||||
|
return source.ThenBy(keySelector, StringComparer.InvariantCultureIgnoreCase);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,356 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.Patches;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Commands
|
||||||
|
{
|
||||||
|
/// <summary>Handles the 'patch' console command.</summary>
|
||||||
|
internal class CommandHandler
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>Encapsulates monitoring and logging.</summary>
|
||||||
|
private readonly IMonitor Monitor;
|
||||||
|
|
||||||
|
/// <summary>Manages loaded tokens.</summary>
|
||||||
|
private readonly TokenManager TokenManager;
|
||||||
|
|
||||||
|
/// <summary>Manages loaded patches.</summary>
|
||||||
|
private readonly PatchManager PatchManager;
|
||||||
|
|
||||||
|
/// <summary>A callback which immediately updates the current condition context.</summary>
|
||||||
|
private readonly Action UpdateContext;
|
||||||
|
|
||||||
|
/// <summary>A regex pattern matching asset names which incorrectly include the Content folder.</summary>
|
||||||
|
private readonly Regex AssetNameWithContentPattern = new Regex(@"^Content[/\\]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||||
|
|
||||||
|
/// <summary>A regex pattern matching asset names which incorrectly include an extension.</summary>
|
||||||
|
private readonly Regex AssetNameWithExtensionPattern = new Regex(@"(\.\w+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||||
|
|
||||||
|
/// <summary>A regex pattern matching asset names which incorrectly include the locale code.</summary>
|
||||||
|
private readonly Regex AssetNameWithLocalePattern = new Regex(@"^\.(?:de-DE|es-ES|ja-JP|pt-BR|ru-RU|zh-CN)(?:\.xnb)?$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The name of the root command.</summary>
|
||||||
|
public string CommandName { get; } = "patch";
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="tokenManager">Manages loaded tokens.</param>
|
||||||
|
/// <param name="patchManager">Manages loaded patches.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
/// <param name="updateContext">A callback which immediately updates the current condition context.</param>
|
||||||
|
public CommandHandler(TokenManager tokenManager, PatchManager patchManager, IMonitor monitor, Action updateContext)
|
||||||
|
{
|
||||||
|
this.TokenManager = tokenManager;
|
||||||
|
this.PatchManager = patchManager;
|
||||||
|
this.Monitor = monitor;
|
||||||
|
this.UpdateContext = updateContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Handle a console command.</summary>
|
||||||
|
/// <param name="args">The command arguments.</param>
|
||||||
|
/// <returns>Returns whether the command was handled.</returns>
|
||||||
|
public bool Handle(string[] args)
|
||||||
|
{
|
||||||
|
string subcommand = args.FirstOrDefault();
|
||||||
|
string[] subcommandArgs = args.Skip(1).ToArray();
|
||||||
|
|
||||||
|
switch (subcommand?.ToLower())
|
||||||
|
{
|
||||||
|
case null:
|
||||||
|
case "help":
|
||||||
|
return this.HandleHelp(subcommandArgs);
|
||||||
|
|
||||||
|
case "summary":
|
||||||
|
return this.HandleSummary();
|
||||||
|
|
||||||
|
case "update":
|
||||||
|
return this.HandleUpdate();
|
||||||
|
|
||||||
|
default:
|
||||||
|
this.Monitor.Log($"The '{this.CommandName} {args[0]}' command isn't valid. Type '{this.CommandName} help' for a list of valid commands.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/****
|
||||||
|
** Commands
|
||||||
|
****/
|
||||||
|
/// <summary>Handle the 'patch help' command.</summary>
|
||||||
|
/// <param name="args">The subcommand arguments.</param>
|
||||||
|
/// <returns>Returns whether the command was handled.</returns>
|
||||||
|
private bool HandleHelp(string[] args)
|
||||||
|
{
|
||||||
|
// generate command info
|
||||||
|
var helpEntries = new InvariantDictionary<string>
|
||||||
|
{
|
||||||
|
["help"] = $"{this.CommandName} help\n Usage: {this.CommandName} help\n Lists all available {this.CommandName} commands.\n\n Usage: {this.CommandName} help <cmd>\n Provides information for a specific {this.CommandName} command.\n - cmd: The {this.CommandName} command name.",
|
||||||
|
["summary"] = $"{this.CommandName} summary\n Usage: {this.CommandName} summary\n Shows a summary of the current conditions and loaded patches.",
|
||||||
|
["update"] = $"{this.CommandName} update\n Usage: {this.CommandName} update\n Imediately refreshes the condition context and rechecks all patches."
|
||||||
|
};
|
||||||
|
|
||||||
|
// build output
|
||||||
|
StringBuilder help = new StringBuilder();
|
||||||
|
if (!args.Any())
|
||||||
|
{
|
||||||
|
help.AppendLine(
|
||||||
|
$"The '{this.CommandName}' command is the entry point for Content Patcher commands. These are "
|
||||||
|
+ "intended for troubleshooting and aren't intended for players. You use it by specifying a more "
|
||||||
|
+ $"specific command (like 'help' in '{this.CommandName} help'). Here are the available commands:\n\n"
|
||||||
|
);
|
||||||
|
foreach (var entry in helpEntries.OrderByIgnoreCase(p => p.Key))
|
||||||
|
{
|
||||||
|
help.AppendLine(entry.Value);
|
||||||
|
help.AppendLine();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (helpEntries.TryGetValue(args[0], out string entry))
|
||||||
|
help.AppendLine(entry);
|
||||||
|
else
|
||||||
|
help.AppendLine($"Unknown command '{this.CommandName} {args[0]}'. Type '{this.CommandName} help' for available commands.");
|
||||||
|
|
||||||
|
// write output
|
||||||
|
this.Monitor.Log(help.ToString());
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Handle the 'patch summary' command.</summary>
|
||||||
|
/// <returns>Returns whether the command was handled.</returns>
|
||||||
|
private bool HandleSummary()
|
||||||
|
{
|
||||||
|
StringBuilder output = new StringBuilder();
|
||||||
|
|
||||||
|
// add condition summary
|
||||||
|
output.AppendLine();
|
||||||
|
output.AppendLine("=====================");
|
||||||
|
output.AppendLine("== Global tokens ==");
|
||||||
|
output.AppendLine("=====================");
|
||||||
|
{
|
||||||
|
// get data
|
||||||
|
IToken[] tokens =
|
||||||
|
(
|
||||||
|
from token in this.TokenManager.GetTokens(enforceContext: false)
|
||||||
|
let subkeys = token.GetSubkeys().ToArray()
|
||||||
|
let rootValues = !token.RequiresSubkeys ? token.GetValues(token.Name).ToArray() : new string[0]
|
||||||
|
let multiValue =
|
||||||
|
subkeys.Length > 1
|
||||||
|
|| rootValues.Length > 1
|
||||||
|
|| (subkeys.Length == 1 && token.GetValues(subkeys[0]).Count() > 1)
|
||||||
|
orderby multiValue, token.Name.Key // single-value tokens first, then alphabetically
|
||||||
|
select token
|
||||||
|
)
|
||||||
|
.ToArray();
|
||||||
|
int labelWidth = tokens.Max(p => p.Name.Key.Length);
|
||||||
|
|
||||||
|
// print table header
|
||||||
|
output.AppendLine($" {"token name".PadRight(labelWidth)} | value");
|
||||||
|
output.AppendLine($" {"".PadRight(labelWidth, '-')} | -----");
|
||||||
|
|
||||||
|
// print tokens
|
||||||
|
foreach (IToken token in tokens)
|
||||||
|
{
|
||||||
|
output.Append($" {token.Name.Key.PadRight(labelWidth)} | ");
|
||||||
|
|
||||||
|
if (!token.IsValidInContext)
|
||||||
|
output.AppendLine("[ ] n/a");
|
||||||
|
else if (token.RequiresSubkeys)
|
||||||
|
{
|
||||||
|
bool isFirst = true;
|
||||||
|
foreach (TokenName name in token.GetSubkeys().OrderByIgnoreCase(key => key.Subkey))
|
||||||
|
{
|
||||||
|
if (isFirst)
|
||||||
|
{
|
||||||
|
output.Append("[X] ");
|
||||||
|
isFirst = false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
output.Append($" {"".PadRight(labelWidth, ' ')} | ");
|
||||||
|
output.AppendLine($":{name.Subkey}: {string.Join(", ", token.GetValues(name))}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
output.AppendLine("[X] " + string.Join(", ", token.GetValues(token.Name).OrderByIgnoreCase(p => p)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
output.AppendLine();
|
||||||
|
|
||||||
|
// add patch summary
|
||||||
|
var patches = this.GetAllPatches()
|
||||||
|
.GroupByIgnoreCase(p => p.ContentPack.Manifest.Name)
|
||||||
|
.OrderByIgnoreCase(p => p.Key);
|
||||||
|
|
||||||
|
output.AppendLine(
|
||||||
|
"=====================\n"
|
||||||
|
+ "== Content patches ==\n"
|
||||||
|
+ "=====================\n"
|
||||||
|
+ "The following patches were loaded. For each patch:\n"
|
||||||
|
+ " - 'loaded' shows whether the patch is loaded and enabled (see details for the reason if not).\n"
|
||||||
|
+ " - 'conditions' shows whether the patch matches with the current conditions (see details for the reason if not). If this is unexpectedly false, check (a) the conditions above and (b) your Where field.\n"
|
||||||
|
+ " - 'applied' shows whether the target asset was loaded and patched. If you expected it to be loaded by this point but it's false, double-check (a) that the game has actually loaded the asset yet, and (b) your Targets field is correct.\n"
|
||||||
|
+ "\n"
|
||||||
|
);
|
||||||
|
foreach (IGrouping<string, PatchInfo> patchGroup in patches)
|
||||||
|
{
|
||||||
|
ModTokenContext tokenContext = this.TokenManager.TrackLocalTokens(patchGroup.First().ContentPack.Pack);
|
||||||
|
output.AppendLine($"{patchGroup.Key}:");
|
||||||
|
output.AppendLine("".PadRight(patchGroup.Key.Length + 1, '-'));
|
||||||
|
|
||||||
|
// print tokens
|
||||||
|
{
|
||||||
|
IToken[] localTokens = tokenContext
|
||||||
|
.GetTokens(localOnly: true, enforceContext: false)
|
||||||
|
.Where(p => p.Name.Key != ConditionType.HasFile.ToString()) // no value to display
|
||||||
|
.ToArray();
|
||||||
|
if (localTokens.Any())
|
||||||
|
{
|
||||||
|
output.AppendLine();
|
||||||
|
output.AppendLine(" Local tokens:");
|
||||||
|
foreach (IToken token in localTokens.OrderBy(p => p.Name))
|
||||||
|
{
|
||||||
|
if (token.RequiresSubkeys)
|
||||||
|
{
|
||||||
|
foreach (TokenName name in token.GetSubkeys().OrderBy(p => p))
|
||||||
|
output.AppendLine($" {name}: {string.Join(", ", token.GetValues(name))}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
output.AppendLine($" {token.Name}: {string.Join(", ", token.GetValues(token.Name))}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// print patches
|
||||||
|
output.AppendLine();
|
||||||
|
output.AppendLine(" loaded | conditions | applied | name + details");
|
||||||
|
output.AppendLine(" ------- | ---------- | ------- | --------------");
|
||||||
|
foreach (PatchInfo patch in patchGroup.OrderByIgnoreCase(p => p.ShortName))
|
||||||
|
{
|
||||||
|
// log checkbox and patch name
|
||||||
|
output.Append($" [{(patch.IsLoaded ? "X" : " ")}] | [{(patch.MatchesContext ? "X" : " ")}] | [{(patch.IsApplied ? "X" : " ")}] | {patch.ShortName}");
|
||||||
|
|
||||||
|
// log raw target (if not in name)
|
||||||
|
if (!patch.ShortName.Contains($"{patch.Type} {patch.RawTargetAsset}"))
|
||||||
|
output.Append($" | {patch.Type} {patch.RawTargetAsset}");
|
||||||
|
|
||||||
|
// log parsed target if tokenised
|
||||||
|
if (patch.MatchesContext && patch.ParsedTargetAsset != null && patch.ParsedTargetAsset.Tokens.Any())
|
||||||
|
output.Append($" | => {patch.ParsedTargetAsset.Value}");
|
||||||
|
|
||||||
|
// log reason not applied
|
||||||
|
string errorReason = this.GetReasonNotLoaded(patch, tokenContext);
|
||||||
|
if (errorReason != null)
|
||||||
|
output.Append($" // {errorReason}");
|
||||||
|
|
||||||
|
// log common issues
|
||||||
|
if (errorReason == null && patch.IsLoaded && !patch.IsApplied && patch.ParsedTargetAsset?.Value != null)
|
||||||
|
{
|
||||||
|
string assetName = patch.ParsedTargetAsset.Value;
|
||||||
|
|
||||||
|
List<string> issues = new List<string>();
|
||||||
|
if (this.AssetNameWithContentPattern.IsMatch(assetName))
|
||||||
|
issues.Add("shouldn't include 'Content/' prefix");
|
||||||
|
if (this.AssetNameWithExtensionPattern.IsMatch(assetName))
|
||||||
|
{
|
||||||
|
var match = this.AssetNameWithExtensionPattern.Match(assetName);
|
||||||
|
issues.Add($"shouldn't include '{match.Captures[0]}' extension");
|
||||||
|
}
|
||||||
|
if (this.AssetNameWithLocalePattern.IsMatch(assetName))
|
||||||
|
issues.Add("shouldn't include language code (use conditions instead)");
|
||||||
|
|
||||||
|
if (issues.Any())
|
||||||
|
output.Append($" | hint: asset name may be incorrect ({string.Join("; ", issues)}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
// end line
|
||||||
|
output.AppendLine();
|
||||||
|
}
|
||||||
|
output.AppendLine(); // blank line between groups
|
||||||
|
}
|
||||||
|
|
||||||
|
this.Monitor.Log(output.ToString());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Handle the 'patch update' command.</summary>
|
||||||
|
/// <returns>Returns whether the command was handled.</returns>
|
||||||
|
private bool HandleUpdate()
|
||||||
|
{
|
||||||
|
this.UpdateContext();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Helpers
|
||||||
|
****/
|
||||||
|
/// <summary>Get basic info about all patches, including those which couldn't be loaded.</summary>
|
||||||
|
public IEnumerable<PatchInfo> GetAllPatches()
|
||||||
|
{
|
||||||
|
foreach (IPatch patch in this.PatchManager.GetPatches())
|
||||||
|
yield return new PatchInfo(patch);
|
||||||
|
foreach (DisabledPatch patch in this.PatchManager.GetPermanentlyDisabledPatches())
|
||||||
|
yield return new PatchInfo(patch);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get a human-readable reason that the patch isn't applied.</summary>
|
||||||
|
/// <param name="patch">The patch to check.</param>
|
||||||
|
/// <param name="tokenContext">The token context for the content pack.</param>
|
||||||
|
private string GetReasonNotLoaded(PatchInfo patch, IContext tokenContext)
|
||||||
|
{
|
||||||
|
if (patch.IsApplied)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
// load error
|
||||||
|
if (!patch.IsLoaded)
|
||||||
|
return $"not loaded: {patch.ReasonDisabled}";
|
||||||
|
|
||||||
|
// uses tokens not available in the current context
|
||||||
|
{
|
||||||
|
IList<TokenName> tokensOutOfContext = patch
|
||||||
|
.TokensUsed
|
||||||
|
.Union(patch.ParsedConditions.Keys)
|
||||||
|
.Where(p => !tokenContext.GetToken(p, enforceContext: false).IsValidInContext)
|
||||||
|
.OrderByIgnoreCase(p => p.ToString())
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
if (tokensOutOfContext.Any())
|
||||||
|
return $"uses tokens not available right now: {string.Join(", ", tokensOutOfContext)}";
|
||||||
|
}
|
||||||
|
|
||||||
|
// conditions not matched
|
||||||
|
if (!patch.MatchesContext && patch.ParsedConditions != null)
|
||||||
|
{
|
||||||
|
string[] failedConditions = (
|
||||||
|
from condition in patch.ParsedConditions.Values
|
||||||
|
orderby condition.Name.ToString()
|
||||||
|
where !condition.IsMatch(tokenContext)
|
||||||
|
select $"{condition.Name} ({string.Join(", ", condition.Values)})"
|
||||||
|
).ToArray();
|
||||||
|
|
||||||
|
if (failedConditions.Any())
|
||||||
|
return $"conditions don't match: {string.Join(", ", failedConditions)}";
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,99 @@
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.Patches;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Commands
|
||||||
|
{
|
||||||
|
/// <summary>A summary of patch info shown in the SMAPI console.</summary>
|
||||||
|
internal class PatchInfo
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The patch name shown in log messages, without the content pack prefix.</summary>
|
||||||
|
public string ShortName { get; }
|
||||||
|
|
||||||
|
/// <summary>The patch type.</summary>
|
||||||
|
public string Type { get; }
|
||||||
|
|
||||||
|
/// <summary>The asset name to intercept.</summary>
|
||||||
|
public string RawTargetAsset { get; }
|
||||||
|
|
||||||
|
/// <summary>The parsed asset name (if available).</summary>
|
||||||
|
public TokenString ParsedTargetAsset { get; }
|
||||||
|
|
||||||
|
/// <summary>The parsed conditions (if available).</summary>
|
||||||
|
public ConditionDictionary ParsedConditions { get; }
|
||||||
|
|
||||||
|
/// <summary>The content pack which requested the patch.</summary>
|
||||||
|
public ManagedContentPack ContentPack { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the patch is loaded.</summary>
|
||||||
|
public bool IsLoaded { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the patch should be applied in the current context.</summary>
|
||||||
|
public bool MatchesContext { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the patch is currently applied.</summary>
|
||||||
|
public bool IsApplied { get; }
|
||||||
|
|
||||||
|
/// <summary>The reason this patch is disabled (if applicable).</summary>
|
||||||
|
public string ReasonDisabled { get; }
|
||||||
|
|
||||||
|
/// <summary>The tokens used by this patch in its fields.</summary>
|
||||||
|
public TokenName[] TokensUsed { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="patch">The patch to represent.</param>
|
||||||
|
public PatchInfo(DisabledPatch patch)
|
||||||
|
{
|
||||||
|
this.ShortName = this.GetShortName(patch.ContentPack, patch.LogName);
|
||||||
|
this.Type = patch.Type;
|
||||||
|
this.RawTargetAsset = patch.AssetName;
|
||||||
|
this.ParsedTargetAsset = null;
|
||||||
|
this.ParsedConditions = null;
|
||||||
|
this.ContentPack = patch.ContentPack;
|
||||||
|
this.IsLoaded = false;
|
||||||
|
this.MatchesContext = false;
|
||||||
|
this.IsApplied = false;
|
||||||
|
this.ReasonDisabled = patch.ReasonDisabled;
|
||||||
|
this.TokensUsed = new TokenName[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="patch">The patch to represent.</param>
|
||||||
|
public PatchInfo(IPatch patch)
|
||||||
|
{
|
||||||
|
this.ShortName = this.GetShortName(patch.ContentPack, patch.LogName);
|
||||||
|
this.Type = patch.Type.ToString();
|
||||||
|
this.RawTargetAsset = patch.RawTargetAsset.Raw;
|
||||||
|
this.ParsedTargetAsset = patch.RawTargetAsset;
|
||||||
|
this.ParsedConditions = patch.Conditions;
|
||||||
|
this.ContentPack = patch.ContentPack;
|
||||||
|
this.IsLoaded = true;
|
||||||
|
this.MatchesContext = patch.MatchesContext;
|
||||||
|
this.IsApplied = patch.IsApplied;
|
||||||
|
this.TokensUsed = patch.GetTokensUsed().ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get the patch name shown in log messages, without the content pack prefix.</summary>
|
||||||
|
/// <param name="contentPack">The content pack which requested the patch.</param>
|
||||||
|
/// <param name="logName">The unique patch name shown in log messages.</param>
|
||||||
|
private string GetShortName(ManagedContentPack contentPack, string logName)
|
||||||
|
{
|
||||||
|
string prefix = contentPack.Manifest.Name + " > ";
|
||||||
|
return logName.StartsWith(prefix)
|
||||||
|
? logName.Substring(prefix.Length)
|
||||||
|
: logName;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,41 @@
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Conditions
|
||||||
|
{
|
||||||
|
/// <summary>A condition that can be checked against the token context.</summary>
|
||||||
|
internal class Condition
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The token name in the context.</summary>
|
||||||
|
public TokenName Name { get; }
|
||||||
|
|
||||||
|
/// <summary>The token values for which this condition is valid.</summary>
|
||||||
|
public InvariantHashSet Values { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="name">The token name in the context.</param>
|
||||||
|
/// <param name="values">The token values for which this condition is valid.</param>
|
||||||
|
public Condition(TokenName name, InvariantHashSet values)
|
||||||
|
{
|
||||||
|
this.Name = name;
|
||||||
|
this.Values = values;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether the condition matches.</summary>
|
||||||
|
/// <param name="context">The condition context.</param>
|
||||||
|
public bool IsMatch(IContext context)
|
||||||
|
{
|
||||||
|
return context
|
||||||
|
.GetValues(this.Name, enforceContext: true)
|
||||||
|
.Any(value => this.Values.Contains(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Conditions
|
||||||
|
{
|
||||||
|
/// <summary>A set of conditions that can be checked against the context.</summary>
|
||||||
|
internal class ConditionDictionary : Dictionary<TokenName, Condition>
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Add an element with the given key and condition values.</summary>
|
||||||
|
/// <param name="name">The token name to add.</param>
|
||||||
|
/// <param name="values">The token values to match.</param>
|
||||||
|
public void Add(TokenName name, IEnumerable<string> values)
|
||||||
|
{
|
||||||
|
this.Add(name, new Condition(name, new InvariantHashSet(values)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,93 @@
|
||||||
|
namespace ContentPatcher.Framework.Conditions
|
||||||
|
{
|
||||||
|
/// <summary>The condition types that can be checked.</summary>
|
||||||
|
internal enum ConditionType
|
||||||
|
{
|
||||||
|
/****
|
||||||
|
** Tokenisable basic conditions
|
||||||
|
****/
|
||||||
|
/// <summary>The day of month.</summary>
|
||||||
|
Day,
|
||||||
|
|
||||||
|
/// <summary>The <see cref="System.DayOfWeek"/> name.</summary>
|
||||||
|
DayOfWeek,
|
||||||
|
|
||||||
|
/// <summary>The total number of days played in the current save.</summary>
|
||||||
|
DaysPlayed,
|
||||||
|
|
||||||
|
/// <summary>The farm cave type.</summary>
|
||||||
|
FarmCave,
|
||||||
|
|
||||||
|
/// <summary>The upgrade level for the main farmhouse.</summary>
|
||||||
|
FarmhouseUpgrade,
|
||||||
|
|
||||||
|
/// <summary>The current farm name.</summary>
|
||||||
|
FarmName,
|
||||||
|
|
||||||
|
/// <summary>The current farm type.</summary>
|
||||||
|
FarmType,
|
||||||
|
|
||||||
|
/// <summary>The <see cref="StardewValley.LocalizedContentManager.LanguageCode"/> name.</summary>
|
||||||
|
Language,
|
||||||
|
|
||||||
|
/// <summary>The name of the current player.</summary>
|
||||||
|
PlayerName,
|
||||||
|
|
||||||
|
/// <summary>The gender of the current player.</summary>
|
||||||
|
PlayerGender,
|
||||||
|
|
||||||
|
/// <summary>The preferred pet selected by the player.</summary>
|
||||||
|
PreferredPet,
|
||||||
|
|
||||||
|
/// <summary>The season name.</summary>
|
||||||
|
Season,
|
||||||
|
|
||||||
|
/// <summary>The current weather.</summary>
|
||||||
|
Weather,
|
||||||
|
|
||||||
|
/// <summary>The current year number.</summary>
|
||||||
|
Year,
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Other basic conditions
|
||||||
|
****/
|
||||||
|
/// <summary>The name of today's festival (if any), or 'wedding' if the current player is getting married.</summary>
|
||||||
|
DayEvent,
|
||||||
|
|
||||||
|
/// <summary>A letter ID or mail flag set for the player.</summary>
|
||||||
|
HasFlag,
|
||||||
|
|
||||||
|
/// <summary>An installed mod ID.</summary>
|
||||||
|
HasMod,
|
||||||
|
|
||||||
|
/// <summary>A profession ID the player has.</summary>
|
||||||
|
HasProfession,
|
||||||
|
|
||||||
|
/// <summary>An event ID the player saw.</summary>
|
||||||
|
HasSeenEvent,
|
||||||
|
|
||||||
|
/// <summary>The special items in the player's wallet.</summary>
|
||||||
|
HasWalletItem,
|
||||||
|
|
||||||
|
/// <summary>The current player's internal spouse name (if any).</summary>
|
||||||
|
Spouse,
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Multi-part conditions
|
||||||
|
****/
|
||||||
|
/// <summary>The current player's number of hearts with the character.</summary>
|
||||||
|
Hearts,
|
||||||
|
|
||||||
|
/// <summary>The current player's relationship status with the character (matching <see cref="StardewValley.FriendshipStatus"/>)</summary>
|
||||||
|
Relationship,
|
||||||
|
|
||||||
|
/// <summary>The current player's level for a skill.</summary>
|
||||||
|
SkillLevel,
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Magic conditions
|
||||||
|
****/
|
||||||
|
/// <summary>Whether a file exists in the content pack's folder.</summary>
|
||||||
|
HasFile
|
||||||
|
};
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
namespace ContentPatcher.Framework.Conditions
|
||||||
|
{
|
||||||
|
/// <summary>The patch type.</summary>
|
||||||
|
internal enum PatchType
|
||||||
|
{
|
||||||
|
/// <summary>Load the initial version of the file.</summary>
|
||||||
|
Load,
|
||||||
|
|
||||||
|
/// <summary>Edit an image.</summary>
|
||||||
|
EditImage,
|
||||||
|
|
||||||
|
/// <summary>Edit a data file.</summary>
|
||||||
|
EditData
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,144 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using ContentPatcher.Framework.Lexing;
|
||||||
|
using ContentPatcher.Framework.Lexing.LexTokens;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Conditions
|
||||||
|
{
|
||||||
|
/// <summary>A string value which can contain condition tokens.</summary>
|
||||||
|
internal class TokenString
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The lexical tokens parsed from the raw string.</summary>
|
||||||
|
private readonly ILexToken[] LexTokens;
|
||||||
|
|
||||||
|
/// <summary>The underlying value for <see cref="Value"/>.</summary>
|
||||||
|
private string ValueImpl;
|
||||||
|
|
||||||
|
/// <summary>The underlying value for <see cref="IsReady"/>.</summary>
|
||||||
|
private bool IsReadyImpl;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The raw string without token substitution.</summary>
|
||||||
|
public string Raw { get; }
|
||||||
|
|
||||||
|
/// <summary>The tokens used in the string.</summary>
|
||||||
|
public HashSet<TokenName> Tokens { get; } = new HashSet<TokenName>();
|
||||||
|
|
||||||
|
/// <summary>The unrecognised tokens in the string.</summary>
|
||||||
|
public InvariantHashSet InvalidTokens { get; } = new InvariantHashSet();
|
||||||
|
|
||||||
|
/// <summary>Whether the string contains any tokens (including invalid tokens).</summary>
|
||||||
|
public bool HasAnyTokens => this.Tokens.Count > 0 || this.InvalidTokens.Count > 0;
|
||||||
|
|
||||||
|
/// <summary>Whether the token string value may change depending on the context.</summary>
|
||||||
|
public bool IsMutable { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the token string consists of a single token with no surrounding text.</summary>
|
||||||
|
public bool IsSingleTokenOnly { get; }
|
||||||
|
|
||||||
|
/// <summary>The string with tokens substituted for the last context update.</summary>
|
||||||
|
public string Value => this.ValueImpl;
|
||||||
|
|
||||||
|
/// <summary>Whether all tokens in the value have been replaced.</summary>
|
||||||
|
public bool IsReady => this.IsReadyImpl;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="raw">The raw string before token substitution.</param>
|
||||||
|
/// <param name="tokenContext">The available token context.</param>
|
||||||
|
public TokenString(string raw, IContext tokenContext)
|
||||||
|
{
|
||||||
|
// set raw value
|
||||||
|
this.Raw = raw?.Trim();
|
||||||
|
if (string.IsNullOrWhiteSpace(this.Raw))
|
||||||
|
{
|
||||||
|
this.ValueImpl = this.Raw;
|
||||||
|
this.IsReadyImpl = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// extract tokens
|
||||||
|
this.LexTokens = new Lexer().ParseBits(raw, impliedBraces: false).ToArray();
|
||||||
|
foreach (LexTokenToken token in this.LexTokens.OfType<LexTokenToken>())
|
||||||
|
{
|
||||||
|
TokenName name = new TokenName(token.Name, token.InputArg?.Text);
|
||||||
|
if (tokenContext.Contains(name, enforceContext: false))
|
||||||
|
this.Tokens.Add(name);
|
||||||
|
else
|
||||||
|
this.InvalidTokens.Add(token.Text);
|
||||||
|
}
|
||||||
|
|
||||||
|
// set metadata
|
||||||
|
this.IsMutable = this.Tokens.Any();
|
||||||
|
if (!this.IsMutable)
|
||||||
|
{
|
||||||
|
this.ValueImpl = this.Raw;
|
||||||
|
this.IsReadyImpl = !this.InvalidTokens.Any();
|
||||||
|
}
|
||||||
|
this.IsSingleTokenOnly = this.LexTokens.Length == 1 && this.LexTokens.First().Type == LexTokenType.Token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Update the <see cref="Value"/> with the given tokens.</summary>
|
||||||
|
/// <param name="context">Provides access to contextual tokens.</param>
|
||||||
|
/// <returns>Returns whether the value changed.</returns>
|
||||||
|
public bool UpdateContext(IContext context)
|
||||||
|
{
|
||||||
|
if (!this.IsMutable)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
string prevValue = this.Value;
|
||||||
|
this.GetApplied(context, out this.ValueImpl, out this.IsReadyImpl);
|
||||||
|
return this.Value != prevValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get a new string with tokens substituted.</summary>
|
||||||
|
/// <param name="context">Provides access to contextual tokens.</param>
|
||||||
|
/// <param name="result">The input string with tokens substituted.</param>
|
||||||
|
/// <param name="isReady">Whether all tokens in the <paramref name="result"/> have been replaced.</param>
|
||||||
|
private void GetApplied(IContext context, out string result, out bool isReady)
|
||||||
|
{
|
||||||
|
bool allReplaced = true;
|
||||||
|
StringBuilder str = new StringBuilder();
|
||||||
|
foreach (ILexToken lexToken in this.LexTokens)
|
||||||
|
{
|
||||||
|
switch (lexToken)
|
||||||
|
{
|
||||||
|
case LexTokenToken lexTokenToken:
|
||||||
|
TokenName name = new TokenName(lexTokenToken.Name, lexTokenToken.InputArg?.Text);
|
||||||
|
IToken token = context.GetToken(name, enforceContext: true);
|
||||||
|
if (token != null)
|
||||||
|
str.Append(token.GetValues(name).FirstOrDefault());
|
||||||
|
else
|
||||||
|
{
|
||||||
|
allReplaced = false;
|
||||||
|
str.Append(lexToken.Text);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
str.Append(lexToken.Text);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result = str.ToString();
|
||||||
|
isReady = allReplaced;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
namespace ContentPatcher.Framework.Conditions
|
||||||
|
{
|
||||||
|
/// <summary>An in-game weather.</summary>
|
||||||
|
internal enum Weather
|
||||||
|
{
|
||||||
|
/// <summary>The weather is sunny (including festival/wedding days). This is the default weather if no other value applies.</summary>
|
||||||
|
Sun,
|
||||||
|
|
||||||
|
/// <summary>Rain is falling, but without lightning.</summary>
|
||||||
|
Rain,
|
||||||
|
|
||||||
|
/// <summary>Rain is falling with lightning.</summary>
|
||||||
|
Storm,
|
||||||
|
|
||||||
|
/// <summary>Snow is falling.</summary>
|
||||||
|
Snow,
|
||||||
|
|
||||||
|
/// <summary>The wind is blowing with visible debris (e.g. flower petals in spring and leaves in fall).</summary>
|
||||||
|
Wind
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,206 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.ConfigModels;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework
|
||||||
|
{
|
||||||
|
/// <summary>Handles the logic for reading, normalising, and saving the configuration for a content pack.</summary>
|
||||||
|
internal class ConfigFileHandler
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The name of the config file.</summary>
|
||||||
|
private readonly string Filename;
|
||||||
|
|
||||||
|
/// <summary>Parse a comma-delimited set of case-insensitive condition values.</summary>
|
||||||
|
private readonly Func<string, InvariantHashSet> ParseCommaDelimitedField;
|
||||||
|
|
||||||
|
/// <summary>A callback to invoke when a validation warning occurs. This is passed the content pack, label, and reason phrase respectively.</summary>
|
||||||
|
private readonly Action<ManagedContentPack, string, string> LogWarning;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="filename">The name of the config file.</param>
|
||||||
|
/// <param name="parseCommandDelimitedField">Parse a comma-delimited set of case-insensitive condition values.</param>
|
||||||
|
/// <param name="logWarning">A callback to invoke when a validation warning occurs. This is passed the content pack, label, and reason phrase respectively.</param>
|
||||||
|
public ConfigFileHandler(string filename, Func<string, InvariantHashSet> parseCommandDelimitedField, Action<ManagedContentPack, string, string> logWarning)
|
||||||
|
{
|
||||||
|
this.Filename = filename;
|
||||||
|
this.ParseCommaDelimitedField = parseCommandDelimitedField;
|
||||||
|
this.LogWarning = logWarning;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Read the configuration file for a content pack.</summary>
|
||||||
|
/// <param name="contentPack">The content pack.</param>
|
||||||
|
/// <param name="rawSchema">The raw config schema from the mod's <c>content.json</c>.</param>
|
||||||
|
public InvariantDictionary<ConfigField> Read(ManagedContentPack contentPack, InvariantDictionary<ConfigSchemaFieldConfig> rawSchema)
|
||||||
|
{
|
||||||
|
InvariantDictionary<ConfigField> config = this.LoadConfigSchema(rawSchema, logWarning: (field, reason) => this.LogWarning(contentPack, $"{nameof(ContentConfig.ConfigSchema)} field '{field}'", reason));
|
||||||
|
this.LoadConfigValues(contentPack, config, logWarning: (field, reason) => this.LogWarning(contentPack, $"{this.Filename} > {field}", reason));
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Save the configuration file for a content pack.</summary>
|
||||||
|
/// <param name="contentPack">The content pack.</param>
|
||||||
|
/// <param name="config">The configuration to save.</param>
|
||||||
|
/// <param name="modHelper">The mod helper through which to save the file.</param>
|
||||||
|
public void Save(ManagedContentPack contentPack, InvariantDictionary<ConfigField> config, IModHelper modHelper)
|
||||||
|
{
|
||||||
|
// save if settings valid
|
||||||
|
if (config.Any())
|
||||||
|
{
|
||||||
|
InvariantDictionary<string> data = new InvariantDictionary<string>(config.ToDictionary(p => p.Key, p => string.Join(", ", p.Value.Value)));
|
||||||
|
contentPack.WriteJsonFile(this.Filename, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// delete if no settings
|
||||||
|
else
|
||||||
|
{
|
||||||
|
FileInfo file = new FileInfo(Path.Combine(contentPack.GetFullPath(this.Filename)));
|
||||||
|
if (file.Exists)
|
||||||
|
file.Delete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Parse a raw config schema for a content pack.</summary>
|
||||||
|
/// <param name="rawSchema">The raw config schema.</param>
|
||||||
|
/// <param name="logWarning">The callback to invoke on each validation warning, passed the field name and reason respectively.</param>
|
||||||
|
private InvariantDictionary<ConfigField> LoadConfigSchema(InvariantDictionary<ConfigSchemaFieldConfig> rawSchema, Action<string, string> logWarning)
|
||||||
|
{
|
||||||
|
InvariantDictionary<ConfigField> schema = new InvariantDictionary<ConfigField>();
|
||||||
|
if (rawSchema == null || !rawSchema.Any())
|
||||||
|
return schema;
|
||||||
|
|
||||||
|
foreach (string rawKey in rawSchema.Keys)
|
||||||
|
{
|
||||||
|
ConfigSchemaFieldConfig field = rawSchema[rawKey];
|
||||||
|
|
||||||
|
// validate format
|
||||||
|
if (!TokenName.TryParse(rawKey, out TokenName name))
|
||||||
|
{
|
||||||
|
logWarning(rawKey, $"the name '{rawKey}' is not in a valid format.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (name.HasSubkey())
|
||||||
|
{
|
||||||
|
logWarning(rawKey, $"the name '{rawKey}' can't have a subkey (:).");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate reserved keys
|
||||||
|
if (name.TryGetConditionType(out ConditionType _))
|
||||||
|
{
|
||||||
|
logWarning(rawKey, $"can't use {name.Key} as a config field, because it's a reserved condition key.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// read allowed values
|
||||||
|
InvariantHashSet allowValues = this.ParseCommaDelimitedField(field.AllowValues);
|
||||||
|
if (!allowValues.Any())
|
||||||
|
{
|
||||||
|
logWarning(rawKey, $"no {nameof(ConfigSchemaFieldConfig.AllowValues)} specified.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// read default values
|
||||||
|
InvariantHashSet defaultValues = this.ParseCommaDelimitedField(field.Default);
|
||||||
|
{
|
||||||
|
// inject default
|
||||||
|
if (!defaultValues.Any() && !field.AllowBlank)
|
||||||
|
defaultValues = new InvariantHashSet(allowValues.First());
|
||||||
|
|
||||||
|
// validate values
|
||||||
|
string[] invalidValues = defaultValues.ExceptIgnoreCase(allowValues).ToArray();
|
||||||
|
if (invalidValues.Any())
|
||||||
|
{
|
||||||
|
logWarning(rawKey, $"default values '{string.Join(", ", invalidValues)}' are not allowed according to {nameof(ConfigSchemaFieldConfig.AllowBlank)}.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate allow multiple
|
||||||
|
if (!field.AllowMultiple && defaultValues.Count > 1)
|
||||||
|
{
|
||||||
|
logWarning(rawKey, $"can't have multiple default values because {nameof(ConfigSchemaFieldConfig.AllowMultiple)} is false.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// add to schema
|
||||||
|
schema[rawKey] = new ConfigField(allowValues, defaultValues, field.AllowBlank, field.AllowMultiple);
|
||||||
|
}
|
||||||
|
|
||||||
|
return schema;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Load config values from the content pack.</summary>
|
||||||
|
/// <param name="contentPack">The content pack whose config file to read.</param>
|
||||||
|
/// <param name="config">The config schema.</param>
|
||||||
|
/// <param name="logWarning">The callback to invoke on each validation warning, passed the field name and reason respectively.</param>
|
||||||
|
private void LoadConfigValues(ManagedContentPack contentPack, InvariantDictionary<ConfigField> config, Action<string, string> logWarning)
|
||||||
|
{
|
||||||
|
if (!config.Any())
|
||||||
|
return;
|
||||||
|
|
||||||
|
// read raw config
|
||||||
|
InvariantDictionary<InvariantHashSet> configValues = new InvariantDictionary<InvariantHashSet>(
|
||||||
|
from entry in (contentPack.ReadJsonFile<InvariantDictionary<string>>(this.Filename) ?? new InvariantDictionary<string>())
|
||||||
|
let key = entry.Key.Trim()
|
||||||
|
let value = this.ParseCommaDelimitedField(entry.Value)
|
||||||
|
select new KeyValuePair<string, InvariantHashSet>(key, value)
|
||||||
|
);
|
||||||
|
|
||||||
|
// remove invalid values
|
||||||
|
foreach (string key in configValues.Keys.ExceptIgnoreCase(config.Keys).ToArray())
|
||||||
|
{
|
||||||
|
logWarning(key, "no such field supported by this content pack.");
|
||||||
|
configValues.Remove(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
// inject default values
|
||||||
|
foreach (string key in config.Keys)
|
||||||
|
{
|
||||||
|
ConfigField field = config[key];
|
||||||
|
if (!configValues.TryGetValue(key, out InvariantHashSet values) || (!field.AllowBlank && !values.Any()))
|
||||||
|
configValues[key] = field.DefaultValues;
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse each field
|
||||||
|
foreach (string key in config.Keys)
|
||||||
|
{
|
||||||
|
// set value
|
||||||
|
ConfigField field = config[key];
|
||||||
|
field.Value = configValues[key];
|
||||||
|
|
||||||
|
// validate allow-multiple
|
||||||
|
if (!field.AllowMultiple && field.Value.Count > 1)
|
||||||
|
{
|
||||||
|
logWarning(key, "field only allows a single value.");
|
||||||
|
field.Value = field.DefaultValues;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate allow-values
|
||||||
|
string[] invalidValues = field.Value.ExceptIgnoreCase(field.AllowValues).ToArray();
|
||||||
|
if (invalidValues.Any())
|
||||||
|
{
|
||||||
|
logWarning(key, $"found invalid values ({string.Join(", ", invalidValues)}), expected: {string.Join(", ", field.AllowValues)}.");
|
||||||
|
field.Value = field.DefaultValues;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,43 @@
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.ConfigModels
|
||||||
|
{
|
||||||
|
/// <summary>The parsed schema and value for a field in the <c>config.json</c> file.</summary>
|
||||||
|
internal class ConfigField
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The values to allow.</summary>
|
||||||
|
public InvariantHashSet AllowValues { get; }
|
||||||
|
|
||||||
|
/// <summary>The default values if the field is missing or (if <see cref="AllowBlank"/> is <c>false</c>) blank.</summary>
|
||||||
|
public InvariantHashSet DefaultValues { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether to allow blank values.</summary>
|
||||||
|
public bool AllowBlank { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the player can specify multiple values for this field.</summary>
|
||||||
|
public bool AllowMultiple { get; }
|
||||||
|
|
||||||
|
/// <summary>The value read from the player settings.</summary>
|
||||||
|
public InvariantHashSet Value { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="allowValues">The values to allow.</param>
|
||||||
|
/// <param name="defaultValues">The default values if the field is missing or (if <paramref name="allowBlank"/> is <c>false</c>) blank.</param>
|
||||||
|
/// <param name="allowBlank">Whether to allow blank values.</param>
|
||||||
|
/// <param name="allowMultiple">Whether the player can specify multiple values for this field.</param>
|
||||||
|
public ConfigField(InvariantHashSet allowValues, InvariantHashSet defaultValues, bool allowBlank, bool allowMultiple)
|
||||||
|
{
|
||||||
|
this.AllowValues = allowValues;
|
||||||
|
this.DefaultValues = defaultValues;
|
||||||
|
this.AllowBlank = allowBlank;
|
||||||
|
this.AllowMultiple = allowMultiple;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
namespace ContentPatcher.Framework.ConfigModels
|
||||||
|
{
|
||||||
|
/// <summary>The schema for a field in the <c>config.json</c> file.</summary>
|
||||||
|
internal class ConfigSchemaFieldConfig
|
||||||
|
{
|
||||||
|
/// <summary>The comma-delimited values to allow.</summary>
|
||||||
|
public string AllowValues { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The default value if the field is missing or (if <see cref="AllowBlank"/> is <c>false</c>) blank.</summary>
|
||||||
|
public string Default { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Whether to allow blank values.</summary>
|
||||||
|
public bool AllowBlank { get; set; } = false;
|
||||||
|
|
||||||
|
/// <summary>Whether the player can specify multiple values for this field.</summary>
|
||||||
|
public bool AllowMultiple { get; set; } = false;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.ConfigModels
|
||||||
|
{
|
||||||
|
/// <summary>The model for a content patch file.</summary>
|
||||||
|
internal class ContentConfig
|
||||||
|
{
|
||||||
|
/// <summary>The format version.</summary>
|
||||||
|
public ISemanticVersion Format { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The user-defined tokens whose values may depend on other tokens.</summary>
|
||||||
|
public DynamicTokenConfig[] DynamicTokens { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The changes to make.</summary>
|
||||||
|
public PatchConfig[] Changes { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The schema for the <c>config.json</c> file (if any).</summary>
|
||||||
|
public InvariantDictionary<ConfigSchemaFieldConfig> ConfigSchema { get; set; }
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.ConfigModels
|
||||||
|
{
|
||||||
|
/// <summary>A user-defined token whose value may depend on other tokens.</summary>
|
||||||
|
internal class DynamicTokenConfig
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The name of the token to set.</summary>
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The value to set.</summary>
|
||||||
|
public string Value { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The criteria to apply. See readme for valid values.</summary>
|
||||||
|
public InvariantDictionary<string> When { get; set; }
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Pathoschild.Stardew.Common;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.ConfigModels
|
||||||
|
{
|
||||||
|
/// <summary>The mod configuration.</summary>
|
||||||
|
internal class ModConfig
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>Whether to enable debug features.</summary>
|
||||||
|
public bool EnableDebugFeatures { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The control bindings.</summary>
|
||||||
|
public ModConfigControls Controls { get; set; } = new ModConfigControls();
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Nested models
|
||||||
|
*********/
|
||||||
|
/// <summary>A set of control bindings.</summary>
|
||||||
|
internal class ModConfigControls
|
||||||
|
{
|
||||||
|
/// <summary>Toggle the display of debug information.</summary>
|
||||||
|
[JsonConverter(typeof(StringEnumArrayConverter))]
|
||||||
|
public SButton[] ToggleDebug { get; set; } = { SButton.F3 };
|
||||||
|
|
||||||
|
/// <summary>Switch to the previous texture.</summary>
|
||||||
|
[JsonConverter(typeof(StringEnumArrayConverter))]
|
||||||
|
public SButton[] DebugPrevTexture { get; set; } = { SButton.LeftControl };
|
||||||
|
|
||||||
|
/// <summary>Switch to the next texture.</summary>
|
||||||
|
[JsonConverter(typeof(StringEnumArrayConverter))]
|
||||||
|
public SButton[] DebugNextTexture { get; set; } = { SButton.RightControl };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,83 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.ConfigModels
|
||||||
|
{
|
||||||
|
/// <summary>The input settings for a patch from the configuration file.</summary>
|
||||||
|
internal class PatchConfig
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/****
|
||||||
|
** All actions
|
||||||
|
****/
|
||||||
|
/// <summary>A name for this patch shown in log messages.</summary>
|
||||||
|
public string LogName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The patch type to apply.</summary>
|
||||||
|
public string Action { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The asset key to change.</summary>
|
||||||
|
public string Target { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Whether to apply this patch.</summary>
|
||||||
|
/// <remarks>This must be a string to support config tokens.</remarks>
|
||||||
|
public string Enabled { get; set; } = "true";
|
||||||
|
|
||||||
|
/// <summary>The criteria to apply. See readme for valid values.</summary>
|
||||||
|
public InvariantDictionary<string> When { get; set; }
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Some actions
|
||||||
|
****/
|
||||||
|
/// <summary>The local file to load.</summary>
|
||||||
|
public string FromFile { get; set; }
|
||||||
|
|
||||||
|
/****
|
||||||
|
** EditImage
|
||||||
|
****/
|
||||||
|
/// <summary>The sprite area from which to read an image.</summary>
|
||||||
|
public Rectangle FromArea { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The sprite area to overwrite.</summary>
|
||||||
|
public Rectangle ToArea { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Indicates how the image should be patched.</summary>
|
||||||
|
public string PatchMode { get; set; }
|
||||||
|
|
||||||
|
/****
|
||||||
|
** EditData
|
||||||
|
****/
|
||||||
|
/// <summary>The data records to edit.</summary>
|
||||||
|
public IDictionary<string, string> Entries { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The individual fields to edit in data records.</summary>
|
||||||
|
public IDictionary<string, IDictionary<int, string>> Fields { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
public PatchConfig() { }
|
||||||
|
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="other">The other patch to clone.</param>
|
||||||
|
public PatchConfig(PatchConfig other)
|
||||||
|
{
|
||||||
|
this.LogName = other.LogName;
|
||||||
|
this.Action = other.Action;
|
||||||
|
this.Target = other.Target;
|
||||||
|
this.Enabled = other.Enabled;
|
||||||
|
this.When = other.When != null ? new InvariantDictionary<string>(other.When) : null;
|
||||||
|
this.FromFile = other.FromFile;
|
||||||
|
this.FromArea = other.FromArea;
|
||||||
|
this.ToArea = other.ToArea;
|
||||||
|
this.PatchMode = other.PatchMode;
|
||||||
|
this.Entries = other.Entries != null ? new Dictionary<string, string>(other.Entries) : null;
|
||||||
|
this.Fields = other.Fields != null ? new Dictionary<string, IDictionary<int, string>>(other.Fields) : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Constants
|
||||||
|
{
|
||||||
|
/// <summary>A farm cave type.</summary>
|
||||||
|
internal enum FarmCaveType
|
||||||
|
{
|
||||||
|
/// <summary>The player hasn't chosen a farm cave yet.</summary>
|
||||||
|
None = Farmer.caveNothing,
|
||||||
|
|
||||||
|
/// <summary>The fruit bat cave.</summary>
|
||||||
|
Bats = Farmer.caveBats,
|
||||||
|
|
||||||
|
/// <summary>The mushroom cave.</summary>
|
||||||
|
Mushrooms = Farmer.caveMushrooms
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Constants
|
||||||
|
{
|
||||||
|
/// <summary>A farm type.</summary>
|
||||||
|
internal enum FarmType
|
||||||
|
{
|
||||||
|
/// <summary>The standard farm type.</summary>
|
||||||
|
Standard = 0,
|
||||||
|
|
||||||
|
/// <summary>The riverland farm type.</summary>
|
||||||
|
Riverland = 1,
|
||||||
|
|
||||||
|
/// <summary>The forest farm type.</summary>
|
||||||
|
Forest = 2,
|
||||||
|
|
||||||
|
/// <summary>The hill-top farm type.</summary>
|
||||||
|
Hilltop = 3,
|
||||||
|
|
||||||
|
/// <summary>The wilderness farm type.</summary>
|
||||||
|
Wilderness = 4,
|
||||||
|
|
||||||
|
/// <summary>A custom farm type.</summary>
|
||||||
|
Custom = 100
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
namespace ContentPatcher.Framework.Constants
|
||||||
|
{
|
||||||
|
/// <summary>A player gender.</summary>
|
||||||
|
internal enum Gender
|
||||||
|
{
|
||||||
|
/// <summary>The female gender.</summary>
|
||||||
|
Female,
|
||||||
|
|
||||||
|
/// <summary>The male gender.</summary>
|
||||||
|
Male
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
namespace ContentPatcher.Framework.Constants
|
||||||
|
{
|
||||||
|
/// <summary>A pet type.</summary>
|
||||||
|
internal enum PetType
|
||||||
|
{
|
||||||
|
/// <summary>The cat pet.</summary>
|
||||||
|
Cat,
|
||||||
|
|
||||||
|
/// <summary>The dog pet.</summary>
|
||||||
|
Dog
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,113 @@
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Constants
|
||||||
|
{
|
||||||
|
/// <summary>A player profession.</summary>
|
||||||
|
internal enum Profession
|
||||||
|
{
|
||||||
|
/***
|
||||||
|
** Combat
|
||||||
|
***/
|
||||||
|
/// <summary>The acrobat profession for the combat skill.</summary>
|
||||||
|
Acrobat = Farmer.acrobat,
|
||||||
|
|
||||||
|
/// <summary>The brute profession for the combat skill.</summary>
|
||||||
|
Brute = Farmer.brute,
|
||||||
|
|
||||||
|
/// <summary>The defender profession for the combat skill.</summary>
|
||||||
|
Defender = Farmer.defender,
|
||||||
|
|
||||||
|
/// <summary>The desperado profession for the combat skill.</summary>
|
||||||
|
Desperado = Farmer.desperado,
|
||||||
|
|
||||||
|
/// <summary>The fighter profession for the combat skill.</summary>
|
||||||
|
Fighter = Farmer.fighter,
|
||||||
|
|
||||||
|
/// <summary>The scout profession for the combat skill.</summary>
|
||||||
|
Scout = Farmer.scout,
|
||||||
|
|
||||||
|
/***
|
||||||
|
** Farming
|
||||||
|
***/
|
||||||
|
/// <summary>The agriculturist profession for the farming skill.</summary>
|
||||||
|
Agriculturist = Farmer.agriculturist,
|
||||||
|
|
||||||
|
/// <summary>The shepherd profession for the farming skill.</summary>
|
||||||
|
Artisan = Farmer.artisan,
|
||||||
|
|
||||||
|
/// <summary>The coopmaster profession for the farming skill.</summary>
|
||||||
|
Coopmaster = Farmer.butcher, // game's constant name doesn't match usage
|
||||||
|
|
||||||
|
/// <summary>The rancher profession for the farming skill.</summary>
|
||||||
|
Rancher = Farmer.rancher,
|
||||||
|
|
||||||
|
/// <summary>The shepherd profession for the farming skill.</summary>
|
||||||
|
Shepherd = Farmer.shepherd,
|
||||||
|
|
||||||
|
/// <summary>The tiller profession for the farming skill.</summary>
|
||||||
|
Tiller = Farmer.tiller,
|
||||||
|
|
||||||
|
/***
|
||||||
|
** Fishing
|
||||||
|
***/
|
||||||
|
/// <summary>The angler profession for the fishing skill.</summary>
|
||||||
|
Angler = Farmer.angler,
|
||||||
|
|
||||||
|
/// <summary>The fisher profession for the fishing skill.</summary>
|
||||||
|
Fisher = Farmer.fisher,
|
||||||
|
|
||||||
|
/// <summary>The mariner profession for the fishing skill.</summary>
|
||||||
|
Mariner = Farmer.baitmaster, // game's constant name is confusing
|
||||||
|
|
||||||
|
/// <summary>The pirate profession for the fishing skill.</summary>
|
||||||
|
Pirate = Farmer.pirate,
|
||||||
|
|
||||||
|
/// <summary>The luremaster profession for the fishing skill.</summary>
|
||||||
|
Luremaster = Farmer.mariner, // game's constant name is confusing
|
||||||
|
|
||||||
|
/// <summary>The trapper profession for the fishing skill.</summary>
|
||||||
|
Trapper = Farmer.trapper,
|
||||||
|
|
||||||
|
/***
|
||||||
|
** Foraging
|
||||||
|
***/
|
||||||
|
/// <summary>The botanist profession for the foraging skill.</summary>
|
||||||
|
Botanist = Farmer.botanist,
|
||||||
|
|
||||||
|
/// <summary>The forester profession for the foraging skill.</summary>
|
||||||
|
Forester = Farmer.forester,
|
||||||
|
|
||||||
|
/// <summary>The gatherer profession for the foraging skill.</summary>
|
||||||
|
Gatherer = Farmer.gatherer,
|
||||||
|
|
||||||
|
/// <summary>The lumberjack profession for the foraging skill.</summary>
|
||||||
|
Lumberjack = Farmer.lumberjack,
|
||||||
|
|
||||||
|
/// <summary>The tapper profession for the foraging skill.</summary>
|
||||||
|
Tapper = Farmer.tapper,
|
||||||
|
|
||||||
|
/// <summary>The tracker profession for the foraging skill.</summary>
|
||||||
|
Tracker = Farmer.tracker,
|
||||||
|
|
||||||
|
/***
|
||||||
|
** Mining
|
||||||
|
***/
|
||||||
|
/// <summary>The blacksmith profession for the foraging skill.</summary>
|
||||||
|
Blacksmith = Farmer.blacksmith,
|
||||||
|
|
||||||
|
/// <summary>The excavator profession for the foraging skill.</summary>
|
||||||
|
Excavator = Farmer.excavator,
|
||||||
|
|
||||||
|
/// <summary>The gemologist profession for the foraging skill.</summary>
|
||||||
|
Gemologist = Farmer.gemologist,
|
||||||
|
|
||||||
|
/// <summary>The geologist profession for the foraging skill.</summary>
|
||||||
|
Geologist = Farmer.geologist,
|
||||||
|
|
||||||
|
/// <summary>The miner profession for the foraging skill.</summary>
|
||||||
|
Miner = Farmer.miner,
|
||||||
|
|
||||||
|
/// <summary>The prospector profession for the foraging skill.</summary>
|
||||||
|
Prospector = Farmer.burrower, // game's constant name is confusing
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Constants
|
||||||
|
{
|
||||||
|
/// <summary>A player Skill.</summary>
|
||||||
|
internal enum Skill
|
||||||
|
{
|
||||||
|
/// <summary>The combat skill.</summary>
|
||||||
|
Combat = Farmer.combatSkill,
|
||||||
|
|
||||||
|
/// <summary>The farming skill.</summary>
|
||||||
|
Farming = Farmer.farmingSkill,
|
||||||
|
|
||||||
|
/// <summary>The fishing skill.</summary>
|
||||||
|
Fishing = Farmer.fishingSkill,
|
||||||
|
|
||||||
|
/// <summary>The foraging skill.</summary>
|
||||||
|
Foraging = Farmer.foragingSkill,
|
||||||
|
|
||||||
|
/// <summary>The luck skill.</summary>
|
||||||
|
Luck = Farmer.luckSkill,
|
||||||
|
|
||||||
|
/// <summary>The mining skill.</summary>
|
||||||
|
Mining = Farmer.miningSkill
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,36 @@
|
||||||
|
namespace ContentPatcher.Framework.Constants
|
||||||
|
{
|
||||||
|
/// <summary>A special item slot in the player's wallet.</summary>
|
||||||
|
internal enum WalletItem
|
||||||
|
{
|
||||||
|
/// <summary>Unlocks speaking to the Dwarf.</summary>
|
||||||
|
DwarvishTranslationGuide,
|
||||||
|
|
||||||
|
/// <summary>Unlocks the sewers.</summary>
|
||||||
|
RustyKey,
|
||||||
|
|
||||||
|
/// <summary>Unlocks the desert casino.</summary>
|
||||||
|
ClubCard,
|
||||||
|
|
||||||
|
/// <summary>Permanently increases daily luck.</summary>
|
||||||
|
SpecialCharm,
|
||||||
|
|
||||||
|
/// <summary>Unlocks the Skull Cavern in the desert, and the Junimo Kart machine in the Stardrop Saloon.</summary>
|
||||||
|
SkullKey,
|
||||||
|
|
||||||
|
/// <summary>Unlocks the ability to find secret notes.</summary>
|
||||||
|
MagnifyingGlass,
|
||||||
|
|
||||||
|
/// <summary>Unlocks the Witch's Swamp.</summary>
|
||||||
|
DarkTalisman,
|
||||||
|
|
||||||
|
/// <summary>Unlocks magical buildings through the Wizard, and the dark shrines in the Witch's Swamp.</summary>
|
||||||
|
MagicInk,
|
||||||
|
|
||||||
|
/// <summary>Increases sell price of blackberries and salmonberries.</summary>
|
||||||
|
BearsKnowledge,
|
||||||
|
|
||||||
|
/// <summary>Increases sell price of spring onions.</summary>
|
||||||
|
SpringOnionMastery
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,109 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using Microsoft.Xna.Framework.Graphics;
|
||||||
|
using Pathoschild.Stardew.Common;
|
||||||
|
using Pathoschild.Stardew.Common.UI;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
using StardewModdingAPI.Events;
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework
|
||||||
|
{
|
||||||
|
/// <summary>Renders debug information to the screen.</summary>
|
||||||
|
internal class DebugOverlay : BaseOverlay
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The size of the margin around the displayed legend.</summary>
|
||||||
|
private readonly int Margin = 30;
|
||||||
|
|
||||||
|
/// <summary>The padding between the border and content.</summary>
|
||||||
|
private readonly int Padding = 5;
|
||||||
|
|
||||||
|
/// <summary>The content helper from which to read textures.</summary>
|
||||||
|
private readonly IContentHelper Content;
|
||||||
|
|
||||||
|
/// <summary>The spritesheets to render.</summary>
|
||||||
|
private readonly string[] TextureNames;
|
||||||
|
|
||||||
|
/// <summary>The current spritesheet to display.</summary>
|
||||||
|
private string CurrentName;
|
||||||
|
|
||||||
|
/// <summary>The current texture to display.</summary>
|
||||||
|
private Texture2D CurrentTexture;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="events">The SMAPI events available for mods.</param>
|
||||||
|
/// <param name="inputHelper">An API for checking and changing input state.</param>
|
||||||
|
/// <param name="contentHelper">The content helper from which to read textures.</param>
|
||||||
|
public DebugOverlay(IModEvents events, IInputHelper inputHelper, IContentHelper contentHelper)
|
||||||
|
: base(events, inputHelper)
|
||||||
|
{
|
||||||
|
this.Content = contentHelper;
|
||||||
|
this.TextureNames = this.GetTextureNames(contentHelper).OrderByIgnoreCase(p => p).ToArray();
|
||||||
|
this.NextTexture();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Switch to the next texture.</summary>
|
||||||
|
public void NextTexture()
|
||||||
|
{
|
||||||
|
int index = Array.IndexOf(this.TextureNames, this.CurrentName) + 1;
|
||||||
|
if (index >= this.TextureNames.Length)
|
||||||
|
index = 0;
|
||||||
|
this.CurrentName = this.TextureNames[index];
|
||||||
|
this.CurrentTexture = this.Content.Load<Texture2D>(this.CurrentName, ContentSource.GameContent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Switch to the previous data map.</summary>
|
||||||
|
public void PrevTexture()
|
||||||
|
{
|
||||||
|
int index = Array.IndexOf(this.TextureNames, this.CurrentName) - 1;
|
||||||
|
if (index < 0)
|
||||||
|
index = this.TextureNames.Length - 1;
|
||||||
|
this.CurrentName = this.TextureNames[index];
|
||||||
|
this.CurrentTexture = this.Content.Load<Texture2D>(this.CurrentName, ContentSource.GameContent);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Protected methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Draw to the screen.</summary>
|
||||||
|
/// <param name="spriteBatch">The sprite batch to which to draw.</param>
|
||||||
|
protected override void Draw(SpriteBatch spriteBatch)
|
||||||
|
{
|
||||||
|
Vector2 labelSize = Game1.smallFont.MeasureString(this.CurrentName);
|
||||||
|
int contentWidth = (int)Math.Max(labelSize.X, this.CurrentTexture?.Width ?? 0);
|
||||||
|
|
||||||
|
CommonHelper.DrawScroll(spriteBatch, new Vector2(this.Margin), new Vector2(contentWidth, labelSize.Y + this.Padding + (this.CurrentTexture?.Height ?? (int)labelSize.Y)), out Vector2 contentPos, out Rectangle _, padding: this.Padding);
|
||||||
|
spriteBatch.DrawString(Game1.smallFont, this.CurrentName, new Vector2(contentPos.X + ((contentWidth - labelSize.X) / 2), contentPos.Y), Color.Black);
|
||||||
|
|
||||||
|
if (this.CurrentTexture != null)
|
||||||
|
spriteBatch.Draw(this.CurrentTexture, contentPos + new Vector2(0, labelSize.Y + this.Padding), Color.White);
|
||||||
|
else
|
||||||
|
spriteBatch.DrawString(Game1.smallFont, "(null)", contentPos + new Vector2(0, labelSize.Y + this.Padding), Color.Black);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get all texture asset names in the given content helper.</summary>
|
||||||
|
/// <param name="contentHelper">The content helper to search.</param>
|
||||||
|
private IEnumerable<string> GetTextureNames(IContentHelper contentHelper)
|
||||||
|
{
|
||||||
|
// get all texture keys from the content helper (this is such a hack)
|
||||||
|
IList<string> textureKeys = new List<string>();
|
||||||
|
contentHelper.InvalidateCache(asset =>
|
||||||
|
{
|
||||||
|
if (asset.DataType == typeof(Texture2D) && !asset.AssetName.Contains("..") && !asset.AssetName.StartsWith(StardewModdingAPI.Constants.ExecutionPath))
|
||||||
|
textureKeys.Add(asset.AssetName);
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
return textureKeys;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,84 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework
|
||||||
|
{
|
||||||
|
/// <summary>A generic token context.</summary>
|
||||||
|
/// <typeparam name="TToken">The token type to store.</typeparam>
|
||||||
|
internal class GenericTokenContext<TToken> : IContext where TToken : class, IToken
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The available tokens.</summary>
|
||||||
|
public IDictionary<TokenName, TToken> Tokens { get; } = new Dictionary<TokenName, TToken>();
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>Save the given token to the context.</summary>
|
||||||
|
/// <param name="token">The token to save.</param>
|
||||||
|
public void Save(TToken token)
|
||||||
|
{
|
||||||
|
this.Tokens[token.Name] = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get whether the context contains the given token.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
public bool Contains(TokenName name, bool enforceContext)
|
||||||
|
{
|
||||||
|
return this.GetToken(name, enforceContext) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the underlying token which handles a key.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
/// <returns>Returns the matching token, or <c>null</c> if none was found.</returns>
|
||||||
|
public IToken GetToken(TokenName name, bool enforceContext)
|
||||||
|
{
|
||||||
|
return this.Tokens.TryGetValue(name.GetRoot(), out TToken token) && this.ShouldConsider(token, enforceContext)
|
||||||
|
? token
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the underlying tokens.</summary>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
public IEnumerable<IToken> GetTokens(bool enforceContext)
|
||||||
|
{
|
||||||
|
foreach (TToken token in this.Tokens.Values)
|
||||||
|
{
|
||||||
|
if (this.ShouldConsider(token, enforceContext))
|
||||||
|
yield return token;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the current values of the given token for comparison.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
/// <returns>Return the values of the matching token, or an empty list if the token doesn't exist.</returns>
|
||||||
|
/// <exception cref="ArgumentNullException">The specified key is null.</exception>
|
||||||
|
public IEnumerable<string> GetValues(TokenName name, bool enforceContext)
|
||||||
|
{
|
||||||
|
IToken token = this.GetToken(name, enforceContext);
|
||||||
|
return token?.GetValues(name) ?? new string[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get whether a given token should be considered.</summary>
|
||||||
|
/// <param name="token">The token to check.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
private bool ShouldConsider(IToken token, bool enforceContext)
|
||||||
|
{
|
||||||
|
return !enforceContext || token.IsValidInContext;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A generic token context.</summary>
|
||||||
|
internal class GenericTokenContext : GenericTokenContext<IToken> { }
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
namespace ContentPatcher.Framework.Lexing.LexTokens
|
||||||
|
{
|
||||||
|
/// <summary>A lexical token within a string, which combines one or more <see cref="LexBit"/> patterns into a cohesive part.</summary>
|
||||||
|
internal interface ILexToken
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The lexical token type.</summary>
|
||||||
|
LexTokenType Type { get; }
|
||||||
|
|
||||||
|
/// <summary>A text representation of the lexical token.</summary>
|
||||||
|
string Text { get; }
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
namespace ContentPatcher.Framework.Lexing.LexTokens
|
||||||
|
{
|
||||||
|
/// <summary>A low-level character pattern within a string/</summary>
|
||||||
|
internal class LexBit
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The lexical character pattern type.</summary>
|
||||||
|
public LexBitType Type { get; }
|
||||||
|
|
||||||
|
/// <summary>The raw matched text.</summary>
|
||||||
|
public string Text { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="type">The lexical character pattern type.</param>
|
||||||
|
/// <param name="text">The raw matched text.</param>
|
||||||
|
public LexBit(LexBitType type, string text)
|
||||||
|
{
|
||||||
|
this.Type = type;
|
||||||
|
this.Text = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
namespace ContentPatcher.Framework.Lexing.LexTokens
|
||||||
|
{
|
||||||
|
/// <summary>A lexical character pattern type.</summary>
|
||||||
|
public enum LexBitType
|
||||||
|
{
|
||||||
|
/// <summary>A literal string.</summary>
|
||||||
|
Literal,
|
||||||
|
|
||||||
|
/// <summary>The characters which start a token ('{{').</summary>
|
||||||
|
StartToken,
|
||||||
|
|
||||||
|
/// <summary>The characters which end a token ('}}').</summary>
|
||||||
|
EndToken,
|
||||||
|
|
||||||
|
/// <summary>The character which separates a token name from its input argument (':').</summary>
|
||||||
|
InputArgSeparator,
|
||||||
|
|
||||||
|
/// <summary>The character which pipes the output of one token into the input of another ('|').</summary>
|
||||||
|
TokenPipe
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,33 @@
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Lexing.LexTokens
|
||||||
|
{
|
||||||
|
/// <summary>A lexical token representing the input argument for a Content Patcher token.</summary>
|
||||||
|
internal readonly struct LexTokenInputArg : ILexToken
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The lexical token type.</summary>
|
||||||
|
public LexTokenType Type { get; }
|
||||||
|
|
||||||
|
/// <summary>A text representation of the lexical token.</summary>
|
||||||
|
public string Text { get; }
|
||||||
|
|
||||||
|
/// <summary>The lexical tokens making up the input argument.</summary>
|
||||||
|
public ILexToken[] Parts { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="tokenParts">The lexical tokens making up the input argument.</param>
|
||||||
|
public LexTokenInputArg(ILexToken[] tokenParts)
|
||||||
|
{
|
||||||
|
this.Type = LexTokenType.TokenInput;
|
||||||
|
this.Text = string.Join("", tokenParts.Select(p => p.Text));
|
||||||
|
this.Parts = tokenParts;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
namespace ContentPatcher.Framework.Lexing.LexTokens
|
||||||
|
{
|
||||||
|
/// <summary>A lexical token representing a literal string value.</summary>
|
||||||
|
internal readonly struct LexTokenLiteral : ILexToken
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The lexical token type.</summary>
|
||||||
|
public LexTokenType Type { get; }
|
||||||
|
|
||||||
|
/// <summary>A text representation of the lexical token.</summary>
|
||||||
|
public string Text { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="text">The literal text value.</param>
|
||||||
|
public LexTokenLiteral(string text)
|
||||||
|
{
|
||||||
|
this.Type = LexTokenType.Literal;
|
||||||
|
this.Text = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
namespace ContentPatcher.Framework.Lexing.LexTokens
|
||||||
|
{
|
||||||
|
/// <summary>A lexical token which represents a pipe that transfers the output of one token into the input of another.</summary>
|
||||||
|
internal readonly struct LexTokenPipe : ILexToken
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The lexical token type.</summary>
|
||||||
|
public LexTokenType Type { get; }
|
||||||
|
|
||||||
|
/// <summary>A text representation of the lexical token.</summary>
|
||||||
|
public string Text { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="text">A text representation of the lexical token.</param>
|
||||||
|
public LexTokenPipe(string text)
|
||||||
|
{
|
||||||
|
this.Type = LexTokenType.TokenPipe;
|
||||||
|
this.Text = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,72 @@
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Lexing.LexTokens
|
||||||
|
{
|
||||||
|
/// <summary>A lexical token representing a Content Patcher token.</summary>
|
||||||
|
internal readonly struct LexTokenToken : ILexToken
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The lexical token type.</summary>
|
||||||
|
public LexTokenType Type { get; }
|
||||||
|
|
||||||
|
/// <summary>A text representation of the lexical token.</summary>
|
||||||
|
public string Text { get; }
|
||||||
|
|
||||||
|
/// <summary>The Content Patcher token name.</summary>
|
||||||
|
public string Name { get; }
|
||||||
|
|
||||||
|
/// <summary>The input argument passed to the Content Patcher token.</summary>
|
||||||
|
public LexTokenInputArg? InputArg { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the token omits the start/end character patterns because it's in a token-only context.</summary>
|
||||||
|
public bool ImpliedBraces { get; }
|
||||||
|
|
||||||
|
/// <summary>A sequence of tokens to invoke after this token is processed, each getting the output of the previous token as its input.</summary>
|
||||||
|
public LexTokenToken[] PipedTokens { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="name">The Content Patcher token name.</param>
|
||||||
|
/// <param name="inputArg">The input argument passed to the Content Patcher token.</param>
|
||||||
|
/// <param name="impliedBraces">Whether the token omits the start/end character patterns because it's in a token-only context.</param>
|
||||||
|
/// <param name="pipedTokens">A sequence of tokens to invoke after this token is processed, each getting the output of the previous token as its input.</param>
|
||||||
|
public LexTokenToken(string name, LexTokenInputArg? inputArg, bool impliedBraces, LexTokenToken[] pipedTokens)
|
||||||
|
{
|
||||||
|
this.Type = LexTokenType.Token;
|
||||||
|
this.Text = LexTokenToken.GetRawText(name, inputArg, impliedBraces);
|
||||||
|
this.Name = name;
|
||||||
|
this.InputArg = inputArg;
|
||||||
|
this.ImpliedBraces = impliedBraces;
|
||||||
|
this.PipedTokens = pipedTokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get a string representation of a token.</summary>
|
||||||
|
/// <param name="name">The Content Patcher token name.</param>
|
||||||
|
/// <param name="tokenInputArgArgument">The input argument passed to the Content Patcher token.</param>
|
||||||
|
/// <param name="impliedBraces">Whether the token omits the start/end character patterns because it's in a token-only context.</param>
|
||||||
|
private static string GetRawText(string name, LexTokenInputArg? tokenInputArgArgument, bool impliedBraces)
|
||||||
|
{
|
||||||
|
StringBuilder str = new StringBuilder();
|
||||||
|
if (!impliedBraces)
|
||||||
|
str.Append("{{");
|
||||||
|
str.Append(name);
|
||||||
|
if (tokenInputArgArgument != null)
|
||||||
|
{
|
||||||
|
str.Append(":");
|
||||||
|
str.Append(tokenInputArgArgument.Value.Text);
|
||||||
|
}
|
||||||
|
if (!impliedBraces)
|
||||||
|
str.Append("}}");
|
||||||
|
return str.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
namespace ContentPatcher.Framework.Lexing.LexTokens
|
||||||
|
{
|
||||||
|
/// <summary>A lexical token type.</summary>
|
||||||
|
public enum LexTokenType
|
||||||
|
{
|
||||||
|
/// <summary>A literal string.</summary>
|
||||||
|
Literal,
|
||||||
|
|
||||||
|
/// <summary>A Content Patcher token.</summary>
|
||||||
|
Token,
|
||||||
|
|
||||||
|
/// <summary>The input argument to a Content Patcher token.</summary>
|
||||||
|
TokenInput,
|
||||||
|
|
||||||
|
/// <summary>A pipe which transfers the output of one token into the input of another.</summary>
|
||||||
|
TokenPipe
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,305 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using ContentPatcher.Framework.Lexing.LexTokens;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Lexing
|
||||||
|
{
|
||||||
|
/// <summary>Handles parsing raw strings into tokens.</summary>
|
||||||
|
internal class Lexer
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>A regular expression which matches lexical patterns that split lexical patterns. For example, ':' is a <see cref="LexBitType.InputArgSeparator"/> pattern that splits a token name and its input arguments. The split pattern is itself a lexical pattern.</summary>
|
||||||
|
private readonly Regex LexicalSplitPattern = new Regex(@"({{|}}|:|\|)", RegexOptions.Compiled);
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Break a raw string into its constituent lexical character patterns.</summary>
|
||||||
|
/// <param name="rawText">The raw text to tokenise.</param>
|
||||||
|
public IEnumerable<LexBit> TokeniseString(string rawText)
|
||||||
|
{
|
||||||
|
// special cases
|
||||||
|
if (rawText == null)
|
||||||
|
yield break;
|
||||||
|
if (string.IsNullOrWhiteSpace(rawText))
|
||||||
|
{
|
||||||
|
yield return new LexBit(LexBitType.Literal, rawText);
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse
|
||||||
|
string[] parts = this.LexicalSplitPattern.Split(rawText);
|
||||||
|
foreach (string part in parts)
|
||||||
|
{
|
||||||
|
if (part == "")
|
||||||
|
continue; // split artifact
|
||||||
|
|
||||||
|
LexBitType type;
|
||||||
|
switch (part)
|
||||||
|
{
|
||||||
|
case "{{":
|
||||||
|
type = LexBitType.StartToken;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "}}":
|
||||||
|
type = LexBitType.EndToken;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ":":
|
||||||
|
type = LexBitType.InputArgSeparator;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "|":
|
||||||
|
type = LexBitType.TokenPipe;
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
type = LexBitType.Literal;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
yield return new LexBit(type, part);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Parse a sequence of lexical character patterns into higher-level lexical tokens.</summary>
|
||||||
|
/// <param name="rawText">The raw text to tokenise.</param>
|
||||||
|
/// <param name="impliedBraces">Whether we're parsing a token context (so the outer '{{' and '}}' are implied); else parse as a tokenisable string which main contain a mix of literal and {{token}} values.</param>
|
||||||
|
public IEnumerable<ILexToken> ParseBits(string rawText, bool impliedBraces)
|
||||||
|
{
|
||||||
|
IEnumerable<LexBit> bits = this.TokeniseString(rawText);
|
||||||
|
return this.ParseBits(bits, impliedBraces);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Parse a sequence of lexical character patterns into higher-level lexical tokens.</summary>
|
||||||
|
/// <param name="bits">The lexical character patterns to parse.</param>
|
||||||
|
/// <param name="impliedBraces">Whether we're parsing a token context (so the outer '{{' and '}}' are implied); else parse as a tokenisable string which main contain a mix of literal and {{token}} values.</param>
|
||||||
|
public IEnumerable<ILexToken> ParseBits(IEnumerable<LexBit> bits, bool impliedBraces)
|
||||||
|
{
|
||||||
|
return this.ParseBitQueue(new Queue<LexBit>(bits), impliedBraces, trim: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Parse a sequence of lexical character patterns into higher-level lexical tokens.</summary>
|
||||||
|
/// <param name="input">The lexical character patterns to parse.</param>
|
||||||
|
/// <param name="impliedBraces">Whether we're parsing a token context (so the outer '{{' and '}}' are implied); else parse as a tokenisable string which main contain a mix of literal and {{token}} values.</param>
|
||||||
|
/// <param name="trim">Whether the value should be trimmed.</param>
|
||||||
|
private IEnumerable<ILexToken> ParseBitQueue(Queue<LexBit> input, bool impliedBraces, bool trim)
|
||||||
|
{
|
||||||
|
// perform a raw parse
|
||||||
|
IEnumerable<ILexToken> RawParse()
|
||||||
|
{
|
||||||
|
// 'Implied braces' means we're parsing inside a token. This necessarily starts with a token name,
|
||||||
|
// optionally followed by an input argument and token pipes.
|
||||||
|
if (impliedBraces)
|
||||||
|
{
|
||||||
|
while (input.Any())
|
||||||
|
{
|
||||||
|
yield return this.ExtractToken(input, impliedBraces: true);
|
||||||
|
if (!input.Any())
|
||||||
|
yield break;
|
||||||
|
|
||||||
|
var next = input.Peek();
|
||||||
|
switch (next.Type)
|
||||||
|
{
|
||||||
|
case LexBitType.TokenPipe:
|
||||||
|
yield return new LexTokenPipe(input.Dequeue().Text);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new InvalidOperationException($"Unexpected {next.Type}, expected {LexBitType.Literal} or {LexBitType.TokenPipe}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise this is a tokenisable string which may contain a mix of literal and {{token}} values.
|
||||||
|
while (input.Any())
|
||||||
|
{
|
||||||
|
LexBit next = input.Peek();
|
||||||
|
switch (next.Type)
|
||||||
|
{
|
||||||
|
// start token
|
||||||
|
case LexBitType.StartToken:
|
||||||
|
yield return this.ExtractToken(input, impliedBraces: false);
|
||||||
|
break;
|
||||||
|
|
||||||
|
// pipe/separator outside token
|
||||||
|
case LexBitType.Literal:
|
||||||
|
case LexBitType.TokenPipe:
|
||||||
|
case LexBitType.InputArgSeparator:
|
||||||
|
input.Dequeue();
|
||||||
|
yield return new LexTokenLiteral(next.Text);
|
||||||
|
break;
|
||||||
|
|
||||||
|
// anything else is invalid
|
||||||
|
default:
|
||||||
|
throw new InvalidOperationException($"Unexpected {next.Type}, expected {LexBitType.StartToken} or {LexBitType.Literal}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalise literal values
|
||||||
|
LinkedList<ILexToken> tokens = new LinkedList<ILexToken>(RawParse());
|
||||||
|
IList<LinkedListNode<ILexToken>> removeQueue = new List<LinkedListNode<ILexToken>>();
|
||||||
|
for (LinkedListNode<ILexToken> node = tokens.First; node != null; node = node.Next)
|
||||||
|
{
|
||||||
|
if (node.Value.Type != LexTokenType.Literal)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
// fetch info
|
||||||
|
ILexToken current = node.Value;
|
||||||
|
ILexToken previous = node.Previous?.Value;
|
||||||
|
ILexToken next = node.Next?.Value;
|
||||||
|
string newText = node.Value.Text;
|
||||||
|
|
||||||
|
// collapse sequential literals
|
||||||
|
if (previous?.Type == LexTokenType.Literal)
|
||||||
|
{
|
||||||
|
newText = previous.Text + newText;
|
||||||
|
removeQueue.Add(node.Previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
// trim before/after separator
|
||||||
|
if (next?.Type == LexTokenType.TokenInput || next?.Type == LexTokenType.TokenPipe)
|
||||||
|
newText = newText.TrimEnd();
|
||||||
|
if (previous?.Type == LexTokenType.TokenInput || previous?.Type == LexTokenType.TokenPipe)
|
||||||
|
newText = newText.TrimStart();
|
||||||
|
|
||||||
|
// trim whole result
|
||||||
|
if (trim && (previous == null || next == null))
|
||||||
|
{
|
||||||
|
if (previous == null)
|
||||||
|
newText = newText.TrimStart();
|
||||||
|
if (next == null)
|
||||||
|
newText = newText.TrimEnd();
|
||||||
|
|
||||||
|
if (newText == "")
|
||||||
|
removeQueue.Add(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
// replace value if needed
|
||||||
|
if (newText != current.Text)
|
||||||
|
node.Value = new LexTokenLiteral(newText);
|
||||||
|
}
|
||||||
|
foreach (LinkedListNode<ILexToken> entry in removeQueue)
|
||||||
|
tokens.Remove(entry);
|
||||||
|
|
||||||
|
// yield result
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Extract a token from the front of a lexical input queue.</summary>
|
||||||
|
/// <param name="input">The input from which to extract a token. The extracted lexical bits will be removed from the queue.</param>
|
||||||
|
/// <param name="impliedBraces">Whether we're parsing a token context (so the outer '{{' and '}}' are implied); else parse as a tokenisable string which main contain a mix of literal and {{token}} values.</param>
|
||||||
|
/// <param name="endBeforePipe">Whether a <see cref="LexTokenType.TokenPipe"/> should signal the end of the token. Only valid if <see cref="impliedBraces"/> is true.</param>
|
||||||
|
/// <returns>Returns the token, or multiple tokens if chained using <see cref="LexBitType.TokenPipe"/>.</returns>
|
||||||
|
public LexTokenToken ExtractToken(Queue<LexBit> input, bool impliedBraces, bool endBeforePipe = false)
|
||||||
|
{
|
||||||
|
LexBit GetNextAndAssert()
|
||||||
|
{
|
||||||
|
if (!input.Any())
|
||||||
|
throw new InvalidOperationException();
|
||||||
|
return input.Dequeue();
|
||||||
|
}
|
||||||
|
|
||||||
|
// start token
|
||||||
|
if (!impliedBraces)
|
||||||
|
{
|
||||||
|
LexBit startToken = GetNextAndAssert();
|
||||||
|
if (startToken.Type != LexBitType.StartToken)
|
||||||
|
throw new InvalidOperationException($"Unexpected {startToken.Type} at start of token.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// extract token name
|
||||||
|
LexBit name = GetNextAndAssert();
|
||||||
|
if (name.Type != LexBitType.Literal)
|
||||||
|
throw new InvalidOperationException($"Unexpected {name.Type} where token name should be.");
|
||||||
|
|
||||||
|
// extract input argument if present
|
||||||
|
LexTokenInputArg? inputArg = null;
|
||||||
|
if (input.Any() && input.Peek().Type == LexBitType.InputArgSeparator)
|
||||||
|
{
|
||||||
|
input.Dequeue();
|
||||||
|
inputArg = this.ExtractInputArgument(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
// extract piped tokens
|
||||||
|
IList<LexTokenToken> pipedTokens = new List<LexTokenToken>();
|
||||||
|
if (!endBeforePipe)
|
||||||
|
{
|
||||||
|
while (input.Any() && input.Peek().Type == LexBitType.TokenPipe)
|
||||||
|
{
|
||||||
|
input.Dequeue();
|
||||||
|
pipedTokens.Add(this.ExtractToken(input, impliedBraces: true, endBeforePipe: true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// end token
|
||||||
|
if (!impliedBraces)
|
||||||
|
{
|
||||||
|
LexBit endToken = GetNextAndAssert();
|
||||||
|
if (endToken.Type != LexBitType.EndToken)
|
||||||
|
throw new InvalidOperationException($"Unexpected {endToken.Type} before end of token.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new LexTokenToken(name.Text.Trim(), inputArg, impliedBraces, pipedTokens.ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Extract a token input argument from the front of a lexical input queue.</summary>
|
||||||
|
/// <param name="input">The input from which to extract an input argument. The extracted lexical bits will be removed from the queue.</param>
|
||||||
|
public LexTokenInputArg ExtractInputArgument(Queue<LexBit> input)
|
||||||
|
{
|
||||||
|
// extract input arg parts
|
||||||
|
Queue<LexBit> inputArgBits = new Queue<LexBit>();
|
||||||
|
int tokenDepth = 0;
|
||||||
|
bool reachedEnd = false;
|
||||||
|
while (!reachedEnd && input.Any())
|
||||||
|
{
|
||||||
|
LexBit next = input.Peek();
|
||||||
|
switch (next.Type)
|
||||||
|
{
|
||||||
|
case LexBitType.StartToken:
|
||||||
|
tokenDepth++;
|
||||||
|
inputArgBits.Enqueue(input.Dequeue());
|
||||||
|
break;
|
||||||
|
|
||||||
|
case LexBitType.TokenPipe:
|
||||||
|
if (tokenDepth > 0)
|
||||||
|
throw new InvalidOperationException($"Unexpected {next.Type} within token input argument");
|
||||||
|
|
||||||
|
reachedEnd = true;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case LexBitType.EndToken:
|
||||||
|
tokenDepth--;
|
||||||
|
|
||||||
|
if (tokenDepth < 0)
|
||||||
|
{
|
||||||
|
reachedEnd = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
inputArgBits.Enqueue(input.Dequeue());
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
inputArgBits.Enqueue(input.Dequeue());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse
|
||||||
|
ILexToken[] tokenised = this.ParseBitQueue(inputArgBits, impliedBraces: false, trim: true).ToArray();
|
||||||
|
return new LexTokenInputArg(tokenised);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,111 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using Pathoschild.Stardew.Common;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework
|
||||||
|
{
|
||||||
|
/// <summary>Handles loading assets from content packs.</summary>
|
||||||
|
internal class ManagedContentPack
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>A dictionary which matches case-insensitive relative paths to the exact path on disk, for case-insensitive file lookups on Linux/Mac.</summary>
|
||||||
|
private IDictionary<string, string> RelativePaths;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The managed content pack.</summary>
|
||||||
|
public IContentPack Pack { get; }
|
||||||
|
|
||||||
|
/// <summary>The content pack's manifest.</summary>
|
||||||
|
public IManifest Manifest => this.Pack.Manifest;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="pack">The content pack to manage.</param>
|
||||||
|
public ManagedContentPack(IContentPack pack)
|
||||||
|
{
|
||||||
|
this.Pack = pack;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get whether a file exists in the content pack.</summary>
|
||||||
|
/// <param name="key">The asset key.</param>
|
||||||
|
public bool HasFile(string key)
|
||||||
|
{
|
||||||
|
return this.GetRealPath(key) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get an asset from the content pack.</summary>
|
||||||
|
/// <typeparam name="T">The asset type.</typeparam>
|
||||||
|
/// <param name="key">The asset key.</param>
|
||||||
|
public T Load<T>(string key)
|
||||||
|
{
|
||||||
|
key = this.GetRealPath(key) ?? throw new FileNotFoundException($"The file '{key}' does not exist in the {this.Pack.Manifest.Name} content patch folder.");
|
||||||
|
return this.Pack.LoadAsset<T>(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Read a JSON file from the content pack folder.</summary>
|
||||||
|
/// <typeparam name="TModel">The model type.</typeparam>
|
||||||
|
/// <param name="path">The file path relative to the content pack directory.</param>
|
||||||
|
/// <returns>Returns the deserialised model, or <c>null</c> if the file doesn't exist or is empty.</returns>
|
||||||
|
public TModel ReadJsonFile<TModel>(string path) where TModel : class
|
||||||
|
{
|
||||||
|
return this.Pack.ReadJsonFile<TModel>(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Save data to a JSON file in the content pack's folder.</summary>
|
||||||
|
/// <typeparam name="TModel">The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types.</typeparam>
|
||||||
|
/// <param name="path">The file path relative to the mod folder.</param>
|
||||||
|
/// <param name="data">The arbitrary data to save.</param>
|
||||||
|
public void WriteJsonFile<TModel>(string path, TModel data) where TModel : class
|
||||||
|
{
|
||||||
|
this.Pack.WriteJsonFile(path, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the raw absolute path for a path within the content pack.</summary>
|
||||||
|
/// <param name="relativePath">The path relative to the content pack folder.</param>
|
||||||
|
public string GetFullPath(string relativePath)
|
||||||
|
{
|
||||||
|
return Path.Combine(this.Pack.DirectoryPath, relativePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get the actual relative path within the content pack for a file, matched case-insensitively, or <c>null</c> if not found.</summary>
|
||||||
|
/// <param name="key">The case-insensitive asset key.</param>
|
||||||
|
private string GetRealPath(string key)
|
||||||
|
{
|
||||||
|
key = PathUtilities.NormalisePathSeparators(key);
|
||||||
|
|
||||||
|
// cache file paths
|
||||||
|
if (this.RelativePaths == null)
|
||||||
|
{
|
||||||
|
this.RelativePaths = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
|
||||||
|
foreach (string path in this.GetRealRelativePaths())
|
||||||
|
this.RelativePaths[path] = path;
|
||||||
|
}
|
||||||
|
|
||||||
|
// find match
|
||||||
|
return this.RelativePaths.TryGetValue(key, out string relativePath)
|
||||||
|
? relativePath
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get all relative paths in the content pack directory.</summary>
|
||||||
|
private IEnumerable<string> GetRealRelativePaths()
|
||||||
|
{
|
||||||
|
foreach (string path in Directory.EnumerateFiles(this.Pack.DirectoryPath, "*", SearchOption.AllDirectories))
|
||||||
|
yield return path.Substring(this.Pack.DirectoryPath.Length + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,105 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.ConfigModels;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Migrations
|
||||||
|
{
|
||||||
|
/// <summary>Aggregates content pack migrations.</summary>
|
||||||
|
internal class AggregateMigration : IMigration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The valid format versions.</summary>
|
||||||
|
private readonly HashSet<string> ValidVersions;
|
||||||
|
|
||||||
|
/// <summary>The migrations to apply.</summary>
|
||||||
|
private readonly IMigration[] Migrations;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The version to which this migration applies.</summary>
|
||||||
|
public ISemanticVersion Version { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="version">The content pack version.</param>
|
||||||
|
/// <param name="validVersions">The valid format versions.</param>
|
||||||
|
/// <param name="migrations">The migrations to apply.</param>
|
||||||
|
public AggregateMigration(ISemanticVersion version, string[] validVersions, IMigration[] migrations)
|
||||||
|
{
|
||||||
|
this.Version = version;
|
||||||
|
this.ValidVersions = new HashSet<string>(validVersions);
|
||||||
|
this.Migrations = migrations.Where(m => m.Version.IsNewerThan(version)).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Migrate a content pack.</summary>
|
||||||
|
/// <param name="content">The content pack data to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed.</param>
|
||||||
|
/// <returns>Returns whether the content pack was successfully migrated.</returns>
|
||||||
|
public bool TryMigrate(ContentConfig content, out string error)
|
||||||
|
{
|
||||||
|
// validate format version
|
||||||
|
if (!this.ValidVersions.Contains(content.Format.ToString()))
|
||||||
|
{
|
||||||
|
error = $"unsupported format {content.Format} (supported version: {string.Join(", ", this.ValidVersions)}).";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// apply migrations
|
||||||
|
foreach (IMigration migration in this.Migrations)
|
||||||
|
{
|
||||||
|
if (!migration.TryMigrate(content, out error))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// no issues found
|
||||||
|
error = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Migrate a token name.</summary>
|
||||||
|
/// <param name="name">The token name to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed (if any).</param>
|
||||||
|
/// <returns>Returns whether migration succeeded.</returns>
|
||||||
|
public bool TryMigrate(ref TokenName name, out string error)
|
||||||
|
{
|
||||||
|
// apply migrations
|
||||||
|
foreach (IMigration migration in this.Migrations)
|
||||||
|
{
|
||||||
|
if (!migration.TryMigrate(ref name, out error))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// no issues found
|
||||||
|
error = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Migrate a tokenised string.</summary>
|
||||||
|
/// <param name="tokenStr">The tokenised string to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed (if any).</param>
|
||||||
|
/// <returns>Returns whether migration succeeded.</returns>
|
||||||
|
public bool TryMigrate(ref TokenString tokenStr, out string error)
|
||||||
|
{
|
||||||
|
// apply migrations
|
||||||
|
foreach (IMigration migration in this.Migrations)
|
||||||
|
{
|
||||||
|
if (!migration.TryMigrate(ref tokenStr, out error))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// no issues found
|
||||||
|
error = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,96 @@
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.ConfigModels;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Migrations
|
||||||
|
{
|
||||||
|
/// <summary>The base implementation for a format version migrator.</summary>
|
||||||
|
internal abstract class BaseMigration : IMigration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>The tokens added in this format version.</summary>
|
||||||
|
protected InvariantHashSet AddedTokens { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The format version to which this migration applies.</summary>
|
||||||
|
public ISemanticVersion Version { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Migrate a content pack.</summary>
|
||||||
|
/// <param name="content">The content pack data to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed.</param>
|
||||||
|
/// <returns>Returns whether the content pack was successfully migrated.</returns>
|
||||||
|
public virtual bool TryMigrate(ContentConfig content, out string error)
|
||||||
|
{
|
||||||
|
error = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Migrate a token name.</summary>
|
||||||
|
/// <param name="name">The token name to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed (if any).</param>
|
||||||
|
/// <returns>Returns whether migration succeeded.</returns>
|
||||||
|
public virtual bool TryMigrate(ref TokenName name, out string error)
|
||||||
|
{
|
||||||
|
// tokens which need a higher version
|
||||||
|
if (this.AddedTokens.Contains(name.Key))
|
||||||
|
{
|
||||||
|
error = this.GetNounPhraseError($"using token {name}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// no issue found
|
||||||
|
error = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Migrate a tokenised string.</summary>
|
||||||
|
/// <param name="tokenStr">The tokenised string to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed (if any).</param>
|
||||||
|
/// <returns>Returns whether migration succeeded.</returns>
|
||||||
|
public virtual bool TryMigrate(ref TokenString tokenStr, out string error)
|
||||||
|
{
|
||||||
|
// tokens which need a high version
|
||||||
|
foreach (TokenName token in tokenStr.Tokens)
|
||||||
|
{
|
||||||
|
if (this.AddedTokens.Contains(token.Key))
|
||||||
|
{
|
||||||
|
error = this.GetNounPhraseError($"using token {token.Key}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// no issue found
|
||||||
|
error = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Protected methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="version">The version to which this migration applies.</param>
|
||||||
|
protected BaseMigration(ISemanticVersion version)
|
||||||
|
{
|
||||||
|
this.Version = version;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get an error message indicating an action or feature requires a newer format version.</summary>
|
||||||
|
/// <param name="nounPhrase">The noun phrase, like "using X feature".</param>
|
||||||
|
protected string GetNounPhraseError(string nounPhrase)
|
||||||
|
{
|
||||||
|
return $"{nounPhrase} requires {nameof(ContentConfig.Format)} version {this.Version} or later";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.ConfigModels;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Migrations
|
||||||
|
{
|
||||||
|
/// <summary>Migrates patches to a given format version.</summary>
|
||||||
|
internal interface IMigration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The format version to which this migration applies.</summary>
|
||||||
|
ISemanticVersion Version { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Migrate a content pack.</summary>
|
||||||
|
/// <param name="content">The content pack data to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed.</param>
|
||||||
|
/// <returns>Returns whether migration succeeded.</returns>
|
||||||
|
bool TryMigrate(ContentConfig content, out string error);
|
||||||
|
|
||||||
|
/// <summary>Migrate a token name.</summary>
|
||||||
|
/// <param name="name">The token name to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed (if any).</param>
|
||||||
|
/// <returns>Returns whether migration succeeded.</returns>
|
||||||
|
bool TryMigrate(ref TokenName name, out string error);
|
||||||
|
|
||||||
|
/// <summary>Migrate a tokenised string.</summary>
|
||||||
|
/// <param name="tokenStr">The tokenised string to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed (if any).</param>
|
||||||
|
/// <returns>Returns whether migration succeeded.</returns>
|
||||||
|
bool TryMigrate(ref TokenString tokenStr, out string error);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,56 @@
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.ConfigModels;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Migrations
|
||||||
|
{
|
||||||
|
/// <summary>Migrate patches to format version 1.3.</summary>
|
||||||
|
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Named for clarity.")]
|
||||||
|
internal class Migration_1_3 : BaseMigration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
public Migration_1_3()
|
||||||
|
: base(new SemanticVersion(1, 3, 0)) { }
|
||||||
|
|
||||||
|
/// <summary>Migrate a content pack.</summary>
|
||||||
|
/// <param name="content">The content pack data to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed.</param>
|
||||||
|
/// <returns>Returns whether the content pack was successfully migrated.</returns>
|
||||||
|
public override bool TryMigrate(ContentConfig content, out string error)
|
||||||
|
{
|
||||||
|
if (!base.TryMigrate(content, out error))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// 1.3 adds config.json
|
||||||
|
if (content.ConfigSchema?.Any() == true)
|
||||||
|
{
|
||||||
|
error = this.GetNounPhraseError($"using the {nameof(ContentConfig.ConfigSchema)} field");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// check patch format
|
||||||
|
foreach (PatchConfig patch in content.Changes)
|
||||||
|
{
|
||||||
|
// 1.3 adds tokens in FromFile
|
||||||
|
if (patch.FromFile != null && patch.FromFile.Contains("{{"))
|
||||||
|
{
|
||||||
|
error = this.GetNounPhraseError($"using the {{{{token}}}} feature in {nameof(PatchConfig.FromFile)} fields");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.3 adds When
|
||||||
|
if (content.Changes.Any(p => p.When != null && p.When.Any()))
|
||||||
|
{
|
||||||
|
error = this.GetNounPhraseError($"using the condition feature ({nameof(ContentConfig.Changes)}.{nameof(PatchConfig.When)} field)");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Migrations
|
||||||
|
{
|
||||||
|
/// <summary>Migrate patches to format version 1.4.</summary>
|
||||||
|
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Named for clarity.")]
|
||||||
|
internal class Migration_1_4 : BaseMigration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
public Migration_1_4()
|
||||||
|
: base(new SemanticVersion(1, 4, 0))
|
||||||
|
{
|
||||||
|
this.AddedTokens = new InvariantHashSet
|
||||||
|
{
|
||||||
|
ConditionType.DayEvent.ToString(),
|
||||||
|
ConditionType.HasFlag.ToString(),
|
||||||
|
ConditionType.HasSeenEvent.ToString(),
|
||||||
|
ConditionType.Hearts.ToString(),
|
||||||
|
ConditionType.Relationship.ToString(),
|
||||||
|
ConditionType.Spouse.ToString()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,65 @@
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.ConfigModels;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Migrations
|
||||||
|
{
|
||||||
|
/// <summary>Migrate patches to format version 1.5.</summary>
|
||||||
|
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Named for clarity.")]
|
||||||
|
internal class Migration_1_5 : BaseMigration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
public Migration_1_5()
|
||||||
|
: base(new SemanticVersion(1, 5, 0))
|
||||||
|
{
|
||||||
|
this.AddedTokens = new InvariantHashSet
|
||||||
|
{
|
||||||
|
ConditionType.FarmCave.ToString(),
|
||||||
|
ConditionType.FarmhouseUpgrade.ToString(),
|
||||||
|
ConditionType.FarmName.ToString(),
|
||||||
|
ConditionType.HasFile.ToString(),
|
||||||
|
ConditionType.HasProfession.ToString(),
|
||||||
|
ConditionType.PlayerGender.ToString(),
|
||||||
|
ConditionType.PlayerName.ToString(),
|
||||||
|
ConditionType.PreferredPet.ToString(),
|
||||||
|
ConditionType.Year.ToString()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Migrate a content pack.</summary>
|
||||||
|
/// <param name="content">The content pack data to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed.</param>
|
||||||
|
/// <returns>Returns whether the content pack was successfully migrated.</returns>
|
||||||
|
public override bool TryMigrate(ContentConfig content, out string error)
|
||||||
|
{
|
||||||
|
if (!base.TryMigrate(content, out error))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// 1.5 adds dynamic tokens
|
||||||
|
if (content.DynamicTokens?.Any() == true)
|
||||||
|
{
|
||||||
|
error = this.GetNounPhraseError($"using the {nameof(ContentConfig.DynamicTokens)} field");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// check patch format
|
||||||
|
foreach (PatchConfig patch in content.Changes)
|
||||||
|
{
|
||||||
|
// 1.5 adds multiple Target values
|
||||||
|
if (patch.Target?.Contains(",") == true)
|
||||||
|
{
|
||||||
|
error = this.GetNounPhraseError($"specifying multiple {nameof(PatchConfig.Target)} values");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,46 @@
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.ConfigModels;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Migrations
|
||||||
|
{
|
||||||
|
/// <summary>Migrate patches to format version 1.6.</summary>
|
||||||
|
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Named for clarity.")]
|
||||||
|
internal class Migration_1_6 : BaseMigration
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
public Migration_1_6()
|
||||||
|
: base(new SemanticVersion(1, 6, 0))
|
||||||
|
{
|
||||||
|
this.AddedTokens = new InvariantHashSet
|
||||||
|
{
|
||||||
|
ConditionType.HasWalletItem.ToString(),
|
||||||
|
ConditionType.SkillLevel.ToString()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Migrate a content pack.</summary>
|
||||||
|
/// <param name="content">The content pack data to migrate.</param>
|
||||||
|
/// <param name="error">An error message which indicates why migration failed.</param>
|
||||||
|
/// <returns>Returns whether the content pack was successfully migrated.</returns>
|
||||||
|
public override bool TryMigrate(ContentConfig content, out string error)
|
||||||
|
{
|
||||||
|
if (!base.TryMigrate(content, out error))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// before 1.6, the 'sun' weather included 'wind'
|
||||||
|
foreach (PatchConfig patch in content.Changes)
|
||||||
|
{
|
||||||
|
if (patch.When != null && patch.When.TryGetValue(ConditionType.Weather.ToString(), out string value) && value.Contains("Sun"))
|
||||||
|
patch.When[ConditionType.Weather.ToString()] = $"{value}, Wind";
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,161 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework
|
||||||
|
{
|
||||||
|
/// <summary>Manages the token context for a specific content pack.</summary>
|
||||||
|
internal class ModTokenContext : IContext
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The available global tokens.</summary>
|
||||||
|
private readonly IContext GlobalContext;
|
||||||
|
|
||||||
|
/// <summary>The standard self-contained tokens.</summary>
|
||||||
|
private readonly GenericTokenContext StandardContext = new GenericTokenContext();
|
||||||
|
|
||||||
|
/// <summary>The dynamic tokens whose value depends on <see cref="DynamicTokenValues"/>.</summary>
|
||||||
|
private readonly GenericTokenContext<DynamicToken> DynamicContext = new GenericTokenContext<DynamicToken>();
|
||||||
|
|
||||||
|
/// <summary>The conditional values used to set the values of <see cref="DynamicContext"/> tokens.</summary>
|
||||||
|
private readonly IList<DynamicTokenValue> DynamicTokenValues = new List<DynamicTokenValue>();
|
||||||
|
|
||||||
|
/// <summary>The underlying token contexts in priority order.</summary>
|
||||||
|
private readonly IContext[] Contexts;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/****
|
||||||
|
** Token management
|
||||||
|
****/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="tokenManager">Manages the available global tokens.</param>
|
||||||
|
public ModTokenContext(TokenManager tokenManager)
|
||||||
|
{
|
||||||
|
this.GlobalContext = tokenManager;
|
||||||
|
this.Contexts = new[] { this.GlobalContext, this.StandardContext, this.DynamicContext };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Add a standard token to the context.</summary>
|
||||||
|
/// <param name="token">The config token to add.</param>
|
||||||
|
public void Add(IToken token)
|
||||||
|
{
|
||||||
|
if (token.Name.HasSubkey())
|
||||||
|
throw new InvalidOperationException($"Can't register the '{token.Name}' mod token because subkeys aren't supported.");
|
||||||
|
if (this.GlobalContext.Contains(token.Name, enforceContext: false))
|
||||||
|
throw new InvalidOperationException($"Can't register the '{token.Name}' mod token because there's a global token with that name.");
|
||||||
|
if (this.StandardContext.Contains(token.Name, enforceContext: false))
|
||||||
|
throw new InvalidOperationException($"The '{token.Name}' token is already registered.");
|
||||||
|
|
||||||
|
this.StandardContext.Tokens[token.Name] = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Add a dynamic token value to the context.</summary>
|
||||||
|
/// <param name="tokenValue">The token to add.</param>
|
||||||
|
public void Add(DynamicTokenValue tokenValue)
|
||||||
|
{
|
||||||
|
// validate
|
||||||
|
if (this.GlobalContext.Contains(tokenValue.Name, enforceContext: false))
|
||||||
|
throw new InvalidOperationException($"Can't register a '{tokenValue.Name}' token because there's a global token with that name.");
|
||||||
|
if (this.StandardContext.Contains(tokenValue.Name, enforceContext: false))
|
||||||
|
throw new InvalidOperationException($"Can't register a '{tokenValue.Name}' dynamic token because there's a config token with that name.");
|
||||||
|
|
||||||
|
// get (or create) token
|
||||||
|
if (!this.DynamicContext.Tokens.TryGetValue(tokenValue.Name, out DynamicToken token))
|
||||||
|
this.DynamicContext.Save(token = new DynamicToken(tokenValue.Name));
|
||||||
|
|
||||||
|
// add token value
|
||||||
|
token.AddAllowedValues(tokenValue.Value);
|
||||||
|
this.DynamicTokenValues.Add(tokenValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Update the current context.</summary>
|
||||||
|
public void UpdateContext(IContext globalContext)
|
||||||
|
{
|
||||||
|
// update config tokens
|
||||||
|
foreach (IToken token in this.StandardContext.Tokens.Values)
|
||||||
|
{
|
||||||
|
if (token.IsMutable)
|
||||||
|
token.UpdateContext(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
// reset dynamic tokens
|
||||||
|
foreach (DynamicToken token in this.DynamicContext.Tokens.Values)
|
||||||
|
token.SetValidInContext(false);
|
||||||
|
foreach (DynamicTokenValue tokenValue in this.DynamicTokenValues)
|
||||||
|
{
|
||||||
|
if (tokenValue.Conditions.Values.All(p => p.IsMatch(this)))
|
||||||
|
{
|
||||||
|
DynamicToken token = this.DynamicContext.Tokens[tokenValue.Name];
|
||||||
|
token.SetValue(tokenValue.Value);
|
||||||
|
token.SetValidInContext(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the underlying tokens.</summary>
|
||||||
|
/// <param name="localOnly">Whether to only return local tokens.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
public IEnumerable<IToken> GetTokens(bool localOnly, bool enforceContext)
|
||||||
|
{
|
||||||
|
foreach (IContext context in this.Contexts)
|
||||||
|
{
|
||||||
|
if (localOnly && context == this.GlobalContext)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
foreach (IToken token in context.GetTokens(enforceContext))
|
||||||
|
yield return token;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** IContext
|
||||||
|
****/
|
||||||
|
/// <summary>Get whether the context contains the given token.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
public bool Contains(TokenName name, bool enforceContext)
|
||||||
|
{
|
||||||
|
return this.Contexts.Any(p => p.Contains(name, enforceContext));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the underlying token which handles a name.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
/// <returns>Returns the matching token, or <c>null</c> if none was found.</returns>
|
||||||
|
public IToken GetToken(TokenName name, bool enforceContext)
|
||||||
|
{
|
||||||
|
foreach (IContext context in this.Contexts)
|
||||||
|
{
|
||||||
|
IToken token = context.GetToken(name, enforceContext);
|
||||||
|
if (token != null)
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the underlying tokens.</summary>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
public IEnumerable<IToken> GetTokens(bool enforceContext)
|
||||||
|
{
|
||||||
|
return this.GetTokens(localOnly: false, enforceContext: enforceContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the current values of the given token for comparison.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
/// <returns>Return the values of the matching token, or an empty list if the token doesn't exist.</returns>
|
||||||
|
/// <exception cref="ArgumentNullException">The specified token name is null.</exception>
|
||||||
|
public IEnumerable<string> GetValues(TokenName name, bool enforceContext)
|
||||||
|
{
|
||||||
|
IToken token = this.GetToken(name, enforceContext);
|
||||||
|
return token?.GetValues(name) ?? Enumerable.Empty<string>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,310 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.ConfigModels;
|
||||||
|
using ContentPatcher.Framework.Patches;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using ContentPatcher.Framework.Validators;
|
||||||
|
using Microsoft.Xna.Framework.Graphics;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework
|
||||||
|
{
|
||||||
|
/// <summary>Manages loaded patches.</summary>
|
||||||
|
internal class PatchManager : IAssetLoader, IAssetEditor
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/****
|
||||||
|
** State
|
||||||
|
****/
|
||||||
|
/// <summary>Manages the available contextual tokens.</summary>
|
||||||
|
private readonly TokenManager TokenManager;
|
||||||
|
|
||||||
|
/// <summary>Encapsulates monitoring and logging.</summary>
|
||||||
|
private readonly IMonitor Monitor;
|
||||||
|
|
||||||
|
/// <summary>Handle special validation logic on loaded or edited assets.</summary>
|
||||||
|
private readonly IAssetValidator[] AssetValidators;
|
||||||
|
|
||||||
|
/// <summary>The patches which are permanently disabled for this session.</summary>
|
||||||
|
private readonly IList<DisabledPatch> PermanentlyDisabledPatches = new List<DisabledPatch>();
|
||||||
|
|
||||||
|
/// <summary>The patches to apply.</summary>
|
||||||
|
private readonly HashSet<IPatch> Patches = new HashSet<IPatch>();
|
||||||
|
|
||||||
|
/// <summary>The patches to apply, indexed by asset name.</summary>
|
||||||
|
private InvariantDictionary<HashSet<IPatch>> PatchesByCurrentTarget = new InvariantDictionary<HashSet<IPatch>>();
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
/// <param name="tokenManager">Manages the available contextual tokens.</param>
|
||||||
|
/// <param name="assetValidators">Handle special validation logic on loaded or edited assets.</param>
|
||||||
|
public PatchManager(IMonitor monitor, TokenManager tokenManager, IAssetValidator[] assetValidators)
|
||||||
|
{
|
||||||
|
this.Monitor = monitor;
|
||||||
|
this.TokenManager = tokenManager;
|
||||||
|
this.AssetValidators = assetValidators;
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Patching
|
||||||
|
****/
|
||||||
|
/// <summary>Get whether this instance can load the initial version of the given asset.</summary>
|
||||||
|
/// <param name="asset">Basic metadata about the asset being loaded.</param>
|
||||||
|
public bool CanLoad<T>(IAssetInfo asset)
|
||||||
|
{
|
||||||
|
IPatch[] patches = this.GetCurrentLoaders(asset).ToArray();
|
||||||
|
if (patches.Length > 1)
|
||||||
|
{
|
||||||
|
this.Monitor.Log($"Multiple patches want to load {asset.AssetName} ({string.Join(", ", from entry in patches orderby entry.LogName select entry.LogName)}). None will be applied.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool canLoad = patches.Any();
|
||||||
|
this.Monitor.VerboseLog($"check: [{(canLoad ? "X" : " ")}] can load {asset.AssetName}");
|
||||||
|
return canLoad;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get whether this instance can edit the given asset.</summary>
|
||||||
|
/// <param name="asset">Basic metadata about the asset being loaded.</param>
|
||||||
|
public bool CanEdit<T>(IAssetInfo asset)
|
||||||
|
{
|
||||||
|
bool canEdit = this.GetCurrentEditors(asset).Any();
|
||||||
|
this.Monitor.VerboseLog($"check: [{(canEdit ? "X" : " ")}] can edit {asset.AssetName}");
|
||||||
|
return canEdit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Load a matched asset.</summary>
|
||||||
|
/// <param name="asset">Basic metadata about the asset being loaded.</param>
|
||||||
|
public T Load<T>(IAssetInfo asset)
|
||||||
|
{
|
||||||
|
// get applicable patches for context
|
||||||
|
IPatch[] patches = this.GetCurrentLoaders(asset).ToArray();
|
||||||
|
if (!patches.Any())
|
||||||
|
throw new InvalidOperationException($"Can't load asset key '{asset.AssetName}' because no patches currently apply. This should never happen because it means validation failed.");
|
||||||
|
if (patches.Length > 1)
|
||||||
|
throw new InvalidOperationException($"Can't load asset key '{asset.AssetName}' because multiple patches apply ({string.Join(", ", from entry in patches orderby entry.LogName select entry.LogName)}). This should never happen because it means validation failed.");
|
||||||
|
|
||||||
|
// apply patch
|
||||||
|
IPatch patch = patches.Single();
|
||||||
|
if (this.Monitor.IsVerbose)
|
||||||
|
this.Monitor.VerboseLog($"Patch \"{patch.LogName}\" loaded {asset.AssetName}.");
|
||||||
|
else
|
||||||
|
this.Monitor.Log($"{patch.ContentPack.Manifest.Name} loaded {asset.AssetName}.", LogLevel.Trace);
|
||||||
|
|
||||||
|
T data = patch.Load<T>(asset);
|
||||||
|
|
||||||
|
foreach (IAssetValidator validator in this.AssetValidators)
|
||||||
|
{
|
||||||
|
if (!validator.TryValidate(asset, data, patch, out string error))
|
||||||
|
{
|
||||||
|
this.Monitor.Log($"Can't apply patch {patch.LogName} to {asset.AssetName}: {error}.", LogLevel.Error);
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
patch.IsApplied = true;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Edit a matched asset.</summary>
|
||||||
|
/// <param name="asset">A helper which encapsulates metadata about an asset and enables changes to it.</param>
|
||||||
|
public void Edit<T>(IAssetData asset)
|
||||||
|
{
|
||||||
|
IPatch[] patches = this.GetCurrentEditors(asset).ToArray();
|
||||||
|
if (!patches.Any())
|
||||||
|
throw new InvalidOperationException($"Can't edit asset key '{asset.AssetName}' because no patches currently apply. This should never happen.");
|
||||||
|
|
||||||
|
InvariantHashSet loggedContentPacks = new InvariantHashSet();
|
||||||
|
foreach (IPatch patch in patches)
|
||||||
|
{
|
||||||
|
if (this.Monitor.IsVerbose)
|
||||||
|
this.Monitor.VerboseLog($"Applied patch \"{patch.LogName}\" to {asset.AssetName}.");
|
||||||
|
else if (loggedContentPacks.Add(patch.ContentPack.Manifest.Name))
|
||||||
|
this.Monitor.Log($"{patch.ContentPack.Manifest.Name} edited {asset.AssetName}.", LogLevel.Trace);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
patch.Edit<T>(asset);
|
||||||
|
patch.IsApplied = true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
this.Monitor.Log($"unhandled exception applying patch: {patch.LogName}.\n{ex}", LogLevel.Error);
|
||||||
|
patch.IsApplied = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Update the current context.</summary>
|
||||||
|
/// <param name="contentHelper">The content helper through which to invalidate assets.</param>
|
||||||
|
public void UpdateContext(IContentHelper contentHelper)
|
||||||
|
{
|
||||||
|
this.Monitor.VerboseLog("Propagating context...");
|
||||||
|
|
||||||
|
// update patches
|
||||||
|
InvariantHashSet reloadAssetNames = new InvariantHashSet();
|
||||||
|
string prevAssetName = null;
|
||||||
|
foreach (IPatch patch in this.Patches.OrderByIgnoreCase(p => p.TargetAsset).ThenByIgnoreCase(p => p.LogName))
|
||||||
|
{
|
||||||
|
// log asset name
|
||||||
|
if (this.Monitor.IsVerbose && prevAssetName != patch.TargetAsset)
|
||||||
|
{
|
||||||
|
this.Monitor.VerboseLog($" {patch.TargetAsset}:");
|
||||||
|
prevAssetName = patch.TargetAsset;
|
||||||
|
}
|
||||||
|
|
||||||
|
// track old values
|
||||||
|
string wasAssetName = patch.TargetAsset;
|
||||||
|
bool wasApplied = patch.MatchesContext;
|
||||||
|
|
||||||
|
// update patch
|
||||||
|
IContext tokenContext = this.TokenManager.TrackLocalTokens(patch.ContentPack.Pack);
|
||||||
|
bool changed = patch.UpdateContext(tokenContext);
|
||||||
|
bool shouldApply = patch.MatchesContext;
|
||||||
|
|
||||||
|
// track patches to reload
|
||||||
|
bool reload = (wasApplied && changed) || (!wasApplied && shouldApply);
|
||||||
|
if (reload)
|
||||||
|
{
|
||||||
|
patch.IsApplied = false;
|
||||||
|
if (wasApplied)
|
||||||
|
reloadAssetNames.Add(wasAssetName);
|
||||||
|
if (shouldApply)
|
||||||
|
reloadAssetNames.Add(patch.TargetAsset);
|
||||||
|
}
|
||||||
|
|
||||||
|
// log change
|
||||||
|
if (this.Monitor.IsVerbose)
|
||||||
|
{
|
||||||
|
IList<string> changes = new List<string>();
|
||||||
|
if (wasApplied != shouldApply)
|
||||||
|
changes.Add(shouldApply ? "enabled" : "disabled");
|
||||||
|
if (wasAssetName != patch.TargetAsset)
|
||||||
|
changes.Add($"target: {wasAssetName} => {patch.TargetAsset}");
|
||||||
|
string changesStr = string.Join(", ", changes);
|
||||||
|
|
||||||
|
this.Monitor.VerboseLog($" [{(shouldApply ? "X" : " ")}] {patch.LogName}: {(changes.Any() ? changesStr : "OK")}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// warn for invalid load patch
|
||||||
|
if (patch is LoadPatch loadPatch && patch.MatchesContext && !patch.ContentPack.HasFile(loadPatch.FromLocalAsset.Value))
|
||||||
|
this.Monitor.Log($"Patch error: {patch.LogName} has a {nameof(PatchConfig.FromFile)} which matches non-existent file '{loadPatch.FromLocalAsset.Value}'.", LogLevel.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// rebuild asset name lookup
|
||||||
|
this.PatchesByCurrentTarget = new InvariantDictionary<HashSet<IPatch>>(
|
||||||
|
from patchGroup in this.Patches.GroupByIgnoreCase(p => p.TargetAsset)
|
||||||
|
let key = patchGroup.Key
|
||||||
|
let value = new HashSet<IPatch>(patchGroup)
|
||||||
|
select new KeyValuePair<string, HashSet<IPatch>>(key, value)
|
||||||
|
);
|
||||||
|
|
||||||
|
// reload assets if needed
|
||||||
|
if (reloadAssetNames.Any())
|
||||||
|
{
|
||||||
|
this.Monitor.VerboseLog($" reloading {reloadAssetNames.Count} assets: {string.Join(", ", reloadAssetNames.OrderByIgnoreCase(p => p))}");
|
||||||
|
contentHelper.InvalidateCache(asset =>
|
||||||
|
{
|
||||||
|
this.Monitor.VerboseLog($" [{(reloadAssetNames.Contains(asset.AssetName) ? "X" : " ")}] reload {asset.AssetName}");
|
||||||
|
return reloadAssetNames.Contains(asset.AssetName);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Patches
|
||||||
|
****/
|
||||||
|
/// <summary>Add a patch.</summary>
|
||||||
|
/// <param name="patch">The patch to add.</param>
|
||||||
|
public void Add(IPatch patch)
|
||||||
|
{
|
||||||
|
// set initial context
|
||||||
|
IContext tokenContext = this.TokenManager.TrackLocalTokens(patch.ContentPack.Pack);
|
||||||
|
patch.UpdateContext(tokenContext);
|
||||||
|
|
||||||
|
// add to patch list
|
||||||
|
this.Monitor.VerboseLog($" added {patch.Type} {patch.TargetAsset}.");
|
||||||
|
this.Patches.Add(patch);
|
||||||
|
|
||||||
|
// add to lookup cache
|
||||||
|
if (this.PatchesByCurrentTarget.TryGetValue(patch.TargetAsset, out HashSet<IPatch> patches))
|
||||||
|
patches.Add(patch);
|
||||||
|
else
|
||||||
|
this.PatchesByCurrentTarget[patch.TargetAsset] = new HashSet<IPatch> { patch };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Add a patch that's permanently disabled for this session.</summary>
|
||||||
|
/// <param name="patch">The patch to add.</param>
|
||||||
|
public void AddPermanentlyDisabled(DisabledPatch patch)
|
||||||
|
{
|
||||||
|
this.PermanentlyDisabledPatches.Add(patch);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get valid patches regardless of context.</summary>
|
||||||
|
public IEnumerable<IPatch> GetPatches()
|
||||||
|
{
|
||||||
|
return this.Patches;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get valid patches regardless of context.</summary>
|
||||||
|
/// <param name="assetName">The asset name for which to find patches.</param>
|
||||||
|
public IEnumerable<IPatch> GetPatches(string assetName)
|
||||||
|
{
|
||||||
|
if (this.PatchesByCurrentTarget.TryGetValue(assetName, out HashSet<IPatch> patches))
|
||||||
|
return patches;
|
||||||
|
return new IPatch[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get patches which are permanently disabled for this session, along with the reason they were.</summary>
|
||||||
|
public IEnumerable<DisabledPatch> GetPermanentlyDisabledPatches()
|
||||||
|
{
|
||||||
|
return this.PermanentlyDisabledPatches;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get patches which load the given asset in the current context.</summary>
|
||||||
|
/// <param name="asset">The asset being intercepted.</param>
|
||||||
|
public IEnumerable<IPatch> GetCurrentLoaders(IAssetInfo asset)
|
||||||
|
{
|
||||||
|
return this
|
||||||
|
.GetPatches(asset.AssetName)
|
||||||
|
.Where(patch => patch.Type == PatchType.Load && patch.MatchesContext && patch.IsValidInContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get patches which edit the given asset in the current context.</summary>
|
||||||
|
/// <param name="asset">The asset being intercepted.</param>
|
||||||
|
public IEnumerable<IPatch> GetCurrentEditors(IAssetInfo asset)
|
||||||
|
{
|
||||||
|
PatchType? patchType = this.GetEditType(asset.DataType);
|
||||||
|
if (patchType == null)
|
||||||
|
return new IPatch[0];
|
||||||
|
|
||||||
|
return this
|
||||||
|
.GetPatches(asset.AssetName)
|
||||||
|
.Where(patch => patch.Type == patchType && patch.MatchesContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get the patch type which applies when editing a given asset type.</summary>
|
||||||
|
/// <param name="assetType">The asset type.</param>
|
||||||
|
private PatchType? GetEditType(Type assetType)
|
||||||
|
{
|
||||||
|
if (assetType == typeof(Texture2D))
|
||||||
|
return PatchType.EditImage;
|
||||||
|
if (assetType.IsGenericType && assetType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
|
||||||
|
return PatchType.EditData;
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
namespace ContentPatcher.Framework.Patches
|
||||||
|
{
|
||||||
|
/// <summary>An invalid patch that couldn't be loaded.</summary>
|
||||||
|
internal class DisabledPatch
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>A unique name for this patch shown in log messages.</summary>
|
||||||
|
public string LogName { get; }
|
||||||
|
|
||||||
|
/// <summary>The raw patch type.</summary>
|
||||||
|
public string Type { get; }
|
||||||
|
|
||||||
|
/// <summary>The raw asset name to intercept.</summary>
|
||||||
|
public string AssetName { get; }
|
||||||
|
|
||||||
|
/// <summary>The content pack which requested the patch.</summary>
|
||||||
|
public ManagedContentPack ContentPack { get; }
|
||||||
|
|
||||||
|
/// <summary>The reason this patch is disabled.</summary>
|
||||||
|
public string ReasonDisabled { get; }
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="logName">A unique name for this patch shown in log messages.</param>
|
||||||
|
/// <param name="type">The raw patch type.</param>
|
||||||
|
/// <param name="assetName">The raw asset name to intercept.</param>
|
||||||
|
/// <param name="contentPack">The content pack which requested the patch.</param>
|
||||||
|
/// <param name="reasonDisabled">The reason this patch is disabled.</param>
|
||||||
|
public DisabledPatch(string logName, string type, string assetName, ManagedContentPack contentPack, string reasonDisabled)
|
||||||
|
{
|
||||||
|
this.LogName = logName;
|
||||||
|
this.Type = type;
|
||||||
|
this.ContentPack = contentPack;
|
||||||
|
this.AssetName = assetName;
|
||||||
|
this.ReasonDisabled = reasonDisabled;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,184 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.ConfigModels;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using Microsoft.Xna.Framework.Graphics;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Patches
|
||||||
|
{
|
||||||
|
/// <summary>Metadata for a data to edit into a data file.</summary>
|
||||||
|
internal class EditDataPatch : Patch
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>Encapsulates monitoring and logging.</summary>
|
||||||
|
private readonly IMonitor Monitor;
|
||||||
|
|
||||||
|
/// <summary>The data records to edit.</summary>
|
||||||
|
private readonly EditDataPatchRecord[] Records;
|
||||||
|
|
||||||
|
/// <summary>The data fields to edit.</summary>
|
||||||
|
private readonly EditDataPatchField[] Fields;
|
||||||
|
|
||||||
|
/// <summary>The token strings which contain mutable tokens.</summary>
|
||||||
|
private readonly TokenString[] MutableTokenStrings;
|
||||||
|
|
||||||
|
/// <summary>Whether the next context update is the first one.</summary>
|
||||||
|
private bool IsFirstUpdate = true;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="logName">A unique name for this patch shown in log messages.</param>
|
||||||
|
/// <param name="contentPack">The content pack which requested the patch.</param>
|
||||||
|
/// <param name="assetName">The normalised asset name to intercept.</param>
|
||||||
|
/// <param name="conditions">The conditions which determine whether this patch should be applied.</param>
|
||||||
|
/// <param name="records">The data records to edit.</param>
|
||||||
|
/// <param name="fields">The data fields to edit.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
/// <param name="normaliseAssetName">Normalise an asset name.</param>
|
||||||
|
public EditDataPatch(string logName, ManagedContentPack contentPack, TokenString assetName, ConditionDictionary conditions, IEnumerable<EditDataPatchRecord> records, IEnumerable<EditDataPatchField> fields, IMonitor monitor, Func<string, string> normaliseAssetName)
|
||||||
|
: base(logName, PatchType.EditData, contentPack, assetName, conditions, normaliseAssetName)
|
||||||
|
{
|
||||||
|
this.Records = records.ToArray();
|
||||||
|
this.Fields = fields.ToArray();
|
||||||
|
this.Monitor = monitor;
|
||||||
|
this.MutableTokenStrings = this.GetTokenStrings(this.Records, this.Fields).Where(str => str.Tokens.Any()).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Update the patch data when the context changes.</summary>
|
||||||
|
/// <param name="context">Provides access to contextual tokens.</param>
|
||||||
|
/// <returns>Returns whether the patch data changed.</returns>
|
||||||
|
public override bool UpdateContext(IContext context)
|
||||||
|
{
|
||||||
|
bool changed = base.UpdateContext(context);
|
||||||
|
|
||||||
|
// We need to update all token strings once. After this first time, we can skip
|
||||||
|
// updating any immutable tokens.
|
||||||
|
if (this.IsFirstUpdate)
|
||||||
|
{
|
||||||
|
this.IsFirstUpdate = false;
|
||||||
|
foreach (TokenString str in this.GetTokenStrings(this.Records, this.Fields))
|
||||||
|
changed |= str.UpdateContext(context);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
foreach (TokenString str in this.MutableTokenStrings)
|
||||||
|
changed |= str.UpdateContext(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the tokens used by this patch in its fields.</summary>
|
||||||
|
public override IEnumerable<TokenName> GetTokensUsed()
|
||||||
|
{
|
||||||
|
if (this.MutableTokenStrings.Length == 0)
|
||||||
|
return base.GetTokensUsed();
|
||||||
|
|
||||||
|
return base
|
||||||
|
.GetTokensUsed()
|
||||||
|
.Union(this.MutableTokenStrings.SelectMany(p => p.Tokens));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Apply the patch to a loaded asset.</summary>
|
||||||
|
/// <typeparam name="T">The asset type.</typeparam>
|
||||||
|
/// <param name="asset">The asset to edit.</param>
|
||||||
|
/// <exception cref="NotSupportedException">The current patch type doesn't support editing assets.</exception>
|
||||||
|
public override void Edit<T>(IAssetData asset)
|
||||||
|
{
|
||||||
|
// validate
|
||||||
|
if (!typeof(T).IsGenericType || typeof(T).GetGenericTypeDefinition() != typeof(Dictionary<,>))
|
||||||
|
{
|
||||||
|
this.Monitor.Log($"Can't apply data patch \"{this.LogName}\" to {this.TargetAsset}: this file isn't a data file (found {(typeof(T) == typeof(Texture2D) ? "image" : typeof(T).Name)}).", LogLevel.Warn);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// get dictionary's key type
|
||||||
|
Type keyType = typeof(T).GetGenericArguments().FirstOrDefault();
|
||||||
|
if (keyType == null)
|
||||||
|
throw new InvalidOperationException("Can't parse the asset's dictionary key type.");
|
||||||
|
|
||||||
|
// get underlying apply method
|
||||||
|
MethodInfo method = this.GetType().GetMethod(nameof(this.ApplyImpl), BindingFlags.Instance | BindingFlags.NonPublic);
|
||||||
|
if (method == null)
|
||||||
|
throw new InvalidOperationException("Can't fetch the internal apply method.");
|
||||||
|
|
||||||
|
// invoke method
|
||||||
|
method
|
||||||
|
.MakeGenericMethod(keyType)
|
||||||
|
.Invoke(this, new object[] { asset });
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get all token strings in the given data.</summary>
|
||||||
|
/// <param name="records">The data records to edit.</param>
|
||||||
|
/// <param name="fields">The data fields to edit.</param>
|
||||||
|
private IEnumerable<TokenString> GetTokenStrings(IEnumerable<EditDataPatchRecord> records, IEnumerable<EditDataPatchField> fields)
|
||||||
|
{
|
||||||
|
foreach (TokenString tokenStr in records.SelectMany(p => p.GetTokenStrings()))
|
||||||
|
yield return tokenStr;
|
||||||
|
foreach (TokenString tokenStr in fields.SelectMany(p => p.GetTokenStrings()))
|
||||||
|
yield return tokenStr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Apply the patch to an asset.</summary>
|
||||||
|
/// <typeparam name="TKey">The dictionary key type.</typeparam>
|
||||||
|
/// <param name="asset">The asset to edit.</param>
|
||||||
|
private void ApplyImpl<TKey>(IAssetData asset)
|
||||||
|
{
|
||||||
|
IDictionary<TKey, string> data = asset.AsDictionary<TKey, string>().Data;
|
||||||
|
|
||||||
|
// apply records
|
||||||
|
if (this.Records != null)
|
||||||
|
{
|
||||||
|
foreach (EditDataPatchRecord record in this.Records)
|
||||||
|
{
|
||||||
|
TKey key = (TKey)Convert.ChangeType(record.Key.Value, typeof(TKey));
|
||||||
|
if (record.Value.Value != null)
|
||||||
|
data[key] = record.Value.Value;
|
||||||
|
else
|
||||||
|
data.Remove(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// apply fields
|
||||||
|
if (this.Fields != null)
|
||||||
|
{
|
||||||
|
foreach (var recordGroup in this.Fields.GroupByIgnoreCase(p => p.Key.Value))
|
||||||
|
{
|
||||||
|
TKey key = (TKey)Convert.ChangeType(recordGroup.Key, typeof(TKey));
|
||||||
|
if (!data.ContainsKey(key))
|
||||||
|
{
|
||||||
|
this.Monitor.Log($"Can't apply data patch \"{this.LogName}\" to {this.TargetAsset}: there's no record matching key '{key}' under {nameof(PatchConfig.Fields)}.", LogLevel.Warn);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
string[] actualFields = data[key].Split('/');
|
||||||
|
foreach (EditDataPatchField field in recordGroup)
|
||||||
|
{
|
||||||
|
if (field.FieldIndex < 0 || field.FieldIndex > actualFields.Length - 1)
|
||||||
|
{
|
||||||
|
this.Monitor.Log($"Can't apply data field \"{this.LogName}\" to {this.TargetAsset}: record '{key}' under {nameof(PatchConfig.Fields)} has no field with index {field.FieldIndex} (must be 0 to {actualFields.Length - 1}).", LogLevel.Warn);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
actualFields[field.FieldIndex] = field.Value.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
data[key] = string.Join("/", actualFields);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,43 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Patches
|
||||||
|
{
|
||||||
|
/// <summary>An specific field in a data file to change.</summary>
|
||||||
|
internal class EditDataPatchField
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The unique key for the entry in the data file.</summary>
|
||||||
|
public TokenString Key { get; }
|
||||||
|
|
||||||
|
/// <summary>The field index to change.</summary>
|
||||||
|
public int FieldIndex { get; }
|
||||||
|
|
||||||
|
/// <summary>The entry value to set.</summary>
|
||||||
|
public TokenString Value { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="key">The unique key for the entry in the data file.</param>
|
||||||
|
/// <param name="field">The field number to change.</param>
|
||||||
|
/// <param name="value">The entry value to set.</param>
|
||||||
|
public EditDataPatchField(TokenString key, int field, TokenString value)
|
||||||
|
{
|
||||||
|
this.Key = key;
|
||||||
|
this.FieldIndex = field;
|
||||||
|
this.Value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get all token strings used in the record.</summary>
|
||||||
|
public IEnumerable<TokenString> GetTokenStrings()
|
||||||
|
{
|
||||||
|
yield return this.Key;
|
||||||
|
yield return this.Value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,38 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Patches
|
||||||
|
{
|
||||||
|
/// <summary>An entry in a data file to change.</summary>
|
||||||
|
internal class EditDataPatchRecord
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The unique key for the entry in the data file.</summary>
|
||||||
|
public TokenString Key { get; }
|
||||||
|
|
||||||
|
/// <summary>The entry value to set.</summary>
|
||||||
|
public TokenString Value { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="key">The unique key for the entry in the data file.</param>
|
||||||
|
/// <param name="value">The entry value to set.</param>
|
||||||
|
public EditDataPatchRecord(TokenString key, TokenString value)
|
||||||
|
{
|
||||||
|
this.Key = key;
|
||||||
|
this.Value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get all token strings used in the record.</summary>
|
||||||
|
public IEnumerable<TokenString> GetTokenStrings()
|
||||||
|
{
|
||||||
|
yield return this.Key;
|
||||||
|
yield return this.Value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,129 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using Microsoft.Xna.Framework;
|
||||||
|
using Microsoft.Xna.Framework.Graphics;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Patches
|
||||||
|
{
|
||||||
|
/// <summary>Metadata for an asset that should be patched with a new image.</summary>
|
||||||
|
internal class EditImagePatch : Patch
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>Encapsulates monitoring and logging.</summary>
|
||||||
|
private readonly IMonitor Monitor;
|
||||||
|
|
||||||
|
/// <summary>The asset key to load from the content pack instead.</summary>
|
||||||
|
private readonly TokenString FromLocalAsset;
|
||||||
|
|
||||||
|
/// <summary>The sprite area from which to read an image.</summary>
|
||||||
|
private readonly Rectangle? FromArea;
|
||||||
|
|
||||||
|
/// <summary>The sprite area to overwrite.</summary>
|
||||||
|
private readonly Rectangle? ToArea;
|
||||||
|
|
||||||
|
/// <summary>Indicates how the image should be patched.</summary>
|
||||||
|
private readonly PatchMode PatchMode;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="logName">A unique name for this patch shown in log messages.</param>
|
||||||
|
/// <param name="contentPack">The content pack which requested the patch.</param>
|
||||||
|
/// <param name="assetName">The normalised asset name to intercept.</param>
|
||||||
|
/// <param name="conditions">The conditions which determine whether this patch should be applied.</param>
|
||||||
|
/// <param name="fromLocalAsset">The asset key to load from the content pack instead.</param>
|
||||||
|
/// <param name="fromArea">The sprite area from which to read an image.</param>
|
||||||
|
/// <param name="toArea">The sprite area to overwrite.</param>
|
||||||
|
/// <param name="patchMode">Indicates how the image should be patched.</param>
|
||||||
|
/// <param name="monitor">Encapsulates monitoring and logging.</param>
|
||||||
|
/// <param name="normaliseAssetName">Normalise an asset name.</param>
|
||||||
|
public EditImagePatch(string logName, ManagedContentPack contentPack, TokenString assetName, ConditionDictionary conditions, TokenString fromLocalAsset, Rectangle fromArea, Rectangle toArea, PatchMode patchMode, IMonitor monitor, Func<string, string> normaliseAssetName)
|
||||||
|
: base(logName, PatchType.EditImage, contentPack, assetName, conditions, normaliseAssetName)
|
||||||
|
{
|
||||||
|
this.FromLocalAsset = fromLocalAsset;
|
||||||
|
this.FromArea = fromArea != Rectangle.Empty ? fromArea : null as Rectangle?;
|
||||||
|
this.ToArea = toArea != Rectangle.Empty ? toArea : null as Rectangle?;
|
||||||
|
this.PatchMode = patchMode;
|
||||||
|
this.Monitor = monitor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Update the patch data when the context changes.</summary>
|
||||||
|
/// <param name="context">The condition context.</param>
|
||||||
|
/// <returns>Returns whether the patch data changed.</returns>
|
||||||
|
public override bool UpdateContext(IContext context)
|
||||||
|
{
|
||||||
|
bool localAssetChanged = this.FromLocalAsset.UpdateContext(context);
|
||||||
|
return base.UpdateContext(context) || localAssetChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Apply the patch to a loaded asset.</summary>
|
||||||
|
/// <typeparam name="T">The asset type.</typeparam>
|
||||||
|
/// <param name="asset">The asset to edit.</param>
|
||||||
|
public override void Edit<T>(IAssetData asset)
|
||||||
|
{
|
||||||
|
// validate
|
||||||
|
if (typeof(T) != typeof(Texture2D))
|
||||||
|
{
|
||||||
|
this.Monitor.Log($"Can't apply image patch \"{this.LogName}\" to {this.TargetAsset}: this file isn't an image file (found {typeof(T)}).", LogLevel.Warn);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetch data
|
||||||
|
Texture2D source = this.ContentPack.Load<Texture2D>(this.FromLocalAsset.Value);
|
||||||
|
Rectangle sourceArea = this.FromArea ?? new Rectangle(0, 0, source.Width, source.Height);
|
||||||
|
Rectangle targetArea = this.ToArea ?? new Rectangle(0, 0, sourceArea.Width, sourceArea.Height);
|
||||||
|
IAssetDataForImage editor = asset.AsImage();
|
||||||
|
|
||||||
|
// validate error conditions
|
||||||
|
if (sourceArea.X < 0 || sourceArea.Y < 0 || sourceArea.Width < 0 || sourceArea.Height < 0)
|
||||||
|
{
|
||||||
|
this.Monitor.Log($"Can't apply image patch \"{this.LogName}\": source area (X:{sourceArea.X}, Y:{sourceArea.Y}, Width:{sourceArea.Width}, Height:{sourceArea.Height}) has negative values, which isn't valid.", LogLevel.Error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (targetArea.X < 0 || targetArea.Y < 0 || targetArea.Width < 0 || targetArea.Height < 0)
|
||||||
|
{
|
||||||
|
this.Monitor.Log($"Can't apply image patch \"{this.LogName}\": target area (X:{targetArea.X}, Y:{targetArea.Y}, Width:{targetArea.Width}, Height:{targetArea.Height}) has negative values, which isn't valid.", LogLevel.Error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (targetArea.Right > editor.Data.Width)
|
||||||
|
{
|
||||||
|
this.Monitor.Log($"Can't apply image patch \"{this.LogName}\": target area (X:{targetArea.X}, Y:{targetArea.Y}, Width:{targetArea.Width}, Height:{targetArea.Height}) extends past the right edge of the image (Width:{editor.Data.Width}), which isn't allowed. Patches can only extend the tilesheet downwards.", LogLevel.Error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (sourceArea.Width != targetArea.Width || sourceArea.Height != targetArea.Height)
|
||||||
|
{
|
||||||
|
string sourceAreaLabel = this.FromArea.HasValue ? $"{nameof(this.FromArea)}" : "source image";
|
||||||
|
string targetAreaLabel = this.ToArea.HasValue ? $"{nameof(this.ToArea)}" : "target image";
|
||||||
|
this.Monitor.Log($"Can't apply image patch \"{this.LogName}\": {sourceAreaLabel} size (Width:{sourceArea.Width}, Height:{sourceArea.Height}) doesn't match {targetAreaLabel} size (Width:{targetArea.Width}, Height:{targetArea.Height}).", LogLevel.Error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// extend tilesheet if needed
|
||||||
|
if (targetArea.Bottom > editor.Data.Height)
|
||||||
|
{
|
||||||
|
Texture2D original = editor.Data;
|
||||||
|
Texture2D texture = new Texture2D(Game1.graphics.GraphicsDevice, original.Width, targetArea.Bottom);
|
||||||
|
editor.ReplaceWith(texture);
|
||||||
|
editor.PatchImage(original);
|
||||||
|
}
|
||||||
|
|
||||||
|
// apply source image
|
||||||
|
editor.PatchImage(source, sourceArea, this.ToArea, this.PatchMode);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the tokens used by this patch in its fields.</summary>
|
||||||
|
public override IEnumerable<TokenName> GetTokensUsed()
|
||||||
|
{
|
||||||
|
return base.GetTokensUsed().Union(this.FromLocalAsset.Tokens);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,68 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Patches
|
||||||
|
{
|
||||||
|
/// <summary>A patch which can be applied to an asset.</summary>
|
||||||
|
internal interface IPatch
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>A unique name for this patch shown in log messages.</summary>
|
||||||
|
string LogName { get; }
|
||||||
|
|
||||||
|
/// <summary>The patch type.</summary>
|
||||||
|
PatchType Type { get; }
|
||||||
|
|
||||||
|
/// <summary>The content pack which requested the patch.</summary>
|
||||||
|
ManagedContentPack ContentPack { get; }
|
||||||
|
|
||||||
|
/// <summary>The asset key to load from the content pack instead.</summary>
|
||||||
|
TokenString FromLocalAsset { get; }
|
||||||
|
|
||||||
|
/// <summary>The normalised asset name to intercept.</summary>
|
||||||
|
string TargetAsset { get; }
|
||||||
|
|
||||||
|
/// <summary>The raw asset name to intercept, including tokens.</summary>
|
||||||
|
TokenString RawTargetAsset { get; }
|
||||||
|
|
||||||
|
/// <summary>The conditions which determine whether this patch should be applied.</summary>
|
||||||
|
ConditionDictionary Conditions { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether this patch should be applied in the latest context.</summary>
|
||||||
|
bool MatchesContext { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether this patch is valid if <see cref="MatchesContext"/> is true.</summary>
|
||||||
|
bool IsValidInContext { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the patch is currently applied to the target asset.</summary>
|
||||||
|
bool IsApplied { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Update the patch data when the context changes.</summary>
|
||||||
|
/// <param name="context">Provides access to contextual tokens.</param>
|
||||||
|
/// <returns>Returns whether the patch data changed.</returns>
|
||||||
|
bool UpdateContext(IContext context);
|
||||||
|
|
||||||
|
/// <summary>Load the initial version of the asset.</summary>
|
||||||
|
/// <typeparam name="T">The asset type.</typeparam>
|
||||||
|
/// <param name="asset">The asset to load.</param>
|
||||||
|
/// <exception cref="System.NotSupportedException">The current patch type doesn't support loading assets.</exception>
|
||||||
|
T Load<T>(IAssetInfo asset);
|
||||||
|
|
||||||
|
/// <summary>Apply the patch to a loaded asset.</summary>
|
||||||
|
/// <typeparam name="T">The asset type.</typeparam>
|
||||||
|
/// <param name="asset">The asset to edit.</param>
|
||||||
|
/// <exception cref="System.NotSupportedException">The current patch type doesn't support editing assets.</exception>
|
||||||
|
void Edit<T>(IAssetData asset);
|
||||||
|
|
||||||
|
/// <summary>Get the tokens used by this patch in its fields.</summary>
|
||||||
|
IEnumerable<TokenName> GetTokensUsed();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,65 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using Microsoft.Xna.Framework.Graphics;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Patches
|
||||||
|
{
|
||||||
|
/// <summary>Metadata for an asset that should be replaced with a content pack file.</summary>
|
||||||
|
internal class LoadPatch : Patch
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="logName">A unique name for this patch shown in log messages.</param>
|
||||||
|
/// <param name="contentPack">The content pack which requested the patch.</param>
|
||||||
|
/// <param name="assetName">The normalised asset name to intercept.</param>
|
||||||
|
/// <param name="conditions">The conditions which determine whether this patch should be applied.</param>
|
||||||
|
/// <param name="localAsset">The asset key to load from the content pack instead.</param>
|
||||||
|
/// <param name="normaliseAssetName">Normalise an asset name.</param>
|
||||||
|
public LoadPatch(string logName, ManagedContentPack contentPack, TokenString assetName, ConditionDictionary conditions, TokenString localAsset, Func<string, string> normaliseAssetName)
|
||||||
|
: base(logName, PatchType.Load, contentPack, assetName, conditions, normaliseAssetName)
|
||||||
|
{
|
||||||
|
this.FromLocalAsset = localAsset;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Load the initial version of the asset.</summary>
|
||||||
|
/// <param name="asset">The asset to load.</param>
|
||||||
|
public override T Load<T>(IAssetInfo asset)
|
||||||
|
{
|
||||||
|
T data = this.ContentPack.Load<T>(this.FromLocalAsset.Value);
|
||||||
|
return (data as object) is Texture2D texture
|
||||||
|
? (T)(object)this.CloneTexture(texture)
|
||||||
|
: data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the tokens used by this patch in its fields.</summary>
|
||||||
|
public override IEnumerable<TokenName> GetTokensUsed()
|
||||||
|
{
|
||||||
|
return base.GetTokensUsed().Union(this.FromLocalAsset.Tokens);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Clone a texture.</summary>
|
||||||
|
/// <param name="source">The texture to clone.</param>
|
||||||
|
/// <returns>Cloning a texture is necessary when loading to avoid having it shared between different content managers, which can lead to undesirable effects like two players having synchronised texture changes.</returns>
|
||||||
|
private Texture2D CloneTexture(Texture2D source)
|
||||||
|
{
|
||||||
|
// get data
|
||||||
|
int[] pixels = new int[source.Width * source.Height];
|
||||||
|
source.GetData(pixels);
|
||||||
|
|
||||||
|
// create clone
|
||||||
|
Texture2D target = new Texture2D(source.GraphicsDevice, source.Width, source.Height);
|
||||||
|
target.SetData(pixels);
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,136 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Patches
|
||||||
|
{
|
||||||
|
/// <summary>Metadata for a conditional patch.</summary>
|
||||||
|
internal abstract class Patch : IPatch
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>Normalise an asset name.</summary>
|
||||||
|
private readonly Func<string, string> NormaliseAssetName;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The last context used to update this patch.</summary>
|
||||||
|
protected IContext LastContext { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>A unique name for this patch shown in log messages.</summary>
|
||||||
|
public string LogName { get; }
|
||||||
|
|
||||||
|
/// <summary>The patch type.</summary>
|
||||||
|
public PatchType Type { get; }
|
||||||
|
|
||||||
|
/// <summary>The content pack which requested the patch.</summary>
|
||||||
|
public ManagedContentPack ContentPack { get; }
|
||||||
|
|
||||||
|
/// <summary>The raw asset key to intercept (if applicable), including tokens.</summary>
|
||||||
|
public TokenString FromLocalAsset { get; protected set; }
|
||||||
|
|
||||||
|
/// <summary>The normalised asset name to intercept.</summary>
|
||||||
|
public string TargetAsset { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>The raw asset name to intercept, including tokens.</summary>
|
||||||
|
public TokenString RawTargetAsset { get; }
|
||||||
|
|
||||||
|
/// <summary>The conditions which determine whether this patch should be applied.</summary>
|
||||||
|
public ConditionDictionary Conditions { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether this patch should be applied in the latest context.</summary>
|
||||||
|
public bool MatchesContext { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Whether this patch is valid if <see cref="MatchesContext"/> is true.</summary>
|
||||||
|
public bool IsValidInContext { get; protected set; } = true;
|
||||||
|
|
||||||
|
/// <summary>Whether the patch is currently applied to the target asset.</summary>
|
||||||
|
public bool IsApplied { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Update the patch data when the context changes.</summary>
|
||||||
|
/// <param name="context">Provides access to contextual tokens.</param>
|
||||||
|
/// <returns>Returns whether the patch data changed.</returns>
|
||||||
|
public virtual bool UpdateContext(IContext context)
|
||||||
|
{
|
||||||
|
this.LastContext = context;
|
||||||
|
|
||||||
|
// update conditions
|
||||||
|
bool conditionsChanged;
|
||||||
|
{
|
||||||
|
bool wasMatch = this.MatchesContext;
|
||||||
|
this.MatchesContext =
|
||||||
|
(this.Conditions.Count == 0 || this.Conditions.Values.All(p => p.IsMatch(context)))
|
||||||
|
&& this.GetTokensUsed().All(p => context.Contains(p, enforceContext: true));
|
||||||
|
conditionsChanged = wasMatch != this.MatchesContext;
|
||||||
|
}
|
||||||
|
// update target asset
|
||||||
|
bool targetChanged = this.RawTargetAsset.UpdateContext(context);
|
||||||
|
this.TargetAsset = this.NormaliseAssetName(this.RawTargetAsset.Value);
|
||||||
|
|
||||||
|
// update source asset
|
||||||
|
bool sourceChanged = false;
|
||||||
|
if (this.FromLocalAsset != null)
|
||||||
|
{
|
||||||
|
sourceChanged = this.FromLocalAsset.UpdateContext(context);
|
||||||
|
this.IsValidInContext = this.FromLocalAsset.IsReady && this.ContentPack.HasFile(this.FromLocalAsset.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return conditionsChanged || targetChanged || sourceChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Load the initial version of the asset.</summary>
|
||||||
|
/// <typeparam name="T">The asset type.</typeparam>
|
||||||
|
/// <param name="asset">The asset to load.</param>
|
||||||
|
/// <exception cref="NotSupportedException">The current patch type doesn't support loading assets.</exception>
|
||||||
|
public virtual T Load<T>(IAssetInfo asset)
|
||||||
|
{
|
||||||
|
throw new NotSupportedException("This patch type doesn't support loading assets.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Apply the patch to a loaded asset.</summary>
|
||||||
|
/// <typeparam name="T">The asset type.</typeparam>
|
||||||
|
/// <param name="asset">The asset to edit.</param>
|
||||||
|
/// <exception cref="NotSupportedException">The current patch type doesn't support editing assets.</exception>
|
||||||
|
public virtual void Edit<T>(IAssetData asset)
|
||||||
|
{
|
||||||
|
throw new NotSupportedException("This patch type doesn't support loading assets.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the tokens used by this patch in its fields.</summary>
|
||||||
|
public virtual IEnumerable<TokenName> GetTokensUsed()
|
||||||
|
{
|
||||||
|
return this.RawTargetAsset.Tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Protected methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="logName">A unique name for this patch shown in log messages.</param>
|
||||||
|
/// <param name="type">The patch type.</param>
|
||||||
|
/// <param name="contentPack">The content pack which requested the patch.</param>
|
||||||
|
/// <param name="assetName">The normalised asset name to intercept.</param>
|
||||||
|
/// <param name="conditions">The conditions which determine whether this patch should be applied.</param>
|
||||||
|
/// <param name="normaliseAssetName">Normalise an asset name.</param>
|
||||||
|
protected Patch(string logName, PatchType type, ManagedContentPack contentPack, TokenString assetName, ConditionDictionary conditions, Func<string, string> normaliseAssetName)
|
||||||
|
{
|
||||||
|
this.LogName = logName;
|
||||||
|
this.Type = type;
|
||||||
|
this.ContentPack = contentPack;
|
||||||
|
this.RawTargetAsset = assetName;
|
||||||
|
this.Conditions = conditions;
|
||||||
|
this.NormaliseAssetName = normaliseAssetName;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,40 @@
|
||||||
|
using ContentPatcher.Framework.ConfigModels;
|
||||||
|
using ContentPatcher.Framework.Migrations;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework
|
||||||
|
{
|
||||||
|
/// <summary>A content pack being loaded.</summary>
|
||||||
|
internal class RawContentPack
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The managed content pack instance.</summary>
|
||||||
|
public ManagedContentPack ManagedPack { get; }
|
||||||
|
|
||||||
|
/// <summary>The raw content configuration for this content pack.</summary>
|
||||||
|
public ContentConfig Content { get; }
|
||||||
|
|
||||||
|
/// <summary>The migrations to apply for the content pack version.</summary>
|
||||||
|
public IMigration Migrator { get; }
|
||||||
|
|
||||||
|
/// <summary>The content pack's manifest.</summary>
|
||||||
|
public IManifest Manifest => this.ManagedPack.Manifest;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="contentPack">The managed content pack instance.</param>
|
||||||
|
/// <param name="content">The raw content configuration for this content pack.</param>
|
||||||
|
/// <param name="migrator">The migrations to apply for the content pack version.</param>
|
||||||
|
public RawContentPack(ManagedContentPack contentPack, ContentConfig content, IMigration migrator)
|
||||||
|
{
|
||||||
|
this.ManagedPack = contentPack;
|
||||||
|
this.Content = content;
|
||||||
|
this.Migrator = migrator;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,232 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using ContentPatcher.Framework.Constants;
|
||||||
|
using ContentPatcher.Framework.Tokens;
|
||||||
|
using ContentPatcher.Framework.Tokens.ValueProviders;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
using StardewModdingAPI;
|
||||||
|
using StardewModdingAPI.Utilities;
|
||||||
|
using StardewValley;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework
|
||||||
|
{
|
||||||
|
/// <summary>Manages the available contextual tokens.</summary>
|
||||||
|
internal class TokenManager : IContext
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The available global tokens.</summary>
|
||||||
|
private readonly GenericTokenContext GlobalContext = new GenericTokenContext();
|
||||||
|
|
||||||
|
/// <summary>The available tokens defined within the context of each content pack.</summary>
|
||||||
|
private readonly Dictionary<IContentPack, ModTokenContext> LocalTokens = new Dictionary<IContentPack, ModTokenContext>();
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>Whether the basic save info is loaded (including the date, weather, and player info). The in-game locations and world may not exist yet.</summary>
|
||||||
|
public bool IsBasicInfoLoaded { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="contentHelper">The content helper from which to load data assets.</param>
|
||||||
|
/// <param name="installedMods">The installed mod IDs.</param>
|
||||||
|
public TokenManager(IContentHelper contentHelper, IEnumerable<string> installedMods)
|
||||||
|
{
|
||||||
|
foreach (IValueProvider valueProvider in this.GetGlobalValueProviders(contentHelper, installedMods))
|
||||||
|
this.GlobalContext.Tokens[new TokenName(valueProvider.Name)] = new GenericToken(valueProvider);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the tokens which are defined for a specific content pack. This returns a reference to the list, which can be held for a live view of the tokens. If the content pack isn't currently tracked, this will add it.</summary>
|
||||||
|
/// <param name="contentPack">The content pack to manage.</param>
|
||||||
|
public ModTokenContext TrackLocalTokens(IContentPack contentPack)
|
||||||
|
{
|
||||||
|
if (!this.LocalTokens.TryGetValue(contentPack, out ModTokenContext localTokens))
|
||||||
|
{
|
||||||
|
this.LocalTokens[contentPack] = localTokens = new ModTokenContext(this);
|
||||||
|
foreach (IValueProvider valueProvider in this.GetLocalValueProviders(contentPack))
|
||||||
|
localTokens.Add(new GenericToken(valueProvider));
|
||||||
|
}
|
||||||
|
|
||||||
|
return localTokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Update the current context.</summary>
|
||||||
|
public void UpdateContext()
|
||||||
|
{
|
||||||
|
foreach (IToken token in this.GlobalContext.Tokens.Values)
|
||||||
|
{
|
||||||
|
if (token.IsMutable)
|
||||||
|
token.UpdateContext(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (ModTokenContext localContext in this.LocalTokens.Values)
|
||||||
|
localContext.UpdateContext(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** IContext
|
||||||
|
****/
|
||||||
|
/// <summary>Get whether the context contains the given token.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
public bool Contains(TokenName name, bool enforceContext)
|
||||||
|
{
|
||||||
|
return this.GlobalContext.Contains(name, enforceContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the underlying token which handles a key.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
/// <returns>Returns the matching token, or <c>null</c> if none was found.</returns>
|
||||||
|
public IToken GetToken(TokenName name, bool enforceContext)
|
||||||
|
{
|
||||||
|
return this.GlobalContext.GetToken(name, enforceContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the underlying tokens.</summary>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
public IEnumerable<IToken> GetTokens(bool enforceContext)
|
||||||
|
{
|
||||||
|
return this.GlobalContext.GetTokens(enforceContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the current values of the given token for comparison.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
/// <returns>Return the values of the matching token, or an empty list if the token doesn't exist.</returns>
|
||||||
|
/// <exception cref="ArgumentNullException">The specified key is null.</exception>
|
||||||
|
public IEnumerable<string> GetValues(TokenName name, bool enforceContext)
|
||||||
|
{
|
||||||
|
return this.GlobalContext.GetValues(name, enforceContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Private methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get the global value providers with which to initialise the token manager.</summary>
|
||||||
|
/// <param name="contentHelper">The content helper from which to load data assets.</param>
|
||||||
|
/// <param name="installedMods">The installed mod IDs.</param>
|
||||||
|
private IEnumerable<IValueProvider> GetGlobalValueProviders(IContentHelper contentHelper, IEnumerable<string> installedMods)
|
||||||
|
{
|
||||||
|
bool NeedsBasicInfo() => this.IsBasicInfoLoaded;
|
||||||
|
|
||||||
|
// installed mods
|
||||||
|
yield return new ImmutableValueProvider(ConditionType.HasMod.ToString(), new InvariantHashSet(installedMods), canHaveMultipleValues: true);
|
||||||
|
|
||||||
|
// language
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.Language, () => contentHelper.CurrentLocaleConstant.ToString(), allowedValues: Enum.GetNames(typeof(LocalizedContentManager.LanguageCode)).Where(p => p != LocalizedContentManager.LanguageCode.th.ToString()));
|
||||||
|
|
||||||
|
// in-game date
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.Season, () => SDate.Now().Season, NeedsBasicInfo, allowedValues: new[] { "Spring", "Summer", "Fall", "Winter" });
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.Day, () => SDate.Now().Day.ToString(CultureInfo.InvariantCulture), NeedsBasicInfo, allowedValues: Enumerable.Range(1, 28).Select(p => p.ToString()));
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.DayOfWeek, () => SDate.Now().DayOfWeek.ToString(), NeedsBasicInfo, allowedValues: Enum.GetNames(typeof(DayOfWeek)));
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.Year, () => SDate.Now().Year.ToString(CultureInfo.InvariantCulture), NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.DaysPlayed, () => Game1.stats.DaysPlayed.ToString(CultureInfo.InvariantCulture), NeedsBasicInfo);
|
||||||
|
|
||||||
|
// other in-game conditions
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.DayEvent, () => this.GetDayEvent(contentHelper), NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.FarmCave, () => this.GetEnum(Game1.player.caveChoice.Value, FarmCaveType.None).ToString(), NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.FarmhouseUpgrade, () => Game1.player.HouseUpgradeLevel.ToString(), NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.FarmName, () => Game1.player.farmName.Value, NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.FarmType, () => this.GetEnum(Game1.whichFarm, FarmType.Custom).ToString(), NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.HasFlag, () => this.GetMailFlags(), NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.HasSeenEvent, () => this.GetEventsSeen(), NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.PlayerGender, () => (Game1.player.IsMale ? Gender.Male : Gender.Female).ToString(), NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.PreferredPet, () => (Game1.player.catPerson ? PetType.Cat : PetType.Dog).ToString(), NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.PlayerName, () => Game1.player.Name, NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.Spouse, () => Game1.player?.spouse, NeedsBasicInfo);
|
||||||
|
yield return new ConditionTypeValueProvider(ConditionType.Weather, () => this.GetCurrentWeather(), NeedsBasicInfo, allowedValues: Enum.GetNames(typeof(Weather)));
|
||||||
|
yield return new HasProfessionValueProvider(NeedsBasicInfo);
|
||||||
|
yield return new HasWalletItemValueProvider(NeedsBasicInfo);
|
||||||
|
yield return new SkillLevelValueProvider(NeedsBasicInfo);
|
||||||
|
yield return new VillagerRelationshipValueProvider();
|
||||||
|
yield return new VillagerHeartsValueProvider();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the local value providers with which to initialise a local context.</summary>
|
||||||
|
/// <param name="contentPack">The content pack for which to get tokens.</param>
|
||||||
|
private IEnumerable<IValueProvider> GetLocalValueProviders(IContentPack contentPack)
|
||||||
|
{
|
||||||
|
yield return new HasFileValueProvider(contentPack.DirectoryPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get a constant for a given value.</summary>
|
||||||
|
/// <typeparam name="TEnum">The constant enum type.</typeparam>
|
||||||
|
/// <param name="value">The value to convert.</param>
|
||||||
|
/// <param name="defaultValue">The value to use if the value is invalid.</param>
|
||||||
|
private TEnum GetEnum<TEnum>(int value, TEnum defaultValue)
|
||||||
|
{
|
||||||
|
return Enum.IsDefined(typeof(TEnum), value)
|
||||||
|
? (TEnum)(object)value
|
||||||
|
: defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the current weather from the game state.</summary>
|
||||||
|
private string GetCurrentWeather()
|
||||||
|
{
|
||||||
|
if (Utility.isFestivalDay(Game1.dayOfMonth, Game1.currentSeason) || (SaveGame.loaded?.weddingToday ?? Game1.weddingToday))
|
||||||
|
return Weather.Sun.ToString();
|
||||||
|
|
||||||
|
if (Game1.isSnowing)
|
||||||
|
return Weather.Snow.ToString();
|
||||||
|
if (RainManager.Instance.isRaining)
|
||||||
|
return (Game1.isLightning ? Weather.Storm : Weather.Rain).ToString();
|
||||||
|
if (SaveGame.loaded?.isDebrisWeather ?? WeatherDebrisManager.Instance.isDebrisWeather)
|
||||||
|
return Weather.Wind.ToString();
|
||||||
|
|
||||||
|
return Weather.Sun.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the event IDs seen by the player.</summary>
|
||||||
|
private IEnumerable<string> GetEventsSeen()
|
||||||
|
{
|
||||||
|
Farmer player = Game1.player;
|
||||||
|
if (player == null)
|
||||||
|
return new string[0];
|
||||||
|
|
||||||
|
return player.eventsSeen
|
||||||
|
.OrderBy(p => p)
|
||||||
|
.Select(p => p.ToString(CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the letter IDs and mail flags set for the player.</summary>
|
||||||
|
/// <remarks>See game logic in <see cref="Farmer.hasOrWillReceiveMail"/>.</remarks>
|
||||||
|
private IEnumerable<string> GetMailFlags()
|
||||||
|
{
|
||||||
|
Farmer player = Game1.player;
|
||||||
|
if (player == null)
|
||||||
|
return new string[0];
|
||||||
|
|
||||||
|
return player
|
||||||
|
.mailReceived
|
||||||
|
.Union(player.mailForTomorrow)
|
||||||
|
.Union(player.mailbox);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the name for today's day event (e.g. wedding or festival) from the game data.</summary>
|
||||||
|
/// <param name="contentHelper">The content helper from which to load festival data.</param>
|
||||||
|
private string GetDayEvent(IContentHelper contentHelper)
|
||||||
|
{
|
||||||
|
// marriage
|
||||||
|
if (SaveGame.loaded?.weddingToday ?? Game1.weddingToday)
|
||||||
|
return "wedding";
|
||||||
|
|
||||||
|
// festival
|
||||||
|
IDictionary<string, string> festivalDates = contentHelper.Load<Dictionary<string, string>>("Data\\Festivals\\FestivalDates", ContentSource.GameContent);
|
||||||
|
if (festivalDates.TryGetValue($"{Game1.currentSeason}{Game1.dayOfMonth}", out string festivalName))
|
||||||
|
return festivalName;
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,50 @@
|
||||||
|
using ContentPatcher.Framework.Tokens.ValueProviders;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Tokens
|
||||||
|
{
|
||||||
|
/// <summary>A dynamic token defined by a content pack.</summary>
|
||||||
|
internal class DynamicToken : GenericToken
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The underlying value provider.</summary>
|
||||||
|
private readonly DynamicTokenValueProvider DynamicValues;
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
public DynamicToken(TokenName name)
|
||||||
|
: base(new DynamicTokenValueProvider(name.Key))
|
||||||
|
{
|
||||||
|
this.DynamicValues = (DynamicTokenValueProvider)base.Values;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Add a set of possible values.</summary>
|
||||||
|
/// <param name="possibleValues">The possible values to add.</param>
|
||||||
|
public void AddAllowedValues(InvariantHashSet possibleValues)
|
||||||
|
{
|
||||||
|
this.DynamicValues.AddAllowedValues(possibleValues);
|
||||||
|
this.CanHaveMultipleRootValues = this.DynamicValues.CanHaveMultipleValues();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Set the current values.</summary>
|
||||||
|
/// <param name="values">The values to set.</param>
|
||||||
|
public void SetValue(InvariantHashSet values)
|
||||||
|
{
|
||||||
|
this.DynamicValues.SetValue(values);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Set whether the token is valid in the current context.</summary>
|
||||||
|
/// <param name="validInContext">The value to set.</param>
|
||||||
|
public void SetValidInContext(bool validInContext)
|
||||||
|
{
|
||||||
|
this.DynamicValues.SetValidInContext(validInContext);
|
||||||
|
this.IsValidInContext = this.DynamicValues.IsValidInContext;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,36 @@
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Tokens
|
||||||
|
{
|
||||||
|
/// <summary>A conditional value for a dynamic token.</summary>
|
||||||
|
internal class DynamicTokenValue
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The name of the token whose value to set.</summary>
|
||||||
|
public TokenName Name { get; }
|
||||||
|
|
||||||
|
/// <summary>The token value to set.</summary>
|
||||||
|
public InvariantHashSet Value { get; }
|
||||||
|
|
||||||
|
/// <summary>The conditions that must match to set this value.</summary>
|
||||||
|
public ConditionDictionary Conditions { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="key">The name of the token whose value to set.</param>
|
||||||
|
/// <param name="value">The token value to set.</param>
|
||||||
|
/// <param name="conditions">The conditions that must match to set this value.</param>
|
||||||
|
public DynamicTokenValue(TokenName key, InvariantHashSet value, ConditionDictionary conditions)
|
||||||
|
{
|
||||||
|
this.Name = key;
|
||||||
|
this.Value = value;
|
||||||
|
this.Conditions = conditions;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,239 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Tokens.ValueProviders;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Tokens
|
||||||
|
{
|
||||||
|
/// <summary>A combination of one or more value providers.</summary>
|
||||||
|
internal class GenericToken : IToken
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>The underlying value provider.</summary>
|
||||||
|
protected IValueProvider Values { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the root token may contain multiple values.</summary>
|
||||||
|
protected bool CanHaveMultipleRootValues { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The token name.</summary>
|
||||||
|
public TokenName Name { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the value can change after it's initialised.</summary>
|
||||||
|
public bool IsMutable { get; protected set; } = true;
|
||||||
|
|
||||||
|
/// <summary>Whether this token recognises subkeys (e.g. <c>Relationship:Abigail</c> is a <c>Relationship</c> token with a <c>Abigail</c> subkey).</summary>
|
||||||
|
public bool CanHaveSubkeys { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether this token only allows subkeys (see <see cref="IToken.CanHaveSubkeys"/>).</summary>
|
||||||
|
public bool RequiresSubkeys { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the token is applicable in the current context.</summary>
|
||||||
|
public bool IsValidInContext { get; protected set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="provider">The underlying value provider.</param>
|
||||||
|
public GenericToken(IValueProvider provider)
|
||||||
|
{
|
||||||
|
this.Values = provider;
|
||||||
|
|
||||||
|
this.Name = TokenName.Parse(provider.Name);
|
||||||
|
this.CanHaveSubkeys = provider.AllowsInput;
|
||||||
|
this.RequiresSubkeys = provider.RequiresInput;
|
||||||
|
this.CanHaveMultipleRootValues = provider.CanHaveMultipleValues();
|
||||||
|
this.IsValidInContext = provider.IsValidInContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Update the token data when the context changes.</summary>
|
||||||
|
/// <param name="context">The condition context.</param>
|
||||||
|
/// <returns>Returns whether the token data changed.</returns>
|
||||||
|
public virtual void UpdateContext(IContext context)
|
||||||
|
{
|
||||||
|
if (this.Values.IsMutable)
|
||||||
|
{
|
||||||
|
this.Values.UpdateContext(context);
|
||||||
|
this.IsValidInContext = this.Values.IsValidInContext;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether the token may return multiple values for the given name.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
public bool CanHaveMultipleValues(TokenName name)
|
||||||
|
{
|
||||||
|
return this.Values.CanHaveMultipleValues(name.Subkey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Perform custom validation.</summary>
|
||||||
|
/// <param name="name">The token name to validate.</param>
|
||||||
|
/// <param name="values">The values to validate.</param>
|
||||||
|
/// <param name="error">The validation error, if any.</param>
|
||||||
|
/// <returns>Returns whether validation succeeded.</returns>
|
||||||
|
public bool TryValidate(TokenName name, InvariantHashSet values, out string error)
|
||||||
|
{
|
||||||
|
// parse data
|
||||||
|
KeyValuePair<TokenName, string>[] pairs = this.GetSubkeyValuePairsFor(name, values).ToArray();
|
||||||
|
|
||||||
|
// restrict to allowed subkeys
|
||||||
|
if (this.CanHaveSubkeys)
|
||||||
|
{
|
||||||
|
InvariantHashSet validKeys = this.GetAllowedSubkeys();
|
||||||
|
if (validKeys?.Any() == true)
|
||||||
|
{
|
||||||
|
string[] invalidSubkeys =
|
||||||
|
(
|
||||||
|
from pair in pairs
|
||||||
|
where pair.Key.Subkey != null && !validKeys.Contains(pair.Key.Subkey)
|
||||||
|
select pair.Key.Subkey
|
||||||
|
)
|
||||||
|
.Distinct()
|
||||||
|
.ToArray();
|
||||||
|
if (invalidSubkeys.Any())
|
||||||
|
{
|
||||||
|
error = $"invalid subkeys ({string.Join(", ", invalidSubkeys)}); expected one of {string.Join(", ", validKeys)}";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// restrict to allowed values
|
||||||
|
{
|
||||||
|
InvariantHashSet validValues = this.GetAllowedValues(name);
|
||||||
|
if (validValues?.Any() == true)
|
||||||
|
{
|
||||||
|
string[] invalidValues =
|
||||||
|
(
|
||||||
|
from pair in pairs
|
||||||
|
where !validValues.Contains(pair.Value)
|
||||||
|
select pair.Value
|
||||||
|
)
|
||||||
|
.Distinct()
|
||||||
|
.ToArray();
|
||||||
|
if (invalidValues.Any())
|
||||||
|
{
|
||||||
|
error = $"invalid values ({string.Join(", ", invalidValues)}); expected one of {string.Join(", ", validValues)}";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// custom validation
|
||||||
|
foreach (KeyValuePair<TokenName, string> pair in pairs)
|
||||||
|
{
|
||||||
|
if (!this.Values.TryValidate(pair.Key.Subkey, new InvariantHashSet { pair.Value }, out error))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// no issues found
|
||||||
|
error = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the current subkeys (if supported).</summary>
|
||||||
|
public virtual IEnumerable<TokenName> GetSubkeys()
|
||||||
|
{
|
||||||
|
return this.Values.GetValidInputs()?.Select(input => new TokenName(this.Name.Key, input));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the allowed values for a token name (or <c>null</c> if any value is allowed).</summary>
|
||||||
|
/// <exception cref="InvalidOperationException">The key doesn't match this token, or the key does not respect <see cref="IToken.CanHaveSubkeys"/> or <see cref="IToken.RequiresSubkeys"/>.</exception>
|
||||||
|
public virtual InvariantHashSet GetAllowedValues(TokenName name)
|
||||||
|
{
|
||||||
|
return this.Values.GetAllowedValues(name.Subkey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the current token values.</summary>
|
||||||
|
/// <param name="name">The token name to check.</param>
|
||||||
|
/// <exception cref="InvalidOperationException">The key doesn't match this token, or the key does not respect <see cref="IToken.CanHaveSubkeys"/> or <see cref="IToken.RequiresSubkeys"/>.</exception>
|
||||||
|
public virtual IEnumerable<string> GetValues(TokenName name)
|
||||||
|
{
|
||||||
|
this.AssertTokenName(name);
|
||||||
|
return this.Values.GetValues(name.Subkey);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Protected methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Get the allowed subkeys (or <c>null</c> if any value is allowed).</summary>
|
||||||
|
protected virtual InvariantHashSet GetAllowedSubkeys()
|
||||||
|
{
|
||||||
|
return this.Values.GetValidInputs();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the current token values.</summary>
|
||||||
|
/// <param name="name">The token name to check, if applicable.</param>
|
||||||
|
/// <exception cref="InvalidOperationException">The key doesn't match this token, or the key does not respect <see cref="IToken.RequiresSubkeys"/>.</exception>
|
||||||
|
protected void AssertTokenName(TokenName? name)
|
||||||
|
{
|
||||||
|
if (name == null)
|
||||||
|
{
|
||||||
|
// missing subkey
|
||||||
|
if (this.RequiresSubkeys)
|
||||||
|
throw new InvalidOperationException($"The '{this.Name}' token requires a subkey.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// not same root key
|
||||||
|
if (!this.Name.IsSameRootKey(name.Value))
|
||||||
|
throw new InvalidOperationException($"The specified token key ({name}) is not handled by this token ({this.Name}).");
|
||||||
|
|
||||||
|
// no subkey allowed
|
||||||
|
if (!this.CanHaveSubkeys && name.Value.HasSubkey())
|
||||||
|
throw new InvalidOperationException($"The '{this.Name}' token does not allow subkeys (:).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Try to parse a raw case-insensitive string into an enum value.</summary>
|
||||||
|
/// <typeparam name="TEnum">The enum type.</typeparam>
|
||||||
|
/// <param name="raw">The raw string to parse.</param>
|
||||||
|
/// <param name="result">The resulting enum value.</param>
|
||||||
|
/// <param name="mustBeNamed">When parsing a numeric value, whether it must match one of the named enum values.</param>
|
||||||
|
protected bool TryParseEnum<TEnum>(string raw, out TEnum result, bool mustBeNamed = true) where TEnum : struct
|
||||||
|
{
|
||||||
|
if (!Enum.TryParse(raw, true, out result))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (mustBeNamed && !Enum.IsDefined(typeof(TEnum), result))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the subkey/value pairs used in the given name and values.</summary>
|
||||||
|
/// <param name="name">The token name to validate.</param>
|
||||||
|
/// <param name="values">The values to validate.</param>
|
||||||
|
/// <returns>Returns the subkey/value pairs found. If the <paramref name="name"/> includes a subkey, the <paramref name="values"/> are treated as values of that subkey. Otherwise if <see cref="CanHaveSubkeys"/> is true, then each value is treated as <c>subkey:value</c> (if they contain a colon) or <c>value</c> (with a null subkey).</returns>
|
||||||
|
protected IEnumerable<KeyValuePair<TokenName, string>> GetSubkeyValuePairsFor(TokenName name, InvariantHashSet values)
|
||||||
|
{
|
||||||
|
// no subkeys in values
|
||||||
|
if (!this.CanHaveSubkeys || name.HasSubkey())
|
||||||
|
{
|
||||||
|
foreach (string value in values)
|
||||||
|
yield return new KeyValuePair<TokenName, string>(name, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// possible subkeys in values
|
||||||
|
else
|
||||||
|
{
|
||||||
|
foreach (string value in values)
|
||||||
|
{
|
||||||
|
string[] parts = value.Split(new[] { ':' }, 2);
|
||||||
|
if (parts.Length < 2)
|
||||||
|
yield return new KeyValuePair<TokenName, string>(name, parts[0]);
|
||||||
|
else
|
||||||
|
yield return new KeyValuePair<TokenName, string>(new TokenName(name.Key, parts[0]), parts[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Tokens
|
||||||
|
{
|
||||||
|
/// <summary>Provides access to contextual tokens.</summary>
|
||||||
|
internal interface IContext
|
||||||
|
{
|
||||||
|
/// <summary>Get whether the context contains the given token.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
bool Contains(TokenName name, bool enforceContext);
|
||||||
|
|
||||||
|
/// <summary>Get the underlying token which handles a key.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
/// <returns>Returns the matching token, or <c>null</c> if none was found.</returns>
|
||||||
|
IToken GetToken(TokenName name, bool enforceContext);
|
||||||
|
|
||||||
|
/// <summary>Get the underlying tokens.</summary>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
IEnumerable<IToken> GetTokens(bool enforceContext);
|
||||||
|
|
||||||
|
/// <summary>Get the current values of the given token for comparison.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
|
||||||
|
/// <returns>Return the values of the matching token, or an empty list if the token doesn't exist.</returns>
|
||||||
|
/// <exception cref="ArgumentNullException">The specified key is null.</exception>
|
||||||
|
IEnumerable<string> GetValues(TokenName name, bool enforceContext);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,60 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Tokens
|
||||||
|
{
|
||||||
|
/// <summary>A token whose value may change depending on the current context.</summary>
|
||||||
|
internal interface IToken
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The token name.</summary>
|
||||||
|
TokenName Name { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the token is applicable in the current context.</summary>
|
||||||
|
bool IsValidInContext { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the value can change after it's initialised.</summary>
|
||||||
|
bool IsMutable { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether this token recognises subkeys (e.g. <c>Relationship:Abigail</c> is a <c>Relationship</c> token with a <c>Abigail</c> subkey).</summary>
|
||||||
|
bool CanHaveSubkeys { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether this token only allows subkeys (see <see cref="CanHaveSubkeys"/>).</summary>
|
||||||
|
bool RequiresSubkeys { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Update the token data when the context changes.</summary>
|
||||||
|
/// <param name="context">The condition context.</param>
|
||||||
|
/// <returns>Returns whether the token data changed.</returns>
|
||||||
|
void UpdateContext(IContext context);
|
||||||
|
|
||||||
|
/// <summary>Whether the token may return multiple values for the given name.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
bool CanHaveMultipleValues(TokenName name);
|
||||||
|
|
||||||
|
/// <summary>Perform custom validation.</summary>
|
||||||
|
/// <param name="name">The token name to validate.</param>
|
||||||
|
/// <param name="values">The values to validate.</param>
|
||||||
|
/// <param name="error">The validation error, if any.</param>
|
||||||
|
/// <returns>Returns whether validation succeeded.</returns>
|
||||||
|
bool TryValidate(TokenName name, InvariantHashSet values, out string error);
|
||||||
|
|
||||||
|
/// <summary>Get the current subkeys (if supported).</summary>
|
||||||
|
IEnumerable<TokenName> GetSubkeys();
|
||||||
|
|
||||||
|
/// <summary>Get the allowed values for a token name (or <c>null</c> if any value is allowed).</summary>
|
||||||
|
/// <exception cref="InvalidOperationException">The key doesn't match this token, or the key does not respect <see cref="CanHaveSubkeys"/> or <see cref="RequiresSubkeys"/>.</exception>
|
||||||
|
InvariantHashSet GetAllowedValues(TokenName name);
|
||||||
|
|
||||||
|
/// <summary>Get the current token values.</summary>
|
||||||
|
/// <param name="name">The token name to check.</param>
|
||||||
|
/// <exception cref="InvalidOperationException">The key doesn't match this token, or the key does not respect <see cref="CanHaveSubkeys"/> or <see cref="RequiresSubkeys"/>.</exception>
|
||||||
|
IEnumerable<string> GetValues(TokenName name);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
using ContentPatcher.Framework.Tokens.ValueProviders;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Tokens
|
||||||
|
{
|
||||||
|
/// <summary>A tokens whose values don't change after it's initialised.</summary>
|
||||||
|
internal class ImmutableToken : GenericToken
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="name">The token name.</param>
|
||||||
|
/// <param name="values">Get the current token values.</param>
|
||||||
|
/// <param name="allowedValues">The allowed values (or <c>null</c> if any value is allowed).</param>
|
||||||
|
/// <param name="canHaveMultipleValues">Whether the root may contain multiple values (or <c>null</c> to set it based on the given values).</param>
|
||||||
|
public ImmutableToken(string name, InvariantHashSet values, InvariantHashSet allowedValues = null, bool? canHaveMultipleValues = null)
|
||||||
|
: base(new ImmutableValueProvider(name, values, allowedValues, canHaveMultipleValues)) { }
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,158 @@
|
||||||
|
using System;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Tokens
|
||||||
|
{
|
||||||
|
/// <summary>Represents a token key and subkey if applicable (e.g. <c>Relationship:Abigail</c> is token key <c>Relationship</c> and subkey <c>Abigail</c>).</summary>
|
||||||
|
internal struct TokenName : IEquatable<TokenName>, IComparable
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The token type.</summary>
|
||||||
|
public string Key { get; }
|
||||||
|
|
||||||
|
/// <summary>The token subkey indicating which in-game object the condition type applies to, if applicable. For example, the NPC name when <see cref="Key"/> is <see cref="ConditionType.Relationship"/>.</summary>
|
||||||
|
public string Subkey { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="tokenKey">The condition type.</param>
|
||||||
|
/// <param name="subkey">A unique key indicating which in-game object the condition type applies to. For example, the NPC name when <paramref name="tokenKey"/> is <see cref="ConditionType.Relationship"/>.</param>
|
||||||
|
public TokenName(string tokenKey, string subkey = null)
|
||||||
|
{
|
||||||
|
this.Key = tokenKey?.Trim();
|
||||||
|
this.Subkey = subkey?.Trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="tokenKey">The condition type.</param>
|
||||||
|
/// <param name="subkey">A unique key indicating which in-game object the condition type applies to. For example, the NPC name when <paramref name="tokenKey"/> is <see cref="ConditionType.Relationship"/>.</param>
|
||||||
|
public TokenName(ConditionType tokenKey, string subkey = null)
|
||||||
|
: this(tokenKey.ToString(), subkey) { }
|
||||||
|
|
||||||
|
/// <summary>Get a string representation for this instance.</summary>
|
||||||
|
public override string ToString()
|
||||||
|
{
|
||||||
|
return this.HasSubkey()
|
||||||
|
? $"{this.Key}:{this.Subkey}"
|
||||||
|
: this.Key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get whether this key has the same root <see cref="Key"/> as another.</summary>
|
||||||
|
/// <param name="other">The other key to check.</param>
|
||||||
|
public bool IsSameRootKey(TokenName other)
|
||||||
|
{
|
||||||
|
if (this.Key == null)
|
||||||
|
return other.Key == null;
|
||||||
|
|
||||||
|
return this.Key.Equals(other.Key, StringComparison.InvariantCultureIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether this token key specifies a subkey.</summary>
|
||||||
|
public bool HasSubkey()
|
||||||
|
{
|
||||||
|
return !string.IsNullOrWhiteSpace(this.Subkey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Try to parse the <see cref="Key"/> as a global condition type.</summary>
|
||||||
|
/// <param name="type">The parsed condition type, if applicable.</param>
|
||||||
|
public bool TryGetConditionType(out ConditionType type)
|
||||||
|
{
|
||||||
|
return Enum.TryParse(this.Key, true, out type);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the root token (without the <see cref="Subkey"/>).</summary>
|
||||||
|
public TokenName GetRoot()
|
||||||
|
{
|
||||||
|
return this.HasSubkey()
|
||||||
|
? new TokenName(this.Key)
|
||||||
|
: this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** IEquatable
|
||||||
|
****/
|
||||||
|
/// <summary>Get whether the current object is equal to another object of the same type.</summary>
|
||||||
|
/// <param name="other">An object to compare with this object.</param>
|
||||||
|
public bool Equals(TokenName other)
|
||||||
|
{
|
||||||
|
return this.CompareTo(other) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get whether this instance and a specified object are equal.</summary>
|
||||||
|
/// <param name="obj">The object to compare with the current instance.</param>
|
||||||
|
public override bool Equals(object obj)
|
||||||
|
{
|
||||||
|
return obj is TokenName other && this.Equals(other);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the hash code for this instance.</summary>
|
||||||
|
public override int GetHashCode()
|
||||||
|
{
|
||||||
|
return this.ToString().ToLowerInvariant().GetHashCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** IComparable
|
||||||
|
****/
|
||||||
|
/// <summary>Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.</summary>
|
||||||
|
/// <param name="obj">An object to compare with this instance.</param>
|
||||||
|
/// <returns>A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance precedes <paramref name="obj" /> in the sort order. Zero This instance occurs in the same position in the sort order as <paramref name="obj" />. Greater than zero This instance follows <paramref name="obj" /> in the sort order.</returns>
|
||||||
|
public int CompareTo(object obj)
|
||||||
|
{
|
||||||
|
return string.Compare(this.ToString(), obj?.ToString(), StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
/****
|
||||||
|
** Static parsing
|
||||||
|
****/
|
||||||
|
/// <summary>Parse a raw string into a condition key if it's valid.</summary>
|
||||||
|
/// <param name="raw">The raw string.</param>
|
||||||
|
/// <returns>Returns true if <paramref name="raw"/> was successfully parsed, else false.</returns>
|
||||||
|
public static TokenName Parse(string raw)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(raw))
|
||||||
|
throw new ArgumentNullException(nameof(raw));
|
||||||
|
|
||||||
|
// extract parts
|
||||||
|
string key;
|
||||||
|
string subkey;
|
||||||
|
{
|
||||||
|
string[] parts = raw.Trim().Split(new[] { ':' }, 2);
|
||||||
|
|
||||||
|
key = parts[0].Trim();
|
||||||
|
if (key == "")
|
||||||
|
throw new ArgumentException($"The main key in '{raw}' can't be blank.");
|
||||||
|
|
||||||
|
subkey = parts.Length == 2 ? parts[1].Trim() : null;
|
||||||
|
if (subkey == "")
|
||||||
|
subkey = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// create instance
|
||||||
|
return new TokenName(key, subkey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Parse a raw string into a condition key if it's valid.</summary>
|
||||||
|
/// <param name="raw">The raw string.</param>
|
||||||
|
/// <param name="key">The parsed condition key.</param>
|
||||||
|
/// <returns>Returns true if <paramref name="raw"/> was successfully parsed, else false.</returns>
|
||||||
|
public static bool TryParse(string raw, out TokenName key)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
key = TokenName.Parse(raw);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
key = default(TokenName);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,248 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using ContentPatcher.Framework.Conditions;
|
||||||
|
using Pathoschild.Stardew.Common.Utilities;
|
||||||
|
|
||||||
|
namespace ContentPatcher.Framework.Tokens.ValueProviders
|
||||||
|
{
|
||||||
|
/// <summary>The base class for a value provider.</summary>
|
||||||
|
internal abstract class BaseValueProvider : IValueProvider
|
||||||
|
{
|
||||||
|
/*********
|
||||||
|
** Fields
|
||||||
|
*********/
|
||||||
|
/// <summary>Whether multiple values may exist when no input is provided.</summary>
|
||||||
|
protected bool CanHaveMultipleValuesForRoot { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Whether multiple values may exist when an input argument is provided.</summary>
|
||||||
|
protected bool CanHaveMultipleValuesForInput { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Accessors
|
||||||
|
*********/
|
||||||
|
/// <summary>The value provider name.</summary>
|
||||||
|
public string Name { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the provided values can change after the provider is initialised.</summary>
|
||||||
|
public bool IsMutable { get; protected set; } = true;
|
||||||
|
|
||||||
|
/// <summary>Whether the value provider allows an input argument (e.g. an NPC name for a relationship token).</summary>
|
||||||
|
public bool AllowsInput { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Whether the value provider requires an input argument to work, and does not provide values without it (see <see cref="IValueProvider.AllowsInput"/>).</summary>
|
||||||
|
public bool RequiresInput { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Whether values exist in the current context.</summary>
|
||||||
|
public bool IsValidInContext { get; protected set; }
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Public methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Update the underlying values.</summary>
|
||||||
|
/// <param name="context">The condition context.</param>
|
||||||
|
/// <returns>Returns whether the values changed.</returns>
|
||||||
|
public virtual void UpdateContext(IContext context) { }
|
||||||
|
|
||||||
|
/// <summary>Whether the value provider may return multiple values for the given input.</summary>
|
||||||
|
/// <param name="input">The input argument, if applicable.</param>
|
||||||
|
public bool CanHaveMultipleValues(string input = null)
|
||||||
|
{
|
||||||
|
return input != null
|
||||||
|
? this.CanHaveMultipleValuesForInput
|
||||||
|
: this.CanHaveMultipleValuesForRoot;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Validate that the provided values are valid for the input argument (regardless of whether they match).</summary>
|
||||||
|
/// <param name="input">The input argument, if applicable.</param>
|
||||||
|
/// <param name="values">The values to validate.</param>
|
||||||
|
/// <param name="error">The validation error, if any.</param>
|
||||||
|
/// <returns>Returns whether validation succeeded.</returns>
|
||||||
|
public bool TryValidate(string input, InvariantHashSet values, out string error)
|
||||||
|
{
|
||||||
|
// parse data
|
||||||
|
KeyValuePair<string, string>[] pairs = this.GetInputValuePairs(input, values).ToArray();
|
||||||
|
|
||||||
|
// restrict to allowed input
|
||||||
|
if (this.AllowsInput)
|
||||||
|
{
|
||||||
|
InvariantHashSet validInputs = this.GetValidInputs();
|
||||||
|
if (validInputs?.Any() == true)
|
||||||
|
{
|
||||||
|
string[] invalidInputs =
|
||||||
|
(
|
||||||
|
from pair in pairs
|
||||||
|
where pair.Key != null && !validInputs.Contains(pair.Key)
|
||||||
|
select pair.Key
|
||||||
|
)
|
||||||
|
.Distinct()
|
||||||
|
.ToArray();
|
||||||
|
if (invalidInputs.Any())
|
||||||
|
{
|
||||||
|
error = $"invalid input arguments ({string.Join(", ", invalidInputs)}), expected any of {string.Join(", ", validInputs)}";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// restrict to allowed values
|
||||||
|
{
|
||||||
|
InvariantHashSet validValues = this.GetAllowedValues(input);
|
||||||
|
if (validValues?.Any() == true)
|
||||||
|
{
|
||||||
|
string[] invalidValues =
|
||||||
|
(
|
||||||
|
from pair in pairs
|
||||||
|
where !validValues.Contains(pair.Value)
|
||||||
|
select pair.Value
|
||||||
|
)
|
||||||
|
.Distinct()
|
||||||
|
.ToArray();
|
||||||
|
if (invalidValues.Any())
|
||||||
|
{
|
||||||
|
error = $"invalid values ({string.Join(", ", invalidValues)}); expected one of {string.Join(", ", validValues)}";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// custom validation
|
||||||
|
foreach (KeyValuePair<string, string> pair in pairs)
|
||||||
|
{
|
||||||
|
if (!this.TryValidate(pair.Key, pair.Value, out error))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// no issues found
|
||||||
|
error = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the set of valid input arguments if restricted, or an empty collection if unrestricted.</summary>
|
||||||
|
public virtual InvariantHashSet GetValidInputs()
|
||||||
|
{
|
||||||
|
return new InvariantHashSet();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the allowed values for an input argument (or <c>null</c> if any value is allowed).</summary>
|
||||||
|
/// <param name="input">The input argument, if applicable.</param>
|
||||||
|
/// <exception cref="InvalidOperationException">The input argument doesn't match this value provider, or does not respect <see cref="IValueProvider.AllowsInput"/> or <see cref="IValueProvider.RequiresInput"/>.</exception>
|
||||||
|
public virtual InvariantHashSet GetAllowedValues(string input)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Get the current values.</summary>
|
||||||
|
/// <param name="input">The input argument, if applicable.</param>
|
||||||
|
/// <exception cref="InvalidOperationException">The input argument doesn't match this value provider, or does not respect <see cref="IValueProvider.AllowsInput"/> or <see cref="IValueProvider.RequiresInput"/>.</exception>
|
||||||
|
public virtual IEnumerable<string> GetValues(string input)
|
||||||
|
{
|
||||||
|
this.AssertInputArgument(input);
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*********
|
||||||
|
** Protected methods
|
||||||
|
*********/
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="name">The value provider name.</param>
|
||||||
|
/// <param name="canHaveMultipleValuesForRoot">Whether the root value provider may contain multiple values.</param>
|
||||||
|
protected BaseValueProvider(string name, bool canHaveMultipleValuesForRoot)
|
||||||
|
{
|
||||||
|
this.Name = name;
|
||||||
|
this.CanHaveMultipleValuesForRoot = canHaveMultipleValuesForRoot;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Construct an instance.</summary>
|
||||||
|
/// <param name="type">The value provider name.</param>
|
||||||
|
/// <param name="canHaveMultipleValuesForRoot">Whether the root value provider may contain multiple values.</param>
|
||||||
|
protected BaseValueProvider(ConditionType type, bool canHaveMultipleValuesForRoot)
|
||||||
|
: this(type.ToString(), canHaveMultipleValuesForRoot) { }
|
||||||
|
|
||||||
|
/// <summary>Validate that the provided value is valid for an input argument (regardless of whether they match).</summary>
|
||||||
|
/// <param name="input">The input argument, if applicable.</param>
|
||||||
|
/// <param name="value">The value to validate.</param>
|
||||||
|
/// <param name="error">The validation error, if any.</param>
|
||||||
|
/// <returns>Returns whether validation succeeded.</returns>
|
||||||
|
protected virtual bool TryValidate(string input, string value, out string error)
|
||||||
|
{
|
||||||
|
error = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Enable input arguments for this value provider.</summary>
|
||||||
|
/// <param name="required">Whether an input argument is required when using this value provider.</param>
|
||||||
|
/// <param name="canHaveMultipleValues">Whether the value provider may return multiple values for an input argument.</param>
|
||||||
|
protected void EnableInputArguments(bool required, bool canHaveMultipleValues)
|
||||||
|
{
|
||||||
|
this.AllowsInput = true;
|
||||||
|
this.RequiresInput = required;
|
||||||
|
this.CanHaveMultipleValuesForInput = canHaveMultipleValues;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Assert that an input argument is valid for the value provider.</summary>
|
||||||
|
/// <param name="input">The input argument to check, if applicable.</param>
|
||||||
|
/// <exception cref="InvalidOperationException">The input argument doesn't match this value provider, or does not respect <see cref="AllowsInput"/> or <see cref="RequiresInput"/>.</exception>
|
||||||
|
protected void AssertInputArgument(string input)
|
||||||
|
{
|
||||||
|
if (input == null)
|
||||||
|
{
|
||||||
|
// missing input argument
|
||||||
|
if (this.RequiresInput)
|
||||||
|
throw new InvalidOperationException($"The '{this.Name}' token requires an input argument.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// no subkey allowed
|
||||||
|
if (!this.AllowsInput)
|
||||||
|
throw new InvalidOperationException($"The '{this.Name}' token does not allow input arguments.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Try to parse a raw case-insensitive string into an enum value.</summary>
|
||||||
|
/// <typeparam name="TEnum">The enum type.</typeparam>
|
||||||
|
/// <param name="raw">The raw string to parse.</param>
|
||||||
|
/// <param name="result">The resulting enum value.</param>
|
||||||
|
/// <param name="mustBeNamed">When parsing a numeric value, whether it must match one of the named enum values.</param>
|
||||||
|
protected bool TryParseEnum<TEnum>(string raw, out TEnum result, bool mustBeNamed = true) where TEnum : struct
|
||||||
|
{
|
||||||
|
if (!Enum.TryParse(raw, true, out result))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (mustBeNamed && !Enum.IsDefined(typeof(TEnum), result))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Parse a user-defined set of values for input/value pairs. For example, <c>"Abigail:10"</c> for a relationship token would be parsed as input argument 'Abigail' with value '10'.</summary>
|
||||||
|
/// <param name="input">The current input argument, if applicable.</param>
|
||||||
|
/// <param name="values">The values to parse.</param>
|
||||||
|
/// <returns>Returns the input/value pairs found. If <paramref name="input"/> is non-null, the <paramref name="values"/> are treated as values for that input argument. Otherwise if <see cref="AllowsInput"/> is true, then each value is treated as <c>input:value</c> (if they contain a colon) or <c>value</c> (with a null input).</returns>
|
||||||
|
protected IEnumerable<KeyValuePair<string, string>> GetInputValuePairs(string input, InvariantHashSet values)
|
||||||
|
{
|
||||||
|
// no input arguments in values
|
||||||
|
if (!this.AllowsInput || input != null)
|
||||||
|
{
|
||||||
|
foreach (string value in values)
|
||||||
|
yield return new KeyValuePair<string, string>(input, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// possible input arguments in values
|
||||||
|
else
|
||||||
|
{
|
||||||
|
foreach (string value in values)
|
||||||
|
{
|
||||||
|
string[] parts = value.Split(new[] { ':' }, 2);
|
||||||
|
if (parts.Length < 2)
|
||||||
|
yield return new KeyValuePair<string, string>(input, parts[0]);
|
||||||
|
else
|
||||||
|
yield return new KeyValuePair<string, string>(parts[0], parts[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue