Support for loading module directories now.

支持加载模组目录了。
This commit is contained in:
Cold-Mint 2024-07-23 23:03:03 +08:00
parent d218109354
commit 015efbc271
Signed by: Cold-Mint
GPG Key ID: C5A9BF8A98E0CE99
12 changed files with 266 additions and 73 deletions

View File

@ -52,6 +52,10 @@ You need to fill in the Export Presets > Resources > Filter to export non-resour
data/* data/*
``` ```
#### Custom feature
- **disableVersionIsolation** Disable version isolation.
## Configuring Openobserve ## Configuring Openobserve
> This is optional, and the game will work even if you do not configure Openobserve. > This is optional, and the game will work even if you do not configure Openobserve.

View File

@ -50,6 +50,10 @@ git clone https://github.com/Cold-Mint/Traveller.git
data/* data/*
``` ```
#### 風習特徴
- **disableVersionIsolation** 版孤立を無効化する。
## はいちOpenobserve ## はいちOpenobserve
> これはオプションなので、Openobserveを設定しなくてもゲームは正常に動作します。 > これはオプションなので、Openobserveを設定しなくてもゲームは正常に動作します。

View File

@ -52,6 +52,10 @@ git clone https://github.com/Cold-Mint/Traveller.git
data/* data/*
``` ```
#### 自定义特性
- **disableVersionIsolation** 禁用版本隔离。
## 配置Openobserve ## 配置Openobserve
> 这是可选的操作即使您不配置Openobserve游戏也能正常运行。 > 这是可选的操作即使您不配置Openobserve游戏也能正常运行。

View File

@ -98,3 +98,7 @@ log_load_dll_file_load_exception,加载DLL文件{0}失败。,Failed to load the
log_load_dll_bad_image_format_exception,{0}不是有效的程序集。,{0} is not a valid assembly.,{0}は有効なアセンブリではありません。 log_load_dll_bad_image_format_exception,{0}不是有效的程序集。,{0} is not a valid assembly.,{0}は有効なアセンブリではありません。
log_load_dll_success,成功加载位于{0}的dll文件。,Successfully loaded the dll file located at {0}.,{0}にあるDLLファイルを正常にロードしました。 log_load_dll_success,成功加载位于{0}的dll文件。,Successfully loaded the dll file located at {0}.,{0}にあるDLLファイルを正常にロードしました。
log_mod_folder_does_not_exist,位于{0}的模组文件夹不存在。,The module folder at {0} does not exist.,{0}に位置するモジュールフォルダは存在しません。 log_mod_folder_does_not_exist,位于{0}的模组文件夹不存在。,The module folder at {0} does not exist.,{0}に位置するモジュールフォルダは存在しません。
log_mod_not_contain_dll,模组{0}不包含DLL文件。,The module {0} does not contain a DLL file.,モジュール{0}にDLLファイルが含まれていません。
log_mod_not_contain_pck,模组{0}不包含PCK文件。,The module {0} does not contain a PCK file.,モジュール{0}にPCKファイルが含まれていません。
log_load_pck_success,成功加载位于{0}的PCK文件。,Successfully loaded the PCK file located at {0}.,{0}にあるPCKファイルを正常にロードしました。
log_load_pck_failed,加载PCK文件{0}失败。,Failed to load the PCK file {0}.,PCKファイル{0}のロードに失敗しました。
1 id zh en ja
98 log_load_dll_bad_image_format_exception {0}不是有效的程序集。 {0} is not a valid assembly. {0}は有効なアセンブリではありません。
99 log_load_dll_success 成功加载位于{0}的dll文件。 Successfully loaded the dll file located at {0}. {0}にあるDLLファイルを正常にロードしました。
100 log_mod_folder_does_not_exist 位于{0}的模组文件夹不存在。 The module folder at {0} does not exist. {0}に位置するモジュールフォルダは存在しません。
101 log_mod_not_contain_dll 模组{0}不包含DLL文件。 The module {0} does not contain a DLL file. モジュール{0}にDLLファイルが含まれていません。
102 log_mod_not_contain_pck 模组{0}不包含PCK文件。 The module {0} does not contain a PCK file. モジュール{0}にPCKファイルが含まれていません。
103 log_load_pck_success 成功加载位于{0}的PCK文件。 Successfully loaded the PCK file located at {0}. {0}にあるPCKファイルを正常にロードしました。
104 log_load_pck_failed 加载PCK文件{0}失败。 Failed to load the PCK file {0}. PCKファイル{0}のロードに失敗しました。

View File

@ -119,7 +119,12 @@ public static class Config
/// <para>Whether version isolation is enabled</para> /// <para>Whether version isolation is enabled</para>
/// <para>是否启用版本隔离</para> /// <para>是否启用版本隔离</para>
/// </summary> /// </summary>
public const bool EnableVersionIsolation = true; public static bool EnableVersionIsolation()
{
//By default, we enable version isolation, but special feature identifiers can be set to disable version isolation.
//默认情况,我们启用版本隔离,但是可以设置特殊的功能标识来禁用版本隔离。
return !OS.HasFeature("disableVersionIsolation");
}
/// <summary> /// <summary>
/// <para>Default version name</para> /// <para>Default version name</para>
@ -210,10 +215,14 @@ public static class Config
/// <para>Get what platform is currently running on</para> /// <para>Get what platform is currently running on</para>
/// <para>获取当前在什么平台上运行</para> /// <para>获取当前在什么平台上运行</para>
/// </summary> /// </summary>
/// <param name="containEditor">
///<para>Whether to include an editor environment</para>
///<para>是否包含编辑器环境</para>
/// </param>
/// <returns></returns> /// <returns></returns>
public static OsEnum GetOs() public static OsEnum GetOs(bool containEditor = false)
{ {
if (OS.HasFeature("editor")) if (containEditor && OS.HasFeature("editor"))
{ {
return OsEnum.Editor; return OsEnum.Editor;
} }
@ -271,7 +280,7 @@ public static class Config
/// <returns></returns> /// <returns></returns>
public static string GetGameDataDirectory() public static string GetGameDataDirectory()
{ {
if (EnableVersionIsolation) if (EnableVersionIsolation())
{ {
return Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), CompanyName, return Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), CompanyName,
ProjectSettings.GetSetting("application/config/name").AsString(), UserId, ProjectSettings.GetSetting("application/config/name").AsString(), UserId,
@ -285,6 +294,15 @@ public static class Config
} }
} }
/// <summary>
/// <para>GetModDataDirectory</para>
/// <para>获取模组文件夹</para>
/// </summary>
/// <returns></returns>
public static string GetModDataDirectory()
{
return Path.Join(GetGameDataDirectory(), "Mods");
}
/// <summary> /// <summary>
/// <para>Get the export directory for the level graph</para> /// <para>Get the export directory for the level graph</para>

View File

@ -69,7 +69,7 @@ public static class ItemTypeRegister
/// </summary> /// </summary>
/// <param name="filePath"></param> /// <param name="filePath"></param>
/// <returns></returns> /// <returns></returns>
private static IList<ItemTypeInfo> ParseFile(string filePath) private static IList<ItemTypeInfo>? ParseFile(string filePath)
{ {
var yamlFile = FileAccess.Open(filePath, FileAccess.ModeFlags.Read); var yamlFile = FileAccess.Open(filePath, FileAccess.ModeFlags.Read);

View File

@ -82,7 +82,6 @@ public partial class SplashScreenLoader : UiLoaderTemplate
//Disable all logs in the release version. //Disable all logs in the release version.
//在发行版禁用所有日志。 //在发行版禁用所有日志。
LogCat.MinLogLevel = Config.IsDebug() ? LogCat.InfoLogLevel : LogCat.DisableAllLogLevel; LogCat.MinLogLevel = Config.IsDebug() ? LogCat.InfoLogLevel : LogCat.DisableAllLogLevel;
ModLoader.Init();
ContributorDataManager.RegisterAllContributorData(); ContributorDataManager.RegisterAllContributorData();
DeathInfoGenerator.RegisterDeathInfoHandler(new SelfDeathInfoHandler()); DeathInfoGenerator.RegisterDeathInfoHandler(new SelfDeathInfoHandler());
MapGenerator.RegisterRoomInjectionProcessor(new ChanceRoomInjectionProcessor()); MapGenerator.RegisterRoomInjectionProcessor(new ChanceRoomInjectionProcessor());
@ -97,6 +96,14 @@ public partial class SplashScreenLoader : UiLoaderTemplate
Directory.CreateDirectory(dataPath); Directory.CreateDirectory(dataPath);
} }
ModLoader.Init();
var modPath = Config.GetModDataDirectory();
if (!Directory.Exists(modPath))
{
Directory.CreateDirectory(modPath);
}
ModLoader.LoadAllMods(modPath);
//Registered camp //Registered camp
//注册阵营 //注册阵营
var defaultCamp = new Camp(Config.CampId.Default) var defaultCamp = new Camp(Config.CampId.Default)

View File

@ -1,8 +1,10 @@
using System; using System;
using System.Data;
using System.IO; using System.IO;
using System.Runtime.Loader; using System.Runtime.Loader;
using ColdMint.scripts.debug; using ColdMint.scripts.debug;
using ColdMint.scripts.utils; using ColdMint.scripts.utils;
using Godot;
namespace ColdMint.scripts.mod; namespace ColdMint.scripts.mod;
@ -18,8 +20,16 @@ public class ModLoader
/// </summary> /// </summary>
private static AssemblyLoadContext? _assemblyLoadContext; private static AssemblyLoadContext? _assemblyLoadContext;
private static string[] _requiredDllList = new[] { Config.SolutionName }; private static readonly string[] RequiredDllList = [Config.SolutionName];
/// <summary>
/// <para>Initializes the mod loader</para>
/// <para>初始化模组加载器</para>
/// </summary>
/// <exception cref="FileNotFoundException">
///<para>This exception is thrown if the built-in dll file cannot be found when it is loaded.</para>
///<para>如果加载内置dll文件时找不到文件则抛出此异常。</para>
/// </exception>
public static void Init() public static void Init()
{ {
//Initialize the context. //Initialize the context.
@ -39,7 +49,7 @@ public class ModLoader
return; return;
} }
foreach (var requiredDll in _requiredDllList) foreach (var requiredDll in RequiredDllList)
{ {
var dllPath = Path.Join(dllFolder, requiredDll + ".dll"); var dllPath = Path.Join(dllFolder, requiredDll + ".dll");
//Load the necessary dll files. //Load the necessary dll files.
@ -49,85 +59,214 @@ public class ModLoader
//When the dll that must be loaded does not exist, an error is reported immediately. //When the dll that must be loaded does not exist, an error is reported immediately.
//当必须加载的dll不存在时立即报错。 //当必须加载的dll不存在时立即报错。
LogCat.LogErrorWithFormat("dll_not_exist", LogCat.LogLabel.ModLoader, true, dllPath); LogCat.LogErrorWithFormat("dll_not_exist", LogCat.LogLabel.ModLoader, true, dllPath);
throw new NullReferenceException("dll not exist:" + dllPath); throw new FileNotFoundException("dll not exist:" + dllPath);
} }
//Load the dll. LoadDllFile(dllPath);
//加载dll。
LogCat.LogWithFormat("load_dll", LogCat.LogLabel.ModLoader, true, dllPath);
try
{
_assemblyLoadContext.LoadFromAssemblyPath(dllPath);
}
catch (ArgumentNullException argumentNullException)
{
//The assemblyPath parameter is null.
//assemblyPath参数为空。
LogCat.LogErrorWithFormat("load_dll_argument_null_exception", LogCat.LogLabel.ModLoader, true, dllPath);
LogCat.WhenCaughtException(argumentNullException, LogCat.LogLabel.ModLoader);
return;
}
catch (ArgumentException argumentException)
{
//Not an absolute path.
//不是绝对路径
LogCat.LogErrorWithFormat("load_dll_argument_exception", LogCat.LogLabel.ModLoader, true, dllPath);
LogCat.WhenCaughtException(argumentException, LogCat.LogLabel.ModLoader);
return;
}
catch (FileLoadException fileLoadException)
{
//A file that was found could not be loaded.
//无法加载找到的文件。
LogCat.LogErrorWithFormat("load_dll_file_load_exception", LogCat.LogLabel.ModLoader, true, dllPath);
LogCat.WhenCaughtException(fileLoadException, LogCat.LogLabel.ModLoader);
return;
}
catch (BadImageFormatException badImageFormatException)
{
//assemblyPath is not a valid assembly.
//assemblyPath不是有效的程序集。
LogCat.LogErrorWithFormat("load_dll_bad_image_format_exception", LogCat.LogLabel.ModLoader, true,
dllPath);
LogCat.WhenCaughtException(badImageFormatException, LogCat.LogLabel.ModLoader);
return;
}
//Loading the dll succeeded.
//加载dll成功。
LogCat.LogWithFormat("load_dll_success", LogCat.LogLabel.ModLoader, true, dllPath);
} }
} }
/// <summary> /// <summary>
/// <para>Load a module for a directory</para> /// <para>Load Dll file</para>
/// <para>加载某个目录的模组</para> /// <para>加载Dll文件</para>
/// </summary>
/// <param name="dllPath">
///<para>dll file path</para>
///<para>dll的文件路径</para>
/// </param>
/// <exception cref="NullReferenceException">
///<para>Throw this error if the assemblyLoadContext has not been initialized.</para>
///<para>如果assemblyLoadContext尚未初始化那么抛出此错误。</para>
/// </exception>
private static void LoadDllFile(string dllPath)
{
if (_assemblyLoadContext == null)
{
throw new NullReferenceException("assemblyLoadContext is null.");
}
//Load the dll.
//加载dll。
LogCat.LogWithFormat("load_dll", LogCat.LogLabel.ModLoader, true, dllPath);
try
{
_assemblyLoadContext.LoadFromAssemblyPath(dllPath);
}
catch (ArgumentNullException argumentNullException)
{
//The assemblyPath parameter is null.
//assemblyPath参数为空。
LogCat.LogErrorWithFormat("load_dll_argument_null_exception", LogCat.LogLabel.ModLoader, true, dllPath);
LogCat.WhenCaughtException(argumentNullException, LogCat.LogLabel.ModLoader);
return;
}
catch (ArgumentException argumentException)
{
//Not an absolute path.
//不是绝对路径
LogCat.LogErrorWithFormat("load_dll_argument_exception", LogCat.LogLabel.ModLoader, true, dllPath);
LogCat.WhenCaughtException(argumentException, LogCat.LogLabel.ModLoader);
return;
}
catch (FileLoadException fileLoadException)
{
//A file that was found could not be loaded.
//无法加载找到的文件。
LogCat.LogErrorWithFormat("load_dll_file_load_exception", LogCat.LogLabel.ModLoader, true, dllPath);
LogCat.WhenCaughtException(fileLoadException, LogCat.LogLabel.ModLoader);
return;
}
catch (BadImageFormatException badImageFormatException)
{
//assemblyPath is not a valid assembly.
//assemblyPath不是有效的程序集。
LogCat.LogErrorWithFormat("load_dll_bad_image_format_exception", LogCat.LogLabel.ModLoader, true,
dllPath);
LogCat.WhenCaughtException(badImageFormatException, LogCat.LogLabel.ModLoader);
return;
}
//Loading the dll succeeded.
//加载dll成功。
LogCat.LogWithFormat("load_dll_success", LogCat.LogLabel.ModLoader, true, dllPath);
}
/// <summary>
/// <para>Load all mods</para>
/// <para>加载全部模组</para>
/// </summary>
/// <remarks>
///<para>This method scans the incoming subfolders and loads them as module folders.</para>
///<para>此方法会将扫描传入的子文件夹,并将其子文件夹看作模组文件夹加载。</para>
/// </remarks>
/// <param name="modFolder">
///<para>Mod folder</para>
///<para>模组文件夹</para>
/// </param>
/// <exception cref="DirectoryNotFoundException">
///<para>If the given folder does not exist, throw this exception.</para>
///<para>如果给定的文件夹不存在,则抛出此异常。</para>
/// </exception>
public static void LoadAllMods(string modFolder)
{
if (!Directory.Exists(modFolder))
{
//The mod directory does not exist.
//模组目录不存在。
throw new DirectoryNotFoundException("mod folder not exist:" + modFolder);
}
var directoryInfo = new DirectoryInfo(modFolder);
foreach (var directory in directoryInfo.GetDirectories())
{
LoadSingleMod(directory.FullName);
}
}
/// <summary>
/// <para>Load a single mod</para>
/// <para>加载单个模组</para>
/// </summary> /// </summary>
/// <param name="modFolderPath"> /// <param name="modFolderPath">
///<para>Mod path</para> ///<para>Mod path</para>
///<para>模组路径</para> ///<para>模组路径</para>
/// </param> /// </param>
public static void LoadMod(string modFolderPath) /// <exception cref="DirectoryNotFoundException">
/// <para>If the given directory does not exist, throw this exception.</para>
///<para>如果给定的目录不存在,那么抛出此异常。</para>
/// </exception>
/// <exception cref="NullReferenceException">
///<para>Throw this exception if the manifest file creation deserialization fails.</para>
///<para>如果清单文件创建反序列化失败,则抛出此异常。</para>
/// </exception>
private static void LoadSingleMod(string modFolderPath)
{ {
if (!Directory.Exists(modFolderPath)) if (!Directory.Exists(modFolderPath))
{ {
//The module folder does not exist. //The module folder does not exist.
//模组文件夹不存在。 //模组文件夹不存在。
LogCat.LogErrorWithFormat("mod_folder_does_not_exist", LogCat.LogLabel.ModLoader, true, modFolderPath); throw new DirectoryNotFoundException("Mod folder does not exist:" + modFolderPath);
return;
} }
try var modManifestPath = Path.Join(modFolderPath, Config.ModManifestFileName);
var modManifest =
ModManifest.CreateModManifestFromPath(modManifestPath);
if (modManifest == null)
{ {
var modManifest = throw new NullReferenceException("mod manifest is null:" + modManifestPath);
ModManifest.CreateModManifestFromPath(Path.Join(modFolderPath, Config.ModManifestFileName));
} }
catch (FileNotFoundException fileNotFoundException)
var dllList = modManifest.DllList;
if (dllList == null || dllList.Length == 0)
{ {
//Do not continue to load the file when it does not exist. //The module does not contain a dll file.
//当文件不存在时就不要继续加载了。 //模组不包含dll文件。
LogCat.WhenCaughtException(fileNotFoundException, LogCat.LogLabel.ModLoader); LogCat.LogWarningWithFormat("mod_not_contain_dll", true, LogCat.LogLabel.ModLoader, modFolderPath);
return; }
else
{
//The module contains dll files, load the dll files.
//包含dll文件加载dll文件。
foreach (var dll in dllList)
{
var dllPath = Path.GetFullPath(dll, modFolderPath);
LoadDllFile(dllPath);
}
}
var pakList = modManifest.PckList;
if (pakList == null || pakList.Length == 0)
{
//The module does not contain a pck file.
//模组不包含pck文件。
LogCat.LogWarningWithFormat("mod_not_contain_pck", true, LogCat.LogLabel.ModLoader, modFolderPath);
}
else
{
//The module contains pck files, load the pck files.
//包含pck文件加载pck文件。
foreach (var pak in pakList)
{
var pakPath = Path.GetFullPath(pak, modFolderPath);
LoadPckFile(pakPath);
}
}
}
/// <summary>
/// <para>Load the Pck file</para>
/// <para>加载Pck文件</para>
/// </summary>
/// <param name="pckPath">
///<para>Pck path</para>
///<para>Pck路径</para>
/// </param>
/// <exception cref="FileNotFoundException">
///<para>If the given path does not exist, throw this exception.</para>
///<para>如果给定的路径不存在,那么抛出此异常。</para>
/// </exception>
/// <exception cref="Exception">
///<para>Throw this exception if the pck package fails to load.</para>
///<para>如果pck包加载失败了抛出此异常。</para>
/// </exception>
private static void LoadPckFile(string pckPath)
{
if (!File.Exists(pckPath))
{
throw new FileNotFoundException("pck file not exist:" + pckPath);
}
var success = ProjectSettings.LoadResourcePack(pckPath);
if (success)
{
LogCat.LogWithFormat("load_pck_success", LogCat.LogLabel.ModLoader, true, pckPath);
}
else
{
LogCat.LogErrorWithFormat("load_pck_failed", LogCat.LogLabel.ModLoader, true, pckPath);
//Throw a suitable exception here for handling at the caller.
//为这里抛出合适的异常,以便在调用方处理。
throw new DataException("load pck failed:" + pckPath);
} }
} }
} }

View File

@ -25,12 +25,20 @@ public class ModManifest
/// <para>Dll path list of the mod</para> /// <para>Dll path list of the mod</para>
/// <para>模组的Dll路径列表</para> /// <para>模组的Dll路径列表</para>
/// </summary> /// </summary>
/// <remarks>
///<para>Allow relative paths, such as:... / Points to the parent directory.</para>
///<para>允许使用相对路径,例如: ../指向上级目录。</para>
/// </remarks>
public string[]? DllList { get; set; } public string[]? DllList { get; set; }
/// <summary> /// <summary>
/// <para>Pck path list of mod</para> /// <para>Pck path list of mod</para>
/// <para>模组的Pck路径列表</para> /// <para>模组的Pck路径列表</para>
/// </summary> /// </summary>
/// <remarks>
///<para>Allow relative paths, such as:... / Points to the parent directory.</para>
///<para>允许使用相对路径,例如: ../指向上级目录。</para>
/// </remarks>
public string[]? PckList { get; set; } public string[]? PckList { get; set; }
/// <summary> /// <summary>
@ -50,7 +58,7 @@ public class ModManifest
///<para>当给定的路径不存在时,抛出此异常。</para> ///<para>当给定的路径不存在时,抛出此异常。</para>
/// </exception> /// </exception>
/// <returns></returns> /// <returns></returns>
public static ModManifest CreateModManifestFromPath(string filePath) public static ModManifest? CreateModManifestFromPath(string filePath)
{ {
if (!filePath.EndsWith(Config.ModManifestFileName)) if (!filePath.EndsWith(Config.ModManifestFileName))
{ {

View File

@ -51,8 +51,10 @@ public static class YamlSerialization
/// <param name="yaml"></param> /// <param name="yaml"></param>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
public static T Deserialize<T>(string yaml) // ReSharper disable ReturnTypeCanBeNotNullable
public static T? Deserialize<T>(string yaml)
{ {
return YamlDeserializer.Deserialize<T>(yaml); return YamlDeserializer.Deserialize<T>(yaml);
} }
// ReSharper restore ReturnTypeCanBeNotNullable
} }

View File

@ -58,6 +58,7 @@ public static class ExplorerUtils
case Config.OsEnum.Macos: case Config.OsEnum.Macos:
case Config.OsEnum.Ios: case Config.OsEnum.Ios:
case Config.OsEnum.Web: case Config.OsEnum.Web:
case Config.OsEnum.Editor:
default: default:
throw new ArgumentOutOfRangeException(); throw new ArgumentOutOfRangeException();
} }

View File

@ -23,20 +23,22 @@ public static class ResUtils
public static string? GetSelfDllFolder() public static string? GetSelfDllFolder()
{ {
var currentDirectory = Environment.CurrentDirectory; var currentDirectory = Environment.CurrentDirectory;
if (Config.GetOs() == Config.OsEnum.Editor) var osEnum = Config.GetOs(true);
if (osEnum == Config.OsEnum.Editor)
{ {
return Path.Join(currentDirectory, ".godot", "mono", "temp", "bin", "Debug"); return Path.Join(currentDirectory, ".godot", "mono", "temp", "bin", "Debug");
} }
if (Config.GetOs() == Config.OsEnum.Windows) if (osEnum == Config.OsEnum.Windows)
{ {
return Path.Join(currentDirectory, "data_" + Config.SolutionName + "_windows_x86_64"); return Path.Join(currentDirectory, "data_" + Config.SolutionName + "_windows_x86_64");
} }
if (Config.GetOs() == Config.OsEnum.Linux) if (osEnum == Config.OsEnum.Linux)
{ {
return Path.Join(currentDirectory, "data_" + Config.SolutionName + "_linuxbsd_x86_64"); return Path.Join(currentDirectory, "data_" + Config.SolutionName + "_linuxbsd_x86_64");
} }
return null; return null;
} }