Merge branch 'develop' into stable

This commit is contained in:
Jesse Plamondon-Willard 2017-05-03 13:02:15 -04:00
commit c84310dfeb
14 changed files with 149 additions and 55 deletions

BIN
lib/libgdiplus.dylib Normal file

Binary file not shown.

View File

@ -10,6 +10,22 @@ For mod developers:
images).
-->
## 1.12
See [log](https://github.com/Pathoschild/SMAPI/compare/1.11...1.12).
For players:
* The installer now lets you choose the install path if you have multiple copies of the game, instead of using the first path found.
* Fixed mod draw errors breaking the game.
* Fixed mods on Linux/Mac no longer working after the game saves.
* Fixed libgdiplus DLL-not-found errors on Linux/Mac when mods read PNG files.
* Adopted pufferchick.
For mod developers:
* Unknown mod manifest fields are now stored in `IManifest::ExtraFields`.
* The content API now defaults to `ContentSource.ModFolder`.
* Fixed content API error when loading a PNG during early game init (e.g. in mod's `Entry`).
* Fixed content API error when loading an XNB from the mod folder on Mac.
## 1.11
See [log](https://github.com/Pathoschild/SMAPI/compare/1.10...1.11).

View File

@ -2,5 +2,5 @@
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.11.0.0")]
[assembly: AssemblyFileVersion("1.11.0.0")]
[assembly: AssemblyVersion("1.12.0.0")]
[assembly: AssemblyFileVersion("1.12.0.0")]

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
@ -128,7 +129,11 @@ namespace StardewModdingApi.Installer
/****
** collect details
****/
// get platform
Platform platform = this.DetectPlatform();
this.PrintDebug($"Platform: {(platform == Platform.Windows ? "Windows" : "Linux or Mac")}.");
// get folders
DirectoryInfo packageDir = new DirectoryInfo(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "internal", platform.ToString()));
DirectoryInfo installDir = this.InteractivelyGetInstallPath(platform);
DirectoryInfo modsDir = new DirectoryInfo(Path.Combine(installDir.FullName, "Mods"));
@ -139,7 +144,7 @@ namespace StardewModdingApi.Installer
unixLauncher = Path.Combine(installDir.FullName, "StardewValley"),
unixLauncherBackup = Path.Combine(installDir.FullName, "StardewValley-original")
};
this.PrintDebug($"Detected {(platform == Platform.Windows ? "Windows" : "Linux or Mac")} with game in {installDir}.");
this.PrintDebug($"Install path: {installDir}.");
/****
** validate assumptions
@ -494,7 +499,7 @@ namespace StardewModdingApi.Installer
}
}
/// <summary>Interactively locate the game's install path.</summary>
/// <summary>Interactively locate the game install path to update.</summary>
/// <param name="platform">The current platform.</param>
private DirectoryInfo InteractivelyGetInstallPath(Platform platform)
{
@ -503,12 +508,34 @@ namespace StardewModdingApi.Installer
? "Stardew Valley.exe"
: "StardewValley.exe";
// try default paths
foreach (string defaultPath in this.GetDefaultInstallPaths(platform))
// get installed paths
DirectoryInfo[] defaultPaths =
(
from path in this.GetDefaultInstallPaths(platform).Distinct()
let dir = new DirectoryInfo(path)
where dir.Exists && dir.EnumerateFiles(executableFilename).Any()
select dir
)
.ToArray();
// choose where to install
if (defaultPaths.Any())
{
DirectoryInfo dir = new DirectoryInfo(defaultPath);
if (dir.Exists && dir.EnumerateFiles(executableFilename).Any())
return new DirectoryInfo(defaultPath);
// only one path
if (defaultPaths.Length == 1)
return defaultPaths.First();
// let user choose path
Console.WriteLine();
Console.WriteLine("Found multiple copies of the game:");
for (int i = 0; i < defaultPaths.Length; i++)
Console.WriteLine($"[{i + 1}] {defaultPaths[i].FullName}");
Console.WriteLine();
string[] validOptions = Enumerable.Range(1, defaultPaths.Length).Select(p => p.ToString(CultureInfo.InvariantCulture)).ToArray();
string choice = this.InteractivelyChoose("Where do you want to add/remove SMAPI? Type the number next to your choice, then press enter.", validOptions);
int index = int.Parse(choice, CultureInfo.InvariantCulture) - 1;
return defaultPaths[index];
}
// ask user

View File

@ -33,7 +33,7 @@ namespace StardewModdingAPI
** Public
****/
/// <summary>SMAPI's current semantic version.</summary>
public static ISemanticVersion ApiVersion { get; } = new SemanticVersion(1, 11, 0);
public static ISemanticVersion ApiVersion { get; } = new SemanticVersion(1, 12, 0);
/// <summary>The minimum supported version of Stardew Valley.</summary>
public static ISemanticVersion MinimumGameVersion { get; } = new SemanticVersion("1.2.26");

View File

@ -1,4 +1,5 @@
using StardewValley;
using StardewValley.Menus;
namespace StardewModdingAPI
{
@ -12,7 +13,7 @@ namespace StardewModdingAPI
public static bool IsSaveLoaded => Game1.hasLoadedGame && !string.IsNullOrEmpty(Game1.player.name);
/// <summary>Whether the game is currently writing to the save file.</summary>
public static bool IsSaving => SaveGame.IsProcessing;
public static bool IsSaving => SaveGame.IsProcessing && (Game1.activeClickableMenu is SaveGameMenu || Game1.activeClickableMenu is ShippingMenu); // IsProcessing is never set to false on Linux/Mac
/// <summary>Whether the game is currently running the draw loop.</summary>
public static bool IsInDrawLoop { get; set; }

View File

@ -45,11 +45,11 @@ namespace StardewModdingAPI.Framework
/// <summary>Load content from the game folder or mod folder (if not already cached), and return it. When loading a <c>.png</c> file, this must be called outside the game's draw loop.</summary>
/// <typeparam name="T">The expected data type. The main supported types are <see cref="Texture2D"/> and dictionaries; other types may be supported by the game's content pipeline.</typeparam>
/// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to an XNB file relative to the mod folder.</param>
/// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to a content file relative to the mod folder.</param>
/// <param name="source">Where to search for a matching content asset.</param>
/// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception>
/// <exception cref="ContentLoadException">The content asset couldn't be loaded (e.g. because it doesn't exist).</exception>
public T Load<T>(string key, ContentSource source)
public T Load<T>(string key, ContentSource source = ContentSource.ModFolder)
{
this.AssertValidAssetKeyFormat(key);
try
@ -57,25 +57,22 @@ namespace StardewModdingAPI.Framework
switch (source)
{
case ContentSource.GameContent:
return this.ContentManager.Load<T>(this.StripXnbExtension(key));
return this.ContentManager.Load<T>(key);
case ContentSource.ModFolder:
// find content file
key = this.ContentManager.NormalisePathSeparators(key);
FileInfo file = new FileInfo(Path.Combine(this.ModFolderPath, key));
if (!file.Exists && file.Extension == "")
file = new FileInfo(Path.Combine(this.ModFolderPath, key + ".xnb"));
// get file
FileInfo file = this.GetModFile(key);
if (!file.Exists)
throw new ContentLoadException($"There is no file at path '{file.FullName}'.");
// get underlying asset key
string actualKey = this.GetActualAssetKey(key, source);
// get asset path
string assetPath = this.GetModAssetPath(key, file.FullName);
// load content
switch (file.Extension.ToLower())
{
case ".xnb":
return this.ContentManager.Load<T>(actualKey);
return this.ContentManager.Load<T>(assetPath);
case ".png":
// validate
@ -83,15 +80,15 @@ namespace StardewModdingAPI.Framework
throw new ContentLoadException($"Can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Texture2D)}'.");
// try cache
if (this.ContentManager.IsLoaded(actualKey))
return this.ContentManager.Load<T>(actualKey);
if (this.ContentManager.IsLoaded(assetPath))
return this.ContentManager.Load<T>(assetPath);
// fetch & cache
using (FileStream stream = File.OpenRead(file.FullName))
{
Texture2D texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream);
texture = this.PremultiplyTransparency(texture);
this.ContentManager.Inject(actualKey, texture);
this.ContentManager.Inject(assetPath, texture);
return (T)(object)texture;
}
@ -110,19 +107,19 @@ namespace StardewModdingAPI.Framework
}
/// <summary>Get the underlying key in the game's content cache for an asset. This can be used to load custom map tilesheets, but should be avoided when you can use the content API instead. This does not validate whether the asset exists.</summary>
/// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to an XNB file relative to the mod folder.</param>
/// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to a content file relative to the mod folder.</param>
/// <param name="source">Where to search for a matching content asset.</param>
/// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception>
public string GetActualAssetKey(string key, ContentSource source)
public string GetActualAssetKey(string key, ContentSource source = ContentSource.ModFolder)
{
switch (source)
{
case ContentSource.GameContent:
return this.ContentManager.NormaliseAssetName(this.StripXnbExtension(key));
return this.ContentManager.NormaliseAssetName(key);
case ContentSource.ModFolder:
string contentPath = Path.Combine(this.ModFolderPathFromContent, key);
return this.ContentManager.NormaliseAssetName(this.StripXnbExtension(contentPath));
FileInfo file = this.GetModFile(key);
return this.ContentManager.NormaliseAssetName(this.GetModAssetPath(key, file.FullName));
default:
throw new NotSupportedException($"Unknown content source '{source}'.");
@ -145,13 +142,29 @@ namespace StardewModdingAPI.Framework
throw new ArgumentException("The asset key or local path contains invalid characters.");
}
/// <summary>Strip the .xnb extension from an asset key, since it's assumed by the underlying content manager.</summary>
/// <param name="key">The asset key.</param>
private string StripXnbExtension(string key)
/// <summary>Get a file from the mod folder.</summary>
/// <param name="path">The asset path relative to the mod folder.</param>
private FileInfo GetModFile(string path)
{
if (key.EndsWith(".xnb", StringComparison.InvariantCultureIgnoreCase))
return key.Substring(0, key.Length - 4);
return key;
path = Path.Combine(this.ModFolderPath, this.ContentManager.NormalisePathSeparators(path));
FileInfo file = new FileInfo(path);
if (!file.Exists && file.Extension == "")
file = new FileInfo(Path.Combine(this.ModFolderPath, path + ".xnb"));
return file;
}
/// <summary>Get the asset path which loads a mod folder through a content manager.</summary>
/// <param name="localPath">The file path relative to the mod's folder.</param>
/// <param name="absolutePath">The absolute file path.</param>
private string GetModAssetPath(string localPath, string absolutePath)
{
#if SMAPI_FOR_WINDOWS
// XNA doesn't allow absolute asset paths, so get a path relative to the content folder
return Path.Combine(this.ModFolderPathFromContent, localPath);
#else
// MonoGame is weird about relative paths on Mac, but allows absolute paths
return absolutePath;
#endif
}
/// <summary>Get a directory path relative to a given root.</summary>
@ -181,14 +194,13 @@ namespace StardewModdingAPI.Framework
throw new NotSupportedException("Can't load a PNG file while the game is drawing to the screen. Make sure you load content outside the draw loop.");
// process texture
SpriteBatch spriteBatch = Game1.spriteBatch;
GraphicsDevice gpu = Game1.graphics.GraphicsDevice;
using (RenderTarget2D renderTarget = new RenderTarget2D(Game1.graphics.GraphicsDevice, texture.Width, texture.Height))
using (SpriteBatch spriteBatch = new SpriteBatch(Game1.graphics.GraphicsDevice))
{
//Viewport originalViewport = Game1.graphics.GraphicsDevice.Viewport;
// create blank slate in render target
Game1.graphics.GraphicsDevice.SetRenderTarget(renderTarget);
Game1.graphics.GraphicsDevice.Clear(Color.Black);
// create blank render target to premultiply
gpu.SetRenderTarget(renderTarget);
gpu.Clear(Color.Black);
// multiply each color by the source alpha, and write just the color values into the final texture
spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState
@ -214,16 +226,17 @@ namespace StardewModdingAPI.Framework
spriteBatch.Draw(texture, texture.Bounds, Color.White);
spriteBatch.End();
// release the GPU
Game1.graphics.GraphicsDevice.SetRenderTarget(null);
//Game1.graphics.GraphicsDevice.Viewport = originalViewport;
// release GPU
gpu.SetRenderTarget(null);
// store data from render target because the RenderTarget2D is volatile
// extract premultiplied data
Color[] data = new Color[texture.Width * texture.Height];
renderTarget.GetData(data);
// unset texture from graphic device and set modified data back to it
Game1.graphics.GraphicsDevice.Textures[0] = null;
// unset texture from GPU to regain control
gpu.Textures[0] = null;
// update texture with premultiplied data
texture.SetData(data);
}

View File

@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StardewModdingAPI.Framework.Serialisation;
namespace StardewModdingAPI.Framework
@ -35,5 +37,9 @@ namespace StardewModdingAPI.Framework
/// <summary>Whether the mod uses per-save config files.</summary>
[Obsolete("Use " + nameof(Mod) + "." + nameof(Mod.Helper) + "." + nameof(IModHelper.ReadConfig) + " instead")]
public bool PerSaveConfigs { get; set; }
/// <summary>Any manifest fields which didn't match a valid field.</summary>
[JsonExtensionData]
public IDictionary<string, object> ExtraFields { get; set; }
}
}

View File

@ -99,6 +99,8 @@ namespace StardewModdingAPI.Framework
public string NormaliseAssetName(string assetName)
{
assetName = this.NormalisePathSeparators(assetName);
if (assetName.EndsWith(".xnb", StringComparison.InvariantCultureIgnoreCase))
return assetName.Substring(0, assetName.Length - 4);
return this.NormaliseAssetNameForPlatform(assetName);
}

View File

@ -947,7 +947,28 @@ namespace StardewModdingAPI.Framework
}
catch (Exception ex)
{
// log error
this.Monitor.Log($"An error occured in the overridden draw loop: {ex.GetLogSummary()}", LogLevel.Error);
// fix sprite batch
try
{
bool isSpriteBatchOpen =
#if SMAPI_FOR_WINDOWS
SGame.Reflection.GetPrivateValue<bool>(Game1.spriteBatch, "inBeginEndPair");
#else
SGame.Reflection.GetPrivateValue<bool>(Game1.spriteBatch, "_beginCalled");
#endif
if (isSpriteBatchOpen)
{
this.Monitor.Log("Recovering sprite batch from error...", LogLevel.Trace);
Game1.spriteBatch.End();
}
}
catch (Exception innerEx)
{
this.Monitor.Log($"Could not recover sprite batch state: {innerEx.GetLogSummary()}", LogLevel.Error);
}
}
Context.IsInDrawLoop = false;
}
@ -1345,8 +1366,8 @@ namespace StardewModdingAPI.Framework
/// <param name="enumerable">The enumeration of items to hash.</param>
private int GetHash(IEnumerable enumerable)
{
var hash = 0;
foreach (var v in enumerable)
int hash = 0;
foreach (object v in enumerable)
hash ^= v.GetHashCode();
return hash;
}

