Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
13 changes: 11 additions & 2 deletions Utils.cs → Src/PlanetbaseFramework/Common/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public static class Utils
/// </summary>
public static Texture2D ErrorTexture { get; internal set; }

/// <summary>
#region Split to ResourceLoaders
/// <summary>
/// Load the a XML file containing strings (for localization/translations)
/// </summary>
/// <param name="absolutePath">The absolute path to the XML file</param>
Expand Down Expand Up @@ -130,6 +131,9 @@ public static Texture2D LoadPngFromFile(string absolutePath)
return loadedTexture;
}

#endregion


/// <summary>
/// Set the normal map on a texture. This should be called on any normal maps either at the init stage or the constructor of the mod.
/// </summary>
Expand All @@ -149,6 +153,7 @@ public static void SetNormalMap(this Texture2D texture)
texture.SetPixels(pixels);
}

#region Split to Object finder
public static T FindObjectByFilename<T>(this List<T> list, string filename) where T : UnityEngine.Object
{
try
Expand All @@ -169,8 +174,10 @@ public static T FindObjectByFilepath<T>(this List<T> list, string filepath) wher
{
return FindObjectByFilename(list, Path.GetFileName(filepath));
}
#endregion

public static bool IsValidTag(this string toCheck)
#region GameObjectExtensions
public static bool IsValidTag(this string toCheck)
{
try
{
Expand All @@ -184,6 +191,8 @@ public static bool IsValidTag(this string toCheck)

public static bool Compare(this Type t1, Type t2) => t1.FullName != null && t1.FullName.Equals(t2.FullName);

#endregion

public static string[] ListEmbeddedFiles()
{
var assembly = Assembly.GetCallingAssembly();
Expand Down
10 changes: 5 additions & 5 deletions Modloader.cs → Src/PlanetbaseFramework/Loader/Modloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,9 @@ namespace PlanetbaseFramework
* This is the core class behind loading all mods. The patcher injects calls to loadMods() and updateMods() into the native PB code, which then
* calls the methods in this file. This allows for minimal changes to PB's native code, while still allowing it to be extended.
*/
public class ModLoader
public static class ModLoader
{
/// <summary>
/// A list of all mods that have been initialized
/// </summary>
public static List<ModBase> ModList = new List<ModBase>();
public static List<ModBase> InitializedMods = new List<ModBase>();

/// <summary>
/// Called by the game manager on startup to load in mods
Expand All @@ -25,6 +22,7 @@ public static void LoadMods()
{
Debug.Log("Loading mods...");

// Split to function: LoadAssemblyFiles
var modDLLs = new List<string>();

modDLLs.Add(Assembly.GetExecutingAssembly().Location);
Expand All @@ -46,6 +44,7 @@ public static void LoadMods()

foreach (var file in modDLLs)
{
// Split to function- LoadTypes()
Type[] types;
try
{
Expand All @@ -72,6 +71,7 @@ public static void LoadMods()
continue;
}

// Create method- InjectMods(types)
foreach (var type in types)
{
//Skip if the type isn't a mod
Expand Down
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ public BaseModuleType(Texture2D icon, GameObject[] moduleObjects)

public override GameObject loadPrefab(int sizeIndex)
{
int adjustedSizeIndex = sizeIndex - mMinSize; //Takes into account the edge case where mMinSize != 0
//Takes into account the edge case where mMinSize != 0
int adjustedSizeIndex = sizeIndex - mMinSize;

ModuleObjects[adjustedSizeIndex].calculateSmoothMeshRecursive(mMeshes);

Expand Down
File renamed without changes.
212 changes: 112 additions & 100 deletions ModBase.cs → Src/PlanetbaseFramework/Mod/ModBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,122 +7,44 @@
using ICSharpCode.SharpZipLib.Zip;
using PlanetbaseFramework.Patches.Planetbase.GameStateTitle;
using UnityEngine;
using System.ComponentModel;

namespace PlanetbaseFramework
{
public abstract class ModBase
{
public abstract string ModName { get; }

public virtual Version ModVersion => new Version(0, 0, 0, 0);
public virtual string ModPath => Path.Combine(BasePath, ModName);
public virtual string AssetsPath => Path.Combine(ModPath, "assets");

public List<Texture2D> ModTextures { get; protected set; }
public List<GameObject> ModObjects { get; protected set; }

public virtual Version ModVersion => new Version(0, 0, 0, 0);
//Some of you might notice the odd '/' character in this string. This is because native PB code doesn't use Path.DirectorySeparatorChar, causing
//one char to be wrong. I'll fix it at some point after I rewrite the patcher.
public static string BasePath { get; } = Path.Combine(Util.getFilesFolder(), "Mods");

private static IResourceUnpacker _resourceUnpacker;

private HarmonyInstance Harmony { get; set; }

private static FastZip ZipInstance { get; } = new FastZip();

protected ModBase()
{
//Extract embedded assets
ZipConstants.DefaultCodePage = 0; //This is a workaround to get files to extract properly

var currentAssembly = Assembly.GetCallingAssembly();
var manifest = currentAssembly.GetManifestResourceNames();

PreProcessEmbeddedResources(manifest);

foreach (var file in manifest)
{
if (!PreProcessEmbeddedResource(file)) continue;

Debug.Log($"Processing embedded file \"{file}\"");

using (var resourceStream = currentAssembly.GetManifestResourceStream(file))
{
switch (Path.GetExtension(file))
{
case ".zip":
Debug.Log("zip " + GetResourceRelativeFilePath(file));
ZipInstance.ExtractZip(
resourceStream,
ModPath,
FastZip.Overwrite.Always,
null,
null,
null,
false,
false
);
break;
default: //Copy the file to a directory matching the name under the mod's folder
var filePath = Path.Combine(ModPath, GetResourceRelativeFilePath(file));

Debug.Log($"Loading \"{file}\" to \"{filePath}\"");

Directory.CreateDirectory(Path.GetDirectoryName(filePath));

using (var fileStream = File.Create(filePath))
{
resourceStream.CopyTo(fileStream);
}

break;
}
}
}

try
{
LoadAllStrings("strings");
}
catch (Exception e)
{
Debug.Log("Failed to load strings files due to exception:");
Utils.LogException(e);
}

try
{
ModTextures = LoadAllPngs("png");

if (ModTextures.Count > 0)
{
Debug.Log($"Successfully loaded {ModTextures.Count} texture(s)");
}
}
catch (Exception e)
{
Debug.Log("Failed to load PNG files due to exception:");
Utils.LogException(e);
}

try
{
ModObjects = LoadAllObjs("obj");

if(ModObjects.Count > 0)
{
Debug.Log($"Successfully loaded {ModObjects.Count} object(s)");
}
}
catch (Exception e)
{
Debug.Log("Failed to load OBJ files due to exception:");
Utils.LogException(e);
}
// Consider moving out.
ExtractAssets();
LoadStrings();
LoadTextures();
LoadMeshes();
SetupUnpackers();
}

public abstract string ModName { get; }

//Some of you might notice the odd '/' character in this string. This is because native PB code doesn't use Path.DirectorySeparatorChar, causing
//one char to be wrong. I'll fix it at some point after I rewrite the patcher.
public static string BasePath { get; } = Path.Combine(Util.getFilesFolder(), "Mods");

public virtual string ModPath => Path.Combine(BasePath, ModName);

public virtual string AssetsPath => Path.Combine(ModPath, "assets");

public virtual void Init() //This is virtual instead of abstract so mods aren't required to implement it. Same with Update below
/// <summary>
/// This is virtual instead of abstract so mods aren't required to implement it. Same with Update below
/// </summary>
public virtual void Init()
{
}

Expand Down Expand Up @@ -226,6 +148,84 @@ protected virtual bool PreProcessEmbeddedResource(string resourceName)
return true;
}

private static void SetupUnpackers()
{
var resourceUnpacker = new ResourceUnpacker();

var zipUnpacker = new ZipUnpacker();
resourceUnpacker.RegisterUnpacker(zipUnpacker);

var defaultUnpacker = new NoUnpacker();
resourceUnpacker.RegisterDefault(defaultUnpacker);
}

private static void ExtractAssets()
{
var currentAssembly = Assembly.GetCallingAssembly();
var manifest = currentAssembly.GetManifestResourceNames();

PreProcessEmbeddedResources(manifest);

foreach (var file in manifest)
{
if (!PreProcessEmbeddedResource(file)) continue;

Debug.Log($"Processing embedded file \"{file}\"");
}

_resourceUnpacker.Unpack(re)
}

private static void LoadStrings()
{
// LoadStrings
try
{
LoadAllStrings("strings");
}
catch (Exception e)
{
Debug.Log("Failed to load strings files due to exception:");
Utils.LogException(e);
}
}

private static void LoadTextures()
{
try
{
ModTextures = LoadAllPngs("png");

if (ModTextures.Count > 0)
{
Debug.Log($"Successfully loaded {ModTextures.Count} texture(s)");
}
}
catch (Exception e)
{
Debug.Log("Failed to load PNG files due to exception:");
Utils.LogException(e);
}
}

private static void LoadMeshes()
{
try
{
ModObjects = LoadAllObjs("obj");

if (ModObjects.Count > 0)
{
Debug.Log($"Successfully loaded {ModObjects.Count} object(s)");
}
}
catch (Exception e)
{
Debug.Log("Failed to load OBJ files due to exception:");
Utils.LogException(e);
}
}

private static string GetResourceRelativeFilePath(string resourceName)
{
//Remove the project name from the path, including the preceding '.'
Expand All @@ -237,5 +237,17 @@ private static string GetResourceRelativeFilePath(string resourceName)

return convertedFilePath;
}

private class SomethingFastZip : FastZip
{
public SomethingFastZip()
{
//This is a workaround to get files to extract properly.
// Define properly.
// Don't inline comments.
ZipConstants.DefaultCodePage = 0;
}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ public class ModListGameState : GameState
{
private GuiRenderer Renderer { get; } = new GuiRenderer();

public override bool isTitleState()
{
return true;
}
public override bool isTitleState() => true;

public override void onGui()
{
Expand All @@ -20,8 +17,10 @@ public override void onGui()
return;
}


PrintLine("Loaded Mods:", 0);
for(var i = 0; i < ModLoader.ModList.Count; i++)
// This should be split to a method
for (var i = 0; i < ModLoader.ModList.Count; i++)
{
PrintLine(ModLoader.ModList[i].ModName, i + 1);
}
Expand Down
File renamed without changes.
Loading