RustToDust/client/NativeLibraries.cs

89 lines
3.2 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 RustToDust.HbGpu;
using Ymir.Box3D;
namespace RustToDust.Client;
/// <summary>
/// Resolves native libraries (ymir_box3d, rtd_hbgpu) for Godot's AssemblyLoadContext.
/// </summary>
internal static class NativeLibraries
{
private const string YmirLibrary = "ymir_box3d";
private const string HbGpuLibrary = "rtd_hbgpu";
#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);
NativeLibrary.SetDllImportResolver(typeof(HbGpuNative).Assembly, Resolve);
}
private static IntPtr Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath)
{
string? stem = name switch
{
YmirLibrary => YmirLibrary,
HbGpuLibrary => HbGpuLibrary,
_ => null
};
if (stem is null)
{
return IntPtr.Zero;
}
string fileName = FileName(stem);
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(string stem) =>
OperatingSystem.IsWindows() ? $"{stem}.dll" : OperatingSystem.IsMacOS() ? $"lib{stem}.dylib" : $"lib{stem}.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";
}