RustToDust/client/NativeLibraries.cs

76 lines
3 KiB
C#
Raw Permalink Normal View History

using System;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Godot;
using Ymir.Box3D;
namespace RustToDust.Client;
/// <summary>
/// Finds ymir_box3d for Ymir.Box3D's DllImports. Godot loads game assemblies into its own load context, so the
/// default probing does not look beside them. A run from the editor or <c>--path</c> loads the library from the
/// project's build directory; an exported run from the data folder Godot puts beside the executable.
/// </summary>
internal static class NativeLibraries
{
private const string Library = "ymir_box3d";
#pragma warning disable CA2255 // application code: the resolver must exist before the first DllImport
[ModuleInitializer]
internal static void Register() =>
NativeLibrary.SetDllImportResolver(typeof(Box3DSoaWorld).Assembly, Resolve);
private static IntPtr Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath)
{
if (name != Library) return IntPtr.Zero;
string fileName = FileName();
if (OS.HasFeature("template"))
{
string exePath = OS.GetExecutablePath();
string exeDir = exePath.GetBaseDir();
string exeStem = Path.GetFileNameWithoutExtension(exePath);
string platArch = $"{Platform()}_{Arch()}";
string[] candidates =
{
Path.Combine(exeDir, fileName),
Path.Combine(exeDir, $"data_{exeStem}_{platArch}", fileName),
Path.Combine(exeDir, $"data_RustToDust_{platArch}", fileName),
Path.Combine(exeDir, $"data_RustToDust.Client_{platArch}", fileName),
Path.Combine(AppContext.BaseDirectory, fileName),
};
foreach (string candidate in candidates)
{
if (File.Exists(candidate) && NativeLibrary.TryLoad(candidate, out var exportHandle))
{
return exportHandle;
}
}
return IntPtr.Zero;
}
string debugPath = Path.Combine(ProjectSettings.GlobalizePath("res://.godot/mono/temp/bin/Debug"), fileName);
if (File.Exists(debugPath) && NativeLibrary.TryLoad(debugPath, out var debugHandle))
{
return debugHandle;
}
string releasePath = Path.Combine(ProjectSettings.GlobalizePath("res://.godot/mono/temp/bin/Release"), fileName);
return File.Exists(releasePath) && NativeLibrary.TryLoad(releasePath, out var releaseHandle)
? releaseHandle
: IntPtr.Zero;
}
private static string FileName() =>
OperatingSystem.IsWindows() ? "ymir_box3d.dll" : OperatingSystem.IsMacOS() ? "libymir_box3d.dylib" : "libymir_box3d.so";
private static string Platform() =>
OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linuxbsd";
private static string Arch() =>
RuntimeInformation.ProcessArchitecture == System.Runtime.InteropServices.Architecture.Arm64 ? "arm64" : "x86_64";
}