Skip to content

Commit

Permalink
Merge pull request #236 from SpaceWarpDev/v1.3.0
Browse files Browse the repository at this point in the history
V1.3.0 -> Main for release
  • Loading branch information
cheese3660 authored Jun 22, 2023
2 parents aa04c41 + d1fa207 commit ef41555
Show file tree
Hide file tree
Showing 71 changed files with 105,466 additions and 602 deletions.
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<SpaceWarpVersion>1.2.0</SpaceWarpVersion>
<SpaceWarpVersion>1.3.0</SpaceWarpVersion>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>11</LangVersion>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
Expand Down
52 changes: 52 additions & 0 deletions SpaceWarp/API/Assets/AssetManager.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SpaceWarp.API.Lua;
using UnityEngine;
using Logger = BepInEx.Logging.Logger;

namespace SpaceWarp.API.Assets;

[SpaceWarpLuaAPI("Assets")]
public static class AssetManager
{
private static readonly Dictionary<string, UnityObject> AllAssets = new();
Expand Down Expand Up @@ -133,4 +135,54 @@ public static bool TryGetAsset<T>(string path, out T asset) where T : UnityObjec

return true;
}

/// <summary>
/// Gets an asset from the specified asset path
/// </summary>
/// <param name="path">an asset path, format: {mod_id}/{asset_bundle}/{asset_path}</param>
/// <returns></returns>
public static UnityObject GetAsset(string path)
{
path = path.ToLower();
var subPaths = path.Split('/', '\\');
if (subPaths.Length < 3)
{
throw new ArgumentException(
"Invalid path, asset paths must follow to following structure: {mod_id}/{asset_bundle}/{asset_path}");
}

if (!AllAssets.TryGetValue(path, out var value))
{
throw new IndexOutOfRangeException($"Unable to find asset at path \"{path}\"");
}

return value;
}

/// <summary>
/// Tries to get an asset from the specified asset path
/// </summary>
/// <param name="path">an asset path, format: {mod_id}/{asset_bundle}/{asset_name}</param>
/// <param name="asset">the asset output</param>
/// <returns>Whether or not the asset exists and is loaded</returns>
public static bool TryGetAsset(string path, out UnityObject asset)
{
path = path.ToLower();
asset = null;
var subPaths = path.Split('/', '\\');

if (subPaths.Length < 3)
{
return false;
}

if (!AllAssets.TryGetValue(path, out var value))
{
return false;
}

asset = value;

return true;
}
}
2 changes: 2 additions & 0 deletions SpaceWarp/API/Game/Vehicle.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using KSP.Game;
using KSP.Sim.impl;
using SpaceWarp.API.Lua;

namespace SpaceWarp.API.Game;