View File

@ -9,16 +9,16 @@ namespace StardewModdingAPI
{
/// <summary>Load content from the game folder or mod folder (if not already cached), and return it. When loading a <c>.png</c> file, this must be called outside the game's draw loop.</summary>
/// <typeparam name="T">The expected data type. The main supported types are <see cref="Texture2D"/> and dictionaries; other types may be supported by the game's content pipeline.</typeparam>
/// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to an XNB file relative to the mod folder.</param>
/// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to a content file relative to the mod folder.</param>
/// <param name="source">Where to search for a matching content asset.</param>
/// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception>
/// <exception cref="ContentLoadException">The content asset couldn't be loaded (e.g. because it doesn't exist).</exception>
T Load<T>(string key, ContentSource source);
T Load<T>(string key, ContentSource source = ContentSource.ModFolder);
/// <summary>Get the underlying key in the game's content cache for an asset. This can be used to load custom map tilesheets, but should be avoided when you can use the content API instead. This does not validate whether the asset exists.</summary>
/// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to an XNB file relative to the mod folder.</param>
/// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to a content file relative to the mod folder.</param>
/// <param name="source">Where to search for a matching content asset.</param>
/// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception>
string GetActualAssetKey(string key, ContentSource source);
string GetActualAssetKey(string key, ContentSource source = ContentSource.ModFolder);
}
}