[SpaceWarpLuaAPI("Vehicle")]
public static class Vehicle
{
public static VesselVehicle ActiveVesselVehicle => GameManager.Instance.Game.ViewController._activeVesselVehicle;
Expand Down
118 changes: 112 additions & 6 deletions SpaceWarp/API/Loading/Loading.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,20 @@
using SpaceWarp.API.Assets;
using SpaceWarp.API.Mods;
using SpaceWarp.API.Mods.JSON;
using SpaceWarp.InternalUtilities;
using SpaceWarp.Patching.LoadingActions;

namespace SpaceWarp.API.Loading;

public static class Loading
{
internal static List<Func<SpaceWarpPluginDescriptor, DescriptorLoadingAction>> DescriptorLoadingActionGenerators =
new();

internal static List<Func<SpaceWarpPluginDescriptor, DescriptorLoadingAction>>
FallbackDescriptorLoadingActionGenerators =
new();

internal static List<Func<BaseSpaceWarpPlugin, ModLoadingAction>> LoadingActionGenerators = new();
internal static List<FlowAction> GeneralLoadingActions = new();

Expand All @@ -29,15 +37,31 @@ public static void AddAssetLoadingAction(string subfolder, string name,
extensions.Length == 0
? CreateAssetLoadingActionWithoutExtension(subfolder, importFunction)
: CreateAssetLoadingActionWithExtensions(subfolder, importFunction, extensions));
FallbackDescriptorLoadingActionGenerators.Add(d => new DescriptorLoadingAction(name,
extensions.Length == 0
? CreateAssetLoadingActionWithoutExtensionDescriptor(subfolder, importFunction)
: CreateAssetLoadingActionWithExtensionsDescriptor(subfolder, importFunction, extensions), d));
}

/// <summary>
/// Registers a per mod loading action
/// </summary>
/// <param name="name">The name of the action</param>
/// <param name="action">The action</param>
[Obsolete("Use AddDescriptorLoadingAction instead")]
public static void AddModLoadingAction(string name, Action<BaseSpaceWarpPlugin> action)
{
LoadingActionGenerators.Add(p => new ModLoadingAction(name,action,p));
LoadingActionGenerators.Add(p => new ModLoadingAction(name, action, p));
}

/// <summary>
/// Registers a per mod loading action (but more general)
/// </summary>
/// <param name="name">The name of the action</param>
/// <param name="action">The action</param>
public static void AddDescriptorLoadingAction(string name, Action<SpaceWarpPluginDescriptor> action)
{
DescriptorLoadingActionGenerators.Add(p => new DescriptorLoadingAction(name, action, p));
}

/// <summary>
Expand All @@ -56,13 +80,15 @@ public static void AddGeneralLoadingAction(FlowAction action)
/// <param name="label">The addressables label to hook into</param>
/// <param name="action">The action to be done on each addressables asset</param>
/// <typeparam name="T">The type of asset that this action is done upon</typeparam>
public static void AddAddressablesLoadingAction<T>(string name, string label, Action<T> action) where T : UnityObject
public static void AddAddressablesLoadingAction<T>(string name, string label, Action<T> action)
where T : UnityObject
{
AddGeneralLoadingAction(new AddressableAction<T>(name, label, action));
}


private static Action<BaseSpaceWarpPlugin> CreateAssetLoadingActionWithExtensions(string subfolder, Func<string, string, List<(string name, UnityObject asset)>> importFunction, string[] extensions)
private static Action<BaseSpaceWarpPlugin> CreateAssetLoadingActionWithExtensions(string subfolder,
Func<string, string, List<(string name, UnityObject asset)>> importFunction, string[] extensions)
{
return plugin =>
{
Expand All @@ -87,7 +113,37 @@ private static Action<BaseSpaceWarpPlugin> CreateAssetLoadingActionWithExtension
};
}

private static void LoadSingleAsset(Func<string, string, List<(string name, UnityObject asset)>> importFunction, string path, string file, BaseSpaceWarpPlugin plugin)
private static Action<SpaceWarpPluginDescriptor> CreateAssetLoadingActionWithExtensionsDescriptor(string subfolder,
Func<string, string, List<(string name, UnityObject asset)>> importFunction, string[] extensions)
{
return plugin =>
{
var path = Path.Combine(plugin.Folder.FullName, "assets", subfolder);
if (!Directory.Exists(path)) return;
var directoryInfo = new DirectoryInfo(path);
foreach (var extension in extensions)
{
foreach (var file in directoryInfo.EnumerateFiles($"*.{extension}", SearchOption.AllDirectories)
.Select(fileInfo => fileInfo.FullName))
{
try
{
LoadSingleAsset(importFunction, path, file, plugin);
}
catch (Exception e)
{
if (plugin.Plugin != null)
plugin.Plugin.ModLogger.LogError(e.ToString());
else
SpaceWarpPlugin.Logger.LogError(plugin.SWInfo.Name + ": " + e);
}
}
}
};
}

private static void LoadSingleAsset(Func<string, string, List<(string name, UnityObject asset)>> importFunction,
string path, string file, BaseSpaceWarpPlugin plugin)
{
var assetPathList = PathHelpers.GetRelativePath(path, file)
.Split(Path.DirectorySeparatorChar);
Expand All @@ -108,7 +164,30 @@ private static void LoadSingleAsset(Func<string, string, List<(string name, Unit
}
}

private static Action<BaseSpaceWarpPlugin> CreateAssetLoadingActionWithoutExtension(string subfolder, Func<string, string, List<(string name, UnityObject asset)>> importFunction)
private static void LoadSingleAsset(Func<string, string, List<(string name, UnityObject asset)>> importFunction,
string path, string file, SpaceWarpPluginDescriptor plugin)
{
var assetPathList = PathHelpers.GetRelativePath(path, file)
.Split(Path.DirectorySeparatorChar);
var assetPath = "";
for (var i = 0; i < assetPathList.Length; i++)
{
assetPath += assetPathList[i].ToLower();
if (i != assetPathList.Length - 1)
{
assetPath += "/";
}
}

var assets = importFunction(assetPath, file);
foreach (var asset in assets)
{
AssetManager.RegisterSingleAsset(plugin.Guid, asset.name, asset.asset);
}
}

private static Action<BaseSpaceWarpPlugin> CreateAssetLoadingActionWithoutExtension(string subfolder,
Func<string, string, List<(string name, UnityObject asset)>> importFunction)
{
return plugin =>
{
Expand All @@ -117,7 +196,8 @@ private static Action<BaseSpaceWarpPlugin> CreateAssetLoadingActionWithoutExtens
var directoryInfo = new DirectoryInfo(path);
foreach (var file in directoryInfo.EnumerateFiles("*", SearchOption.AllDirectories)
.Select(fileInfo => fileInfo.FullName))
{try
{
try
{
LoadSingleAsset(importFunction, path, file, plugin);
}
Expand All @@ -128,4 +208,30 @@ private static Action<BaseSpaceWarpPlugin> CreateAssetLoadingActionWithoutExtens
}
};
}

private static Action<SpaceWarpPluginDescriptor> CreateAssetLoadingActionWithoutExtensionDescriptor(
string subfolder, Func<string, string, List<(string name, UnityObject asset)>> importFunction)
{
return plugin =>
{
var path = Path.Combine(plugin.Folder.FullName, "assets", subfolder);
if (!Directory.Exists(path)) return;
var directoryInfo = new DirectoryInfo(path);
foreach (var file in directoryInfo.EnumerateFiles("*", SearchOption.AllDirectories)
.Select(fileInfo => fileInfo.FullName))
{
try
{
LoadSingleAsset(importFunction, path, file, plugin);
}
catch (Exception e)
{
if (plugin.Plugin != null)
plugin.Plugin.ModLogger.LogError(e.ToString());
else
SpaceWarpPlugin.Logger.LogError(plugin.SWInfo.Name + ": " + e);
}
}
};
}
}
106 changes: 106 additions & 0 deletions SpaceWarp/API/Lua/AppBarInterop.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using System;
using JetBrains.Annotations;
using MoonSharp.Interpreter;
using SpaceWarp.API.Assets;
using SpaceWarp.API.UI.Appbar;
using UnityEngine;
using UnityEngine.UIElements;

// ReSharper disable MemberCanBePrivate.Global

// ReSharper disable UnusedMember.Global
namespace SpaceWarp.API.Lua;

[SpaceWarpLuaAPI("AppBar")]
// ReSharper disable once UnusedType.Global
public static class AppBarInterop
{
public static Sprite GetSprite(string texturePath, int width = 0, int height = 0)
{
return GetSprite(AssetManager.GetAsset<Texture2D>(texturePath));
}

public static Sprite GetSprite(Texture2D texture, int width = 0, int height = 0)
{
if (width == 0)
{
width = texture.width;
}

if (height == 0)
{
height = texture.height;
}

return Sprite.Create(texture, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
}

public static void RegisterAppButton(bool oab, bool inFlight, string name, string ID, Sprite icon,
Closure toggleCallback, [CanBeNull] DynValue self = null)
{
Action<bool> callback;
if (self != null)
{
callback = b => toggleCallback.Call(self, b);
}
else
{
callback = b => toggleCallback.Call(b);
}

if (oab)
{
Appbar.RegisterAppButton(name, ID, icon, callback);
}

if (inFlight)
{
Appbar.RegisterOABAppButton(name, ID, icon, callback);
}
}

public static void RegisterAppButton(bool oab, bool inFlight, string name, string ID, string texturePath,
Closure toggleCallback, [CanBeNull] DynValue self = null) =>
RegisterAppButton(oab, inFlight, name, ID, GetSprite(texturePath), toggleCallback, self);

public static void RegisterAppWindow(bool oab, bool inFlight, string name, string ID, Sprite icon, VisualElement window, Closure toggleCallback, [CanBeNull] DynValue self = null)
{

Action<bool> callback;
if (self != null)
{
callback = b =>
{
window.visible = b;
toggleCallback.Call(self, b);
};
}
else
{
callback = b =>
{
window.visible = b;
toggleCallback.Call(b);
};
}

if (oab)
{
Appbar.RegisterAppButton(name, ID, icon, callback);
}

if (inFlight)
{
Appbar.RegisterOABAppButton(name, ID, icon, callback);
}
}

public static void RegisterAppWindow(bool oab, bool inFlight, string name, string ID, string texturePath, VisualElement window,
Closure toggleCallback, [CanBeNull] DynValue self = null) =>
RegisterAppWindow(oab, inFlight, name, ID, GetSprite(texturePath), window, toggleCallback, self);

public static void SetAppButtonIndicator(string id, bool b)
{
Appbar.SetAppBarButtonIndicator(id, b);
}
}
Loading

0 comments on commit ef41555

Please sign in to comment.