View File

@ -1,4 +1,6 @@
namespace StardewModdingAPI
using System.Collections.Generic;
namespace StardewModdingAPI
{
/// <summary>A manifest which describes a mod for SMAPI.</summary>
public interface IManifest
@ -23,5 +25,8 @@
/// <summary>The name of the DLL in the directory that has the <see cref="Mod.Entry"/> method.</summary>
string EntryDll { get; set; }
/// <summary>Any manifest fields which didn't match a valid field.</summary>
IDictionary<string, object> ExtraFields { get; set; }
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -33,6 +33,9 @@
<Copy Condition="$(OS) != 'Windows_NT'" SourceFiles="$(CompiledSmapiPath)\unix-launcher.sh" DestinationFiles="$(PackageInternalPath)\Mono\StardewModdingAPI" />
<Copy Condition="$(OS) != 'Windows_NT'" SourceFiles="$(CompiledSmapiPath)\steam_appid.txt" DestinationFolder="$(PackageInternalPath)\Mono" />
<Copy Condition="$(OS) != 'Windows_NT'" SourceFiles="@(CompiledMods)" DestinationFolder="$(PackageInternalPath)\Mono\Mods\%(RecursiveDir)" />
<!--copy Mono files needed by SMAPI on Linux/Mac -->
<Copy Condition="$(OS) != 'Windows_NT'" SourceFiles="$(SolutionDir)\..\lib\libgdiplus.dylib" DestinationFolder="$(PackageInternalPath)\Mono" />
<!-- copy SMAPI files for Windows -->
<Copy Condition="$(OS) == 'Windows_NT'" SourceFiles="$(CompiledSmapiPath)\Mono.Cecil.dll" DestinationFolder="$(PackageInternalPath)\Windows" />